task_id
stringlengths
30
61
workdir
stringclasses
1 value
project_name
stringclasses
32 values
tag_name
stringlengths
19
32
report_path
stringlengths
53
84
vulnerability_description
stringlengths
76
116
patch_diff
stringlengths
375
461k
3rdn4/libxml2:5f4ec41-global_buffer_overflow
/workspace/skyset/
libxml2
5f4ec41-global_buffer_overflow
/workspace/skyset/libxml2/5f4ec41-global_buffer_overflow/report.txt
A global buffer overflow found in /workspace/skyset/libxml2/5f4ec41-global_buffer_overflow/immutable/
From ca2bfecea9c23f8d2e11741fff7c6a5372c56bb8 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Wed, 15 Mar 2023 16:18:11 +0100 Subject: [PATCH] malloc-fail: Fix buffer overread when reading from input Found by OSS-Fuzz, see #344. --- HTMLparser.c | 29 ++++++++++------------ parserInternals.c | 61 +++++++++++++++++++---------------------------- 2 files changed, 38 insertions(+), 52 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 509e029eb..0830584f5 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -410,6 +410,11 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { *len = 0; return(ctxt->token); } + + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if (ctxt->charset != XML_CHAR_ENCODING_UTF8) { xmlChar * guess; xmlCharEncodingHandlerPtr handler; @@ -470,29 +475,21 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { cur = ctxt->input->cur; c = *cur; if (c & 0x80) { + size_t avail; + if ((c & 0x40) == 0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || ((cur[1] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xe0) == 0xe0) { - - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || ((cur[2] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; diff --git a/parserInternals.c b/parserInternals.c index a7f0aa95a..c0281be27 100644 --- a/parserInternals.c +++ b/parserInternals.c @@ -554,8 +554,11 @@ xmlNextChar(xmlParserCtxtPtr ctxt) return; } - if ((ctxt->input->cur >= ctxt->input->end) && (xmlParserGrow(ctxt) <= 0)) { - return; + if (ctxt->input->end - ctxt->input->cur < 4) { + if (xmlParserGrow(ctxt) < 0) + return; + if (ctxt->input->cur >= ctxt->input->end) + return; } if (ctxt->charset == XML_CHAR_ENCODING_UTF8) { @@ -588,30 +591,23 @@ xmlNextChar(xmlParserCtxtPtr ctxt) c = *cur; if (c & 0x80) { + size_t avail; + if (c == 0xC0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { unsigned int val; - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ ctxt->input->cur += 4; @@ -652,8 +648,6 @@ xmlNextChar(xmlParserCtxtPtr ctxt) ctxt->input->col++; ctxt->input->cur++; } - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); return; encoding_error: /* @@ -707,6 +701,10 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { if (ctxt->instate == XML_PARSER_EOF) return(0); + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if ((*ctxt->input->cur >= 0x20) && (*ctxt->input->cur <= 0x7F)) { *len = 1; return(*ctxt->input->cur); @@ -729,28 +727,21 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { c = *cur; if (c & 0x80) { + size_t avail; + if (((c & 0x40) == 0) || (c == 0xC0)) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; @@ -785,8 +776,6 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { } else { /* 1-byte code */ *len = 1; - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); if ((*ctxt->input->cur == 0) && (ctxt->input->end > ctxt->input->cur)) { xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
3rdn4/libxml2:7fbd454-global_buffer_overflow
/workspace/skyset/
libxml2
7fbd454-global_buffer_overflow
/workspace/skyset/libxml2/7fbd454-global_buffer_overflow/report.txt
A global buffer overflow found in /workspace/skyset/libxml2/7fbd454-global_buffer_overflow/immutable/
From 1061537efdf3874c91fd50d18f98c4b8a3518e52 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Sun, 26 Mar 2023 22:40:54 +0200 Subject: [PATCH] malloc-fail: Fix buffer overread with HTML doctype declarations Found by OSS-Fuzz, see #344. --- HTMLparser.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index b8b6bd230..abcdfe246 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -3010,9 +3010,9 @@ htmlParseSystemLiteral(htmlParserCtxtPtr ctxt) { htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, "Unfinished SystemLiteral\n", NULL, NULL); } else { - NEXT; if (err == 0) ret = xmlStrndup((BASE_PTR+startPosition), len); + NEXT; } return(ret); @@ -3065,9 +3065,9 @@ htmlParsePubidLiteral(htmlParserCtxtPtr ctxt) { htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, "Unfinished PubidLiteral\n", NULL, NULL); } else { - NEXT; if (err == 0) ret = xmlStrndup((BASE_PTR + startPosition), len); + NEXT; } return(ret);
3rdn4/libxml2:9ef2a9a-global_buffer_overflow_a
/workspace/skyset/
libxml2
9ef2a9a-global_buffer_overflow_a
/workspace/skyset/libxml2/9ef2a9a-global_buffer_overflow_a/report.txt
A global buffer overflow a found in /workspace/skyset/libxml2/9ef2a9a-global_buffer_overflow_a/immutable/
From 067986fa674f0811614dab4c4572f5f7ff483400 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Sat, 18 Mar 2023 14:44:28 +0100 Subject: [PATCH] parser: Fix regressions from previous commits - Fix memory leak in xmlParseNmtoken. - Fix buffer overread after htmlParseCharDataInternal. --- HTMLparser.c | 2 +- parser.c | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 0e79dffdd..ca3ebc413 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -3203,6 +3203,7 @@ htmlParseCharDataInternal(htmlParserCtxtPtr ctxt, int readahead) { } else { COPY_BUF(l,buf,nbchar,cur); } + NEXTL(l); if (nbchar >= HTML_PARSER_BIG_BUFFER_SIZE) { buf[nbchar] = 0; @@ -3228,7 +3229,6 @@ htmlParseCharDataInternal(htmlParserCtxtPtr ctxt, int readahead) { nbchar = 0; SHRINK; } - NEXTL(l); cur = CUR_CHAR(l); } if (ctxt->instate == XML_PARSER_EOF) diff --git a/parser.c b/parser.c index f69231d5a..8e548cdae 100644 --- a/parser.c +++ b/parser.c @@ -3683,8 +3683,10 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { c = CUR_CHAR(l); } buffer[len] = 0; - if (ctxt->instate == XML_PARSER_EOF) + if (ctxt->instate == XML_PARSER_EOF) { + xmlFree(buffer); return(NULL); + } return(buffer); } }
3rdn4/libxml2:9ef2a9a-global_buffer_overflow_b
/workspace/skyset/
libxml2
9ef2a9a-global_buffer_overflow_b
/workspace/skyset/libxml2/9ef2a9a-global_buffer_overflow_b/report.txt
A global buffer overflow b found in /workspace/skyset/libxml2/9ef2a9a-global_buffer_overflow_b/immutable/
From 04d1bedd8c3fc5d9e41d11e2d0da08a966b732d3 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Tue, 21 Mar 2023 13:08:44 +0100 Subject: [PATCH] parser: Rework shrinking of input buffers Don't try to grow the input buffer in xmlParserShrink. This makes sure that no memory allocations are made and the function always succeeds. Remove unnecessary invocations of SHRINK. Invoke SHRINK at the end of DTD parsing loops. Shrink before growing. --- HTMLparser.c | 7 ++----- include/private/parser.h | 2 +- parser.c | 29 +++++------------------------ parserInternals.c | 16 ++-------------- 4 files changed, 10 insertions(+), 44 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 81bd11f9a..3bebda6e2 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -3100,7 +3100,6 @@ htmlParseScript(htmlParserCtxtPtr ctxt) { int nbchar = 0; int cur,l; - SHRINK; cur = CUR_CHAR(l); while (cur != 0) { if ((cur == '<') && (NXT(1) == '/')) { @@ -3358,7 +3357,6 @@ htmlParsePI(htmlParserCtxtPtr ctxt) { * this is a Processing Instruction. */ SKIP(2); - SHRINK; /* * Parse the target name and check for special support like @@ -3481,7 +3479,6 @@ htmlParseComment(htmlParserCtxtPtr ctxt) { state = ctxt->instate; ctxt->instate = XML_PARSER_COMMENT; - SHRINK; SKIP(4); buf = (xmlChar *) xmlMallocAtomic(size); if (buf == NULL) { @@ -4477,8 +4474,8 @@ htmlParseContent(htmlParserCtxtPtr ctxt) { htmlParseCharData(ctxt); } - GROW; SHRINK; + GROW; } if (currentNode != NULL) xmlFree(currentNode); } @@ -4920,8 +4917,8 @@ htmlParseContentInternal(htmlParserCtxtPtr ctxt) { htmlParseCharData(ctxt); } - GROW; SHRINK; + GROW; } if (currentNode != NULL) xmlFree(currentNode); } diff --git a/include/private/parser.h b/include/private/parser.h index 18036db58..820bb587c 100644 --- a/include/private/parser.h +++ b/include/private/parser.h @@ -27,7 +27,7 @@ XML_HIDDEN void xmlHaltParser(xmlParserCtxtPtr ctxt); XML_HIDDEN int xmlParserGrow(xmlParserCtxtPtr ctxt); -XML_HIDDEN int +XML_HIDDEN void xmlParserShrink(xmlParserCtxtPtr ctxt); #endif /* XML_PARSER_H_PRIVATE__ */ diff --git a/parser.c b/parser.c index 8e548cdae..bf4d08bde 100644 --- a/parser.c +++ b/parser.c @@ -4183,7 +4183,6 @@ xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { xmlChar stop; int state = ctxt->instate; - SHRINK; if (RAW == '"') { NEXT; stop = '"'; @@ -4265,7 +4264,6 @@ xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) { xmlChar stop; xmlParserInputState oldstate = ctxt->instate; - SHRINK; if (RAW == '"') { NEXT; stop = '"'; @@ -4387,7 +4385,6 @@ xmlParseCharData(xmlParserCtxtPtr ctxt, ATTRIBUTE_UNUSED int cdata) { int col = ctxt->input->col; int ccol; - SHRINK; GROW; /* * Accelerated common case where input don't need to be @@ -4533,7 +4530,6 @@ xmlParseCharDataComplex(xmlParserCtxtPtr ctxt) { int nbchar = 0; int cur, l; - SHRINK; cur = CUR_CHAR(l); while ((cur != '<') && /* checked */ (cur != '&') && @@ -4629,8 +4625,6 @@ xmlChar * xmlParseExternalID(xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict) { xmlChar *URI = NULL; - SHRINK; - *publicID = NULL; if (CMP6(CUR_PTR, 'S', 'Y', 'S', 'T', 'E', 'M')) { SKIP(6); @@ -4847,7 +4841,6 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { ctxt->instate = XML_PARSER_COMMENT; inputid = ctxt->input->id; SKIP(2); - SHRINK; GROW; /* @@ -5133,7 +5126,6 @@ xmlParsePI(xmlParserCtxtPtr ctxt) { * this is a Processing Instruction. */ SKIP(2); - SHRINK; /* * Parse the target name and check for special support like @@ -5272,7 +5264,6 @@ xmlParseNotationDecl(xmlParserCtxtPtr ctxt) { if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) { int inputid = ctxt->input->id; - SHRINK; SKIP(8); if (SKIP_BLANKS == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, @@ -5360,7 +5351,6 @@ xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { /* GROW; done in the caller */ if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) { int inputid = ctxt->input->id; - SHRINK; SKIP(6); if (SKIP_BLANKS == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, @@ -5684,7 +5674,6 @@ xmlParseNotationType(xmlParserCtxtPtr ctxt) { xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL); return(NULL); } - SHRINK; do { NEXT; SKIP_BLANKS; @@ -5756,7 +5745,6 @@ xmlParseEnumerationType(xmlParserCtxtPtr ctxt) { xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_STARTED, NULL); return(NULL); } - SHRINK; do { NEXT; SKIP_BLANKS; @@ -5885,7 +5873,6 @@ xmlParseEnumeratedType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) { */ int xmlParseAttributeType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) { - SHRINK; if (CMP5(CUR_PTR, 'C', 'D', 'A', 'T', 'A')) { SKIP(5); return(XML_ATTRIBUTE_CDATA); @@ -6070,7 +6057,6 @@ xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; - SHRINK; if (RAW == ')') { if (ctxt->input->id != inputchk) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, @@ -6242,7 +6228,6 @@ xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk, GROW; } SKIP_BLANKS; - SHRINK; while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) { /* * Each loop we parse one separator and one element. @@ -6787,6 +6772,7 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { break; SKIP_BLANKS; + SHRINK; GROW; } @@ -7018,6 +7004,7 @@ xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, return; } SKIP_BLANKS; + SHRINK; } if (RAW != 0) { @@ -8343,6 +8330,8 @@ xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { return; } SKIP_BLANKS; + SHRINK; + GROW; } if (RAW == ']') { NEXT; @@ -9229,14 +9218,6 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, if (RAW != '<') return(NULL); NEXT1; - /* - * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that - * point since the attribute values may be stored as pointers to - * the buffer and calling SHRINK would destroy them ! - * The Shrinking is only possible once the full set of attribute - * callbacks have been done. - */ - SHRINK; cur = ctxt->input->cur - ctxt->input->base; inputid = ctxt->input->id; nbatts = 0; @@ -9881,8 +9862,8 @@ xmlParseContentInternal(xmlParserCtxtPtr ctxt) { xmlParseCharData(ctxt, 0); } - GROW; SHRINK; + GROW; } } diff --git a/parserInternals.c b/parserInternals.c index dd165790e..ce4f75e02 100644 --- a/parserInternals.c +++ b/parserInternals.c @@ -409,17 +409,16 @@ xmlParserInputGrow(xmlParserInputPtr in, int len) { * xmlParserShrink: * @ctxt: an XML parser context */ -int +void xmlParserShrink(xmlParserCtxtPtr ctxt) { xmlParserInputPtr in = ctxt->input; xmlParserInputBufferPtr buf = in->buf; size_t used; - int ret = 0; /* Don't shrink memory buffers. */ if ((buf == NULL) || ((buf->encoder == NULL) && (buf->readcallback == NULL))) - return(0); + return; used = in->cur - in->base; /* @@ -439,18 +438,7 @@ xmlParserShrink(xmlParserCtxtPtr ctxt) { } } - if (xmlBufUse(buf->buffer) < INPUT_CHUNK) - ret = xmlParserInputBufferGrow(buf, INPUT_CHUNK); - xmlBufSetInputBaseCur(buf->buffer, in, 0, used); - - /* TODO: Get error code from xmlParserInputBufferGrow */ - if (ret < 0) { - xmlErrInternal(ctxt, "Growing input buffer", NULL); - xmlHaltParser(ctxt); - } - - return(ret); } /**
3rdn4/libxml2:b167c73-global_buffer_overflow_a
/workspace/skyset/
libxml2
b167c73-global_buffer_overflow_a
/workspace/skyset/libxml2/b167c73-global_buffer_overflow_a/report.txt
A global buffer overflow a found in /workspace/skyset/libxml2/b167c73-global_buffer_overflow_a/immutable/
From ca2bfecea9c23f8d2e11741fff7c6a5372c56bb8 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Wed, 15 Mar 2023 16:18:11 +0100 Subject: [PATCH] malloc-fail: Fix buffer overread when reading from input Found by OSS-Fuzz, see #344. --- HTMLparser.c | 29 ++++++++++------------ parserInternals.c | 61 +++++++++++++++++++---------------------------- 2 files changed, 38 insertions(+), 52 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 509e029eb..0830584f5 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -410,6 +410,11 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { *len = 0; return(ctxt->token); } + + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if (ctxt->charset != XML_CHAR_ENCODING_UTF8) { xmlChar * guess; xmlCharEncodingHandlerPtr handler; @@ -470,29 +475,21 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { cur = ctxt->input->cur; c = *cur; if (c & 0x80) { + size_t avail; + if ((c & 0x40) == 0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || ((cur[1] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xe0) == 0xe0) { - - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || ((cur[2] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; diff --git a/parserInternals.c b/parserInternals.c index a7f0aa95a..c0281be27 100644 --- a/parserInternals.c +++ b/parserInternals.c @@ -554,8 +554,11 @@ xmlNextChar(xmlParserCtxtPtr ctxt) return; } - if ((ctxt->input->cur >= ctxt->input->end) && (xmlParserGrow(ctxt) <= 0)) { - return; + if (ctxt->input->end - ctxt->input->cur < 4) { + if (xmlParserGrow(ctxt) < 0) + return; + if (ctxt->input->cur >= ctxt->input->end) + return; } if (ctxt->charset == XML_CHAR_ENCODING_UTF8) { @@ -588,30 +591,23 @@ xmlNextChar(xmlParserCtxtPtr ctxt) c = *cur; if (c & 0x80) { + size_t avail; + if (c == 0xC0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { unsigned int val; - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ ctxt->input->cur += 4; @@ -652,8 +648,6 @@ xmlNextChar(xmlParserCtxtPtr ctxt) ctxt->input->col++; ctxt->input->cur++; } - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); return; encoding_error: /* @@ -707,6 +701,10 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { if (ctxt->instate == XML_PARSER_EOF) return(0); + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if ((*ctxt->input->cur >= 0x20) && (*ctxt->input->cur <= 0x7F)) { *len = 1; return(*ctxt->input->cur); @@ -729,28 +727,21 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { c = *cur; if (c & 0x80) { + size_t avail; + if (((c & 0x40) == 0) || (c == 0xC0)) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; @@ -785,8 +776,6 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { } else { /* 1-byte code */ *len = 1; - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); if ((*ctxt->input->cur == 0) && (ctxt->input->end > ctxt->input->cur)) { xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
3rdn4/libxml2:b167c73-global_buffer_overflow_b
/workspace/skyset/
libxml2
b167c73-global_buffer_overflow_b
/workspace/skyset/libxml2/b167c73-global_buffer_overflow_b/report.txt
A global buffer overflow b found in /workspace/skyset/libxml2/b167c73-global_buffer_overflow_b/immutable/
From ca2bfecea9c23f8d2e11741fff7c6a5372c56bb8 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Wed, 15 Mar 2023 16:18:11 +0100 Subject: [PATCH] malloc-fail: Fix buffer overread when reading from input Found by OSS-Fuzz, see #344. --- HTMLparser.c | 29 ++++++++++------------ parserInternals.c | 61 +++++++++++++++++++---------------------------- 2 files changed, 38 insertions(+), 52 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 509e029eb..0830584f5 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -410,6 +410,11 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { *len = 0; return(ctxt->token); } + + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if (ctxt->charset != XML_CHAR_ENCODING_UTF8) { xmlChar * guess; xmlCharEncodingHandlerPtr handler; @@ -470,29 +475,21 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { cur = ctxt->input->cur; c = *cur; if (c & 0x80) { + size_t avail; + if ((c & 0x40) == 0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || ((cur[1] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xe0) == 0xe0) { - - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || ((cur[2] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; diff --git a/parserInternals.c b/parserInternals.c index a7f0aa95a..c0281be27 100644 --- a/parserInternals.c +++ b/parserInternals.c @@ -554,8 +554,11 @@ xmlNextChar(xmlParserCtxtPtr ctxt) return; } - if ((ctxt->input->cur >= ctxt->input->end) && (xmlParserGrow(ctxt) <= 0)) { - return; + if (ctxt->input->end - ctxt->input->cur < 4) { + if (xmlParserGrow(ctxt) < 0) + return; + if (ctxt->input->cur >= ctxt->input->end) + return; } if (ctxt->charset == XML_CHAR_ENCODING_UTF8) { @@ -588,30 +591,23 @@ xmlNextChar(xmlParserCtxtPtr ctxt) c = *cur; if (c & 0x80) { + size_t avail; + if (c == 0xC0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { unsigned int val; - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ ctxt->input->cur += 4; @@ -652,8 +648,6 @@ xmlNextChar(xmlParserCtxtPtr ctxt) ctxt->input->col++; ctxt->input->cur++; } - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); return; encoding_error: /* @@ -707,6 +701,10 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { if (ctxt->instate == XML_PARSER_EOF) return(0); + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if ((*ctxt->input->cur >= 0x20) && (*ctxt->input->cur <= 0x7F)) { *len = 1; return(*ctxt->input->cur); @@ -729,28 +727,21 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { c = *cur; if (c & 0x80) { + size_t avail; + if (((c & 0x40) == 0) || (c == 0xC0)) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; @@ -785,8 +776,6 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { } else { /* 1-byte code */ *len = 1; - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); if ((*ctxt->input->cur == 0) && (ctxt->input->end > ctxt->input->cur)) { xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
3rdn4/libxml2:b167c73-global_buffer_overflow_c
/workspace/skyset/
libxml2
b167c73-global_buffer_overflow_c
/workspace/skyset/libxml2/b167c73-global_buffer_overflow_c/report.txt
A global buffer overflow c found in /workspace/skyset/libxml2/b167c73-global_buffer_overflow_c/immutable/
From ca2bfecea9c23f8d2e11741fff7c6a5372c56bb8 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Wed, 15 Mar 2023 16:18:11 +0100 Subject: [PATCH] malloc-fail: Fix buffer overread when reading from input Found by OSS-Fuzz, see #344. --- HTMLparser.c | 29 ++++++++++------------ parserInternals.c | 61 +++++++++++++++++++---------------------------- 2 files changed, 38 insertions(+), 52 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 509e029eb..0830584f5 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -410,6 +410,11 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { *len = 0; return(ctxt->token); } + + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if (ctxt->charset != XML_CHAR_ENCODING_UTF8) { xmlChar * guess; xmlCharEncodingHandlerPtr handler; @@ -470,29 +475,21 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { cur = ctxt->input->cur; c = *cur; if (c & 0x80) { + size_t avail; + if ((c & 0x40) == 0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || ((cur[1] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xe0) == 0xe0) { - - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || ((cur[2] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; diff --git a/parserInternals.c b/parserInternals.c index a7f0aa95a..c0281be27 100644 --- a/parserInternals.c +++ b/parserInternals.c @@ -554,8 +554,11 @@ xmlNextChar(xmlParserCtxtPtr ctxt) return; } - if ((ctxt->input->cur >= ctxt->input->end) && (xmlParserGrow(ctxt) <= 0)) { - return; + if (ctxt->input->end - ctxt->input->cur < 4) { + if (xmlParserGrow(ctxt) < 0) + return; + if (ctxt->input->cur >= ctxt->input->end) + return; } if (ctxt->charset == XML_CHAR_ENCODING_UTF8) { @@ -588,30 +591,23 @@ xmlNextChar(xmlParserCtxtPtr ctxt) c = *cur; if (c & 0x80) { + size_t avail; + if (c == 0xC0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { unsigned int val; - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ ctxt->input->cur += 4; @@ -652,8 +648,6 @@ xmlNextChar(xmlParserCtxtPtr ctxt) ctxt->input->col++; ctxt->input->cur++; } - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); return; encoding_error: /* @@ -707,6 +701,10 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { if (ctxt->instate == XML_PARSER_EOF) return(0); + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if ((*ctxt->input->cur >= 0x20) && (*ctxt->input->cur <= 0x7F)) { *len = 1; return(*ctxt->input->cur); @@ -729,28 +727,21 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { c = *cur; if (c & 0x80) { + size_t avail; + if (((c & 0x40) == 0) || (c == 0xC0)) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; @@ -785,8 +776,6 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { } else { /* 1-byte code */ *len = 1; - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); if ((*ctxt->input->cur == 0) && (ctxt->input->end > ctxt->input->cur)) { xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
3rdn4/libxml2:b167c73-global_buffer_overflow_d
/workspace/skyset/
libxml2
b167c73-global_buffer_overflow_d
/workspace/skyset/libxml2/b167c73-global_buffer_overflow_d/report.txt
A global buffer overflow d found in /workspace/skyset/libxml2/b167c73-global_buffer_overflow_d/immutable/
From 8090e5856465c0b8e26e2a080f4b498f37fa83ab Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Fri, 17 Mar 2023 12:27:07 +0100 Subject: [PATCH] malloc-fail: Fix buffer overread in htmlParseScript Found by OSS-Fuzz, see #344. --- HTMLparser.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HTMLparser.c b/HTMLparser.c index 0830584f5..67c39385e 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -3151,8 +3151,8 @@ htmlParseScript(htmlParserCtxtPtr ctxt) { } nbchar = 0; } - GROW; NEXTL(l); + GROW; cur = CUR_CHAR(l); }
3rdn4/libxml2:b167c73-global_buffer_overflow_e
/workspace/skyset/
libxml2
b167c73-global_buffer_overflow_e
/workspace/skyset/libxml2/b167c73-global_buffer_overflow_e/report.txt
A global buffer overflow e found in /workspace/skyset/libxml2/b167c73-global_buffer_overflow_e/immutable/
From ca2bfecea9c23f8d2e11741fff7c6a5372c56bb8 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer <wellnhofer@aevum.de> Date: Wed, 15 Mar 2023 16:18:11 +0100 Subject: [PATCH] malloc-fail: Fix buffer overread when reading from input Found by OSS-Fuzz, see #344. --- HTMLparser.c | 29 ++++++++++------------ parserInternals.c | 61 +++++++++++++++++++---------------------------- 2 files changed, 38 insertions(+), 52 deletions(-) diff --git a/HTMLparser.c b/HTMLparser.c index 509e029eb..0830584f5 100644 --- a/HTMLparser.c +++ b/HTMLparser.c @@ -410,6 +410,11 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { *len = 0; return(ctxt->token); } + + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if (ctxt->charset != XML_CHAR_ENCODING_UTF8) { xmlChar * guess; xmlCharEncodingHandlerPtr handler; @@ -470,29 +475,21 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { cur = ctxt->input->cur; c = *cur; if (c & 0x80) { + size_t avail; + if ((c & 0x40) == 0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || ((cur[1] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xe0) == 0xe0) { - - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || ((cur[2] & 0xc0) != 0x80)) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; diff --git a/parserInternals.c b/parserInternals.c index a7f0aa95a..c0281be27 100644 --- a/parserInternals.c +++ b/parserInternals.c @@ -554,8 +554,11 @@ xmlNextChar(xmlParserCtxtPtr ctxt) return; } - if ((ctxt->input->cur >= ctxt->input->end) && (xmlParserGrow(ctxt) <= 0)) { - return; + if (ctxt->input->end - ctxt->input->cur < 4) { + if (xmlParserGrow(ctxt) < 0) + return; + if (ctxt->input->cur >= ctxt->input->end) + return; } if (ctxt->charset == XML_CHAR_ENCODING_UTF8) { @@ -588,30 +591,23 @@ xmlNextChar(xmlParserCtxtPtr ctxt) c = *cur; if (c & 0x80) { + size_t avail; + if (c == 0xC0) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { unsigned int val; - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ ctxt->input->cur += 4; @@ -652,8 +648,6 @@ xmlNextChar(xmlParserCtxtPtr ctxt) ctxt->input->col++; ctxt->input->cur++; } - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); return; encoding_error: /* @@ -707,6 +701,10 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { if (ctxt->instate == XML_PARSER_EOF) return(0); + if ((ctxt->input->end - ctxt->input->cur < 4) && + (xmlParserGrow(ctxt) < 0)) + return(0); + if ((*ctxt->input->cur >= 0x20) && (*ctxt->input->cur <= 0x7F)) { *len = 1; return(*ctxt->input->cur); @@ -729,28 +727,21 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { c = *cur; if (c & 0x80) { + size_t avail; + if (((c & 0x40) == 0) || (c == 0xC0)) goto encoding_error; - if (cur[1] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[1] & 0xc0) != 0x80) + + avail = ctxt->input->end - ctxt->input->cur; + + if ((avail < 2) || (cur[1] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xe0) == 0xe0) { - if (cur[2] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } - if ((cur[2] & 0xc0) != 0x80) + if ((avail < 3) || (cur[2] & 0xc0) != 0x80) goto encoding_error; if ((c & 0xf0) == 0xf0) { - if (cur[3] == 0) { - xmlParserGrow(ctxt); - cur = ctxt->input->cur; - } if (((c & 0xf8) != 0xf0) || - ((cur[3] & 0xc0) != 0x80)) + (avail < 4) || ((cur[3] & 0xc0) != 0x80)) goto encoding_error; /* 4-byte code */ *len = 4; @@ -785,8 +776,6 @@ xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) { } else { /* 1-byte code */ *len = 1; - if (*ctxt->input->cur == 0) - xmlParserGrow(ctxt); if ((*ctxt->input->cur == 0) && (ctxt->input->end > ctxt->input->cur)) { xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
3rdn4/lz4:7654a5a-heap_buffer_overflow
/workspace/skyset/
lz4
7654a5a-heap_buffer_overflow
/workspace/skyset/lz4/7654a5a-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/lz4/7654a5a-heap_buffer_overflow/immutable/
From 13a2d9e34ffc4170720ce417c73e396d0ac1471a Mon Sep 17 00:00:00 2001 From: Nick Terrell <terrelln@fb.com> Date: Wed, 17 Jul 2019 11:50:47 -0700 Subject: [PATCH] [LZ4_compress_destSize] Fix overflow condition --- lib/lz4.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/lz4.c b/lib/lz4.c index 461644da0..74a9247ec 100644 --- a/lib/lz4.c +++ b/lib/lz4.c @@ -1027,7 +1027,7 @@ LZ4_FORCE_INLINE int LZ4_compress_generic( } if ((outputDirective) && /* Check output buffer overflow */ - (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) { + (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) { if (outputDirective == fillOutput) { /* Match description too long : reduce it */ U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255;
3rdn4/lz4:9d20cd5-invalid_free
/workspace/skyset/
lz4
9d20cd5-invalid_free
/workspace/skyset/lz4/9d20cd5-invalid_free/report.txt
A invalid free found in /workspace/skyset/lz4/9d20cd5-invalid_free/immutable/
From 910ec80d2856cfa825e2230ff2de8347a4fa4522 Mon Sep 17 00:00:00 2001 From: Yonatan Komornik <yoniko@gmail.com> Date: Fri, 8 Jul 2022 14:03:14 -0700 Subject: [PATCH] - Fixed incorrect free in `round_trip_fuzzer.c` (https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=48884) - Fixed `round_trip_frame_uncompressed_fuzzer.c` to not use uninitialized memory (https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=48910) --- .../round_trip_frame_uncompressed_fuzzer.c | 214 +++++++++--------- ossfuzz/round_trip_fuzzer.c | 2 +- 2 files changed, 106 insertions(+), 110 deletions(-) diff --git a/ossfuzz/round_trip_frame_uncompressed_fuzzer.c b/ossfuzz/round_trip_frame_uncompressed_fuzzer.c index e578052cf..76a99d229 100644 --- a/ossfuzz/round_trip_frame_uncompressed_fuzzer.c +++ b/ossfuzz/round_trip_frame_uncompressed_fuzzer.c @@ -16,123 +16,119 @@ #include "lz4frame_static.h" static void decompress(LZ4F_dctx *dctx, void *src, void *dst, - size_t dstCapacity, size_t readSize) { - size_t ret = 1; - const void *srcPtr = (const char *)src; - void *dstPtr = (char *)dst; - const void *const srcEnd = (const char *)srcPtr + readSize; - - while (ret != 0) { - while (srcPtr < srcEnd && ret != 0) { - /* Any data within dst has been flushed at this stage */ - size_t dstSize = dstCapacity; - size_t srcSize = (const char *)srcEnd - (const char *)srcPtr; - ret = LZ4F_decompress(dctx, dstPtr, &dstSize, srcPtr, &srcSize, - /* LZ4F_decompressOptions_t */ NULL); - FUZZ_ASSERT(!LZ4F_isError(ret)); - - /* Update input */ - srcPtr = (const char *)srcPtr + srcSize; - dstPtr = (char *)dstPtr + dstSize; + size_t dstCapacity, size_t readSize) { + size_t ret = 1; + const void *srcPtr = (const char *) src; + void *dstPtr = (char *) dst; + const void *const srcEnd = (const char *) srcPtr + readSize; + + while (ret != 0) { + while (srcPtr < srcEnd && ret != 0) { + /* Any data within dst has been flushed at this stage */ + size_t dstSize = dstCapacity; + size_t srcSize = (const char *) srcEnd - (const char *) srcPtr; + ret = LZ4F_decompress(dctx, dstPtr, &dstSize, srcPtr, &srcSize, + /* LZ4F_decompressOptions_t */ NULL); + FUZZ_ASSERT(!LZ4F_isError(ret)); + + /* Update input */ + srcPtr = (const char *) srcPtr + srcSize; + dstPtr = (char *) dstPtr + dstSize; + } + + FUZZ_ASSERT(srcPtr <= srcEnd); } - - FUZZ_ASSERT(srcPtr <= srcEnd); - } } -static void compress_round_trip(const uint8_t* data, size_t size, +static void compress_round_trip(const uint8_t *data, size_t size, FUZZ_dataProducer_t *producer, LZ4F_preferences_t const prefs) { - size = FUZZ_dataProducer_remainingBytes(producer); - - uint8_t *uncompressedData = malloc(size); - size_t uncompressedOffset = rand() % (size + 1); - - FUZZ_dataProducer_t *uncompressedProducer = - FUZZ_dataProducer_create(uncompressedData, size); - size_t uncompressedSize = - FUZZ_dataProducer_remainingBytes(uncompressedProducer); - - size_t const dstCapacity = - LZ4F_compressFrameBound(LZ4_compressBound(size), &prefs) + - uncompressedSize; - char *const dst = (char *)malloc(dstCapacity); - size_t rtCapacity = dstCapacity; - char *const rt = (char *)malloc(rtCapacity); - - FUZZ_ASSERT(dst); - FUZZ_ASSERT(rt); - - /* Compression must succeed and round trip correctly. */ - LZ4F_compressionContext_t ctx; - size_t const ctxCreation = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); - FUZZ_ASSERT(!LZ4F_isError(ctxCreation)); - - size_t const headerSize = LZ4F_compressBegin(ctx, dst, dstCapacity, &prefs); - FUZZ_ASSERT(!LZ4F_isError(headerSize)); - size_t compressedSize = headerSize; - - /* Compress data before uncompressed offset */ - size_t lz4Return = LZ4F_compressUpdate(ctx, dst + compressedSize, dstCapacity, - data, uncompressedOffset, NULL); - FUZZ_ASSERT(!LZ4F_isError(lz4Return)); - compressedSize += lz4Return; - - /* Add uncompressed data */ - lz4Return = LZ4F_uncompressedUpdate(ctx, dst + compressedSize, dstCapacity, - uncompressedData, uncompressedSize, NULL); - FUZZ_ASSERT(!LZ4F_isError(lz4Return)); - compressedSize += lz4Return; - - /* Compress data after uncompressed offset */ - lz4Return = LZ4F_compressUpdate(ctx, dst + compressedSize, dstCapacity, - data + uncompressedOffset, - size - uncompressedOffset, NULL); - FUZZ_ASSERT(!LZ4F_isError(lz4Return)); - compressedSize += lz4Return; - - /* Finish compression */ - lz4Return = LZ4F_compressEnd(ctx, dst + compressedSize, dstCapacity, NULL); - FUZZ_ASSERT(!LZ4F_isError(lz4Return)); - compressedSize += lz4Return; - - LZ4F_decompressOptions_t opts; - memset(&opts, 0, sizeof(opts)); - opts.stableDst = 1; - LZ4F_dctx *dctx; - LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); - FUZZ_ASSERT(dctx); - - decompress(dctx, dst, rt, rtCapacity, compressedSize); - - LZ4F_freeDecompressionContext(dctx); - - char *const expectedData = (char *)malloc(size + uncompressedSize); - memcpy(expectedData, data, uncompressedOffset); - memcpy(expectedData + uncompressedOffset, uncompressedData, uncompressedSize); - memcpy(expectedData + uncompressedOffset + uncompressedSize, - data + uncompressedOffset, size - uncompressedOffset); - - FUZZ_ASSERT_MSG(!memcmp(expectedData, rt, size), "Corruption!"); - free(expectedData); - - free(dst); - free(rt); - free(uncompressedData); - - FUZZ_dataProducer_free(producer); - FUZZ_dataProducer_free(uncompressedProducer); - LZ4F_freeCompressionContext(ctx); + + // Choose random uncompressed offset start and end by producing seeds from random data, calculate the remaining + // data size that will be used for compression later and use the seeds to actually calculate the offsets + size_t const uncompressedOffsetSeed = FUZZ_dataProducer_retrieve32(producer); + size_t const uncompressedEndOffsetSeed = FUZZ_dataProducer_retrieve32(producer); + size = FUZZ_dataProducer_remainingBytes(producer); + + size_t const uncompressedOffset = FUZZ_getRange_from_uint32(uncompressedOffsetSeed, 0, size); + size_t const uncompressedEndOffset = FUZZ_getRange_from_uint32(uncompressedEndOffsetSeed, uncompressedOffset, size); + size_t const uncompressedSize = uncompressedEndOffset - uncompressedOffset; + FUZZ_ASSERT(uncompressedOffset <= uncompressedEndOffset); + FUZZ_ASSERT(uncompressedEndOffset <= size); + + const uint8_t *const uncompressedData = data + uncompressedOffset; + + size_t const dstCapacity = + LZ4F_compressFrameBound(LZ4_compressBound(size), &prefs) + + uncompressedSize; + char *const dst = (char *) malloc(dstCapacity); + size_t rtCapacity = dstCapacity; + char *const rt = (char *) malloc(rtCapacity); + + FUZZ_ASSERT(dst); + FUZZ_ASSERT(rt); + + /* Compression must succeed and round trip correctly. */ + LZ4F_compressionContext_t ctx; + size_t const ctxCreation = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); + FUZZ_ASSERT(!LZ4F_isError(ctxCreation)); + + size_t const headerSize = LZ4F_compressBegin(ctx, dst, dstCapacity, &prefs); + FUZZ_ASSERT(!LZ4F_isError(headerSize)); + size_t compressedSize = headerSize; + + /* Compress data before uncompressed offset */ + size_t lz4Return = LZ4F_compressUpdate(ctx, dst + compressedSize, dstCapacity, + data, uncompressedOffset, NULL); + FUZZ_ASSERT(!LZ4F_isError(lz4Return)); + compressedSize += lz4Return; + + /* Add uncompressed data */ + lz4Return = LZ4F_uncompressedUpdate(ctx, dst + compressedSize, dstCapacity, + uncompressedData, uncompressedSize, NULL); + FUZZ_ASSERT(!LZ4F_isError(lz4Return)); + compressedSize += lz4Return; + + /* Compress data after uncompressed offset */ + lz4Return = LZ4F_compressUpdate(ctx, dst + compressedSize, dstCapacity, + data + uncompressedEndOffset, + size - uncompressedEndOffset, NULL); + FUZZ_ASSERT(!LZ4F_isError(lz4Return)); + compressedSize += lz4Return; + + /* Finish compression */ + lz4Return = LZ4F_compressEnd(ctx, dst + compressedSize, dstCapacity, NULL); + FUZZ_ASSERT(!LZ4F_isError(lz4Return)); + compressedSize += lz4Return; + + LZ4F_decompressOptions_t opts; + memset(&opts, 0, sizeof(opts)); + opts.stableDst = 1; + LZ4F_dctx *dctx; + LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); + FUZZ_ASSERT(dctx); + + decompress(dctx, dst, rt, rtCapacity, compressedSize); + + LZ4F_freeDecompressionContext(dctx); + + FUZZ_ASSERT_MSG(!memcmp(data, rt, size), "Corruption!"); + + free(dst); + free(rt); + + FUZZ_dataProducer_free(producer); + LZ4F_freeCompressionContext(ctx); } -static void compress_independent_block_mode(const uint8_t* data, size_t size) { - FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(data, size); - LZ4F_preferences_t prefs = FUZZ_dataProducer_preferences(producer); - prefs.frameInfo.blockMode = LZ4F_blockIndependent; - compress_round_trip(data, size, producer, prefs); +static void compress_independent_block_mode(const uint8_t *data, size_t size) { + FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(data, size); + LZ4F_preferences_t prefs = FUZZ_dataProducer_preferences(producer); + prefs.frameInfo.blockMode = LZ4F_blockIndependent; + compress_round_trip(data, size, producer, prefs); } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - compress_independent_block_mode(data, size); - return 0; + compress_independent_block_mode(data, size); + return 0; } diff --git a/ossfuzz/round_trip_fuzzer.c b/ossfuzz/round_trip_fuzzer.c index 7a2f76815..2c35d9a2e 100644 --- a/ossfuzz/round_trip_fuzzer.c +++ b/ossfuzz/round_trip_fuzzer.c @@ -108,7 +108,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) free(partial); } - free(dst); + free(dstPlusLargePrefix); free(rt); FUZZ_dataProducer_free(producer);
3rdn4/md4c:3478ec6-heap_buffer_overflow_a
/workspace/skyset/
md4c
3478ec6-heap_buffer_overflow_a
/workspace/skyset/md4c/3478ec6-heap_buffer_overflow_a/report.txt
A heap buffer overflow a found in /workspace/skyset/md4c/3478ec6-heap_buffer_overflow_a/immutable/
From 260cd3394d45bd51f2002936a63401419658ecd7 Mon Sep 17 00:00:00 2001 From: dtldarek <dtl+github@google.com> Date: Wed, 25 Aug 2021 15:02:38 +0200 Subject: [PATCH] Fix buffer overflow on input found with fuzzying (in c-string format): "\n# h1\nc hh##e2ked\n\n A | rong__ ___strong \u0000\u0000\u0000\u0000\u0000\u0000\a\u0000\u0000\u0000\u0000\n# h1\nh# #2\n### h3\n#### h4\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\\\n##### h5\n#*#####\u0000\n6" --- src/md4c.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/md4c.c b/src/md4c.c index 2864010..3565ddf 100644 --- a/src/md4c.c +++ b/src/md4c.c @@ -5685,6 +5685,7 @@ md_is_container_mark(MD_CTX* ctx, unsigned indent, OFF beg, OFF* p_end, MD_CONTA off++; } if(off > beg && + off < ctx->size && (CH(off) == _T('.') || CH(off) == _T(')')) && (off+1 >= ctx->size || ISBLANK(off+1) || ISNEWLINE(off+1))) {
3rdn4/md4c:3478ec6-heap_buffer_overflow_b
/workspace/skyset/
md4c
3478ec6-heap_buffer_overflow_b
/workspace/skyset/md4c/3478ec6-heap_buffer_overflow_b/report.txt
A heap buffer overflow b found in /workspace/skyset/md4c/3478ec6-heap_buffer_overflow_b/immutable/
From f436c3029850c138e54a0de055d61db45130409e Mon Sep 17 00:00:00 2001 From: Thierry Coppey <tcknetwork@hotmail.com> Date: Thu, 6 Jan 2022 16:21:51 +0100 Subject: [PATCH] Fix buffer overflows and other errors found with fuzzying. (#168) Fix multiple buffer overflow on input found with fuzzying. --- src/md4c.c | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/src/md4c.c b/src/md4c.c index 97200b2..48f0e44 100644 --- a/src/md4c.c +++ b/src/md4c.c @@ -2318,7 +2318,7 @@ md_is_inline_link_spec(MD_CTX* ctx, const MD_LINE* lines, int n_lines, /* Optional whitespace followed with final ')'. */ while(off < lines[line_index].end && ISWHITESPACE(off)) off++; - if(off >= lines[line_index].end && ISNEWLINE(off)) { + if (off >= lines[line_index].end && (off >= ctx->size || ISNEWLINE(off))) { line_index++; if(line_index >= n_lines) return FALSE; @@ -2490,6 +2490,7 @@ md_mark_chain(MD_CTX* ctx, int mark_index) case _T('*'): return md_asterisk_chain(ctx, mark->flags); case _T('_'): return &UNDERSCORE_OPENERS; case _T('~'): return (mark->end - mark->beg == 1) ? &TILDE_OPENERS_1 : &TILDE_OPENERS_2; + case _T('!'): MD_FALLTHROUGH(); case _T('['): return &BRACKET_OPENERS; case _T('|'): return &TABLECELLBOUNDARIES; default: return NULL; @@ -2630,8 +2631,11 @@ md_rollback(MD_CTX* ctx, int opener_index, int closer_index, int how) for(i = OPENERS_CHAIN_FIRST; i < OPENERS_CHAIN_LAST+1; i++) { MD_MARKCHAIN* chain = &ctx->mark_chains[i]; - while(chain->tail >= opener_index) + while(chain->tail >= opener_index) { + int same = chain->tail == opener_index; chain->tail = ctx->marks[chain->tail].prev; + if (same) break; + } if(chain->tail >= 0) ctx->marks[chain->tail].next = -1; @@ -3906,7 +3910,9 @@ md_analyze_permissive_url_autolink(MD_CTX* ctx, int mark_index) /* Ok. Lets call it an auto-link. Adapt opener and create closer to zero * length so all the contents becomes the link text. */ - MD_ASSERT(closer->ch == 'D'); + MD_ASSERT(closer->ch == 'D' || + (ctx->parser.flags & MD_FLAG_PERMISSIVEWWWAUTOLINKS && + (closer->ch == '.' || closer->ch == ':' || closer->ch == '@'))); opener->end = opener->beg; closer->ch = opener->ch; closer->beg = off; @@ -3928,7 +3934,7 @@ md_analyze_permissive_email_autolink(MD_CTX* ctx, int mark_index) OFF end = opener->end; int dot_count = 0; - MD_ASSERT(CH(beg) == _T('@')); + MD_ASSERT(opener->ch == _T('@')); /* Scan for name before '@'. */ while(beg > 0 && (ISALNUM(beg-1) || ISANYOF(beg-1, _T(".-_+")))) @@ -3953,7 +3959,7 @@ md_analyze_permissive_email_autolink(MD_CTX* ctx, int mark_index) * length so all the contents becomes the link text. */ closer_index = mark_index + 1; closer = &ctx->marks[closer_index]; - MD_ASSERT(closer->ch == 'D'); + if (closer->ch != 'D') return; opener->beg = beg; opener->end = beg; @@ -4260,7 +4266,7 @@ md_process_inlines(MD_CTX* ctx, const MD_LINE* lines, int n_lines) dest_mark = opener+1; MD_ASSERT(dest_mark->ch == 'D'); title_mark = opener+2; - MD_ASSERT(title_mark->ch == 'D'); + if (title_mark->ch != 'D') break; MD_CHECK(md_enter_leave_span_a(ctx, (mark->ch != ']'), (opener->ch == '!' ? MD_SPAN_IMG : MD_SPAN_A), @@ -5468,20 +5474,16 @@ md_is_html_block_end_condition(MD_CTX* ctx, OFF beg, OFF* p_end) while(off < ctx->size && !ISNEWLINE(off)) { if(CH(off) == _T('<')) { - if(md_ascii_case_eq(STR(off), _T("</script>"), 9)) { - *p_end = off + 9; - return TRUE; - } - - if(md_ascii_case_eq(STR(off), _T("</style>"), 8)) { - *p_end = off + 8; - return TRUE; - } - - if(md_ascii_case_eq(STR(off), _T("</pre>"), 6)) { - *p_end = off + 6; - return TRUE; + #define FIND_TAG_END(string, length) \ + if(off + length <= ctx->size && \ + md_ascii_case_eq(STR(off), _T(string), length)) { \ + *p_end = off + length; \ + return TRUE; \ } + FIND_TAG_END("</script>", 9) + FIND_TAG_END("</style>", 8) + FIND_TAG_END("</pre>", 6) + #undef FIND_TAG_END } off++; @@ -5505,7 +5507,7 @@ md_is_html_block_end_condition(MD_CTX* ctx, OFF beg, OFF* p_end) case 6: /* Pass through */ case 7: *p_end = beg; - return (ISNEWLINE(beg) ? ctx->html_block_type : FALSE); + return (beg >= ctx->size || ISNEWLINE(beg) ? ctx->html_block_type : FALSE); default: MD_UNREACHABLE(); @@ -6100,8 +6102,9 @@ md_analyze_line(MD_CTX* ctx, OFF beg, OFF* p_end, task_container->is_task = TRUE; task_container->task_mark_off = tmp + 1; off = tmp + 3; - while(ISWHITESPACE(off)) + while(off < ctx->size && ISWHITESPACE(off)) off++; + if (off == ctx->size) break; line->beg = off; } }
3rdn4/md4c:db9ab41-heap_buffer_overflow
/workspace/skyset/
md4c
db9ab41-heap_buffer_overflow
/workspace/skyset/md4c/db9ab41-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/md4c/db9ab41-heap_buffer_overflow/immutable/
From 62b60979f6a281b2b3cf883abc84299431fe2f76 Mon Sep 17 00:00:00 2001 From: Martin Mitas <mity@morous.org> Date: Fri, 14 Jan 2022 10:00:09 +0100 Subject: [PATCH] Reset TABLECELLBOUNDARIES with ordinary opener chains. This is needed because special handling of '|' is now done also if the wiki-links extension is enabled so the chain is populated even with that extension. Fixes #174. --- CHANGELOG.md | 6 +++--- src/md4c.c | 8 +++++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccf7c74..eccf901 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,9 +49,9 @@ Fixes: Fix quadratic time behavior caused by unnecessary lookup for link reference definition even if the potential label contains nested brackets. - * [#173](https://github.com/mity/md4c/issues/173): - Fix broken internal state invoked by devilish combination of syntax - constructions. + * [#173](https://github.com/mity/md4c/issues/173), + [#174](https://github.com/mity/md4c/issues/174): + Multiple bugs identified with oss-fuzz were fixed. ## Version 0.4.8 diff --git a/src/md4c.c b/src/md4c.c index 779f808..5cdffe1 100644 --- a/src/md4c.c +++ b/src/md4c.c @@ -192,7 +192,7 @@ struct MD_CTX_tag { #define TILDE_OPENERS_2 (ctx->mark_chains[10]) #define BRACKET_OPENERS (ctx->mark_chains[11]) #define DOLLAR_OPENERS (ctx->mark_chains[12]) -#define OPENERS_CHAIN_FIRST 2 +#define OPENERS_CHAIN_FIRST 1 #define OPENERS_CHAIN_LAST 12 int n_table_cell_boundaries; @@ -2650,6 +2650,10 @@ md_rollback(MD_CTX* ctx, int opener_index, int closer_index, int how) int i; int mark_index; + fprintf(stderr, "md_rollback: %d ... %d [%s]\n", + ctx->marks[opener_index].beg, ctx->marks[closer_index].beg, + (how == MD_ROLLBACK_ALL ? "all" : "crossing")); + /* Cut all unresolved openers at the mark index. */ for(i = OPENERS_CHAIN_FIRST; i < OPENERS_CHAIN_LAST+1; i++) { MD_MARKCHAIN* chain = &ctx->mark_chains[i]; @@ -3439,6 +3443,8 @@ md_resolve_links(MD_CTX* ctx, const MD_LINE* lines, int n_lines) MD_LINK_ATTR attr; int is_link = FALSE; + fprintf(stderr, "md_resolve_links: %d ... %d\n", opener->beg, closer->beg); + if(next_index >= 0) { next_opener = &ctx->marks[next_index]; next_closer = &ctx->marks[next_opener->next];
3rdn4/md4c:db9ab41-unknown_read
/workspace/skyset/
md4c
db9ab41-unknown_read
/workspace/skyset/md4c/db9ab41-unknown_read/report.txt
A unknown read found in /workspace/skyset/md4c/db9ab41-unknown_read/immutable/
From 62b60979f6a281b2b3cf883abc84299431fe2f76 Mon Sep 17 00:00:00 2001 From: Martin Mitas <mity@morous.org> Date: Fri, 14 Jan 2022 10:00:09 +0100 Subject: [PATCH] Reset TABLECELLBOUNDARIES with ordinary opener chains. This is needed because special handling of '|' is now done also if the wiki-links extension is enabled so the chain is populated even with that extension. Fixes #174. --- CHANGELOG.md | 6 +++--- src/md4c.c | 8 +++++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccf7c74..eccf901 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,9 +49,9 @@ Fixes: Fix quadratic time behavior caused by unnecessary lookup for link reference definition even if the potential label contains nested brackets. - * [#173](https://github.com/mity/md4c/issues/173): - Fix broken internal state invoked by devilish combination of syntax - constructions. + * [#173](https://github.com/mity/md4c/issues/173), + [#174](https://github.com/mity/md4c/issues/174): + Multiple bugs identified with oss-fuzz were fixed. ## Version 0.4.8 diff --git a/src/md4c.c b/src/md4c.c index 779f808..5cdffe1 100644 --- a/src/md4c.c +++ b/src/md4c.c @@ -192,7 +192,7 @@ struct MD_CTX_tag { #define TILDE_OPENERS_2 (ctx->mark_chains[10]) #define BRACKET_OPENERS (ctx->mark_chains[11]) #define DOLLAR_OPENERS (ctx->mark_chains[12]) -#define OPENERS_CHAIN_FIRST 2 +#define OPENERS_CHAIN_FIRST 1 #define OPENERS_CHAIN_LAST 12 int n_table_cell_boundaries; @@ -2650,6 +2650,10 @@ md_rollback(MD_CTX* ctx, int opener_index, int closer_index, int how) int i; int mark_index; + fprintf(stderr, "md_rollback: %d ... %d [%s]\n", + ctx->marks[opener_index].beg, ctx->marks[closer_index].beg, + (how == MD_ROLLBACK_ALL ? "all" : "crossing")); + /* Cut all unresolved openers at the mark index. */ for(i = OPENERS_CHAIN_FIRST; i < OPENERS_CHAIN_LAST+1; i++) { MD_MARKCHAIN* chain = &ctx->mark_chains[i]; @@ -3439,6 +3443,8 @@ md_resolve_links(MD_CTX* ctx, const MD_LINE* lines, int n_lines) MD_LINK_ATTR attr; int is_link = FALSE; + fprintf(stderr, "md_resolve_links: %d ... %d\n", opener->beg, closer->beg); + if(next_index >= 0) { next_opener = &ctx->marks[next_index]; next_closer = &ctx->marks[next_opener->next];
3rdn4/mruby:0ed3fcf-heap_out_of_bound
/workspace/skyset/
mruby
0ed3fcf-heap_out_of_bound
/workspace/skyset/mruby/0ed3fcf-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/mruby/0ed3fcf-heap_out_of_bound/immutable/
diff --git a/src/vm.c b/src/vm.c index 6133cbcca..d825b6d59 100644 --- a/src/vm.c +++ b/src/vm.c @@ -692,6 +692,11 @@ mrb_f_send(mrb_state *mrb, mrb_value self) mrb_argnum_error(mrb, 0, 1, -1); } else if (n == 15) { + if (!mrb_array_p(regs[0]) || RARRAY_LEN(regs[0]) == 0) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "first argument is not a valid non-empty array"); + return mrb_nil_value(); /* Or however mrb handles errors appropriately here */ + } + name = mrb_obj_to_sym(mrb, RARRAY_PTR(regs[0])[0]); } else {
3rdn4/mruby:4c196db-heap_out_of_bound
/workspace/skyset/
mruby
4c196db-heap_out_of_bound
/workspace/skyset/mruby/4c196db-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/mruby/4c196db-heap_out_of_bound/immutable/
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c index 5ff33b870..3e9a153c2 100644 --- a/mrbgems/mruby-compiler/core/codegen.c +++ b/mrbgems/mruby-compiler/core/codegen.c @@ -1136,6 +1136,7 @@ gen_int(codegen_scope *s, uint16_t dst, mrb_int i) static mrb_bool gen_uniop(codegen_scope *s, mrb_sym sym, uint16_t dst) { + if (no_peephole(s)) return FALSE; struct mrb_insn_data data = mrb_last_insn(s); mrb_int n;
3rdn4/mruby:55b5261-null_pointer_deref
/workspace/skyset/
mruby
55b5261-null_pointer_deref
/workspace/skyset/mruby/55b5261-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/mruby/55b5261-null_pointer_deref/immutable/
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c index 8f7b5b013..e222094be 100644 --- a/mrbgems/mruby-compiler/core/codegen.c +++ b/mrbgems/mruby-compiler/core/codegen.c @@ -1905,7 +1905,7 @@ gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val) } } if (tree->cdr->car) { /* keyword arguments */ - if (n == 14) { + if (n == 13 || n == 14) { pop_n(n); genop_2(s, OP_ARRAY, cursp(), n); push();
3rdn4/mruby:8aec568-use_after_free
/workspace/skyset/
mruby
8aec568-use_after_free
/workspace/skyset/mruby/8aec568-use_after_free/report.txt
A use after free found in /workspace/skyset/mruby/8aec568-use_after_free/immutable/
diff --git a/src/vm.c b/src/vm.c index 3796f4173..6d61386b3 100644 --- a/src/vm.c +++ b/src/vm.c @@ -2268,9 +2268,9 @@ RETRY_TRY_BLOCK: } if (ci->cci > CINFO_NONE) { ci = cipop(mrb); + mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v); mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; - mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); }
3rdn4/mruby:af5acf3-use_after_free
/workspace/skyset/
mruby
af5acf3-use_after_free
/workspace/skyset/mruby/af5acf3-use_after_free/report.txt
A use after free found in /workspace/skyset/mruby/af5acf3-use_after_free/immutable/
diff --git a/src/vm.c b/src/vm.c index b04c9d7e5..09e557dc8 100644 --- a/src/vm.c +++ b/src/vm.c @@ -1159,18 +1159,20 @@ check_target_class(mrb_state *mrb) return target; } +#define regs (mrb->c->ci->stack) + static mrb_value -hash_new_from_values(mrb_state *mrb, mrb_int argc, mrb_value *regs) +hash_new_from_regs(mrb_state *mrb, mrb_int argc, mrb_int idx) { mrb_value hash = mrb_hash_new_capa(mrb, argc); while (argc--) { - mrb_hash_set(mrb, hash, regs[0], regs[1]); - regs += 2; + mrb_hash_set(mrb, hash, regs[idx+0], regs[idx+1]); + idx += 2; } return hash; } -#define ARGUMENT_NORMALIZE(arg_base, arg_info, insn) do { \ +#define ARGUMENT_NORMALIZE(arg_base, arg_info, insn) do { \ int n = *(arg_info)&0xf; \ int nk = (*(arg_info)>>4)&0xf; \ mrb_int bidx = (arg_base) + mrb_bidx(*(arg_info)); \ @@ -1179,7 +1181,7 @@ hash_new_from_values(mrb_state *mrb, mrb_int argc, mrb_value *regs) } \ else if (nk > 0) { /* pack keyword arguments */ \ mrb_int kidx = (arg_base)+(n==CALL_MAXARGS?1:n)+1; \ - mrb_value kdict = hash_new_from_values(mrb, nk, regs+kidx); \ + mrb_value kdict = hash_new_from_regs(mrb, nk, kidx); \ regs[kidx] = kdict; \ nk = CALL_MAXARGS; \ *(arg_info) = n | (nk<<4); \ @@ -1242,7 +1244,6 @@ RETRY_TRY_BLOCK: mrb->jmp = &c_jmp; mrb_vm_ci_proc_set(mrb->c->ci, proc); -#define regs (mrb->c->ci->stack) INIT_DISPATCH { CASE(OP_NOP, Z) { /* do nothing */
3rdn4/mruby:b4168c9-use_after_free
/workspace/skyset/
mruby
b4168c9-use_after_free
/workspace/skyset/mruby/b4168c9-use_after_free/report.txt
A use after free found in /workspace/skyset/mruby/b4168c9-use_after_free/immutable/
diff --git a/src/vm.c b/src/vm.c index 8b81031a3..fd17e90cc 100644 --- a/src/vm.c +++ b/src/vm.c @@ -1394,7 +1394,8 @@ RETRY_TRY_BLOCK: regs[a] = mrb_ary_entry(va, mrb_integer(vb)); break; case MRB_TT_HASH: - regs[a] = mrb_hash_get(mrb, va, vb); + va = mrb_hash_get(mrb, va, vb); + regs[a] = va; break; case MRB_TT_STRING: switch (mrb_type(vb)) {
3rdn4/mruby:bdc244e-null_pointer_deref
/workspace/skyset/
mruby
bdc244e-null_pointer_deref
/workspace/skyset/mruby/bdc244e-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/mruby/bdc244e-null_pointer_deref/immutable/
diff --git a/src/vm.c b/src/vm.c index 5013c877d..aa043b06a 100644 --- a/src/vm.c +++ b/src/vm.c @@ -1750,10 +1750,7 @@ RETRY_TRY_BLOCK: mrb_exc_set(mrb, exc); goto L_RAISE; } - if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) { - target_class = mrb_vm_ci_target_class(ci); - } - else if (target_class->tt == MRB_TT_MODULE) { + if ((target_class->flags & MRB_FL_CLASS_IS_PREPENDED) || target_class->tt == MRB_TT_MODULE) { target_class = mrb_vm_ci_target_class(ci); if (!target_class || target_class->tt != MRB_TT_ICLASS) { goto super_typeerror;
3rdn4/mruby:bf5bbf0-use_after_free
/workspace/skyset/
mruby
bf5bbf0-use_after_free
/workspace/skyset/mruby/bf5bbf0-use_after_free/report.txt
A use after free found in /workspace/skyset/mruby/bf5bbf0-use_after_free/immutable/
diff --git a/src/vm.c b/src/vm.c index fd17e90cc..77edbb38f 100644 --- a/src/vm.c +++ b/src/vm.c @@ -2819,13 +2819,15 @@ RETRY_TRY_BLOCK: } CASE(OP_RANGE_INC, B) { - regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], FALSE); + mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE); + regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_RANGE_EXC, B) { - regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], TRUE); + mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE); + regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; }
3rdn4/mruby:c30e6eb-heap_out_of_bound
/workspace/skyset/
mruby
c30e6eb-heap_out_of_bound
/workspace/skyset/mruby/c30e6eb-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/mruby/c30e6eb-heap_out_of_bound/immutable/
diff --git a/src/class.c b/src/class.c index 37fc4e68a..68a0ff084 100644 --- a/src/class.c +++ b/src/class.c @@ -2361,7 +2361,10 @@ mrb_remove_method(mrb_state *mrb, struct RClass *c, mrb_sym mid) MRB_CLASS_ORIGIN(c); h = c->mt; - if (h && mt_del(mrb, h, mid)) return; + if (h && mt_del(mrb, h, mid)) { + mrb_mc_clear_by_class(mrb, c); + return; + } mrb_name_error(mrb, mid, "method '%n' not defined in %C", mid, c); }
3rdn4/mruby:d1f1b4e-null_pointe_deref
/workspace/skyset/
mruby
d1f1b4e-null_pointe_deref
/workspace/skyset/mruby/d1f1b4e-null_pointe_deref/report.txt
A null pointe deref found in /workspace/skyset/mruby/d1f1b4e-null_pointe_deref/immutable/
diff --git a/src/vm.c b/src/vm.c index 77edbb38f..3bb9510ec 100644 --- a/src/vm.c +++ b/src/vm.c @@ -1749,7 +1749,7 @@ RETRY_TRY_BLOCK: } else if (target_class->tt == MRB_TT_MODULE) { target_class = mrb_vm_ci_target_class(ci); - if (target_class->tt != MRB_TT_ICLASS) { + if (!target_class || target_class->tt != MRB_TT_ICLASS) { goto super_typeerror; } }
3rdn4/openexr:115e42e-heap_buffer_overflow_a
/workspace/skyset/
openexr
115e42e-heap_buffer_overflow_a
/workspace/skyset/openexr/115e42e-heap_buffer_overflow_a/report.txt
A heap buffer overflow a found in /workspace/skyset/openexr/115e42e-heap_buffer_overflow_a/immutable/
From 043a50807eb19af844dd34281900b2ad8571325f Mon Sep 17 00:00:00 2001 From: Kimball Thurston <kdt3rd@gmail.com> Date: Tue, 25 Oct 2022 12:51:17 +1300 Subject: [PATCH] fix huf memory boundary checks (#1290) Fixes OSS-Fuzz 49698 Signed-off-by: Kimball Thurston <kdt3rd@gmail.com> Signed-off-by: Kimball Thurston <kdt3rd@gmail.com> --- src/lib/OpenEXRCore/internal_huf.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/lib/OpenEXRCore/internal_huf.c b/src/lib/OpenEXRCore/internal_huf.c index 544ad5ee8..796b17708 100644 --- a/src/lib/OpenEXRCore/internal_huf.c +++ b/src/lib/OpenEXRCore/internal_huf.c @@ -1757,6 +1757,7 @@ internal_huf_decompress ( const uint8_t* ptr; exr_result_t rv; const struct _internal_exr_context* pctxt = NULL; + const uint64_t hufInfoBlockSize = 5 * sizeof (uint32_t); if (decode) pctxt = EXR_CCTXT (decode->context); // @@ -1779,10 +1780,12 @@ internal_huf_decompress ( if (im >= HUF_ENCSIZE || iM >= HUF_ENCSIZE) return EXR_ERR_CORRUPT_CHUNK; - ptr = compressed + 20; + ptr = compressed + hufInfoBlockSize; nBytes = (((uint64_t) (nBits) + 7)) / 8; - if (ptr + nBytes > compressed + nCompressed) return EXR_ERR_OUT_OF_MEMORY; + + // must be nBytes remaining in buffer + if (hufInfoBlockSize + nBytes > nCompressed) return EXR_ERR_OUT_OF_MEMORY; // // Fast decoder needs at least 2x64-bits of compressed data, and @@ -1793,14 +1796,13 @@ internal_huf_decompress ( { FastHufDecoder* fhd = (FastHufDecoder*) spare; - // must be nBytes remaining in buffer - if (ptr - compressed + nBytes > (uint64_t) nCompressed) - return EXR_ERR_OUT_OF_MEMORY; - - rv = fasthuf_initialize ( - pctxt, fhd, &ptr, nCompressed - (ptr - compressed), im, iM, iM); + rv = fasthuf_initialize (pctxt, fhd, &ptr, nCompressed - hufInfoBlockSize, im, iM, iM); if (rv == EXR_ERR_SUCCESS) + { + if ( (uint64_t)(ptr - compressed) + nBytes > nCompressed ) + return EXR_ERR_OUT_OF_MEMORY; rv = fasthuf_decode (pctxt, fhd, ptr, nBits, raw, nRaw); + } } else {
3rdn4/openexr:115e42e-heap_buffer_overflow_b
/workspace/skyset/
openexr
115e42e-heap_buffer_overflow_b
/workspace/skyset/openexr/115e42e-heap_buffer_overflow_b/report.txt
A heap buffer overflow b found in /workspace/skyset/openexr/115e42e-heap_buffer_overflow_b/immutable/
From 063a881e7a5cd57156dbd0c9b6ad4d30f7023e55 Mon Sep 17 00:00:00 2001 From: Kimball Thurston <kdt3rd@gmail.com> Date: Thu, 2 Feb 2023 14:04:12 +1300 Subject: [PATCH] Fix missing guard check (#1329) Addresses OSS-FUZZ https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=52730 Signed-off-by: Kimball Thurston <kdt3rd@gmail.com> --- src/lib/OpenEXRCore/internal_huf.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/lib/OpenEXRCore/internal_huf.c b/src/lib/OpenEXRCore/internal_huf.c index fa769c9ef..92fcc3233 100644 --- a/src/lib/OpenEXRCore/internal_huf.c +++ b/src/lib/OpenEXRCore/internal_huf.c @@ -1280,9 +1280,21 @@ fasthuf_initialize ( codeCount[codeLen]++; } else if (codeLen == (uint64_t) LONG_ZEROCODE_RUN) + { + if (currByte >= topByte) + { + if (pctxt) + pctxt->print_error ( + pctxt, + EXR_ERR_CORRUPT_CHUNK, + "Error decoding Huffman table (Truncated table data)."); + return EXR_ERR_CORRUPT_CHUNK; + } + symbol += fasthuf_read_bits (8, &currBits, &currBitCount, &currByte) + SHORTEST_LONG_RUN - 1; + } else symbol += codeLen - SHORT_ZEROCODE_RUN + 1;
3rdn4/openexr:7c40603-stack_buffer_overflow
/workspace/skyset/
openexr
7c40603-stack_buffer_overflow
/workspace/skyset/openexr/7c40603-stack_buffer_overflow/report.txt
A stack buffer overflow found in /workspace/skyset/openexr/7c40603-stack_buffer_overflow/immutable/
From 6f235a803c6370583891f008181f85a91eedb681 Mon Sep 17 00:00:00 2001 From: Kimball Thurston <kdt3rd@gmail.com> Date: Wed, 24 May 2023 22:47:30 +1200 Subject: [PATCH] fix out of bounds check with a full channel name vs. byte count (#1429) Signed-off-by: Kimball Thurston <kdt3rd@gmail.com> --- src/lib/OpenEXRCore/internal_dwa_classifier.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/OpenEXRCore/internal_dwa_classifier.h b/src/lib/OpenEXRCore/internal_dwa_classifier.h index e1114baf6..d34497e4a 100644 --- a/src/lib/OpenEXRCore/internal_dwa_classifier.h +++ b/src/lib/OpenEXRCore/internal_dwa_classifier.h @@ -102,8 +102,9 @@ Classifier_read ( if (curin[len] == '\0') break; suffix[len] = (char) curin[len]; } - len += 1; if (len == 128 + 1) return EXR_ERR_CORRUPT_CHUNK; + // account for extra byte for nil terminator + len += 1; mem = alloc_fn (len); if (!mem) return EXR_ERR_OUT_OF_MEMORY;
3rdn4/radare2:0927ed3-heap_out_of_bound
/workspace/skyset/
radare2
0927ed3-heap_out_of_bound
/workspace/skyset/radare2/0927ed3-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/0927ed3-heap_out_of_bound/immutable/
diff --git a/shlr/java/class.c b/shlr/java/class.c index 80919af8ec..a2c6747cf1 100644 --- a/shlr/java/class.c +++ b/shlr/java/class.c @@ -6933,6 +6933,10 @@ R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(RBinJavaObj *bin, offset += 6; if (attr) { attr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR; + if (offset + 8 > sz) { + free (attr); + return NULL; + } attr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free);
3rdn4/radare2:0be8f25-heap_out_of_bound
/workspace/skyset/
radare2
0be8f25-heap_out_of_bound
/workspace/skyset/radare2/0be8f25-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/0be8f25-heap_out_of_bound/immutable/
diff --git a/libr/bin/format/mach0/mach0.c b/libr/bin/format/mach0/mach0.c index 679198ed62..033f2e83b0 100644 --- a/libr/bin/format/mach0/mach0.c +++ b/libr/bin/format/mach0/mach0.c @@ -1510,10 +1510,11 @@ static bool parse_chained_fixups(struct MACH0_(obj_t) *bin, ut32 offset, ut32 si if (header.starts_offset > size) { return false; } - ut32 segs_count; - if ((segs_count = r_buf_read_le32_at (bin->b, starts_at)) == UT32_MAX) { + ut32 segs_count = r_buf_read_le32_at (bin->b, starts_at); + if (segs_count == UT32_MAX || segs_count == 0) { return false; } + bin->segs_count = segs_count; bin->chained_starts = R_NEWS0 (struct r_dyld_chained_starts_in_segment *, segs_count); if (!bin->chained_starts) { return false; @@ -1699,6 +1700,7 @@ static bool reconstruct_chained_fixup(struct MACH0_(obj_t) *bin) { } R_FREE (opcodes); + bin->segs_count = bin->nsegs; return true; } @@ -2124,7 +2126,7 @@ void *MACH0_(mach0_free)(struct MACH0_(obj_t) *mo) { free (mo->intrp); free (mo->compiler); if (mo->chained_starts) { - for (i = 0; i < mo->nsegs; i++) { + for (i = 0; i < mo->nsegs && i < mo->segs_count; i++) { if (mo->chained_starts[i]) { free (mo->chained_starts[i]->page_start); free (mo->chained_starts[i]); @@ -4558,7 +4560,7 @@ struct MACH0_(mach_header) *MACH0_(get_hdr)(RBuffer *buf) { void MACH0_(iterate_chained_fixups)(struct MACH0_(obj_t) *bin, ut64 limit_start, ut64 limit_end, ut32 event_mask, RFixupCallback callback, void * context) { int i = 0; - for (; i < bin->nsegs; i++) { + for (; i < bin->nsegs && i < bin->segs_count; i++) { if (!bin->chained_starts[i]) { continue; } diff --git a/libr/bin/format/mach0/mach0.h b/libr/bin/format/mach0/mach0.h index 442b4f1a3f..0ad79a794e 100644 --- a/libr/bin/format/mach0/mach0.h +++ b/libr/bin/format/mach0/mach0.h @@ -130,6 +130,7 @@ struct MACH0_(obj_t) { char *intrp; char *compiler; int nsegs; + int segs_count; struct r_dyld_chained_starts_in_segment **chained_starts; struct dyld_chained_fixups_header fixups_header; ut64 fixups_offset; diff --git a/libr/core/cmd_api.c b/libr/core/cmd_api.c index 14cd7fa97b..71c4136405 100644 --- a/libr/core/cmd_api.c +++ b/libr/core/cmd_api.c @@ -391,7 +391,7 @@ R_API int r_cmd_alias_set_raw(RCmd *cmd, const char *k, const ut8 *v, int sz) { R_API RCmdAliasVal *r_cmd_alias_get(RCmd *cmd, const char *k) { r_return_val_if_fail (cmd && cmd->aliases && k, NULL); - return ht_pp_find(cmd->aliases, k, NULL); + return ht_pp_find (cmd->aliases, k, NULL); } static ut8 *alias_append_internal(int *out_szp, const RCmdAliasVal *first, const ut8 *second, int second_sz) {
3rdn4/radare2:108dc76-heap_out_of_bound
/workspace/skyset/
radare2
108dc76-heap_out_of_bound
/workspace/skyset/radare2/108dc76-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/108dc76-heap_out_of_bound/immutable/
diff --git a/libr/bin/p/bin_dyldcache.c b/libr/bin/p/bin_dyldcache.c index d76699b72f..6b7b512b71 100644 --- a/libr/bin/p/bin_dyldcache.c +++ b/libr/bin/p/bin_dyldcache.c @@ -1144,6 +1144,8 @@ static ut64 resolve_symbols_off(RDyldCache *cache, ut64 pa) { static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) { RList *bins = r_list_newf ((RListFree)free_bin); + ut16 *depArray = NULL; + cache_imgxtr_t *extras = NULL; if (!bins) { return NULL; } @@ -1177,8 +1179,6 @@ static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) { } ut32 j; - ut16 *depArray = NULL; - cache_imgxtr_t *extras = NULL; if (target_libs) { HtPU *path_to_idx = NULL; if (cache->accel) { @@ -1734,12 +1734,12 @@ static void populate_cache_maps(RDyldCache *cache) { cache->n_maps = next_map; } -static cache_accel_t *read_cache_accel(RBuffer *cache_buf, cache_hdr_t *hdr, cache_map_t *maps) { +static cache_accel_t *read_cache_accel(RBuffer *cache_buf, cache_hdr_t *hdr, cache_map_t *maps, int n_maps) { if (!cache_buf || !hdr || !hdr->accelerateInfoSize || !hdr->accelerateInfoAddr) { return NULL; } - - ut64 offset = va2pa (hdr->accelerateInfoAddr, hdr->mappingCount, maps, cache_buf, 0, NULL, NULL); + size_t mc = R_MIN (hdr->mappingCount, n_maps); + ut64 offset = va2pa (hdr->accelerateInfoAddr, mc, maps, cache_buf, 0, NULL, NULL); if (!offset) { return NULL; } @@ -1895,7 +1895,7 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd r_dyldcache_free (cache); return false; } - cache->accel = read_cache_accel (cache->buf, cache->hdr, cache->maps); + cache->accel = read_cache_accel (cache->buf, cache->hdr, cache->maps, cache->n_maps); cache->bins = create_cache_bins (bf, cache); if (!cache->bins) { r_dyldcache_free (cache);
3rdn4/radare2:27fe803-null_pointer_deref
/workspace/skyset/
radare2
27fe803-null_pointer_deref
/workspace/skyset/radare2/27fe803-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/radare2/27fe803-null_pointer_deref/immutable/
diff --git a/libr/bin/p/bin_symbols.c b/libr/bin/p/bin_symbols.c index 394736cfff..183507d2d2 100644 --- a/libr/bin/p/bin_symbols.c +++ b/libr/bin/p/bin_symbols.c @@ -1,4 +1,4 @@ -/* radare - LGPL - Copyright 2018 - pancake */ +/* radare - LGPL - Copyright 2018-2022 - pancake */ #include <r_types.h> #include <r_util.h> @@ -361,6 +361,9 @@ static RList *symbols(RBinFile *bf) { bool found = false; for (i = 0; i < element->hdr->n_lined_symbols; i++) { RCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i]; + if (!sym) { + break; + } ht_uu_find (hash, sym->paddr, &found); if (found) { continue;
3rdn4/radare2:4823451-heap_out_of_bound
/workspace/skyset/
radare2
4823451-heap_out_of_bound
/workspace/skyset/radare2/4823451-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/4823451-heap_out_of_bound/immutable/
diff --git a/libr/bin/format/mach0/coresymbolication.c b/libr/bin/format/mach0/coresymbolication.c index f554898c94..949afc42cc 100644 --- a/libr/bin/format/mach0/coresymbolication.c +++ b/libr/bin/format/mach0/coresymbolication.c @@ -269,6 +269,9 @@ RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut for (i = 0; i < hdr->n_sections && cursor < end; i++) { ut8 *sect_start = cursor; RCoreSymCacheElementSection *sect = &result->sections[i]; + if (cursor + (word_size * 4) > end) { + goto beach; + } sect->vaddr = sect->paddr = r_read_ble (cursor, false, bits); if (sect->vaddr < page_zero_size) { sect->vaddr += page_zero_size; @@ -359,6 +362,10 @@ RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut continue; } string_origin = relative_to_strings? b + start_of_strings : cursor; + if (!string_origin) { + cursor += R_CS_EL_SIZE_LSYM; + continue; + } lsym->flc.file = str_dup_safe (b, string_origin + file_name_off, end); if (!lsym->flc.file) { cursor += R_CS_EL_SIZE_LSYM; diff --git a/libr/bin/p/bin_symbols.c b/libr/bin/p/bin_symbols.c index 779e36940f..5177be7886 100644 --- a/libr/bin/p/bin_symbols.c +++ b/libr/bin/p/bin_symbols.c @@ -353,28 +353,30 @@ static bool check_buffer(RBinFile *bf, RBuffer *b) { } static RList *symbols(RBinFile *bf) { - RList *res = r_list_newf ((RListFree)r_bin_symbol_free); - r_return_val_if_fail (res && bf->o && bf->o->bin_obj, res); + r_return_val_if_fail (bf && bf->o && bf->o->bin_obj, NULL); RCoreSymCacheElement *element = bf->o->bin_obj; size_t i; HtUU *hash = ht_uu_new0 (); if (!hash) { - return res; + return NULL; } + RList *res = r_list_newf ((RListFree)r_bin_symbol_free); bool found = false; - for (i = 0; i < element->hdr->n_lined_symbols; i++) { - RCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i]; - if (!sym) { - break; - } - ht_uu_find (hash, sym->paddr, &found); - if (found) { - continue; - } - RBinSymbol *s = bin_symbol_from_symbol (element, sym); - if (s) { - r_list_append (res, s); - ht_uu_insert (hash, sym->paddr, 1); + if (element->lined_symbols) { + for (i = 0; i < element->hdr->n_lined_symbols; i++) { + RCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i]; + if (!sym) { + break; + } + ht_uu_find (hash, sym->paddr, &found); + if (found) { + continue; + } + RBinSymbol *s = bin_symbol_from_symbol (element, sym); + if (s) { + r_list_append (res, s); + ht_uu_insert (hash, sym->paddr, 1); + } } } if (element->symbols) {
3rdn4/radare2:4b22fc5-null_pointer_deref
/workspace/skyset/
radare2
4b22fc5-null_pointer_deref
/workspace/skyset/radare2/4b22fc5-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/radare2/4b22fc5-null_pointer_deref/immutable/
diff --git a/libr/bin/format/mach0/mach0.c b/libr/bin/format/mach0/mach0.c index 4e8b97c7ba..14bc321727 100644 --- a/libr/bin/format/mach0/mach0.c +++ b/libr/bin/format/mach0/mach0.c @@ -4580,6 +4580,9 @@ void MACH0_(iterate_chained_fixups)(struct MACH0_(obj_t) *bin, ut64 limit_start, if (page_idx >= bin->chained_starts[i]->page_count) { break; } + if (!bin->chained_starts[i]->page_start) { + break; + } ut16 page_start = bin->chained_starts[i]->page_start[page_idx]; if (page_start == DYLD_CHAINED_PTR_START_NONE) { continue;
3rdn4/radare2:515e592-heap_out_of_bound
/workspace/skyset/
radare2
515e592-heap_out_of_bound
/workspace/skyset/radare2/515e592-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/515e592-heap_out_of_bound/immutable/
diff --git a/libr/bin/format/mach0/coresymbolication.c b/libr/bin/format/mach0/coresymbolication.c index 5385509f32..f350199550 100644 --- a/libr/bin/format/mach0/coresymbolication.c +++ b/libr/bin/format/mach0/coresymbolication.c @@ -222,7 +222,7 @@ RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut } size_t i; ut8 *cursor = b + R_CS_EL_OFF_SEGS; - for (i = 0; i < hdr->n_segments && cursor < end; i++) { + for (i = 0; i < hdr->n_segments && cursor + sizeof (RCoreSymCacheElementSegment) < end; i++) { RCoreSymCacheElementSegment *seg = &result->segments[i]; seg->paddr = seg->vaddr = r_read_le64 (cursor); cursor += 8;
3rdn4/radare2:5c0bde8-null_pointer_deref
/workspace/skyset/
radare2
5c0bde8-null_pointer_deref
/workspace/skyset/radare2/5c0bde8-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/radare2/5c0bde8-null_pointer_deref/immutable/
diff --git a/libr/io/io_bank.c b/libr/io/io_bank.c index 7a62773dff..5b170e74f4 100644 --- a/libr/io/io_bank.c +++ b/libr/io/io_bank.c @@ -786,7 +786,7 @@ R_API bool r_io_bank_read_at(RIO *io, const ut32 bankid, ut64 addr, ut8 *buf, in const ut64 buf_off = R_MAX (addr, r_io_submap_from (sm)) - addr; const int read_len = R_MIN (r_io_submap_to ((&fake_sm)), r_io_submap_to (sm)) - (addr + buf_off) + 1; - if (map->perm & R_PERM_RELOC) { + if (map->perm & R_PERM_RELOC && map->reloc_map) { ret &= map->reloc_map->read (io, map, addr + buf_off, &buf[buf_off], read_len); } else { const ut64 paddr = addr + buf_off - r_io_map_from (map) + map->delta; @@ -875,7 +875,7 @@ R_API int r_io_bank_read_from_submap_at(RIO *io, const ut32 bankid, ut64 addr, u return -1; } const int read_len = R_MIN (len, r_io_submap_to (sm) - addr + 1); - if (map->perm & R_PERM_RELOC) { + if (map->perm & R_PERM_RELOC && map->reloc_map) { return map->reloc_map->read (io, map, addr, buf, read_len); } const ut64 paddr = addr - r_io_map_from (map) + map->delta;
3rdn4/radare2:72ffc02-null_pointer_deref
/workspace/skyset/
radare2
72ffc02-null_pointer_deref
/workspace/skyset/radare2/72ffc02-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/radare2/72ffc02-null_pointer_deref/immutable/
diff --git a/libr/bin/p/bin_xnu_kernelcache.c b/libr/bin/p/bin_xnu_kernelcache.c index 36b1c2db08..df5b1fe7d0 100644 --- a/libr/bin/p/bin_xnu_kernelcache.c +++ b/libr/bin/p/bin_xnu_kernelcache.c @@ -242,7 +242,9 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd beach: r_buf_free (fbuf); - obj->cache_buf = NULL; + if (obj) { + obj->cache_buf = NULL; + } MACH0_(mach0_free) (main_mach0); return false; }
3rdn4/radare2:7cfd367-use_after_free
/workspace/skyset/
radare2
7cfd367-use_after_free
/workspace/skyset/radare2/7cfd367-use_after_free/report.txt
A use after free found in /workspace/skyset/radare2/7cfd367-use_after_free/immutable/
diff --git a/libr/io/io_bank.c b/libr/io/io_bank.c index 228e422d65..882dfc48d1 100644 --- a/libr/io/io_bank.c +++ b/libr/io/io_bank.c @@ -230,7 +230,10 @@ R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) { //delete all submaps that are completly included in sm RRBNode *next = r_rbnode_next (entry); // this can be optimized, there is no need to do search here - r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL); + bool a = r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL); + if (!a) { + break; + } entry = next; } if (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) {
3rdn4/radare2:95b648f-heap_out_of_bound
/workspace/skyset/
radare2
95b648f-heap_out_of_bound
/workspace/skyset/radare2/95b648f-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/95b648f-heap_out_of_bound/immutable/
diff --git a/libr/anal/anal.c b/libr/anal/anal.c index 30e7f7b294..727a223ed5 100644 --- a/libr/anal/anal.c +++ b/libr/anal/anal.c @@ -147,7 +147,7 @@ R_API RAnal *r_anal_new(void) { } R_API bool r_anal_plugin_remove(RAnal *anal, RAnalPlugin *plugin) { - // R2_590 TODO + // XXX TODO return true; } diff --git a/libr/anal/xrefs.c b/libr/anal/xrefs.c index b797a48768..3283dc035d 100644 --- a/libr/anal/xrefs.c +++ b/libr/anal/xrefs.c @@ -5,7 +5,7 @@ #include <r_anal.h> #include <r_cons.h> #include <r_vec.h> -#include <cwisstable.h> +#include <sdb/cwisstable.h> R_VEC_TYPE (RVecAnalRef, RAnalRef); diff --git a/libr/arch/p/bf/plugin.c b/libr/arch/p/bf/plugin.c index e2f99e949a..87ebd3cb01 100644 --- a/libr/arch/p/bf/plugin.c +++ b/libr/arch/p/bf/plugin.c @@ -13,8 +13,8 @@ static size_t countChar(const ut8 *buf, int len, char ch) { } static int getid(char ch) { - const char *keys = "[]<>+-,."; - const char *cidx = strchr (keys, ch); + const char *const keys = "[]<>+-,."; + const char *const cidx = strchr (keys, ch); return cidx? cidx - keys + 1: 0; } @@ -136,13 +136,11 @@ static int assemble(const char *buf, ut8 **outbuf) { #define BUFSIZE_INC 32 static bool decode(RArchSession *as, RAnalOp *op, RArchDecodeMask mask) { int len = op->size; - const ut8 *_buf = op->bytes; - const ut64 addr = op->addr; if (len < 1) { return false; } - - ut8 *buf = (ut8*)_buf; // XXX + ut8 *buf = op->bytes; + const ut64 addr = op->addr; ut64 dst = 0LL; if (!op) { return 1; @@ -169,29 +167,32 @@ static bool decode(RArchSession *as, RAnalOp *op, RArchDecodeMask mask) { } r_strbuf_set (&op->esil, "1,pc,-,brk,=[4],4,brk,+="); #if 1 - { + if (len > 1) { const ut8 *p = buf + 1; int lev = 0, i = 1; len--; while (i < len && *p) { - if (*p == '[') { + switch (*p) { + case '[': lev++; - } - if (*p == ']') { + break; + case ']': lev--; - if (lev == -1) { - dst = addr + (size_t)(p - buf) + 1; + if (lev < 1) { + size_t delta = p - buf; + dst = addr + (size_t)delta + 1; op->jump = dst; r_strbuf_set (&op->esil, "1,pc,-,brk,=[4],4,brk,+=,"); goto beach; } - } - if (*p == 0x00 || *p == 0xff) { + break; + case 0: + case 0xff: op->type = R_ANAL_OP_TYPE_ILL; goto beach; } if (read_at && i == len - 1) { - break; +#if 0 // XXX unnecessary just break int new_buf_len = len + 1 + BUFSIZE_INC; ut8 *new_buf = calloc (new_buf_len, 1); @@ -203,6 +204,9 @@ static bool decode(RArchSession *as, RAnalOp *op, RArchDecodeMask mask) { p = buf + i; len += BUFSIZE_INC; } +#else + break; +#endif } p++; i++; diff --git a/libr/arch/p/mips_gnu/plugin.c b/libr/arch/p/mips_gnu/plugin.c index 5599244879..66d025ec2e 100644 --- a/libr/arch/p/mips_gnu/plugin.c +++ b/libr/arch/p/mips_gnu/plugin.c @@ -1697,9 +1697,7 @@ static bool decode(RArchSession *as, RAnalOp *op, RAnalOpMask mask) { } if (rs == 28) { -#if R2_590 op->ptr = as->config->gp + imm; -#endif } else { op->ptr = imm; } diff --git a/libr/arch/p/riscv_cs/plugin.c b/libr/arch/p/riscv_cs/plugin.c index a253615e61..6d296f676a 100644 --- a/libr/arch/p/riscv_cs/plugin.c +++ b/libr/arch/p/riscv_cs/plugin.c @@ -156,7 +156,7 @@ static int parse_reg_name(RRegItem *reg, csh handle, cs_insn *insn, int reg_num) } #endif -// static R_TH_LOCAL RRegItem reg; +// static R_TH_LOCAL RRegItem reg; // R2_590 store in session plugindata static void op_fillval(RArchSession *as, RAnalOp *op, csh *handle, cs_insn *insn) { #if R2_590 // using reg names instead diff --git a/libr/bin/bfilter.c b/libr/bin/bfilter.c index c560283e26..bc0f5feeda 100644 --- a/libr/bin/bfilter.c +++ b/libr/bin/bfilter.c @@ -1,79 +1,68 @@ /* radare - LGPL - Copyright 2015-2023 - pancake */ #include <r_bin.h> +#include <sdb/ht_su.h> #include "i/private.h" -static char *__hashify(char *s, ut64 vaddr) { +static char *__hashify(const char *s, ut64 vaddr) { r_return_val_if_fail (s, NULL); - char *os = s; + const char *os = s; while (*s) { if (!IS_PRINTABLE (*s)) { if (vaddr && vaddr != UT64_MAX) { - char *ret = r_str_newf ("_%" PFMT64d, vaddr); - if (ret) { - free (os); - } - return ret; + return r_str_newf ("_%" PFMT64d, vaddr); } ut32 hash = sdb_hash (s); - char *ret = r_str_newf ("%x", hash); - if (ret) { - free (os); - } - return ret; + return r_str_newf ("%x", hash); } s++; } - return os; + return strdup (os); } -// - name should be allocated on the heap -R_API char *r_bin_filter_name(RBinFile *bf, HtPU *db, ut64 vaddr, char *name) { +R_API char *r_bin_filter_name(RBinFile *bf, HtSU *db, ut64 vaddr, const char *name) { r_return_val_if_fail (db && name, NULL); - char *resname = name; int count = 0; - HtPUKv *kv = ht_pu_find_kv (db, name, NULL); - if (kv) { - kv->value++; - count = kv->value; + bool found = false; + const ut64 value = ht_su_find (db, name, &found); + if (found) { + count = value + 1; + ht_su_update (db, name, count); } else { count = 1; - ht_pu_insert (db, name, 1ULL); + ht_su_insert (db, name, 1ULL); } // check if there's another symbol with the same name and address); char *uname = r_str_newf ("%" PFMT64x ".%s", vaddr, name); - bool found = false; - ht_pu_find (db, uname, &found); + found = false; + (void)ht_su_find (db, uname, &found); if (found) { // TODO: symbol is dupped, so symbol can be removed! free (uname); return NULL; // r_str_newf ("%s_%d", name, count); } - HtPUKv tmp = { - .key = uname, - .key_len = strlen (uname), - .value = count, - .value_len = sizeof (ut64) - }; - ht_pu_insert_kv (db, &tmp, false); + + (void)ht_su_insert (db, uname, count); + + char *resname = NULL; if (vaddr) { - char *p = __hashify (resname, vaddr); - if (p) { - resname = p; - } + resname = __hashify (name, vaddr); } if (count > 1) { - char *p = r_str_appendf (resname, "_%d", count - 1); - if (p) { - resname = p; - } + resname = r_str_appendf (resname, "_%d", count - 1); // two symbols at different addresses and same name wtf R_LOG_DEBUG ("Found duplicated symbol '%s'", resname); } + + free (uname); + + if (!resname) { + resname = strdup (name); + } return resname; } @@ -145,15 +134,16 @@ R_API void r_bin_filter_symbols(RBinFile *bf, RList *list) { R_API void r_bin_filter_sections(RBinFile *bf, RList *list) { RBinSection *sec; - HtPU *db = ht_pu_new0 (); + HtSU *db = ht_su_new0 (); RListIter *iter; r_list_foreach (list, iter, sec) { char *p = r_bin_filter_name (bf, db, sec->vaddr, sec->name); if (p) { + free (sec->name); sec->name = p; } } - ht_pu_free (db); + ht_su_free (db); } static bool false_positive(const char *str) { diff --git a/libr/bin/bin.c b/libr/bin/bin.c index 5c71cc7deb..5967caf305 100644 --- a/libr/bin/bin.c +++ b/libr/bin/bin.c @@ -443,7 +443,7 @@ R_API bool r_bin_plugin_add(RBin *bin, RBinPlugin *foo) { } R_API bool r_bin_plugin_remove(RBin *bin, RBinPlugin *plugin) { - // R2_590 TODO + // XXX TODO return true; } diff --git a/libr/bin/bobj.c b/libr/bin/bobj.c index 7e4fc6a1d6..9a28c4ebcc 100644 --- a/libr/bin/bobj.c +++ b/libr/bin/bobj.c @@ -3,6 +3,7 @@ #define R_LOG_ORIGIN "bin.obj" #include <r_bin.h> +#include <sdb/ht_su.h> #include <r_util.h> #include "i/private.h" @@ -208,7 +209,7 @@ R_IPI RBinObject *r_bin_object_new(RBinFile *bf, RBinPlugin *plugin, ut64 basead } static void filter_classes(RBinFile *bf, RList *list) { - HtPU *db = ht_pu_new0 (); + HtSU *db = ht_su_new0 (); HtPP *ht = ht_pp_new0 (); RListIter *iter, *iter2; RBinClass *cls; @@ -224,6 +225,7 @@ static void filter_classes(RBinFile *bf, RList *list) { strcpy (namepad, cls->name); p = r_bin_filter_name (bf, db, cls->index, namepad); if (p) { + free (namepad); namepad = p; } free (cls->name); @@ -235,7 +237,7 @@ static void filter_classes(RBinFile *bf, RList *list) { } } } - ht_pu_free (db); + ht_su_free (db); ht_pp_free (ht); } diff --git a/libr/bin/format/elf/elf.c b/libr/bin/format/elf/elf.c index 9276e1bf12..044b202698 100644 --- a/libr/bin/format/elf/elf.c +++ b/libr/bin/format/elf/elf.c @@ -1613,8 +1613,7 @@ static bool elf_init(ELFOBJ *eo) { eo->symbols_by_ord = NULL; (void) _load_elf_sections (eo); eo->boffset = Elf_(get_boffset) (eo); - HtUUOptions opt = {0}; - eo->rel_cache = ht_uu_new_opt (&opt); + eo->rel_cache = ht_uu_new0 (); (void) Elf_(load_relocs) (eo); sdb_ns_set (eo->kv, "versioninfo", store_versioninfo (eo)); reloc_fill_local_address (eo); diff --git a/libr/bin/format/pe/pe.c b/libr/bin/format/pe/pe.c index ca59eab156..7bf527d193 100644 --- a/libr/bin/format/pe/pe.c +++ b/libr/bin/format/pe/pe.c @@ -3185,8 +3185,7 @@ R_API void PE_(bin_pe_parse_resource)(RBinPEObj *pe) { Pe_image_resource_directory *rs_directory = pe->resource_directory; ut32 curRes = 0; int totalRes = 0; - HtUUOptions opt = {0}; - HtUU *dirs = ht_uu_new_opt (&opt); //to avoid infinite loops + HtUU *dirs = ht_uu_new0 (); //to avoid infinite loops if (!dirs) { return; } diff --git a/libr/bin/p/bin_dyldcache.c b/libr/bin/p/bin_dyldcache.c index 60af22b155..eb1b82e022 100644 --- a/libr/bin/p/bin_dyldcache.c +++ b/libr/bin/p/bin_dyldcache.c @@ -1,6 +1,7 @@ /* radare2 - LGPL - Copyright 2018-2023 - pancake, mrmacete, keegan */ #include <r_core.h> +#include <sdb/ht_su.h> // #include "../format/mach0/mach0_defines.h" #define R_BIN_MACH064 1 #include "../format/mach0/mach0.h" @@ -1008,8 +1009,8 @@ static int string_contains(const void *a, const void *b) { return !strstr ((const char*) a, (const char*) b); } -static HtPU *create_path_to_index(RBuffer *cache_buf, cache_img_t *img, cache_hdr_t *hdr) { - HtPU *path_to_idx = ht_pu_new0 (); +static HtSU *create_path_to_index(RBuffer *cache_buf, cache_img_t *img, cache_hdr_t *hdr) { + HtSU *path_to_idx = ht_su_new0 (); if (!path_to_idx) { return NULL; } @@ -1020,7 +1021,7 @@ static HtPU *create_path_to_index(RBuffer *cache_buf, cache_img_t *img, cache_hd continue; } file[sizeof (file) - 1] = 0; - ht_pu_insert (path_to_idx, file, (ut64)i); + ht_su_insert (path_to_idx, file, (ut64)i); const char versions_pattern[] = ".framework/Versions/"; char *versions = strstr (file, versions_pattern); @@ -1033,14 +1034,14 @@ static HtPU *create_path_to_index(RBuffer *cache_buf, cache_img_t *img, cache_hd } strcpy (versions + 10, tail); free (tail); - ht_pu_insert (path_to_idx, file, (ut64)i); + ht_su_insert (path_to_idx, file, (ut64)i); // XXX already inserted? } } } return path_to_idx; } -static void carve_deps_at_address(RDyldCache *cache, cache_img_t *img, HtPU *path_to_idx, ut64 address, int *deps, bool printing) { +static void carve_deps_at_address(RDyldCache *cache, cache_img_t *img, HtSU *path_to_idx, ut64 address, int *deps, bool printing) { ut64 pa = va2pa (address, cache->n_maps, cache->maps, cache->buf, 0, NULL, NULL); if (pa == UT64_MAX) { return; @@ -1072,7 +1073,7 @@ static void carve_deps_at_address(RDyldCache *cache, cache_img_t *img, HtPU *pat break; } const char *key = (const char *) cursor + 24; - size_t dep_index = (size_t)ht_pu_find (path_to_idx, key, &found); + size_t dep_index = (size_t)ht_su_find (path_to_idx, key, &found); if (!found || dep_index >= cache->hdr->imagesCount) { R_LOG_WARN ("alien dep '%s'", key); continue; @@ -1186,7 +1187,7 @@ static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) { ut32 j; if (target_libs) { - HtPU *path_to_idx = NULL; + HtSU *path_to_idx = NULL; const ut32 depListCount = (cache->accel)? cache->accel->depListCount: 0; if (cache->accel && depListCount > 0) { depArray = R_NEWS0 (ut16, depListCount); @@ -1250,7 +1251,7 @@ static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) { } } - ht_pu_free (path_to_idx); + ht_su_free (path_to_idx); R_FREE (depArray); R_FREE (extras); } diff --git a/libr/bin/p/bin_elf.inc.c b/libr/bin/p/bin_elf.inc.c index b7be48d030..761c12f303 100644 --- a/libr/bin/p/bin_elf.inc.c +++ b/libr/bin/p/bin_elf.inc.c @@ -930,8 +930,7 @@ static RList* patch_relocs(RBinFile *bf) { if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } - HtUUOptions opt = { 0 }; - if (!(relocs_by_sym = ht_uu_new_opt (&opt))) { + if (!(relocs_by_sym = ht_uu_new0 ())) { r_list_free (ret); return NULL; } diff --git a/libr/bin/p/bin_mach0.c b/libr/bin/p/bin_mach0.c index d583357c14..2b5a722232 100644 --- a/libr/bin/p/bin_mach0.c +++ b/libr/bin/p/bin_mach0.c @@ -181,26 +181,6 @@ static RList *entries(RBinFile *bf) { return ret; } -#if 0 -// XXX this is very slooow -static RList *symbols(RBinFile *bf) { - struct MACH0_(obj_t) *mo = R_UNWRAP3 (bf, bo, bin_obj); - if (!mo) { - return NULL; - } - if (!MACH0_(load_symbols) (mo)) { - return NULL; - } - // R2_590 -- remove this thing we dont want to return cloned symbols, can be infered - RList *list = r_list_newf ((RListFree) r_bin_symbol_free); - RBinSymbol *sym; - R_VEC_FOREACH (&bf->bo->symbols_vec, sym) { - r_list_append (list, r_bin_symbol_clone (sym)); - } - return list; -} -#endif - static bool symbols_vec(RBinFile *bf) { struct MACH0_(obj_t) *mo = R_UNWRAP3 (bf, bo, bin_obj); if (R_LIKELY (mo)) { @@ -993,7 +973,6 @@ RBinPlugin r_bin_plugin_mach0 = { .entries = &entries, .signature = &entitlements, .sections = &sections, - // .symbols = &symbols, .symbols_vec = &symbols_vec, .imports = &imports, .size = &size, diff --git a/libr/core/canal.c b/libr/core/canal.c index f266eb357d..ae22f64f5c 100644 --- a/libr/core/canal.c +++ b/libr/core/canal.c @@ -2187,8 +2187,7 @@ R_API int r_core_print_bb_gml(RCore *core, RAnalFunction *fcn) { return false; } int id = 0; - HtUUOptions opt = {0}; - HtUU *ht = ht_uu_new_opt (&opt); + HtUU *ht = ht_uu_new0 (); r_cons_printf ("graph\n[\n" "hierarchic 1\n" "label \"\"\n" "directed 1\n"); diff --git a/libr/core/cconfig.c b/libr/core/cconfig.c index 173a6bf3de..a6d27be031 100644 --- a/libr/core/cconfig.c +++ b/libr/core/cconfig.c @@ -35,12 +35,8 @@ static void set_options(RConfigNode *node, ...) { } static bool isGdbPlugin(RCore *core) { - if (core->io && core->io->desc && core->io->desc->plugin) { - if (core->io->desc->plugin->name && !strcmp (core->io->desc->plugin->name, "gdb")) { - return true; - } - } - return false; + RIOPlugin *plugin = R_UNWRAP4 (core, io, desc, plugin); + return plugin && plugin->meta.name && !strcmp (plugin->meta.name, "gdb"); } static void print_node_options(RConfigNode *node) { @@ -1573,9 +1569,9 @@ static bool cb_cmdpdc(void *user, void *data) { RListIter *iter; RCorePlugin *cp; r_list_foreach (core->rcmd->plist, iter, cp) { - if (!strcmp (cp->name, "r2retdec")) { + if (!strcmp (cp->meta.name, "r2retdec")) { r_cons_printf ("pdz\n"); - } else if (!strcmp (cp->name, "r2ghidra")) { + } else if (!strcmp (cp->meta.name, "r2ghidra")) { r_cons_printf ("pdg\n"); } } diff --git a/libr/core/cmd_anal.c b/libr/core/cmd_anal.c index 061bf210d7..bc19485915 100644 --- a/libr/core/cmd_anal.c +++ b/libr/core/cmd_anal.c @@ -8719,9 +8719,9 @@ static void _anal_calls(RCore *core, ut64 addr, ut64 addr_end, bool printCommand isValidCall = false; } if (isValidCall) { - ut8 buf[4] = {0}; - r_io_read_at (core->io, op.jump, buf, 4); - isValidCall = memcmp (buf, "\x00\x00\x00\x00", 4); + ut8 zbuf[4] = {0}; + r_io_read_at (core->io, op.jump, zbuf, 4); + isValidCall = memcmp (zbuf, "\x00\x00\x00\x00", 4); } if (isValidCall) { #if JAYRO_03 @@ -8817,9 +8817,8 @@ static void cmd_anal_calls(RCore *core, const char *input, bool printCommands, b } static void cmd_sdbk(Sdb *db, const char *input) { - char *out = (input[0] == ' ') - ? sdb_querys (db, NULL, 0, input + 1) - : sdb_querys (db, NULL, 0, "*"); + const char *arg = (input[0] == ' ')? input + 1: "*"; + char *out = sdb_querys (db, NULL, 0, arg); if (out) { r_cons_println (out); free (out); @@ -9118,7 +9117,7 @@ static void anal_axg(RCore *core, const char *input, int level, Sdb *db, int opt } static void cmd_anal_ucall_ref(RCore *core, ut64 addr) { - RAnalFunction * fcn = r_anal_get_function_at (core->anal, addr); + RAnalFunction *fcn = r_anal_get_function_at (core->anal, addr); if (fcn) { r_cons_printf (" ; %s", fcn->name); } else { @@ -9257,7 +9256,6 @@ static void axfm(RCore *core) { last_addr = ref->addr; } } - RVecAnalRef_free (refs); } diff --git a/libr/core/cmd_log.c b/libr/core/cmd_log.c index 308821d5b7..59938a4f1a 100644 --- a/libr/core/cmd_log.c +++ b/libr/core/cmd_log.c @@ -600,8 +600,8 @@ static int cmd_plugins(void *data, const char *input) { pj_a (pj); r_list_foreach (core->rcmd->plist, iter, cp) { pj_o (pj); - pj_ks (pj, "name", cp->name); - pj_ks (pj, "desc", cp->desc); + pj_ks (pj, "name", cp->meta.name); + pj_ks (pj, "desc", cp->meta.desc); pj_end (pj); } pj_end (pj); @@ -617,12 +617,12 @@ static int cmd_plugins(void *data, const char *input) { break; case 'q': r_list_foreach (core->rcmd->plist, iter, cp) { - r_cons_printf ("%s\n", cp->name); + r_cons_printf ("%s\n", cp->meta.name); } break; case 0: r_list_foreach (core->rcmd->plist, iter, cp) { - r_cons_printf ("%-10s %s\n", cp->name, cp->desc); + r_cons_printf ("%-10s %s\n", cp->meta.name, cp->meta.desc); } break; default: diff --git a/libr/core/cmd_search.c b/libr/core/cmd_search.c index a16fb345b9..88d5dce805 100644 --- a/libr/core/cmd_search.c +++ b/libr/core/cmd_search.c @@ -1185,8 +1185,7 @@ static RList *construct_rop_gadget(RCore *core, ut64 addr, ut8 *buf, int buflen, int grep_find; int search_hit; char *rx = NULL; - HtUUOptions opt = {0}; - HtUU *localbadstart = ht_uu_new_opt (&opt); + HtUU *localbadstart = ht_uu_new0 (); int count = 0; if (grep) { @@ -1560,8 +1559,7 @@ static int r_core_search_rop(RCore *core, RInterval search_itv, int opt, const c r_cons_break_push (NULL, NULL); r_list_foreach (param->boundaries, itermap, map) { - HtUUOptions opt = {0}; - HtUU *badstart = ht_uu_new_opt (&opt); + HtUU *badstart = ht_uu_new0 (); if (!r_itv_overlap (search_itv, map->itv)) { continue; } diff --git a/libr/core/core.c b/libr/core/core.c index 6b9f36eb96..04522478e0 100644 --- a/libr/core/core.c +++ b/libr/core/core.c @@ -3035,6 +3035,41 @@ static void cmdusr2(int p) { } #endif +static void core_visual_init(RCoreVisual *visual) { + visual->printidx = 0; + visual->textedit_mode = true; + visual->obs = 0; + visual->ime = false; + visual->imes = false; + visual->nib = -1; + visual->blocksize = 0; + visual->autoblocksize = true; + visual->disMode = 0; + visual->hexMode = 0; + visual->printMode = 0; + visual->snowMode = false; + visual->snows = NULL; + visual->color = 1; + visual->zoom = 0; + visual->currentFormat = 0; + visual->current0format = 0; + memset (visual->numbuf, 0, sizeof (visual->numbuf)); + visual->numbuf_i = 0; + visual->splitView = false; + visual->splitPtr = UT64_MAX; + visual->current3format = 0; + visual->current4format = 0; + visual->current5format = 0; + visual->hold = NULL; + visual->oldpc = 0; + visual->oseek = UT64_MAX; + memset (visual->debugstr, 0, sizeof (visual->debugstr)); + + visual->firstRun = true; + visual->fromVisual = false; + memset (visual->menus_Colors, 0, sizeof (visual->menus_Colors)); +} + R_API bool r_core_init(RCore *core) { #if R2__UNIX__ Gcore = core; @@ -3098,7 +3133,8 @@ R_API bool r_core_init(RCore *core) { core->scriptstack->free = (RListFree)free; core->times = R_NEW0 (RCoreTimes); core->vmode = false; - core->visual.printidx = 0; + core_visual_init (&core->visual); + core->lastcmd = NULL; if (core->print->charset) { diff --git a/libr/core/cplugin.c b/libr/core/cplugin.c index e78f49dd8b..9249421db2 100644 --- a/libr/core/cplugin.c +++ b/libr/core/cplugin.c @@ -35,11 +35,11 @@ R_API bool r_core_plugin_remove(RCmd *cmd, RCorePlugin *plugin) { if (!cmd) { return false; } - const char *name = plugin->name; + const char *name = plugin->meta.name; RListIter *iter, *iter2; RCorePlugin *p; r_list_foreach_safe (cmd->plist, iter, iter2, p) { - if (p && !strcmp (name, p->name)) { + if (p && !strcmp (name, p->meta.name)) { r_list_delete (cmd->plist, iter); return true; } diff --git a/libr/core/p/core_a2f.c b/libr/core/p/core_a2f.c index 44b9b09b62..9cdad503e6 100644 --- a/libr/core/p/core_a2f.c +++ b/libr/core/p/core_a2f.c @@ -425,9 +425,11 @@ static int r_cmd_anal_call(void *user, const char *input) { // PLUGIN Definition Info RCorePlugin r_core_plugin_a2f = { - .name = "a2f", - .desc = "The reworked analysis from scratch thing", - .license = "LGPL3", + .meta = { + .name = "a2f", + .desc = "The reworked analysis from scratch thing", + .license = "LGPL3", + }, .call = r_cmd_anal_call, }; diff --git a/libr/core/p/core_java.c b/libr/core/p/core_java.c index b191621e40..e2322f28d0 100644 --- a/libr/core/p/core_java.c +++ b/libr/core/p/core_java.c @@ -376,7 +376,7 @@ static int r_cmd_java_handle_help(RCore *core, const char *input) { const char **help_msg = (const char **)malloc (sizeof (char *) * END_CMDS * 4); help_msg[0] = "Usage:"; help_msg[1] = "java [cmd] [arg..] "; - help_msg[2] = r_core_plugin_java.desc; + help_msg[2] = r_core_plugin_java.meta.desc; for (i = 0; JAVA_CMDS[i].name; i++) { RCmdJavaCmd *cmd = &JAVA_CMDS[i]; help_msg[3 + (i * 3) + 0] = cmd->name; @@ -1947,9 +1947,11 @@ static int r_cmd_java_handle_print_exceptions(RCore *core, const char *input) { // PLUGIN Definition Info RCorePlugin r_core_plugin_java = { - .name = "java", - .desc = "Suite of java commands, java help for more info", - .license = "Apache", + .meta = { + .name = "java", + .desc = "Suite of java commands, java help for more info", + .license = "Apache", + }, .call = r_cmd_java_call, }; diff --git a/libr/core/p/core_sixref.c b/libr/core/p/core_sixref.c index 4c27c580ea..b25f5fdda4 100644 --- a/libr/core/p/core_sixref.c +++ b/libr/core/p/core_sixref.c @@ -379,9 +379,11 @@ done: } RCorePlugin r_core_plugin_sixref = { - .name = "sixref", - .desc = "quickly find xrefs in arm64 buffer", - .license = "MIT", + .meta = { + .name = "sixref", + .desc = "quickly find xrefs in arm64 buffer", + .license = "MIT", + }, .call = r_cmdsixref_call, }; diff --git a/libr/core/panels.c b/libr/core/panels.c index c8aa732693..729cf1ba2d 100644 --- a/libr/core/panels.c +++ b/libr/core/panels.c @@ -66,11 +66,6 @@ static void __panels_refresh(RCore *core); #define COUNT(x) (sizeof ((x)) / sizeof ((*x)) - 1) -// TODO: kill mutable globals -static R_TH_LOCAL bool firstRun = true; -static R_TH_LOCAL bool fromVisual = false; -static R_TH_LOCAL char *menus_Colors[128]; - typedef enum { LEFT, RIGHT, @@ -2456,7 +2451,7 @@ static RPanels *__panels_new(RCore *core) { return NULL; } int h, w = r_cons_get_size (&h); - firstRun = true; + core->visual.firstRun = true; if (!__init (core, panels, w, h)) { free (panels); return NULL; @@ -5581,7 +5576,7 @@ static void __init_menu_color_settings_layout(void *_core, const char *parent) { char *now = r_core_cmd_str (core, "eco."); r_str_split (now, '\n'); parent = "Settings.Colors"; - RList *list = __sorted_list (core, (const char **)menus_Colors, COUNT (menus_Colors)); + RList *list = __sorted_list (core, (const char **)core->visual.menus_Colors, COUNT (core->visual.menus_Colors)); char *pos; RListIter* iter; RStrBuf *buf = r_strbuf_new (NULL); @@ -5648,7 +5643,7 @@ static void __load_config_menu(RCore *core) { char *th; int i = 0; r_list_foreach (themes_list, th_iter, th) { - menus_Colors[i++] = th; + core->visual.menus_Colors[i++] = th; } } @@ -5936,9 +5931,9 @@ static void demo_end(RCore *core, RConsCanvas *can) { r_config_set_b (core->config, "scr.utf8", false); RPanel *cur = __get_cur_panel (core->panels); cur->view->refresh = true; - firstRun= false; + core->visual.firstRun = false; __panels_refresh (core); - firstRun= true; + core->visual.firstRun = true; r_config_set_b (core->config, "scr.utf8", utf8); char *s = r_cons_canvas_tostring (can); if (s) { @@ -6018,7 +6013,7 @@ static void __panels_refresh(RCore *core) { } RStrBuf *title = r_strbuf_new (" "); bool utf8 = r_config_get_b (core->config, "scr.utf8"); - if (firstRun) { + if (core->visual.firstRun) { r_config_set_b (core->config, "scr.utf8", false); } @@ -6104,13 +6099,13 @@ static void __panels_refresh(RCore *core) { __print_snow (panels); } - if (firstRun) { + if (core->visual.firstRun) { if (core->panels_root->n_panels < 2) { if (r_config_get_b (core->config, "scr.demo")) { demo_begin (core, can); } } - firstRun = false; + core->visual.firstRun = false; r_config_set_b (core->config, "scr.utf8", utf8); RPanel *cur = __get_cur_panel (core->panels); cur->view->refresh = true; @@ -7286,7 +7281,7 @@ virtualmouse: __set_root_state (core, QUIT); goto exit; case '!': - fromVisual = true; + core->visual.fromVisual = true; case 'q': case -1: // EOF __set_root_state (core, DEL); @@ -7339,7 +7334,7 @@ static void __del_panels(RCore *core) { } R_API bool r_core_panels_root(RCore *core, RPanelsRoot *panels_root) { - fromVisual = core->vmode; + core->visual.fromVisual = core->vmode; if (!panels_root) { panels_root = R_NEW0 (RPanelsRoot); if (!panels_root) { @@ -7396,7 +7391,7 @@ R_API bool r_core_panels_root(RCore *core, RPanelsRoot *panels_root) { } } r_config_set_i (core->config, "scr.maxpage", maxpage); - if (fromVisual) { + if (core->visual.fromVisual) { r_core_visual (core, ""); } else { r_cons_enable_mouse (false); diff --git a/libr/core/visual.c b/libr/core/visual.c index 008f8b7591..72852679ea 100644 --- a/libr/core/visual.c +++ b/libr/core/visual.c @@ -11,27 +11,6 @@ R_VEC_TYPE(RVecAnalRef, RAnalRef); static void visual_refresh(RCore *core); #define PROMPTSTR "> " -// remove globals pls -static R_TH_LOCAL bool textedit_mode = true; -static R_TH_LOCAL int obs = 0; -static R_TH_LOCAL bool __ime = false; -static R_TH_LOCAL int __nib = -1; -static R_TH_LOCAL bool __imes = false; -static R_TH_LOCAL int blocksize = 0; -static R_TH_LOCAL bool autoblocksize = true; -static R_TH_LOCAL int disMode = 0; -static R_TH_LOCAL int hexMode = 0; -static R_TH_LOCAL int printMode = 0; -static R_TH_LOCAL bool snowMode = false; -static R_TH_LOCAL RList *snows = NULL; -static R_TH_LOCAL int color = 1; -static R_TH_LOCAL int zoom = 0; -static R_TH_LOCAL int currentFormat = 0; -static R_TH_LOCAL int current0format = 0; -static R_TH_LOCAL char numbuf[32] = {0}; -static R_TH_LOCAL int numbuf_i = 0; -static R_TH_LOCAL bool splitView = false; -static R_TH_LOCAL ut64 splitPtr = UT64_MAX; typedef struct { int x; @@ -65,23 +44,20 @@ static const char *printfmtColumns[NPF] = { static const char *printHexFormats[PRINT_HEX_FORMATS] = { "px", "pxa", "pxr", "prx", "pxb", "pxh", "pxw", "pxq", "pxu", "pxd", "pxr", }; -static R_TH_LOCAL int current3format = 0; static const char *print3Formats[PRINT_3_FORMATS] = { // not used at all. its handled by the pd format "pxw 64@r:SP;dr=;drcq;pd $r", // DEBUGGER "pCD" }; -static R_TH_LOCAL int current4format = 0; static const char *print4Formats[PRINT_4_FORMATS] = { "prc", "p2", "prc=a", "pxAv", "pxx", "p=e $r-2", "pq 64", "pk 64", "pri", }; -static R_TH_LOCAL int current5format = 0; static const char *print5Formats[PRINT_5_FORMATS] = { "pca", "pcA", "p8x", "pcc", "psb", "pcp", "pcd", }; R_API void r_core_visual_applyHexMode(RCore *core, int hexMode) { - currentFormat = R_ABS (hexMode) % PRINT_HEX_FORMATS; - switch (currentFormat) { + core->visual.currentFormat = R_ABS (hexMode) % PRINT_HEX_FORMATS; + switch (core->visual.currentFormat) { case 0: /* px */ case 3: /* prx */ case 6: /* pxw */ @@ -109,18 +85,17 @@ R_API void r_core_visual_applyHexMode(RCore *core, int hexMode) { } R_API void r_core_visual_toggle_decompiler_disasm(RCore *core, bool for_graph, bool reset) { - static R_TH_LOCAL RConfigHold *hold = NULL; // should be a tab-specific var - if (hold) { - r_config_hold_restore (hold); - r_config_hold_free (hold); - hold = NULL; + if (core->visual.hold) { + r_config_hold_restore (core->visual.hold); + r_config_hold_free (core->visual.hold); + core->visual.hold = NULL; return; } if (reset) { return; } - hold = r_config_hold_new (core->config); - r_config_hold (hold, "asm.hint.pos", "asm.cmt.col", "asm.offset", "asm.lines", + core->visual.hold = r_config_hold_new (core->config); + r_config_hold (core->visual.hold, "asm.hint.pos", "asm.cmt.col", "asm.offset", "asm.lines", "asm.indent", "asm.bytes", "asm.comments", "asm.dwarf", "asm.usercomments", "asm.instr", NULL); if (for_graph) { r_config_set (core->config, "asm.hint.pos", "-2"); @@ -156,8 +131,8 @@ static void setcursor(RCore *core, bool cur) { } R_API void r_core_visual_applyDisMode(RCore *core, int disMode) { - currentFormat = R_ABS (disMode) % 5; - switch (currentFormat) { + core->visual.currentFormat = R_ABS (disMode) % 5; + switch (core->visual.currentFormat) { case 0: r_config_set_b (core->config, "asm.pseudo", false); r_config_set_b (core->config, "asm.bytes", true); @@ -196,22 +171,22 @@ R_API void r_core_visual_applyDisMode(RCore *core, int disMode) { } } -static void nextPrintCommand(void) { - current0format++; - current0format %= PRINT_HEX_FORMATS; - currentFormat = current0format; +static void nextPrintCommand(RCore *core) { + core->visual.current0format++; + core->visual.current0format %= PRINT_HEX_FORMATS; + core->visual.currentFormat = core->visual.current0format; } -static void prevPrintCommand(void) { - current0format--; - if (current0format < 0) { - current0format = 0; +static void prevPrintCommand(RCore *core) { + core->visual.current0format--; + if (core->visual.current0format < 0) { + core->visual.current0format = 0; } - currentFormat = current0format; + core->visual.currentFormat = core->visual.current0format; } static const char *stackPrintCommand(RCore *core) { - if (current0format == 0) { + if (core->visual.current0format == 0) { if (r_config_get_b (core->config, "dbg.slow")) { return "pxr"; } @@ -224,7 +199,7 @@ static const char *stackPrintCommand(RCore *core) { } return "px"; } - return printHexFormats[current0format % PRINT_HEX_FORMATS]; + return printHexFormats[core->visual.current0format % PRINT_HEX_FORMATS]; } static const char *__core_visual_print_command(RCore *core) { @@ -378,8 +353,8 @@ static RCoreHelpMessage help_msg_visual_fn = { #if USE_THREADS static void printSnow(RCore *core) { - if (!snows) { - snows = r_list_newf (free); + if (!core->visual.snows) { + core->visual.snows = r_list_newf (free); } int i, h, w = r_cons_get_size (&h); int amount = r_num_rand (4); @@ -388,21 +363,21 @@ static void printSnow(RCore *core) { Snow *snow = R_NEW (Snow); snow->x = r_num_rand (w); snow->y = 0; - r_list_append (snows, snow); + r_list_append (core->visual.snows, snow); } } RListIter *iter, *iter2; Snow *snow; - r_list_foreach_safe (snows, iter, iter2, snow) { + r_list_foreach_safe (core->visual.snows, iter, iter2, snow) { int pos = (r_num_rand (3)) - 1; snow->x += pos; snow->y++; if (snow->x >= w) { - r_list_delete (snows, iter); + r_list_delete (core->visual.snows, iter); continue; } if (snow->y > h) { - r_list_delete (snows, iter); + r_list_delete (core->visual.snows, iter); continue; } r_cons_gotoxy (snow->x, snow->y); @@ -460,32 +435,32 @@ R_API void r_core_visual_showcursor(RCore *core, int x) { static void printFormat(RCore *core, const int next) { switch (core->visual.printidx) { case R_CORE_VISUAL_MODE_PX: // 0 // xc - hexMode += next; - r_core_visual_applyHexMode (core, hexMode); - printfmtSingle[0] = printHexFormats[R_ABS (hexMode) % PRINT_HEX_FORMATS]; + core->visual.hexMode += next; + r_core_visual_applyHexMode (core, core->visual.hexMode); + printfmtSingle[0] = printHexFormats[R_ABS (core->visual.hexMode) % PRINT_HEX_FORMATS]; break; case R_CORE_VISUAL_MODE_PD: // pd - disMode += next; - r_core_visual_applyDisMode (core, disMode); + core->visual.disMode += next; + r_core_visual_applyDisMode (core, core->visual.disMode); printfmtSingle[1] = rotateAsmemu (core); break; case R_CORE_VISUAL_MODE_DB: // debugger - disMode += next; - r_core_visual_applyDisMode (core, disMode); + core->visual.disMode += next; + r_core_visual_applyDisMode (core, core->visual.disMode); printfmtSingle[1] = rotateAsmemu (core); - current3format += next; - currentFormat = R_ABS (current3format) % PRINT_3_FORMATS; - printfmtSingle[2] = print3Formats[currentFormat]; + core->visual.current3format += next; + core->visual.currentFormat = R_ABS (core->visual.current3format) % PRINT_3_FORMATS; + printfmtSingle[2] = print3Formats[core->visual.currentFormat]; break; case R_CORE_VISUAL_MODE_OV: // overview - current4format += next; - currentFormat = R_ABS (current4format) % PRINT_4_FORMATS; - printfmtSingle[3] = print4Formats[currentFormat]; + core->visual.current4format += next; + core->visual.currentFormat = R_ABS (core->visual.current4format) % PRINT_4_FORMATS; + printfmtSingle[3] = print4Formats[core->visual.currentFormat]; break; case R_CORE_VISUAL_MODE_CD: // code - current5format += next; - currentFormat = R_ABS (current5format) % PRINT_5_FORMATS; - printfmtSingle[4] = print5Formats[currentFormat]; + core->visual.current5format += next; + core->visual.currentFormat = R_ABS (core->visual.current5format) % PRINT_5_FORMATS; + printfmtSingle[4] = print5Formats[core->visual.currentFormat]; break; } } @@ -784,16 +759,16 @@ R_API void r_core_visual_prompt_input(RCore *core) { r_config_set_i (core->config, "scr.vtmode", 1); int curbs = core->blocksize; - if (autoblocksize) { - r_core_block_size (core, obs); + if (core->visual.autoblocksize) { + r_core_block_size (core, core->visual.obs); } backup_current_addr (core, &addr, &bsze, &newaddr); do { ret = r_core_visual_prompt (core); } while (ret); restore_current_addr (core, addr, bsze, newaddr); - if (autoblocksize) { - obs = core->blocksize; + if (core->visual.autoblocksize) { + core->visual.obs = core->blocksize; r_core_block_size (core, curbs); } @@ -1549,7 +1524,7 @@ repeat: // dis = r_core_cmd_strf (core, "pd $r-4 @ 0x%08"PFMT64x, refi->addr); dis = NULL; res = r_str_append (res, "; ---------------------------\n"); - switch (printMode) { + switch (core->visual.printMode) { case 0: dis = r_core_cmd_strf (core, "pd--6 @ 0x%08"PFMT64x, refi->addr); break; @@ -1628,16 +1603,16 @@ repeat: goto repeat; case 'p': r_core_visual_toggle_decompiler_disasm (core, false, true); - printMode++; - if (printMode > lastPrintMode) { - printMode = 0; + core->visual.printMode++; + if (core->visual.printMode > lastPrintMode) { + core->visual.printMode = 0; } goto repeat; case 'P': r_core_visual_toggle_decompiler_disasm (core, false, true); - printMode--; - if (printMode < 0) { - printMode = lastPrintMode; + core->visual.printMode--; + if (core->visual.printMode < 0) { + core->visual.printMode = lastPrintMode; } goto repeat; case '/': @@ -1962,13 +1937,13 @@ static void cursor_nextrow(RCore *core, bool use_ocur) { p->cur += r_config_get_i (core->config, "hex.cols"); return; } - if (splitView) { + if (core->visual.splitView) { int w = r_config_get_i (core->config, "hex.cols"); if (w < 1) { w = 16; } if (core->seltab == 0) { - splitPtr += w; + core->visual.splitPtr += w; } else { core->offset += w; } @@ -2043,13 +2018,13 @@ static void cursor_prevrow(RCore *core, bool use_ocur) { return; } - if (splitView) { + if (core->visual.splitView) { int w = r_config_get_i (core->config, "hex.cols"); if (w < 1) { w = 16; } if (core->seltab == 0) { - splitPtr -= w; + core->visual.splitPtr -= w; } else { core->offset -= w; } @@ -2201,27 +2176,27 @@ static bool fix_cursor(RCore *core) { } static bool insert_mode_enabled(RCore *core) { - if (!__ime) { + if (!core->visual.ime) { return false; } char ch = (ut8)r_cons_readchar (); if ((ut8)ch == KEY_ALTQ) { (void)r_cons_readchar (); - __ime = false; + core->visual.ime = false; return true; } - if (__imes) { + if (core->visual.imes) { if (ch == 0x1b) { - __ime = false; - __imes = false; + core->visual.ime = false; + core->visual.imes = false; return true; } if (ch == 9) { - textedit_mode = !textedit_mode; + core->visual.textedit_mode = !core->visual.textedit_mode; return true; } if (ch == 0x7f) { // backspace - if (textedit_mode) { + if (core->visual.textedit_mode) { if (core->print->cur_enabled && core->print->cur > 0) { r_core_cmdf (core, "r-1@ 0x%08"PFMT64x" + %d", core->offset, core->print->cur - 1); core->print->cur--; @@ -2235,7 +2210,7 @@ static bool insert_mode_enabled(RCore *core) { if (ch == 0xd) { ch = '\n'; } - if (textedit_mode) { + if (core->visual.textedit_mode) { r_core_cmdf (core, "r+1@ 0x%08"PFMT64x" + %d", core->offset, core->print->cur); } r_core_cmdf (core, "wx %02x @ 0x%08"PFMT64x" + %d", ch, core->offset, core->print->cur); @@ -2317,13 +2292,13 @@ static bool insert_mode_enabled(RCore *core) { case 'd': case 'e': case 'f': - if (__nib != -1) { - r_core_cmdf (core, "wx %c%c @ $$+%d", __nib, ch, core->print->cur); + if (core->visual.nib != -1) { + r_core_cmdf (core, "wx %c%c @ $$+%d", core->visual.nib, ch, core->print->cur); core->print->cur++; - __nib = -1; + core->visual.nib = -1; } else { r_core_cmdf (core, "wx %c @ $$+%d", ch, core->print->cur); - __nib = ch; + core->visual.nib = ch; } break; case 'u': @@ -2352,7 +2327,7 @@ static bool insert_mode_enabled(RCore *core) { break; case 'Q': case 'q': - __ime = false; + core->visual.ime = false; break; case '?': r_cons_less_str ("\nVisual Insert Mode:\n\n" @@ -2533,23 +2508,23 @@ static bool isNumber(RCore *core, int ch) { return false; } -static void numbuf_append(int ch) { - if (numbuf_i >= sizeof (numbuf) - 1) { - numbuf_i = 0; +static void numbuf_append(RCore *core, int ch) { + if (core->visual.numbuf_i >= sizeof (core->visual.numbuf) - 1) { + core->visual.numbuf_i = 0; } - numbuf[numbuf_i++] = ch; - numbuf[numbuf_i] = 0; + core->visual.numbuf[core->visual.numbuf_i++] = ch; + core->visual.numbuf[core->visual.numbuf_i] = 0; } -static int numbuf_pull(void) { +static int numbuf_pull(RCore *core) { int distance = 1; - if (numbuf_i) { - numbuf[numbuf_i] = 0; - distance = atoi (numbuf); + if (core->visual.numbuf_i) { + core->visual.numbuf[core->visual.numbuf_i] = 0; + distance = atoi (core->visual.numbuf); if (!distance) { distance = 1; } - numbuf_i = 0; + core->visual.numbuf_i = 0; } return distance; } @@ -2624,14 +2599,14 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { return 1; } } - if (__imes) { + if (core->visual.imes) { // TODO: support arrow keys to move around without losing insert mode // TODO: implement append mode - __ime = true; + core->visual.ime = true; setcursor (core, true); if (ch == 9 || ch == 0x1b) { - __ime = false; - __imes = false; + core->visual.ime = false; + core->visual.imes = false; return 1; } if (ch == 0x7f) { // backspace @@ -2668,10 +2643,10 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { || r_config_get_i (core->config, "asm.hint.call"))) { r_core_visual_jump (core, ch); } else { - numbuf_append (ch); + numbuf_append (core, ch); } } else { - numbuf_append (ch); + numbuf_append (core, ch); } } else { switch (ch) { @@ -2730,7 +2705,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { case 'O': // tab TAB case 9: // tab TAB r_core_visual_toggle_decompiler_disasm (core, false, true); - if (splitView) { + if (core->visual.splitView) { // this split view is kind of useless imho, we should kill it or merge it into tabs core->print->cur = 0; core->curtab = 0; @@ -2873,11 +2848,11 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { } break; case '\\': - if (splitPtr == UT64_MAX) { - splitPtr = core->offset; + if (core->visual.splitPtr == UT64_MAX) { + core->visual.splitPtr = core->offset; } - splitView = !splitView; - setcursor (core, splitView); + core->visual.splitView = !core->visual.splitView; + setcursor (core, core->visual.splitView); break; case 'c': setcursor (core, !core->print->cur_enabled); @@ -2897,15 +2872,15 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { } break; case 'C': - if (++color > 3) { - color = 0; + if (++core->visual.color > 3) { + core->visual.color = 0; } - r_config_set_i (core->config, "scr.color", color); + r_config_set_i (core->config, "scr.color", core->visual.color); break; case 'd': { bool mouse_state = __holdMouseState (core); r_core_visual_showcursor (core, true); - int distance = numbuf_pull (); + int distance = numbuf_pull (core); r_core_visual_define (core, arg + 1, distance - 1); r_core_visual_showcursor (core, false); r_cons_enable_mouse (mouse_state && r_config_get_i (core->config, "scr.wheel")); @@ -3036,13 +3011,13 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { return true; } if (core->print->ocur == -1) { - __ime = true; + core->visual.ime = true; core->print->cur_enabled = true; return true; } } else if (PIDX == 4) { - __ime = true; - __imes = true; + core->visual.ime = true; + core->visual.imes = true; } else if (PIDX == 2) { if (core->seltab == 0) { addr = r_debug_reg_get (core->dbg, "SP") + delta; @@ -3194,7 +3169,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { core->cons->cpos.x = w; } } else { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); if (core->print->cur_enabled) { if (ch == 'h') { for (i = 0; i < distance; i++) { @@ -3216,7 +3191,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { case 'L': case 'H': if (r_config_get_b (core->config, "scr.cursor")) { - int distance = 8; // numbuf_pull (); + int distance = 8; // numbuf_pull (core); core->cons->cpos.x += (ch == 'h' || ch == 'H')? -distance: distance; if (core->cons->cpos.x < 1) { core->cons->cpos.x = 0; @@ -3226,7 +3201,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { core->cons->cpos.x = w; } } else { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); if (core->print->cur_enabled) { if (ch == 'H') { for (i = 0; i < distance; i++) { @@ -3254,13 +3229,13 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { core->cons->cpos.y = h; } } else if (core->print->cur_enabled) { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); for (i = 0; i < distance; i++) { cursor_nextrow (core, false); } } else { if (r_config_get_i (core->config, "scr.wheel.nkey")) { - int i, distance = numbuf_pull (); + int i, distance = numbuf_pull (core); if (distance < 1) { distance = 1; } @@ -3278,7 +3253,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { if (ami) { r_core_seek_delta (core, amisize); } else { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); if (distance > 1) { times = distance; } @@ -3299,7 +3274,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { break; case 'J': if (r_config_get_b (core->config, "scr.cursor")) { - int distance = 4;// numbuf_pull (); + int distance = 4;// numbuf_pull (core); core->cons->cpos.y += distance; int h; (void)r_cons_get_size (&h); @@ -3307,7 +3282,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { core->cons->cpos.y = h; } } else if (core->print->cur_enabled) { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); for (i = 0; i < distance; i++) { cursor_nextrow (core, true); } @@ -3335,7 +3310,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { } r_core_seek (core, addr, true); } else { - r_core_seek (core, core->offset + obs, true); + r_core_seek (core, core->offset + core->visual.obs, true); } } break; @@ -3346,13 +3321,13 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { core->cons->cpos.y = 0; } } else if (core->print->cur_enabled) { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); for (i = 0; i < distance; i++) { cursor_prevrow (core, false); } } else { if (r_config_get_b (core->config, "scr.wheel.nkey")) { - int i, distance = numbuf_pull (); + int i, distance = numbuf_pull (core); if (distance < 1) { distance = 1; } @@ -3364,7 +3339,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { if (times < 1) { times = 1; } - int distance = numbuf_pull (); + int distance = numbuf_pull (core); if (distance > 1) { times = distance; } @@ -3381,13 +3356,13 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { break; case 'K': if (r_config_get_b (core->config, "scr.cursor")) { - int distance = 4;// numbuf_pull (); + int distance = 4;// numbuf_pull (core); core->cons->cpos.y -= distance; if (core->cons->cpos.y < 1) { core->cons->cpos.y = 0; } } else if (core->print->cur_enabled) { - int distance = numbuf_pull (); + int distance = numbuf_pull (core); for (i = 0; i < distance; i++) { cursor_prevrow (core, true); } @@ -3400,8 +3375,8 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { r_core_seek (core, 0, true); } } else { - ut64 at = (core->offset > obs)? core->offset - obs: 0; - if (core->offset > obs) { + ut64 at = (core->offset > core->visual.obs)? core->offset - core->visual.obs: 0; + if (core->offset > core->visual.obs) { r_core_seek (core, at, true); } else { r_core_seek (core, 0, true); @@ -3472,14 +3447,14 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { case 'p': r_core_visual_toggle_decompiler_disasm (core, false, true); if (v->printidx == R_CORE_VISUAL_MODE_DB && core->print->cur_enabled) { - nextPrintCommand (); + nextPrintCommand (core); } else { setprintmode (core, 1); } break; case 'P': if (v->printidx == R_CORE_VISUAL_MODE_DB && core->print->cur_enabled) { - prevPrintCommand (); + prevPrintCommand (core); } else { setprintmode (core, -1); } @@ -3489,11 +3464,11 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { findPair (core); } else { /* do nothing? */ - autoblocksize = !autoblocksize; - if (autoblocksize) { - obs = core->blocksize; + core->visual.autoblocksize = !core->visual.autoblocksize; + if (core->visual.autoblocksize) { + core->visual.obs = core->blocksize; } else { - r_core_block_size (core, obs); + r_core_block_size (core, core->visual.obs); } r_cons_clear (); } @@ -3590,7 +3565,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { } } } else { - if (!autoblocksize) { + if (!core->visual.autoblocksize) { r_core_block_size (core, core->blocksize - 1); } } @@ -3624,7 +3599,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { } } } else { - if (!autoblocksize) { + if (!core->visual.autoblocksize) { r_core_block_size (core, core->blocksize + 1); } } @@ -3648,7 +3623,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { visual_search (core); } } else { - if (autoblocksize) { + if (core->visual.autoblocksize) { r_core_cmd0 (core, "?i highlight;e scr.highlight=`yp`"); } else { r_core_block_size (core, core->blocksize - cols); @@ -3657,10 +3632,10 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { r_cons_enable_mouse (mouse_state && r_config_get_i (core->config, "scr.wheel")); } break; case '(': - snowMode = !snowMode; - if (!snowMode) { - r_list_free (snows); - snows = NULL; + core->visual.snowMode = !core->visual.snowMode; + if (!core->visual.snowMode) { + r_list_free (core->visual.snows); + core->visual.snows = NULL; } break; case ')': @@ -3690,7 +3665,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { } else { r_core_cmdf (core, "dr PC=0x%08"PFMT64x, core->offset + core->print->cur); } - } else if (!autoblocksize) { + } else if (!core->visual.autoblocksize) { r_core_block_size (core, core->blocksize + cols); } break; @@ -3903,7 +3878,7 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { setcursor (core, false); return false; } - numbuf_i = 0; + core->visual.numbuf_i = 0; } r_core_block_read (core); return true; @@ -3911,16 +3886,16 @@ R_API int r_core_visual_cmd(RCore *core, const char *arg) { R_API void r_core_visual_title(RCore *core, int color) { bool showDelta = r_config_get_b (core->config, "asm.slow"); - static R_TH_LOCAL ut64 oldpc = 0; + core->visual.oldpc = 0; const char *BEGIN = core->cons->context->pal.prompt; const char *filename; char pos[512], bar[512], pcs[32]; - if (!oldpc) { - oldpc = r_debug_reg_get (core->dbg, "PC"); + if (!core->visual.oldpc) { + core->visual.oldpc = r_debug_reg_get (core->dbg, "PC"); } /* automatic block size */ int pc, hexcols = r_config_get_i (core->config, "hex.cols"); - if (autoblocksize) { + if (core->visual.autoblocksize) { switch (core->visual.printidx) { #if 0 case R_CORE_VISUAL_MODE_PXR: // prc @@ -3939,9 +3914,9 @@ R_API void r_core_visual_title(RCore *core, int color) { break; #endif case R_CORE_VISUAL_MODE_PX: // x - if (currentFormat == 3 || currentFormat == 9 || currentFormat == 5) { // prx + if (core->visual.currentFormat == 3 || core->visual.currentFormat == 9 || core->visual.currentFormat == 5) { // prx r_core_block_size (core, (int)(core->cons->rows * hexcols * 4)); - } else if ((R_ABS (hexMode) % 3) == 0) { // prx + } else if ((R_ABS (core->visual.hexMode) % 3) == 0) { // prx r_core_block_size (core, (int)(core->cons->rows * hexcols)); } else { r_core_block_size (core, (int)(core->cons->rows * hexcols * 2)); @@ -3974,7 +3949,7 @@ R_API void r_core_visual_title(RCore *core, int color) { } if (r_config_get_b (core->config, "cfg.debug")) { ut64 curpc = r_debug_reg_get (core->dbg, "PC"); - if (curpc && curpc != UT64_MAX && curpc != oldpc) { + if (curpc && curpc != UT64_MAX && curpc != core->visual.oldpc) { // check dbg.follow here int follow = (int) (st64) r_config_get_i (core->config, "dbg.follow"); if (follow > 0) { @@ -3984,7 +3959,7 @@ R_API void r_core_visual_title(RCore *core, int color) { } else if (follow < 0) { r_core_seek (core, curpc + follow, true); } - oldpc = curpc; + core->visual.oldpc = curpc; } } RIOMap *map = r_io_map_get_at (core->io, core->offset); @@ -4073,8 +4048,8 @@ R_API void r_core_visual_title(RCore *core, int color) { char *address = (core->print->wide_offsets && core->dbg->bits & R_SYS_BITS_64) ? r_str_newf ("0x%016"PFMT64x, core->offset) : r_str_newf ("0x%08"PFMT64x, core->offset); - if (__ime) { - const char *text = textedit_mode? "EDITOR MODE": "INSERT MODE"; + if (core->visual.ime) { + const char *text = core->visual.textedit_mode? "EDITOR MODE": "INSERT MODE"; title = r_str_newf ("[%s + %d> * %s * (press ESC to leave, TAB to toggle mode)\n", address, core->print->cur, text); } else { @@ -4091,18 +4066,18 @@ R_API void r_core_visual_title(RCore *core, int color) { if (core->print->ocur == -1) { title = r_str_newf ("[%s *0x%08"PFMT64x" %s%d ($$+0x%x)]> %s %s\n", address, core->offset + core->print->cur, - pm, currentFormat, core->print->cur, + pm, core->visual.currentFormat, core->print->cur, bar, pos); } else { title = r_str_newf ("[%s 0x%08"PFMT64x" %s%d [0x%x..0x%x] %d]> %s %s\n", address, core->offset + core->print->cur, - pm, currentFormat, core->print->ocur, core->print->cur, + pm, core->visual.currentFormat, core->print->ocur, core->print->cur, R_ABS (core->print->cur - core->print->ocur) + 1, bar, pos); } } else { title = r_str_newf ("[%s %s%d %s%d %s]> %s %s\n", - address, pm, currentFormat, pcs, core->blocksize, filename, bar, pos); + address, pm, core->visual.currentFormat, pcs, core->blocksize, filename, bar, pos); } } const int tabsCount = __core_visual_tab_count (core); @@ -4322,7 +4297,6 @@ static void show_cursor(RCore *core) { static void visual_refresh(RCore *core) { r_return_if_fail (core); - static R_TH_LOCAL ut64 oseek = UT64_MAX; char *cmd_str = NULL; r_print_set_cursor (core->print, core->print->cur_enabled, core->print->ocur, core->print->cur); core->cons->blankline = true; @@ -4330,7 +4304,7 @@ static void visual_refresh(RCore *core) { int w = visual_responsive (core); - if (autoblocksize) { + if (core->visual.autoblocksize) { r_cons_gotoxy (0, 0); } else { r_cons_clear (); @@ -4357,17 +4331,17 @@ static void visual_refresh(RCore *core) { // do not show column contents } else { r_cons_printf ("[cmd.cprompt=%s]\n", vi); - if (oseek != UT64_MAX) { - r_core_seek (core, oseek, true); + if (core->visual.oseek != UT64_MAX) { + r_core_seek (core, core->visual.oseek, true); } r_core_cmd0 (core, vi); r_cons_column (split_w); if (r_str_startswith (vi, "p=") && core->print->cur_enabled) { - oseek = core->offset; + core->visual.oseek = core->offset; core->print->cur_enabled = false; r_core_seek (core, core->num->value, true); } else { - oseek = UT64_MAX; + core->visual.oseek = UT64_MAX; } } } @@ -4381,7 +4355,7 @@ static void visual_refresh(RCore *core) { if (R_STR_ISNOTEMPTY (vi)) { r_core_cmd0 (core, vi); } - r_core_visual_title (core, color); + r_core_visual_title (core, core->visual.color); const char *vcmd = r_config_get (core->config, "cmd.visual"); if (R_STR_ISNOTEMPTY (vcmd)) { // disable screen bounds when it's a user-defined command @@ -4389,7 +4363,7 @@ static void visual_refresh(RCore *core) { core->print->screen_bounds = 0; cmd_str = strdup (vcmd); } else { - if (splitView) { + if (core->visual.splitView) { const char *pxw = NULL; int h = r_num_get (core->num, "$r"); int size = (h * 16) / 2; @@ -4406,11 +4380,11 @@ static void visual_refresh(RCore *core) { cmd_str = r_str_newf ( "?t0;%s %d @ %"PFMT64d";cl;" "?t1;%s %d @ %"PFMT64d";", - pxw, size, splitPtr, + pxw, size, core->visual.splitPtr, pxw, size, core->offset); } else { core->print->screen_bounds = 1LL; - cmd_str = strdup ((zoom ? "pz" : __core_visual_print_command (core))); + cmd_str = strdup ((core->visual.zoom ? "pz" : __core_visual_print_command (core))); } } if (R_STR_ISNOTEMPTY (cmd_str)) { @@ -4423,7 +4397,7 @@ static void visual_refresh(RCore *core) { } free (cmd_str); core->print->cur_enabled = ce; - blocksize = core->num->value? core->num->value: core->blocksize; + core->visual.blocksize = core->num->value? core->num->value: core->blocksize; core->cons->context->noflush = false; RConsMark *mark = r_cons_mark_at (0, "cursor"); @@ -4451,7 +4425,7 @@ static void visual_refresh(RCore *core) { core->curtab = 0; // which command are we focusing //core->seltab = 0; // user selected tab - if (snowMode) { + if (core->visual.snowMode) { printSnow (core); } if (r_config_get_i (core->config, "scr.scrollbar")) { @@ -4565,7 +4539,7 @@ R_API int r_core_visual(RCore *core, const char *input) { input[0], 0 }; - splitPtr = UT64_MAX; + core->visual.splitPtr = UT64_MAX; if (r_cons_get_size (&ch) < 1 || ch < 1) { R_LOG_ERROR ("Cannot create Visual context. Use scr.fix_{columns|rows}"); @@ -4574,7 +4548,7 @@ R_API int r_core_visual(RCore *core, const char *input) { int ovtmode = r_config_get_i (core->config, "scr.vtmode"); r_config_set_i (core->config, "scr.vtmode", 2); - obs = core->blocksize; + core->visual.obs = core->blocksize; //r_cons_set_cup (true); if (strchr (input, '?')) { // show V? help message, disables oneliner to open visual help @@ -4604,7 +4578,6 @@ R_API int r_core_visual(RCore *core, const char *input) { teefile = r_cons_singleton ()->teefile; r_cons_singleton ()->teefile = ""; - static R_TH_LOCAL char debugstr[512]; core->print->flags |= R_PRINT_FLAGS_ADDRMOD; do { dodo: @@ -4630,17 +4603,17 @@ dodo: } if (R_STR_ISNOTEMPTY (cmdvhex)) { - snprintf (debugstr, sizeof (debugstr), + snprintf (core->visual.debugstr, sizeof (core->visual.debugstr), "?t0;f tmp;sr %s;%s;?t1;%s;%s?t1;" "ss tmp;f-tmp;pd $r", reg, cmdvhex, ref? "drr": "dr=", have_flags?"drcq;": ""); - debugstr[sizeof (debugstr) - 1] = 0; + core->visual.debugstr[sizeof (core->visual.debugstr) - 1] = 0; } else { const bool cfg_debug = r_config_get_b (core->config, "cfg.debug"); const char *pxw = stackPrintCommand (core); const char sign = (delta < 0)? '+': '-'; const int absdelta = R_ABS (delta); - snprintf (debugstr, sizeof (debugstr), + snprintf (core->visual.debugstr, sizeof (core->visual.debugstr), "%s?t0;f tmp;sr %s;%s %d@$$%c%d;" "?t1;%s%s;" "?t1;ss tmp;f-tmp;afal;pd $r", @@ -4649,7 +4622,7 @@ dodo: have_flags? "drcq;": "", ref? "drr": "dr="); } - printfmtSingle[2] = debugstr; + printfmtSingle[2] = core->visual.debugstr; } #endif r_cons_show_cursor (false); @@ -4658,8 +4631,8 @@ dodo: core->cons->event_data = core; core->cons->event_resize = (RConsEvent) visual_refresh_oneshot; flags = core->print->flags; - color = r_config_get_i (core->config, "scr.color"); - if (color) { + core->visual.color = r_config_get_i (core->config, "scr.color"); + if (core->visual.color) { flags |= R_PRINT_FLAGS_COLOR; } flags |= R_PRINT_FLAGS_ADDRMOD | R_PRINT_FLAGS_HEADER; @@ -4691,7 +4664,7 @@ dodo: goto dodo; } if (!skip) { - if (snowMode) { + if (core->visual.snowMode) { ch = r_cons_readchar_timeout (300); if (ch == -1) { skip = 1; @@ -4789,13 +4762,13 @@ dodo: } while (skip || (*arg && r_core_visual_cmd (core, arg))); r_cons_enable_mouse (false); - if (color) { + if (core->visual.color) { r_cons_print (Color_RESET); } - r_config_set_i (core->config, "scr.color", color); + r_config_set_i (core->config, "scr.color", core->visual.color); core->print->cur_enabled = false; - if (autoblocksize) { - r_core_block_size (core, obs); + if (core->visual.autoblocksize) { + r_core_block_size (core, core->visual.obs); } r_cons_singleton ()->teefile = teefile; r_cons_set_cup (false); diff --git a/libr/core/visual_tabs.inc.c b/libr/core/visual_tabs.inc.c index 398aca393b..494e9a9e26 100644 --- a/libr/core/visual_tabs.inc.c +++ b/libr/core/visual_tabs.inc.c @@ -65,14 +65,14 @@ static void visual_tabset(RCore *core, RCoreVisualTab *tab) { core->print->cur_enabled = tab->cur_enabled; core->print->cur = tab->cur; core->print->ocur = tab->ocur; - disMode = tab->disMode; - hexMode = tab->hexMode; - printMode = tab->printMode; - current3format = tab->current3format; - current4format = tab->current4format; - current5format = tab->current5format; - r_core_visual_applyDisMode (core, disMode); - r_core_visual_applyHexMode (core, hexMode); + core->visual.disMode = tab->disMode; + core->visual.hexMode = tab->hexMode; + core->visual.printMode = tab->printMode; + core->visual.current3format = tab->current3format; + core->visual.current4format = tab->current4format; + core->visual.current5format = tab->current5format; + r_core_visual_applyDisMode (core, core->visual.disMode); + r_core_visual_applyHexMode (core, core->visual.hexMode); r_config_set_i (core->config, "asm.offset", tab->asm_offset); r_config_set_i (core->config, "asm.instr", tab->asm_instr); r_config_set_i (core->config, "asm.bytes", tab->asm_bytes); @@ -80,10 +80,10 @@ static void visual_tabset(RCore *core, RCoreVisualTab *tab) { r_config_set_i (core->config, "asm.cmt.col", tab->asm_cmt_col); r_config_set_i (core->config, "hex.cols", tab->cols); r_config_set_b (core->config, "scr.dumpcols", tab->dumpCols); - printfmtSingle[0] = printHexFormats[R_ABS(hexMode) % PRINT_HEX_FORMATS]; - printfmtSingle[2] = print3Formats[R_ABS(current3format) % PRINT_3_FORMATS]; - printfmtSingle[3] = print4Formats[R_ABS(current4format) % PRINT_4_FORMATS]; - printfmtSingle[4] = print5Formats[R_ABS(current5format) % PRINT_5_FORMATS]; + printfmtSingle[0] = printHexFormats[R_ABS(core->visual.hexMode) % PRINT_HEX_FORMATS]; + printfmtSingle[2] = print3Formats[R_ABS(core->visual.current3format) % PRINT_3_FORMATS]; + printfmtSingle[3] = print4Formats[R_ABS(core->visual.current4format) % PRINT_4_FORMATS]; + printfmtSingle[4] = print5Formats[R_ABS(core->visual.current5format) % PRINT_5_FORMATS]; } static void visual_tabget(RCore *core, RCoreVisualTab *tab) { @@ -101,12 +101,12 @@ static void visual_tabget(RCore *core, RCoreVisualTab *tab) { tab->ocur = core->print->ocur; tab->cols = r_config_get_i (core->config, "hex.cols"); tab->dumpCols = r_config_get_b (core->config, "scr.dumpcols"); - tab->disMode = disMode; - tab->hexMode = hexMode; - tab->printMode = printMode; - tab->current3format = current3format; - tab->current4format = current4format; - tab->current5format = current5format; + tab->disMode = core->visual.disMode; + tab->hexMode = core->visual.hexMode; + tab->printMode = core->visual.printMode; + tab->current3format = core->visual.current3format; + tab->current4format = core->visual.current4format; + tab->current5format = core->visual.current5format; // tab->cols = core->print->cols; } diff --git a/libr/debug/debug.c b/libr/debug/debug.c index 7f2761be90..8ba0c61db4 100644 --- a/libr/debug/debug.c +++ b/libr/debug/debug.c @@ -1718,7 +1718,7 @@ R_API ut64 r_debug_get_baddr(RDebug *dbg, const char *file) { if (!dbg || !dbg->iob.io || !dbg->iob.io->desc) { return 0LL; } - if (!strcmp (dbg->iob.io->desc->plugin->name, "gdb")) { //this is very bad + if (!strcmp (dbg->iob.io->desc->plugin->meta.name, "gdb")) { // this is very bad // Tell gdb that we want baddr, not full mem map dbg->iob.system (dbg->iob.io, "baddr"); } diff --git a/libr/debug/p/debug_bf.c b/libr/debug/p/debug_bf.c index bed0b691e9..c6248ce2ab 100644 --- a/libr/debug/p/debug_bf.c +++ b/libr/debug/p/debug_bf.c @@ -31,8 +31,8 @@ typedef struct plugin_data_t { static bool is_io_bf(RDebug *dbg) { RIODesc *d = dbg->iob.io->desc; - if (d && d->plugin && d->plugin->name) { - if (!strcmp ("bfdbg", d->plugin->name)) { + if (d && d->plugin && d->plugin->meta.name) { + if (!strcmp ("bfdbg", d->plugin->meta.name)) { return true; } } diff --git a/libr/debug/p/debug_bochs.c b/libr/debug/p/debug_bochs.c index 7ee1cdce1e..8675b013e6 100644 --- a/libr/debug/p/debug_bochs.c +++ b/libr/debug/p/debug_bochs.c @@ -21,8 +21,8 @@ typedef struct plugin_data_t { static bool is_bochs(RDebug *dbg) { if (dbg && dbg->iob.io) { RIODesc *d = dbg->iob.io->desc; - if (d && d->plugin && d->plugin->name) { - if (!strcmp ("bochs", d->plugin->name)) { + if (d && d->plugin && d->plugin->meta.name) { + if (!strcmp ("bochs", d->plugin->meta.name)) { return true; } } @@ -365,8 +365,8 @@ static bool r_debug_bochs_attach(RDebug *dbg, int pid) { RIODesc *d = dbg->iob.io->desc; //eprintf ("bochs_attach:\n"); dbg->swstep = false; - if (d && d->plugin && d->plugin->name && d->data) { - if (!strcmp ("bochs", d->plugin->name)) { + if (d && d->plugin && d->plugin->meta.name && d->data) { + if (!strcmp ("bochs", d->plugin->meta.name)) { RIOBochs *g = d->data; //int arch = r_sys_arch_id (dbg->arch); // int bits = dbg->anal->bits; diff --git a/libr/debug/p/debug_gdb.c b/libr/debug/p/debug_gdb.c index f3ce973db9..129f1c77cf 100644 --- a/libr/debug/p/debug_gdb.c +++ b/libr/debug/p/debug_gdb.c @@ -443,8 +443,8 @@ static bool r_debug_gdb_attach(RDebug *dbg, int pid) { RIODesc *d = dbg->iob.io->desc; // TODO: the core must update the dbg.swstep config var when this var is changed dbg->swstep = false; - if (d && d->plugin && d->plugin->name && d->data) { - if (!strcmp ("gdb", d->plugin->name)) { + if (d && d->plugin && d->plugin->meta.name && d->data) { + if (!strcmp ("gdb", d->plugin->meta.name)) { RIOGdb *g = d->data; pd->origriogdb = (RIOGdb **)&d->data; //TODO bit of a hack, please improve pd->support_sw_bp = UNKNOWN; diff --git a/libr/debug/p/debug_qnx.c b/libr/debug/p/debug_qnx.c index e92a428ea5..3a5e44e961 100644 --- a/libr/debug/p/debug_qnx.c +++ b/libr/debug/p/debug_qnx.c @@ -210,8 +210,8 @@ static bool r_debug_qnx_attach(RDebug *dbg, int pid) { return false; } - if (d && d->plugin && d->plugin->name && d->data) { - if (!strcmp ("qnx", d->plugin->name)) { + if (d && d->plugin && d->plugin->meta.name && d->data) { + if (!strcmp ("qnx", d->plugin->meta.name)) { RIOQnx *g = d->data; int arch = r_sys_arch_id (dbg->arch); int bits = dbg->anal->config->bits; diff --git a/libr/debug/p/debug_rap.c b/libr/debug/p/debug_rap.c index 7465b8a17d..7b683f6671 100644 --- a/libr/debug/p/debug_rap.c +++ b/libr/debug/p/debug_rap.c @@ -31,8 +31,8 @@ static RDebugReasonType __rap_wait(RDebug *dbg, int pid) { static bool __rap_attach(RDebug *dbg, int pid) { // XXX TODO PID must be a socket here !!1 RIODesc *d = dbg->iob.io->desc; - if (d && d->plugin && d->plugin->name) { - if (!strcmp ("rap", d->plugin->name)) { + if (d && d->plugin && d->plugin->meta.name) { + if (!strcmp ("rap", d->plugin->meta.name)) { eprintf ("SUCCESS: rap attach with inferior rap rio worked\n"); } else { R_LOG_ERROR ("Underlying IO descriptor is not a rap one"); diff --git a/libr/debug/p/debug_winkd.c b/libr/debug/p/debug_winkd.c index b71cf8b35a..62fbdaafa1 100644 --- a/libr/debug/p/debug_winkd.c +++ b/libr/debug/p/debug_winkd.c @@ -108,10 +108,10 @@ static RDebugReasonType r_debug_winkd_wait(RDebug *dbg, int pid) { static bool r_debug_winkd_attach(RDebug *dbg, int pid) { RIODesc *desc = dbg->iob.io->desc; - if (!desc || !desc->plugin || !desc->plugin->name || !desc->data) { + if (!desc || !desc->plugin || !desc->plugin->meta.name || !desc->data) { return false; } - if (strncmp (desc->plugin->name, "winkd", 6)) { + if (r_str_startswith (desc->plugin->meta.name, "winkd")) { return false; } if (dbg->arch && strcmp (dbg->arch, "x86")) { diff --git a/libr/egg/egg.c b/libr/egg/egg.c index d61d7c3944..6cb5a3fdb9 100644 --- a/libr/egg/egg.c +++ b/libr/egg/egg.c @@ -102,7 +102,7 @@ R_API bool r_egg_plugin_add(REgg *a, REggPlugin *foo) { } R_API bool r_egg_plugin_remove(REgg *a, REggPlugin *plugin) { - // R2_590 TODO + // XXX TODO return true; } diff --git a/libr/esil/esil_trace.c b/libr/esil/esil_trace.c index 7e0e6f1540..3622233905 100644 --- a/libr/esil/esil_trace.c +++ b/libr/esil/esil_trace.c @@ -9,9 +9,6 @@ #define CMP_REG_CHANGE(x, y) ((x) - ((REsilRegChange *)y)->idx) #define CMP_MEM_CHANGE(x, y) ((x) - ((REsilMemChange *)y)->idx) -static R_TH_LOCAL int ocbs_set = false; -static R_TH_LOCAL REsilCallbacks ocbs = {0}; - static void htup_vector_free(HtUPKv *kv) { if (kv) { r_vector_free (kv->value); @@ -124,10 +121,10 @@ static bool trace_hook_reg_read(REsil *esil, const char *name, ut64 *res, int *s // eprintf ("Register not found in profile\n"); return false; } - if (ocbs.hook_reg_read) { + if (esil->ocb.hook_reg_read) { REsilCallbacks cbs = esil->cb; - esil->cb = ocbs; - ret = ocbs.hook_reg_read (esil, name, res, size); + esil->cb = esil->ocb; + ret = esil->ocb.hook_reg_read (esil, name, res, size); esil->cb = cbs; } if (!ret && esil->cb.reg_read) { @@ -152,10 +149,10 @@ static bool trace_hook_reg_write(REsil *esil, const char *name, ut64 *val) { sdb_array_add (DB, KEY ("reg.write"), name, 0); sdb_num_set (DB, KEYREG ("reg.write", name), *val, 0); add_reg_change (esil->trace, esil->trace->idx + 1, ri, *val); - if (ocbs.hook_reg_write) { + if (esil->ocb.hook_reg_write) { REsilCallbacks cbs = esil->cb; - esil->cb = ocbs; - ret = ocbs.hook_reg_write (esil, name, val); + esil->cb = esil->ocb; + ret = esil->ocb.hook_reg_write (esil, name, val); esil->cb = cbs; } r_unref (ri); @@ -176,10 +173,10 @@ static bool trace_hook_mem_read(REsil *esil, ut64 addr, ut8 *buf, int len) { //eprintf ("[ESIL] MEM READ 0x%08"PFMT64x" %s\n", addr, hexbuf); free (hexbuf); - if (ocbs.hook_mem_read) { + if (esil->ocb.hook_mem_read) { REsilCallbacks cbs = esil->cb; - esil->cb = ocbs; - ret = ocbs.hook_mem_read (esil, addr, buf, len); + esil->cb = esil->ocb; + ret = esil->ocb.hook_mem_read (esil, addr, buf, len); esil->cb = cbs; } return ret; @@ -201,10 +198,10 @@ static bool trace_hook_mem_write(REsil *esil, ut64 addr, const ut8 *buf, int len add_mem_change (esil->trace, esil->trace->idx + 1, addr + i, buf[i]); } - if (ocbs.hook_mem_write) { + if (esil->ocb.hook_mem_write) { REsilCallbacks cbs = esil->cb; - esil->cb = ocbs; - ret = ocbs.hook_mem_write (esil, addr, buf, len); + esil->cb = esil->ocb; + ret = esil->ocb.hook_mem_write (esil, addr, buf, len); esil->cb = cbs; } return ret != 0; @@ -232,11 +229,11 @@ R_API void r_esil_trace_op(REsil *esil, RAnalOp *op) { return; } /* save old callbacks */ - if (ocbs_set) { + if (esil->ocb_set) { R_LOG_WARN ("r_esil_trace_op: Cannot call recursively"); } - ocbs = esil->cb; - ocbs_set = true; + esil->ocb = esil->cb; + esil->ocb_set = true; sdb_num_set (DB, "idx", esil->trace->idx, 0); sdb_num_set (DB, KEY ("addr"), op->addr, 0); RRegItem *pc_ri = r_reg_get (esil->anal->reg, "PC", -1); @@ -258,8 +255,8 @@ R_API void r_esil_trace_op(REsil *esil, RAnalOp *op) { r_esil_stack_free (esil); esil->verbose = esil_verbose; /* restore hooks */ - esil->cb = ocbs; - ocbs_set = false; + esil->cb = esil->ocb; + esil->ocb_set = false; /* increment idx */ esil->trace->idx++; esil->trace->end_idx++; diff --git a/libr/fs/fs.c b/libr/fs/fs.c index 4070bee6be..91149cc5df 100644 --- a/libr/fs/fs.c +++ b/libr/fs/fs.c @@ -110,7 +110,7 @@ R_API bool r_fs_plugin_add(RFS* fs, RFSPlugin* p) { } R_API bool r_fs_plugin_remove(RFS *fs, RFSPlugin *p) { - // R2_590 TODO + // XXX TODO return true; } diff --git a/libr/include/cwisstable.h b/libr/include/cwisstable.h deleted file mode 100644 index 66a842c85f..0000000000 --- a/libr/include/cwisstable.h +++ /dev/null @@ -1,2910 +0,0 @@ -// Copyright 2022 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// THIS IS A GENERATED FILE! DO NOT EDIT DIRECTLY! -// Generated using unify.py, by concatenating, in order: -// #include "cwisstable/internal/base.h" -// #include "cwisstable/internal/bits.h" -// #include "cwisstable/internal/control_byte.h" -// #include "cwisstable/internal/capacity.h" -// #include "cwisstable/internal/probe.h" -// #include "cwisstable/internal/absl_hash.h" -// #include "cwisstable/hash.h" -// #include "cwisstable/policy.h" -// #include "cwisstable/internal/raw_table.h" -// #include "cwisstable/declare.h" - -#ifndef CWISSTABLE_H_ -#define CWISSTABLE_H_ - -#include <assert.h> -#include <limits.h> -#include <stdalign.h> -#include <stdbool.h> -#include <stddef.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -/// cwisstable/internal/base.h ///////////////////////////////////////////////// -/// Feature detection and basic helper macros. - -/// C++11 compatibility macros. -/// -/// Atomic support, due to incompatibilities between C++ and C11 atomic syntax. -/// - `CWISS_ATOMIC_T(Type)` names an atomic version of `Type`. We must use this -/// instead of `_Atomic(Type)` to name an atomic type. -/// - `CWISS_ATOMIC_INC(value)` will atomically increment `value` without -/// performing synchronization. This is used as a weak entropy source -/// elsewhere. -/// -/// `extern "C"` support via `CWISS_END_EXTERN` and `CWISS_END_EXTERN`, -/// which open and close an `extern "C"` block in C++ mode. -#ifdef __cplusplus -#include <atomic> - -#define CWISS_BEGIN_EXTERN extern "C" { -#define CWISS_END_EXTERN } -#else -#if _MSC_VER -// #include "msvc_stdatomic.h" -#else -#if __STDC_VERSION__ >= 201112L -#include <stdatomic.h> -#else -#include "gcc_stdatomic.h" -#endif -#endif - -#define CWISS_BEGIN_EXTERN -#define CWISS_END_EXTERN -#endif - -/// Compiler detection macros. -/// -/// The following macros are defined: -/// - `CWISS_IS_CLANG` detects Clang. -/// - `CWISS_IS_GCC` detects GCC (and *not* Clang pretending to be GCC). -/// - `CWISS_IS_MSVC` detects MSCV (and *not* clang-cl). -/// - `CWISS_IS_GCCISH` detects GCC and GCC-mode Clang. -/// - `CWISS_IS_MSVCISH` detects MSVC and clang-cl. -#ifdef __clang__ -#define CWISS_IS_CLANG 1 -#else -#define CWISS_IS_CLANG 0 -#endif -#if defined(__GNUC__) -#define CWISS_IS_GCCISH 1 -#else -#define CWISS_IS_GCCISH 0 -#endif -#if defined(_MSC_VER) -#define CWISS_IS_MSVCISH 1 -#else -#define CWISS_IS_MSVCISH 0 -#endif -#define CWISS_IS_GCC (CWISS_IS_GCCISH && !CWISS_IS_CLANG) -#define CWISS_IS_MSVC (CWISS_IS_MSVCISH && !CWISS_IS_CLANG) - -#define CWISS_PRAGMA(pragma_) _Pragma(#pragma_) - -#if CWISS_IS_GCCISH -#define CWISS_GCC_PUSH CWISS_PRAGMA(GCC diagnostic push) -#define CWISS_GCC_ALLOW(w_) CWISS_PRAGMA(GCC diagnostic ignored w_) -#define CWISS_GCC_POP CWISS_PRAGMA(GCC diagnostic pop) -#else -#define CWISS_GCC_PUSH -#define CWISS_GCC_ALLOW(w_) -#define CWISS_GCC_POP -#endif - -/// Atomic support, due to incompatibilities between C++ and C11 atomic syntax. -/// - `CWISS_ATOMIC_T(Type)` names an atomic version of `Type`. We must use this -/// instead of `_Atomic(Type)` to name an atomic type. -/// - `CWISS_ATOMIC_INC(value)` will atomically increment `value` without -/// performing synchronization. This is used as a weak entropy source -/// elsewhere. -/// -/// MSVC, of course, being that it does not support _Atomic in C mode, forces us -/// into `volatile`. This is *wrong*, but MSVC certainly won't miscompile it any -/// worse than it would a relaxed atomic. It doesn't matter for our use of -/// atomics. -#ifdef __cplusplus -#include <atomic> -#define CWISS_ATOMIC_T(Type_) volatile std::atomic<Type_> -#define CWISS_ATOMIC_INC(val_) (val_).fetch_add(1, std::memory_order_relaxed) -#elif CWISS_IS_MSVC -#define CWISS_ATOMIC_T(Type_) volatile Type_ -#define CWISS_ATOMIC_INC(val_) (val_ += 1) -#else -#define CWISS_ATOMIC_T(Type_) volatile _Atomic(Type_) -#define CWISS_ATOMIC_INC(val_) \ - atomic_fetch_add_explicit(&(val_), 1, memory_order_relaxed) -#endif - -/// Warning control around `CWISS` symbol definitions. These macros will -/// disable certain false-positive warnings that `CWISS` definitions tend to -/// emit. -#define CWISS_BEGIN \ - CWISS_GCC_PUSH \ - CWISS_GCC_ALLOW("-Wunused-function") \ - CWISS_GCC_ALLOW("-Wunused-parameter") \ - CWISS_GCC_ALLOW("-Wcast-qual") \ - CWISS_GCC_ALLOW("-Wmissing-field-initializers") -#define CWISS_END CWISS_GCC_POP - -/// `CWISS_HAVE_SSE2` is nonzero if we have SSE2 support. -/// -/// `-DCWISS_HAVE_SSE2` can be used to override it; it is otherwise detected -/// via the usual non-portable feature-detection macros. -#ifndef CWISS_HAVE_SSE2 -#if defined(__SSE2__) || \ - (CWISS_IS_MSVCISH && \ - (defined(_M_X64) || (defined(_M_IX86) && _M_IX86_FP >= 2))) -#define CWISS_HAVE_SSE2 1 -#else -#define CWISS_HAVE_SSE2 0 -#endif -#endif - -/// `CWISS_HAVE_SSSE2` is nonzero if we have SSSE2 support. -/// -/// `-DCWISS_HAVE_SSSE2` can be used to override it; it is otherwise detected -/// via the usual non-portable feature-detection macros. -#ifndef CWISS_HAVE_SSSE3 -#ifdef __SSSE3__ -#define CWISS_HAVE_SSSE3 1 -#else -#define CWISS_HAVE_SSSE3 0 -#endif -#endif - -#if CWISS_HAVE_SSE2 -#include <emmintrin.h> -#endif - -#if CWISS_HAVE_SSSE3 -#if !CWISS_HAVE_SSE2 -#error "Bad configuration: SSSE3 implies SSE2!" -#endif -#include <tmmintrin.h> -#endif - -/// `CWISS_HAVE_MUL128` is nonzero if there is compiler-specific -/// intrinsics for 128-bit multiplication. -/// -/// `-DCWISS_HAVE_MUL128=0` can be used to explicitly fall back onto the pure -/// C implementation. -#ifndef DCWISS_HAVE_MUL128 -#if defined(__SIZEOF_INT128__) && \ - ((CWISS_IS_CLANG && !CWISS_IS_MSVC) || CWISS_IS_GCC) -#define DCWISS_HAVE_MUL128 1 -#else -#define DCWISS_HAVE_MUL128 0 -#endif -#endif - -/// `CWISS_ALIGN` is a cross-platform `alignas()`: specifically, MSVC doesn't -/// quite believe in it. -#if CWISS_IS_MSVC -#define CWISS_alignas(align_) __declspec(align(align_)) -#define alignof __alignof - -#else -#include <stdalign.h> -#define CWISS_alignas(align_) alignas(align_) -#endif - -/// `CWISS_HAVE_BUILTIN` will, in Clang, detect whether a Clang language -/// extension is enabled. -/// -/// See https://clang.llvm.org/docs/LanguageExtensions.html. -#ifdef __has_builtin -#define CWISS_HAVE_CLANG_BUILTIN(x_) __has_builtin(x_) -#else -#define CWISS_HAVE_CLANG_BUILTIN(x_) 0 -#endif - -/// `CWISS_HAVE_GCC_ATTRIBUTE` detects if a particular `__attribute__(())` is -/// present. -/// -/// GCC: https://gcc.gnu.org/gcc-5/changes.html -/// Clang: https://clang.llvm.org/docs/LanguageExtensions.html -#ifdef __has_attribute -#define CWISS_HAVE_GCC_ATTRIBUTE(x_) __has_attribute(x_) -#else -#define CWISS_HAVE_GCC_ATTRIBUTE(x_) 0 -#endif - -#ifdef __has_feature -#define CWISS_HAVE_FEATURE(x_) __has_feature(x_) -#else -#define CWISS_HAVE_FEATURE(x_) 0 -#endif - -/// `CWISS_THREAD_LOCAL` expands to the appropriate TLS annotation, if one is -/// available. -#if CWISS_IS_GCCISH -#define CWISS_THREAD_LOCAL __thread -#elif CWISS_IS_MSVC -#define CWISS_THREAD_LOCAL -#endif - -/// `CWISS_CHECK` will evaluate `cond_` and, if false, print an error and crash -/// the program. -/// -/// This is like `assert()` but unconditional. -#define CWISS_CHECK(cond_, ...) \ - do { \ - if (cond_) break; \ - fprintf(stderr, "CWISS_CHECK failed at %s:%d\n", __FILE__, __LINE__); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ - fflush(stderr); \ - abort(); \ - } while (false) - -/// `CWISS_DCHECK` is like `CWISS_CHECK` but is disabled by `NDEBUG`. -#ifdef NDEBUG -#define CWISS_DCHECK(cond_, ...) ((void)0) -#else -#define CWISS_DCHECK CWISS_CHECK -#endif - -/// `CWISS_LIKELY` and `CWISS_UNLIKELY` provide a prediction hint to the -/// compiler to encourage branches to be scheduled in a particular way. -#if CWISS_HAVE_CLANG_BUILTIN(__builtin_expect) || CWISS_IS_GCC -#define CWISS_LIKELY(cond_) (__builtin_expect(false || (cond_), true)) -#define CWISS_UNLIKELY(cond_) (__builtin_expect(false || (cond_), false)) -#else -#define CWISS_LIKELY(cond_) (cond_) -#define CWISS_UNLIKELY(cond_) (cond_) -#endif - -/// `CWISS_INLINE_ALWAYS` informs the compiler that it should try really hard -/// to inline a function. -#if CWISS_HAVE_GCC_ATTRIBUTE(always_inline) -#define CWISS_INLINE_ALWAYS __attribute__((always_inline)) -#else -#define CWISS_INLINE_ALWAYS -#endif - -/// `CWISS_INLINE_NEVER` informs the compiler that it should avoid inlining a -/// function. -#if CWISS_HAVE_GCC_ATTRIBUTE(noinline) -#define CWISS_INLINE_NEVER __attribute__((noinline)) -#else -#define CWISS_INLINE_NEVER -#endif - -/// `CWISS_PREFETCH` informs the compiler that it should issue prefetch -/// instructions. -#if CWISS_HAVE_CLANG_BUILTIN(__builtin_prefetch) || CWISS_IS_GCC -#define CWISS_HAVE_PREFETCH 1 -#define CWISS_PREFETCH(addr_, locality_) \ - __builtin_prefetch(addr_, 0, locality_); -#else -#define CWISS_HAVE_PREFETCH 0 -#define CWISS_PREFETCH(addr_, locality_) ((void)0) -#endif - -/// `CWISS_HAVE_ASAN` and `CWISS_HAVE_MSAN` detect the presence of some of the -/// sanitizers. -#if defined(__SANITIZE_ADDRESS__) || CWISS_HAVE_FEATURE(address_sanitizer) -#define CWISS_HAVE_ASAN 1 -#else -#define CWISS_HAVE_ASAN 0 -#endif -#if defined(__SANITIZE_MEMORY__) || \ - (CWISS_HAVE_FEATURE(memory_sanitizer) && !defined(__native_client__)) -#define CWISS_HAVE_MSAN 1 -#else -#define CWISS_HAVE_MSAN 0 -#endif - -#if CWISS_HAVE_ASAN -#include <sanitizer/asan_interface.h> -#endif - -#if CWISS_HAVE_MSAN -#include <sanitizer/msan_interface.h> -#endif - -CWISS_BEGIN -CWISS_BEGIN_EXTERN -/// Informs a sanitizer runtime that this memory is invalid. -static inline void CWISS_PoisonMemory(const void* m, size_t s) { -#if CWISS_HAVE_ASAN - ASAN_POISON_MEMORY_REGION(m, s); -#endif -#if CWISS_HAVE_MSAN - __msan_poison(m, s); -#endif - (void)m; - (void)s; -} - -/// Informs a sanitizer runtime that this memory is no longer invalid. -static inline void CWISS_UnpoisonMemory(const void* m, size_t s) { -#if CWISS_HAVE_ASAN - ASAN_UNPOISON_MEMORY_REGION(m, s); -#endif -#if CWISS_HAVE_MSAN - __msan_unpoison(m, s); -#endif - (void)m; - (void)s; -} -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/base.h ///////////////////////////////////////////////// - -/// cwisstable/internal/bits.h ///////////////////////////////////////////////// -/// Bit manipulation utilities. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// Counts the number of trailing zeroes in the binary representation of `x`. -CWISS_INLINE_ALWAYS -static inline uint32_t CWISS_TrailingZeroes64(uint64_t x) { -#if CWISS_HAVE_CLANG_BUILTIN(__builtin_ctzll) || CWISS_IS_GCC - static_assert(sizeof(unsigned long long) == sizeof(x), - "__builtin_ctzll does not take 64-bit arg"); - return __builtin_ctzll(x); -#elif CWISS_IS_MSVC - unsigned long result = 0; -#if defined(_M_X64) || defined(_M_ARM64) - _BitScanForward64(&result, x); -#else - if (((uint32_t)x) == 0) { - _BitScanForward(&result, (unsigned long)(x >> 32)); - return result + 32; - } - _BitScanForward(&result, (unsigned long)(x)); -#endif - return result; -#else - uint32_t c = 63; - x &= ~x + 1; - if (x & 0x00000000FFFFFFFF) c -= 32; - if (x & 0x0000FFFF0000FFFF) c -= 16; - if (x & 0x00FF00FF00FF00FF) c -= 8; - if (x & 0x0F0F0F0F0F0F0F0F) c -= 4; - if (x & 0x3333333333333333) c -= 2; - if (x & 0x5555555555555555) c -= 1; - return c; -#endif -} - -/// Counts the number of leading zeroes in the binary representation of `x`. -CWISS_INLINE_ALWAYS -static inline uint32_t CWISS_LeadingZeroes64(uint64_t x) { -#if CWISS_HAVE_CLANG_BUILTIN(__builtin_clzll) || CWISS_IS_GCC - static_assert(sizeof(unsigned long long) == sizeof(x), - "__builtin_clzll does not take 64-bit arg"); - // Handle 0 as a special case because __builtin_clzll(0) is undefined. - return x == 0 ? 64 : __builtin_clzll(x); -#elif CWISS_IS_MSVC - unsigned long result = 0; -#if defined(_M_X64) || defined(_M_ARM64) - if (_BitScanReverse64(&result, x)) { - return 63 - result; - } -#else - if ((x >> 32) && _BitScanReverse(&result, (unsigned long)(x >> 32))) { - return 31 - result; - } - if (_BitScanReverse(&result, static_cast<unsigned long>(x))) { - return 63 - result; - } -#endif - return 64; -#else - uint32_t zeroes = 60; - if (x >> 32) { - zeroes -= 32; - x >>= 32; - } - if (x >> 16) { - zeroes -= 16; - x >>= 16; - } - if (x >> 8) { - zeroes -= 8; - x >>= 8; - } - if (x >> 4) { - zeroes -= 4; - x >>= 4; - } - return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; -#endif -} - -/// Counts the number of trailing zeroes in the binary representation of `x_` in -/// a type-generic fashion. -#define CWISS_TrailingZeros(x_) (CWISS_TrailingZeroes64(x_)) - -/// Counts the number of leading zeroes in the binary representation of `x_` in -/// a type-generic fashion. -#define CWISS_LeadingZeros(x_) \ - (CWISS_LeadingZeroes64(x_) - \ - (uint32_t)((sizeof(unsigned long long) - sizeof(x_)) * 8)) - -/// Computes the number of bits necessary to represent `x_`, i.e., the bit index -/// of the most significant one. -#define CWISS_BitWidth(x_) \ - (((uint32_t)(sizeof(x_) * 8)) - CWISS_LeadingZeros(x_)) - -#define CWISS_RotateLeft(x_, bits_) \ - (((x_) << bits_) | ((x_) >> (sizeof(x_) * 8 - bits_))) - -/// The return type of `CWISS_Mul128`. -typedef struct { - uint64_t lo, hi; -} CWISS_U128; - -/// Computes a double-width multiplication operation. -static inline CWISS_U128 CWISS_Mul128(uint64_t a, uint64_t b) { -#ifdef __SIZEOF_INT128__ - // TODO: de-intrinsics-ize this. - __uint128_t p = a; - p *= b; - return (CWISS_U128) { (uint64_t)p, (uint64_t)(p >> 64) }; -#else - /* - * https://stackoverflow.com/questions/25095741/how-can-i-multiply-64-bit-operands-and-get-128-bit-result-portably - * - * Fast yet simple grade school multiply that avoids - * 64-bit carries with the properties of multiplying by 11 - * and takes advantage of UMAAL on ARMv6 to only need 4 - * calculations. - */ - - /* First calculate all of the cross products. */ - const uint64_t lo_lo = (a & 0xFFFFFFFF) * (b & 0xFFFFFFFF); - const uint64_t hi_lo = (a >> 32) * (b & 0xFFFFFFFF); - const uint64_t lo_hi = (a & 0xFFFFFFFF) * (b >> 32); - const uint64_t hi_hi = (a >> 32) * (b >> 32); - - /* Now add the products together. These will never overflow. */ - const uint64_t cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi; - const uint64_t high = (hi_lo >> 32) + (cross >> 32) + hi_hi; - const uint64_t low = (cross << 32) | (lo_lo & 0xFFFFFFFF); - CWISS_U128 result = { .lo = low, .hi = high }; - return result; -#endif -} - -/// Loads an unaligned u32. -static inline uint32_t CWISS_Load32(const void* p) { - uint32_t v; - memcpy(&v, p, sizeof(v)); - return v; -} - -/// Loads an unaligned u64. -static inline uint64_t CWISS_Load64(const void* p) { - uint64_t v; - memcpy(&v, p, sizeof(v)); - return v; -} - -/// Reads 9 to 16 bytes from p. -static inline CWISS_U128 CWISS_Load9To16(const void* p, size_t len) { - const unsigned char* p8 = (const unsigned char*)p; - uint64_t lo = CWISS_Load64(p8); - uint64_t hi = CWISS_Load64(p8 + len - 8); - return (CWISS_U128) { lo, hi >> (128 - len * 8) }; -} - -/// Reads 4 to 8 bytes from p. -static inline uint64_t CWISS_Load4To8(const void* p, size_t len) { - const unsigned char* p8 = (const unsigned char*)p; - uint64_t lo = CWISS_Load32(p8); - uint64_t hi = CWISS_Load32(p8 + len - 4); - return lo | (hi << (len - 4) * 8); -} - -/// Reads 1 to 3 bytes from p. -static inline uint32_t CWISS_Load1To3(const void* p, size_t len) { - const unsigned char* p8 = (const unsigned char*)p; - uint32_t mem0 = p8[0]; - uint32_t mem1 = p8[len / 2]; - uint32_t mem2 = p8[len - 1]; - return (mem0 | (mem1 << (len / 2 * 8)) | (mem2 << ((len - 1) * 8))); -} - -/// A abstract bitmask, such as that emitted by a SIMD instruction. -/// -/// Specifically, this type implements a simple bitset whose representation is -/// controlled by `width` and `shift`. `width` is the number of abstract bits in -/// the bitset, while `shift` is the log-base-two of the width of an abstract -/// bit in the representation. -/// -/// For example, when `width` is 16 and `shift` is zero, this is just an -/// ordinary 16-bit bitset occupying the low 16 bits of `mask`. When `width` is -/// 8 and `shift` is 3, abstract bits are represented as the bytes `0x00` and -/// `0x80`, and it occupies all 64 bits of the bitmask. -typedef struct { - /// The mask, in the representation specified by `width` and `shift`. - uint64_t mask; - /// The number of abstract bits in the mask. - uint32_t width; - /// The log-base-two width of an abstract bit. - uint32_t shift; -} CWISS_BitMask; - -/// Returns the index of the lowest abstract bit set in `self`. -static inline uint32_t CWISS_BitMask_LowestBitSet(const CWISS_BitMask* self) { - return CWISS_TrailingZeros(self->mask) >> self->shift; -} - -/// Returns the index of the highest abstract bit set in `self`. -static inline uint32_t CWISS_BitMask_HighestBitSet(const CWISS_BitMask* self) { - return (uint32_t)(CWISS_BitWidth(self->mask) - 1) >> self->shift; -} - -/// Return the number of trailing zero abstract bits. -static inline uint32_t CWISS_BitMask_TrailingZeros(const CWISS_BitMask* self) { - return CWISS_TrailingZeros(self->mask) >> self->shift; -} - -/// Return the number of leading zero abstract bits. -static inline uint32_t CWISS_BitMask_LeadingZeros(const CWISS_BitMask* self) { - uint32_t total_significant_bits = self->width << self->shift; - uint32_t extra_bits = sizeof(self->mask) * 8 - total_significant_bits; - return (uint32_t)(CWISS_LeadingZeros(self->mask << extra_bits)) >> - self->shift; -} - -/// Iterates over the one bits in the mask. -/// -/// If the mask is empty, returns `false`; otherwise, returns the index of the -/// lowest one bit in the mask, and removes it from the set. -static inline bool CWISS_BitMask_next(CWISS_BitMask* self, uint32_t* bit) { - if (self->mask == 0) { - return false; - } - - *bit = CWISS_BitMask_LowestBitSet(self); - self->mask &= (self->mask - 1); - return true; -} - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/bits.h ///////////////////////////////////////////////// - -/// cwisstable/internal/control_byte.h ///////////////////////////////////////// -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// Control bytes and groups: the core of SwissTable optimization. -/// -/// Control bytes are bytes (collected into groups of a platform-specific size) -/// that define the state of the corresponding slot in the slot array. Group -/// manipulation is tightly optimized to be as efficient as possible. - -/// A `CWISS_ControlByte` is a single control byte, which can have one of four -/// states: empty, deleted, full (which has an associated seven-bit hash) and -/// the sentinel. They have the following bit patterns: -/// -/// ``` -/// empty: 1 0 0 0 0 0 0 0 -/// deleted: 1 1 1 1 1 1 1 0 -/// full: 0 h h h h h h h // h represents the hash bits. -/// sentinel: 1 1 1 1 1 1 1 1 -/// ``` -/// -/// These values are specifically tuned for SSE-flavored SIMD; future ports to -/// other SIMD platforms may require choosing new values. The static_asserts -/// below detail the source of these choices. -typedef int8_t CWISS_ControlByte; -#define CWISS_kEmpty (INT8_C(-128)) -#define CWISS_kDeleted (INT8_C(-2)) -#define CWISS_kSentinel (INT8_C(-1)) -// TODO: Wrap CWISS_ControlByte in a single-field struct to get strict-aliasing -// benefits. - - -/// Returns a pointer to a control byte group that can be used by empty tables. -static inline CWISS_ControlByte* CWISS_EmptyGroup(void) { - // A single block of empty control bytes for tables without any slots - // allocated. This enables removing a branch in the hot path of find(). - CWISS_alignas(16) static const CWISS_ControlByte kEmptyGroup[16] = { - CWISS_kSentinel, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - }; - - // Const must be cast away here; no uses of this function will actually write - // to it, because it is only used for empty tables. - return (CWISS_ControlByte*)&kEmptyGroup; -} - -/// Returns a hash seed. -/// -/// The seed consists of the ctrl_ pointer, which adds enough entropy to ensure -/// non-determinism of iteration order in most cases. -static inline size_t CWISS_HashSeed(const CWISS_ControlByte* ctrl) { - // The low bits of the pointer have little or no entropy because of - // alignment. We shift the pointer to try to use higher entropy bits. A - // good number seems to be 12 bits, because that aligns with page size. - return ((uintptr_t)ctrl) >> 12; -} - -/// Extracts the H1 portion of a hash: the high 57 bits mixed with a per-table -/// salt. -static inline size_t CWISS_H1(size_t hash, const CWISS_ControlByte* ctrl) { - return (hash >> 7) ^ CWISS_HashSeed(ctrl); -} - -/// Extracts the H2 portion of a hash: the low 7 bits, which can be used as -/// control byte. -typedef uint8_t CWISS_h2_t; -static inline CWISS_h2_t CWISS_H2(size_t hash) { return hash & 0x7F; } - -/// Returns whether `c` is empty. -static inline bool CWISS_IsEmpty(CWISS_ControlByte c) { - return c == CWISS_kEmpty; -} - -/// Returns whether `c` is full. -static inline bool CWISS_IsFull(CWISS_ControlByte c) { return c >= 0; } - -/// Returns whether `c` is deleted. -static inline bool CWISS_IsDeleted(CWISS_ControlByte c) { - return c == CWISS_kDeleted; -} - -/// Returns whether `c` is empty or deleted. -static inline bool CWISS_IsEmptyOrDeleted(CWISS_ControlByte c) { - return c < CWISS_kSentinel; -} - -/// Asserts that `ctrl` points to a full control byte. -#define CWISS_AssertIsFull(ctrl) \ - CWISS_CHECK((ctrl) != NULL && CWISS_IsFull(*(ctrl)), \ - "Invalid operation on iterator (%p/%d). The element might have " \ - "been erased, or the table might have rehashed.", \ - (ctrl), (ctrl) ? *(ctrl) : -1) - -/// Asserts that `ctrl` is either null OR points to a full control byte. -#define CWISS_AssertIsValid(ctrl) \ - CWISS_CHECK((ctrl) == NULL || CWISS_IsFull(*(ctrl)), \ - "Invalid operation on iterator (%p/%d). The element might have " \ - "been erased, or the table might have rehashed.", \ - (ctrl), (ctrl) ? *(ctrl) : -1) - -/// Constructs a `BitMask` with the correct parameters for whichever -/// implementation of `CWISS_Group` is in use. -#define CWISS_Group_BitMask(x) \ - (CWISS_BitMask){(uint64_t)(x), CWISS_Group_kWidth, CWISS_Group_kShift}; - -// TODO(#4): Port this to NEON. -#if CWISS_HAVE_SSE2 -// Reference guide for intrinsics used below: -// -// * __m128i: An XMM (128-bit) word. -// -// * _mm_setzero_si128: Returns a zero vector. -// * _mm_set1_epi8: Returns a vector with the same i8 in each lane. -// -// * _mm_subs_epi8: Saturating-subtracts two i8 vectors. -// * _mm_and_si128: Ands two i128s together. -// * _mm_or_si128: Ors two i128s together. -// * _mm_andnot_si128: And-nots two i128s together. -// -// * _mm_cmpeq_epi8: Component-wise compares two i8 vectors for equality, -// filling each lane with 0x00 or 0xff. -// * _mm_cmpgt_epi8: Same as above, but using > rather than ==. -// -// * _mm_loadu_si128: Performs an unaligned load of an i128. -// * _mm_storeu_si128: Performs an unaligned store of a u128. -// -// * _mm_sign_epi8: Retains, negates, or zeroes each i8 lane of the first -// argument if the corresponding lane of the second -// argument is positive, negative, or zero, respectively. -// * _mm_movemask_epi8: Selects the sign bit out of each i8 lane and produces a -// bitmask consisting of those bits. -// * _mm_shuffle_epi8: Selects i8s from the first argument, using the low -// four bits of each i8 lane in the second argument as -// indices. -typedef __m128i CWISS_Group; -#define CWISS_Group_kWidth ((size_t)16) -#define CWISS_Group_kShift 0 - -// https://github.com/abseil/abseil-cpp/issues/209 -// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87853 -// _mm_cmpgt_epi8 is broken under GCC with -funsigned-char -// Work around this by using the portable implementation of Group -// when using -funsigned-char under GCC. -static inline CWISS_Group CWISS_mm_cmpgt_epi8_fixed(CWISS_Group a, - CWISS_Group b) { - if (CWISS_IS_GCC && CHAR_MIN == 0) { // std::is_unsigned_v<char> - const CWISS_Group mask = _mm_set1_epi8(0x80); - const CWISS_Group diff = _mm_subs_epi8(b, a); - return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask); - } - return _mm_cmpgt_epi8(a, b); -} - -static inline CWISS_Group CWISS_Group_new(const CWISS_ControlByte* pos) { - return _mm_loadu_si128((const CWISS_Group*)pos); -} - -// Returns a bitmask representing the positions of slots that match hash. -static inline CWISS_BitMask CWISS_Group_Match(const CWISS_Group* self, - CWISS_h2_t hash) { - return CWISS_Group_BitMask( - _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_set1_epi8(hash), *self))) -} - -// Returns a bitmask representing the positions of empty slots. -static inline CWISS_BitMask CWISS_Group_MatchEmpty(const CWISS_Group* self) { -#if CWISS_HAVE_SSSE3 - // This only works because ctrl_t::kEmpty is -128. - return CWISS_Group_BitMask(_mm_movemask_epi8(_mm_sign_epi8(*self, *self))); -#else - return CWISS_Group_Match(self, CWISS_kEmpty); -#endif -} - -// Returns a bitmask representing the positions of empty or deleted slots. -static inline CWISS_BitMask CWISS_Group_MatchEmptyOrDeleted(const CWISS_Group* self) { - CWISS_Group special = _mm_set1_epi8((uint8_t)CWISS_kSentinel); - return CWISS_Group_BitMask(_mm_movemask_epi8(CWISS_mm_cmpgt_epi8_fixed(special, *self))); -} - -// Returns the number of trailing empty or deleted elements in the group. -static inline uint32_t CWISS_Group_CountLeadingEmptyOrDeleted( - const CWISS_Group* self) { - CWISS_Group special = _mm_set1_epi8((uint8_t)CWISS_kSentinel); - return CWISS_TrailingZeros((uint32_t)(_mm_movemask_epi8(CWISS_mm_cmpgt_epi8_fixed(special, *self)) + 1)); -} - -static inline void CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted(const CWISS_Group* self, CWISS_ControlByte* dst) { - CWISS_Group msbs = _mm_set1_epi8((char)-128); - CWISS_Group x126 = _mm_set1_epi8(126); -#if CWISS_HAVE_SSSE3 - CWISS_Group res = _mm_or_si128(_mm_shuffle_epi8(x126, *self), msbs); -#else - CWISS_Group zero = _mm_setzero_si128(); - CWISS_Group special_mask = CWISS_mm_cmpgt_epi8_fixed(zero, *self); - CWISS_Group res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126)); -#endif - _mm_storeu_si128((CWISS_Group*)dst, res); -} -#else // CWISS_HAVE_SSE2 -typedef uint64_t CWISS_Group; -#define CWISS_Group_kWidth ((size_t)8) -#define CWISS_Group_kShift 3 - -// NOTE: Endian-hostile. -static inline CWISS_Group CWISS_Group_new(const CWISS_ControlByte* pos) { - CWISS_Group val; - memcpy(&val, pos, sizeof(val)); - return val; -} - -static inline CWISS_BitMask CWISS_Group_Match(const CWISS_Group* self, - CWISS_h2_t hash) { - // For the technique, see: - // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord - // (Determine if a word has a byte equal to n). - // - // Caveat: there are false positives but: - // - they only occur if there is a real match - // - they never occur on ctrl_t::kEmpty, ctrl_t::kDeleted, ctrl_t::kSentinel - // - they will be handled gracefully by subsequent checks in code - // - // Example: - // v = 0x1716151413121110 - // hash = 0x12 - // retval = (v - lsbs) & ~v & msbs = 0x0000000080800000 - uint64_t msbs = 0x8080808080808080ULL; - uint64_t lsbs = 0x0101010101010101ULL; - uint64_t x = *self ^ (lsbs * hash); - return CWISS_Group_BitMask((x - lsbs) & ~x & msbs); -} - -static inline CWISS_BitMask CWISS_Group_MatchEmpty(const CWISS_Group* self) { - uint64_t msbs = 0x8080808080808080ULL; - return CWISS_Group_BitMask((*self & (~*self << 6)) & msbs); -} - -static inline CWISS_BitMask CWISS_Group_MatchEmptyOrDeleted( - const CWISS_Group* self) { - uint64_t msbs = 0x8080808080808080ULL; - return CWISS_Group_BitMask((*self & (~*self << 7)) & msbs); -} - -static inline uint32_t CWISS_Group_CountLeadingEmptyOrDeleted( - const CWISS_Group* self) { - uint64_t gaps = 0x00FEFEFEFEFEFEFEULL; - return (CWISS_TrailingZeros(((~*self & (*self >> 7)) | gaps) + 1) + 7) >> 3; -} - -static inline void CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted( - const CWISS_Group* self, CWISS_ControlByte* dst) { - uint64_t msbs = 0x8080808080808080ULL; - uint64_t lsbs = 0x0101010101010101ULL; - uint64_t x = *self & msbs; - uint64_t res = (~x + (x >> 7)) & ~lsbs; - memcpy(dst, &res, sizeof(res)); -} -#endif // CWISS_HAVE_SSE2 - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/control_byte.h ///////////////////////////////////////// - -/// cwisstable/internal/capacity.h ///////////////////////////////////////////// -/// Capacity, load factor, and allocation size computations for a SwissTable. -/// -/// A SwissTable's backing array consists of control bytes followed by slots -/// that may or may not contain objects. -/// -/// The layout of the backing array, for `capacity` slots, is thus, as a -/// pseudo-struct: -/// ``` -/// struct CWISS_BackingArray { -/// // Control bytes for the "real" slots. -/// CWISS_ControlByte ctrl[capacity]; -/// // Always `CWISS_kSentinel`. This is used by iterators to find when to -/// // stop and serves no other purpose. -/// CWISS_ControlByte sentinel; -/// // A copy of the first `kWidth - 1` elements of `ctrl`. This is used so -/// // that if a probe sequence picks a value near the end of `ctrl`, -/// // `CWISS_Group` will have valid control bytes to look at. -/// // -/// // As an interesting special-case, such probe windows will never choose -/// // the zeroth slot as a candidate, because they will see `kSentinel` -/// // instead of the correct H2 value. -/// CWISS_ControlByte clones[kWidth - 1]; -/// // Alignment padding equal to `alignof(slot_type)`. -/// char padding_; -/// // The actual slot data. -/// char slots[capacity * sizeof(slot_type)]; -/// }; -/// ``` -/// -/// The length of this array is computed by `CWISS_AllocSize()`. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// Returns he number of "cloned control bytes". -/// -/// This is the number of control bytes that are present both at the beginning -/// of the control byte array and at the end, such that we can create a -/// `CWISS_Group_kWidth`-width probe window starting from any control byte. -static inline size_t CWISS_NumClonedBytes(void) { - return CWISS_Group_kWidth - 1; -} - -/// Returns whether `n` is a valid capacity (i.e., number of slots). -/// -/// A valid capacity is a non-zero integer `2^m - 1`. -static inline bool CWISS_IsValidCapacity(size_t n) { - return ((n + 1) & n) == 0 && n > 0; -} - -/// Returns some per-call entropy. -/// -/// Currently, the entropy is produced by XOR'ing the address of a (preferably -/// thread-local) value with a perpetually-incrementing value. -static inline size_t RandomSeed(void) { -#ifdef CWISS_THREAD_LOCAL - static CWISS_THREAD_LOCAL size_t counter; - size_t value = counter++; -#else - static CWISS_ATOMIC_T(size_t) counter; - size_t value = CWISS_ATOMIC_INC(counter); -#endif - return value ^ ((size_t)&counter); -} - -/// Mixes a randomly generated per-process seed with `hash` and `ctrl` to -/// randomize insertion order within groups. -CWISS_INLINE_NEVER static bool CWISS_ShouldInsertBackwards( - size_t hash, const CWISS_ControlByte* ctrl) { - // To avoid problems with weak hashes and single bit tests, we use % 13. - // TODO(kfm,sbenza): revisit after we do unconditional mixing - return (CWISS_H1(hash, ctrl) ^ RandomSeed()) % 13 > 6; -} - -/// Applies the following mapping to every byte in the control array: -/// * kDeleted -> kEmpty -/// * kEmpty -> kEmpty -/// * _ -> kDeleted -/// -/// Preconditions: `CWISS_IsValidCapacity(capacity)`, -/// `ctrl[capacity]` == `kSentinel`, `ctrl[i] != kSentinel for i < capacity`. -CWISS_INLINE_NEVER static void CWISS_ConvertDeletedToEmptyAndFullToDeleted( CWISS_ControlByte* ctrl, size_t capacity) { - CWISS_DCHECK(ctrl[capacity] == CWISS_kSentinel, "bad ctrl value at %zu: %02x", capacity, ctrl[capacity]); - CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", capacity); - - for (CWISS_ControlByte* pos = ctrl; pos < ctrl + capacity; pos += CWISS_Group_kWidth) { - CWISS_Group g = CWISS_Group_new(pos); - CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted(&g, pos); - } - // Copy the cloned ctrl bytes. - memcpy(ctrl + capacity + 1, ctrl, CWISS_NumClonedBytes()); - ctrl[capacity] = CWISS_kSentinel; -} - -/// Sets `ctrl` to `{kEmpty, ..., kEmpty, kSentinel}`, marking the entire -/// array as deleted. -static inline void CWISS_ResetCtrl(size_t capacity, CWISS_ControlByte* ctrl, const void* slots, size_t slot_size) { - memset(ctrl, CWISS_kEmpty, capacity + 1 + CWISS_NumClonedBytes()); - ctrl[capacity] = CWISS_kSentinel; - CWISS_PoisonMemory(slots, slot_size * capacity); -} - -/// Sets `ctrl[i]` to `h`. -/// -/// Unlike setting it directly, this function will perform bounds checks and -/// mirror the value to the cloned tail if necessary. -static inline void CWISS_SetCtrl(size_t i, CWISS_ControlByte h, size_t capacity, CWISS_ControlByte* ctrl, const void* slots, size_t slot_size) { - CWISS_DCHECK(i < capacity, "CWISS_SetCtrl out-of-bounds: %zu >= %zu", i, capacity); - - const char* slot = ((const char*)slots) + i * slot_size; - if (CWISS_IsFull(h)) { - CWISS_UnpoisonMemory(slot, slot_size); - } else { - CWISS_PoisonMemory(slot, slot_size); - } - - // This is intentionally branchless. If `i < kWidth`, it will write to the - // cloned bytes as well as the "real" byte; otherwise, it will store `h` - // twice. - size_t mirrored_i = ((i - CWISS_NumClonedBytes()) & capacity) + (CWISS_NumClonedBytes() & capacity); - ctrl[i] = h; - ctrl[mirrored_i] = h; -} - -/// Converts `n` into the next valid capacity, per `CWISS_IsValidCapacity`. -static inline size_t CWISS_NormalizeCapacity(size_t n) { - return n ? SIZE_MAX >> CWISS_LeadingZeros(n) : 1; -} - -// General notes on capacity/growth methods below: -// - We use 7/8th as maximum load factor. For 16-wide groups, that gives an -// average of two empty slots per group. -// - For (capacity+1) >= Group::kWidth, growth is 7/8*capacity. -// - For (capacity+1) < Group::kWidth, growth == capacity. In this case, we -// never need to probe (the whole table fits in one group) so we don't need a -// load factor less than 1. - -/// Given `capacity`, applies the load factor; i.e., it returns the maximum -/// number of values we should put into the table before a rehash. -static inline size_t CWISS_CapacityToGrowth(size_t capacity) { - CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", - capacity); - // `capacity*7/8` - if (CWISS_Group_kWidth == 8 && capacity == 7) { - // x-x/8 does not work when x==7. - return 6; - } - return capacity - capacity / 8; -} - -/// Given `growth`, "unapplies" the load factor to find how large the capacity -/// should be to stay within the load factor. -/// -/// This might not be a valid capacity and `CWISS_NormalizeCapacity()` may be -/// necessary. -static inline size_t CWISS_GrowthToLowerboundCapacity(size_t growth) { - // `growth*8/7` - if (CWISS_Group_kWidth == 8 && growth == 7) { - // x+(x-1)/7 does not work when x==7. - return 8; - } - return growth + (size_t)((((int64_t)growth) - 1) / 7); -} - -// The allocated block consists of `capacity + 1 + NumClonedBytes()` control -// bytes followed by `capacity` slots, which must be aligned to `slot_align`. -// SlotOffset returns the offset of the slots into the allocated block. - -/// Given the capacity of a table, computes the offset (from the start of the -/// backing allocation) at which the slots begin. -static inline size_t CWISS_SlotOffset(size_t capacity, size_t slot_align) { - CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", - capacity); - const size_t num_control_bytes = capacity + 1 + CWISS_NumClonedBytes(); - return (num_control_bytes + slot_align - 1) & (~slot_align + 1); -} - -/// Given the capacity of a table, computes the total size of the backing -/// array. -static inline size_t CWISS_AllocSize(size_t capacity, size_t slot_size, - size_t slot_align) { - return CWISS_SlotOffset(capacity, slot_align) + capacity * slot_size; -} - -/// Whether a table is "small". A small table fits entirely into a probing -/// group, i.e., has a capacity equal to the size of a `CWISS_Group`. -/// -/// In small mode we are able to use the whole capacity. The extra control -/// bytes give us at least one "empty" control byte to stop the iteration. -/// This is important to make 1 a valid capacity. -/// -/// In small mode only the first `capacity` control bytes after the sentinel -/// are valid. The rest contain dummy ctrl_t::kEmpty values that do not -/// represent a real slot. This is important to take into account on -/// `CWISS_FindFirstNonFull()`, where we never try -/// `CWISS_ShouldInsertBackwards()` for small tables. -static inline bool CWISS_IsSmall(size_t capacity) { - return capacity < CWISS_Group_kWidth - 1; -} - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/capacity.h ///////////////////////////////////////////// - -/// cwisstable/internal/probe.h //////////////////////////////////////////////// -/// Table probing functions. -/// -/// "Probing" refers to the process of trying to find the matching entry for a -/// given lookup by repeatedly searching for values throughout the table. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// The state for a probe sequence. -/// -/// Currently, the sequence is a triangular progression of the form -/// ``` -/// p(i) := kWidth/2 * (i^2 - i) + hash (mod mask + 1) -/// ``` -/// -/// The use of `kWidth` ensures that each probe step does not overlap groups; -/// the sequence effectively outputs the addresses of *groups* (although not -/// necessarily aligned to any boundary). The `CWISS_Group` machinery allows us -/// to check an entire group with minimal branching. -/// -/// Wrapping around at `mask + 1` is important, but not for the obvious reason. -/// As described in capacity.h, the first few entries of the control byte array -/// is mirrored at the end of the array, which `CWISS_Group` will find and use -/// for selecting candidates. However, when those candidates' slots are -/// actually inspected, there are no corresponding slots for the cloned bytes, -/// so we need to make sure we've treated those offsets as "wrapping around". -typedef struct { - size_t mask_; - size_t offset_; - size_t index_; -} CWISS_ProbeSeq; - -/// Creates a new probe sequence using `hash` as the initial value of the -/// sequence and `mask` (usually the capacity of the table) as the mask to -/// apply to each value in the progression. -static inline CWISS_ProbeSeq CWISS_ProbeSeq_new(size_t hash, size_t mask) { - return (CWISS_ProbeSeq) { - .mask_ = mask, - .offset_ = hash & mask, - }; -} - -/// Returns the slot `i` indices ahead of `self` within the bounds expressed by -/// `mask`. -static inline size_t CWISS_ProbeSeq_offset(const CWISS_ProbeSeq* self, - size_t i) { - return (self->offset_ + i) & self->mask_; -} - -/// Advances the sequence; the value can be obtained by calling -/// `CWISS_ProbeSeq_offset()` or inspecting `offset_`. -static inline void CWISS_ProbeSeq_next(CWISS_ProbeSeq* self) { - self->index_ += CWISS_Group_kWidth; - self->offset_ += self->index_; - self->offset_ &= self->mask_; -} - -/// Begins a probing operation on `ctrl`, using `hash`. -static inline CWISS_ProbeSeq CWISS_ProbeSeq_Start(const CWISS_ControlByte* ctrl, - size_t hash, - size_t capacity) { - return CWISS_ProbeSeq_new(CWISS_H1(hash, ctrl), capacity); -} - -// The return value of `CWISS_FindFirstNonFull()`. -typedef struct { - size_t offset; - size_t probe_length; -} CWISS_FindInfo; - -/// Probes an array of control bits using a probe sequence derived from `hash`, -/// and returns the offset corresponding to the first deleted or empty slot. -/// -/// Behavior when the entire table is full is undefined. -/// -/// NOTE: this function must work with tables having both empty and deleted -/// slots in the same group. Such tables appear during -/// `CWISS_RawTable_DropDeletesWithoutResize()`. -static inline CWISS_FindInfo CWISS_FindFirstNonFull( - const CWISS_ControlByte* ctrl, size_t hash, size_t capacity) { - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(ctrl, hash, capacity); - while (true) { - CWISS_Group g = CWISS_Group_new(ctrl + seq.offset_); - CWISS_BitMask mask = CWISS_Group_MatchEmptyOrDeleted(&g); - if (mask.mask) { -#ifndef NDEBUG - // We want to add entropy even when ASLR is not enabled. - // In debug build we will randomly insert in either the front or back of - // the group. - // TODO(kfm,sbenza): revisit after we do unconditional mixing - if (!CWISS_IsSmall(capacity) && CWISS_ShouldInsertBackwards(hash, ctrl)) { - return (CWISS_FindInfo) { - CWISS_ProbeSeq_offset(&seq, CWISS_BitMask_HighestBitSet(&mask)), - seq.index_ - }; - } -#endif - return (CWISS_FindInfo) { - CWISS_ProbeSeq_offset(&seq, CWISS_BitMask_TrailingZeros(&mask)), - seq.index_ - }; - } - CWISS_ProbeSeq_next(&seq); - CWISS_DCHECK(seq.index_ <= capacity, "full table!"); - } -} - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/probe.h //////////////////////////////////////////////// - -/// cwisstable/internal/absl_hash.h //////////////////////////////////////////// -/// Implementation details of AbslHash. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -static inline uint64_t CWISS_AbslHash_LowLevelMix(uint64_t v0, uint64_t v1) { -#ifndef __aarch64__ - // The default bit-mixer uses 64x64->128-bit multiplication. - CWISS_U128 p = CWISS_Mul128(v0, v1); - return p.hi ^ p.lo; -#else - // The default bit-mixer above would perform poorly on some ARM microarchs, - // where calculating a 128-bit product requires a sequence of two - // instructions with a high combined latency and poor throughput. - // Instead, we mix bits using only 64-bit arithmetic, which is faster. - uint64_t p = v0 ^ CWISS_RotateLeft(v1, 40); - p *= v1 ^ CWISS_RotateLeft(v0, 39); - return p ^ (p >> 11); -#endif -} - -CWISS_INLINE_NEVER -static uint64_t CWISS_AbslHash_LowLevelHash(const void* data, size_t len, - uint64_t seed, - const uint64_t salt[5]) { - const char* ptr = (const char*)data; - uint64_t starting_length = (uint64_t)len; - uint64_t current_state = seed ^ salt[0]; - - if (len > 64) { - // If we have more than 64 bytes, we're going to handle chunks of 64 - // bytes at a time. We're going to build up two separate hash states - // which we will then hash together. - uint64_t duplicated_state = current_state; - - do { - uint64_t chunk[8]; - memcpy(chunk, ptr, sizeof(chunk)); - - uint64_t cs0 = CWISS_AbslHash_LowLevelMix(chunk[0] ^ salt[1], - chunk[1] ^ current_state); - uint64_t cs1 = CWISS_AbslHash_LowLevelMix(chunk[2] ^ salt[2], - chunk[3] ^ current_state); - current_state = (cs0 ^ cs1); - - uint64_t ds0 = CWISS_AbslHash_LowLevelMix(chunk[4] ^ salt[3], - chunk[5] ^ duplicated_state); - uint64_t ds1 = CWISS_AbslHash_LowLevelMix(chunk[6] ^ salt[4], - chunk[7] ^ duplicated_state); - duplicated_state = (ds0 ^ ds1); - - ptr += 64; - len -= 64; - } while (len > 64); - - current_state = current_state ^ duplicated_state; - } - - // We now have a data `ptr` with at most 64 bytes and the current state - // of the hashing state machine stored in current_state. - while (len > 16) { - uint64_t a = CWISS_Load64(ptr); - uint64_t b = CWISS_Load64(ptr + 8); - - current_state = CWISS_AbslHash_LowLevelMix(a ^ salt[1], b ^ current_state); - - ptr += 16; - len -= 16; - } - - // We now have a data `ptr` with at most 16 bytes. - uint64_t a = 0; - uint64_t b = 0; - if (len > 8) { - // When we have at least 9 and at most 16 bytes, set A to the first 64 - // bits of the input and B to the last 64 bits of the input. Yes, they will - // overlap in the middle if we are working with less than the full 16 - // bytes. - a = CWISS_Load64(ptr); - b = CWISS_Load64(ptr + len - 8); - } - else if (len > 3) { - // If we have at least 4 and at most 8 bytes, set A to the first 32 - // bits and B to the last 32 bits. - a = CWISS_Load32(ptr); - b = CWISS_Load32(ptr + len - 4); - } - else if (len > 0) { - // If we have at least 1 and at most 3 bytes, read all of the provided - // bits into A, with some adjustments. - a = CWISS_Load1To3(ptr, len); - } - - uint64_t w = CWISS_AbslHash_LowLevelMix(a ^ salt[1], b ^ current_state); - uint64_t z = salt[1] ^ starting_length; - return CWISS_AbslHash_LowLevelMix(w, z); -} - -// A non-deterministic seed. -// -// The current purpose of this seed is to generate non-deterministic results -// and prevent having users depend on the particular hash values. -// It is not meant as a security feature right now, but it leaves the door -// open to upgrade it to a true per-process random seed. A true random seed -// costs more and we don't need to pay for that right now. -// -// On platforms with ASLR, we take advantage of it to make a per-process -// random value. -// See https://en.wikipedia.org/wiki/Address_space_layout_randomization -// -// On other platforms this is still going to be non-deterministic but most -// probably per-build and not per-process. -static const void* const CWISS_AbslHash_kSeed = &CWISS_AbslHash_kSeed; - -// The salt array used by LowLevelHash. This array is NOT the mechanism used to -// make absl::Hash non-deterministic between program invocations. See `Seed()` -// for that mechanism. -// -// Any random values are fine. These values are just digits from the decimal -// part of pi. -// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number -static const uint64_t CWISS_AbslHash_kHashSalt[5] = { - 0x243F6A8885A308D3, 0x13198A2E03707344, 0xA4093822299F31D0, - 0x082EFA98EC4E6C89, 0x452821E638D01377, -}; - -#define CWISS_AbslHash_kPiecewiseChunkSize ((size_t)1024) - -typedef uint64_t CWISS_AbslHash_State_; -#define CWISS_AbslHash_kInit_ ((CWISS_AbslHash_State_)(uintptr_t)CWISS_AbslHash_kSeed) - -static inline void CWISS_AbslHash_Mix(CWISS_AbslHash_State_* state, - uint64_t v) { - const uint64_t kMul = sizeof(size_t) == 4 ? 0xcc9e2d51 : 0x9ddfea08eb382d69; - *state = CWISS_AbslHash_LowLevelMix(*state + v, kMul); -} - -CWISS_INLINE_NEVER -static uint64_t CWISS_AbslHash_Hash64(const void* val, size_t len) { - return CWISS_AbslHash_LowLevelHash(val, len, CWISS_AbslHash_kInit_, - CWISS_AbslHash_kHashSalt); -} - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/absl_hash.h //////////////////////////////////////////// - -/// cwisstable/hash.h ////////////////////////////////////////////////////////// -/// Hash functions. -/// -/// This file provides some hash functions to use with cwisstable types. -/// -/// Every hash function defines four symbols: -/// - `CWISS_<Hash>_State`, the state of the hash function. -/// - `CWISS_<Hash>_kInit`, the initial value of the hash state. -/// - `void CWISS_<Hash>_Write(State*, const void*, size_t)`, write some more -/// data into the hash state. -/// - `size_t CWISS_<Hash>_Finish(State)`, digest the state into a final hash -/// value. -/// -/// Currently available are two hashes: `FxHash`, which is small and fast, and -/// `AbslHash`, the hash function used by Abseil. -/// -/// `AbslHash` is the default hash function. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -typedef size_t CWISS_FxHash_State; -#define CWISS_FxHash_kInit ((CWISS_FxHash_State)0) -static inline void CWISS_FxHash_Write(CWISS_FxHash_State* state, - const void* val, size_t len) { - const size_t kSeed = (size_t)(UINT64_C(0x517cc1b727220a95)); - const uint32_t kRotate = 5; - - const char* p = (const char*)val; - CWISS_FxHash_State state_ = *state; - while (len > 0) { - size_t word = 0; - size_t to_read = len >= sizeof(state_) ? sizeof(state_) : len; - memcpy(&word, p, to_read); - - state_ = CWISS_RotateLeft(state_, kRotate); - state_ ^= word; - state_ *= kSeed; - - len -= to_read; - p += to_read; - } - *state = state_; -} -static inline size_t CWISS_FxHash_Finish(CWISS_FxHash_State state) { - return state; -} - -typedef CWISS_AbslHash_State_ CWISS_AbslHash_State; -#define CWISS_AbslHash_kInit CWISS_AbslHash_kInit_ -static inline void CWISS_AbslHash_Write(CWISS_AbslHash_State* state, - const void* val, size_t len) { - const char* val8 = (const char*)val; - if (CWISS_LIKELY(len < CWISS_AbslHash_kPiecewiseChunkSize)) { - goto CWISS_AbslHash_Write_small; - } - - while (len >= CWISS_AbslHash_kPiecewiseChunkSize) { - CWISS_AbslHash_Mix( - state, CWISS_AbslHash_Hash64(val8, CWISS_AbslHash_kPiecewiseChunkSize)); - len -= CWISS_AbslHash_kPiecewiseChunkSize; - val8 += CWISS_AbslHash_kPiecewiseChunkSize; - } - -CWISS_AbslHash_Write_small:; - uint64_t v; - if (len > 16) { - v = CWISS_AbslHash_Hash64(val8, len); - } - else if (len > 8) { - CWISS_U128 p = CWISS_Load9To16(val8, len); - CWISS_AbslHash_Mix(state, p.lo); - v = p.hi; - } - else if (len >= 4) { - v = CWISS_Load4To8(val8, len); - } - else if (len > 0) { - v = CWISS_Load1To3(val8, len); - } - else { - // Empty ranges have no effect. - return; - } - - CWISS_AbslHash_Mix(state, v); -} -static inline size_t CWISS_AbslHash_Finish(CWISS_AbslHash_State state) { - return state; -} - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/hash.h ////////////////////////////////////////////////////////// - -/// cwisstable/policy.h //////////////////////////////////////////////////////// -/// Hash table policies. -/// -/// Table policies are `cwisstable`'s generic code mechanism. All code in -/// `cwisstable`'s internals is completely agnostic to: -/// - The layout of the elements. -/// - The storage strategy for the elements (inline, indirect in the heap). -/// - Hashing, comparison, and allocation. -/// -/// This information is provided to `cwisstable`'s internals by way of a -/// *policy*: a vtable describing how to move elements around, hash them, -/// compare them, allocate storage for them, and so on and on. This design is -/// inspired by Abseil's equivalent, which is a template parameter used for -/// sharing code between all the SwissTable-backed containers. -/// -/// Unlike Abseil, policies are part of `cwisstable`'s public interface. Due to -/// C's lack of any mechanism for detecting the gross properties of types, -/// types with unwritten invariants, such as C strings (NUL-terminated byte -/// arrays), users must be able to carefully describe to `cwisstable` how to -/// correctly do things to their type. DESIGN.md goes into detailed rationale -/// for this polymorphism strategy. -/// -/// # Defining a Policy -/// -/// Policies are defined as read-only globals and passed around by pointer to -/// different `cwisstable` functions; macros are provided for doing this, since -/// most of these functions will not vary significantly from one type to -/// another. There are four of them: -/// -/// - `CWISS_DECLARE_FLAT_SET_POLICY(kPolicy, Type, ...)` -/// - `CWISS_DECLARE_FLAT_MAP_POLICY(kPolicy, Key, Value, ...)` -/// - `CWISS_DECLARE_NODE_SET_POLICY(kPolicy, Type, ...)` -/// - `CWISS_DECLARE_NODE_MAP_POLICY(kPolicy, Key, Value, ...)` -/// -/// These correspond to the four SwissTable types in Abseil: two map types and -/// two set types; "flat" means that elements are stored inline in the backing -/// array, whereas "node" means that the element is stored in its own heap -/// allocation, making it stable across rehashings (which SwissTable does more -/// or less whenever it feels like it). -/// -/// Each macro expands to a read-only global variable definition (with the name -/// `kPolicy`, i.e, the first variable) dedicated for the specified type(s). -/// The arguments that follow are overrides for the default values of each field -/// in the policy; all but the size and alignment fields of `CWISS_ObjectPolicy` -/// may be overridden. To override the field `kPolicy.foo.bar`, pass -/// `(foo_bar, value)` to the macro. If multiple such pairs are passed in, the -/// first one found wins. `examples/stringmap.c` provides an example of how to -/// use this functionality. -/// -/// For "common" uses, where the key and value are plain-old-data, `declare.h` -/// has dedicated macros, and fussing with policies directly is unnecessary. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// A policy describing the basic laying properties of a type. -/// -/// This type describes how to move values of a particular type around. -typedef struct { - /// The layout of the stored object. - size_t size, align; - - /// Performs a deep copy of `src` onto a fresh location `dst`. - void (*copy)(void* dst, const void* src); - - /// Destroys an object. - /// - /// This member may, as an optimization, be null. This will cause it to - /// behave as a no-op, and may be more efficient than making this an empty - /// function. - void (*dtor)(void* val); -} CWISS_ObjectPolicy; - -/// A policy describing the hashing properties of a type. -/// -/// This type describes the necessary information for putting a value into a -/// hash table. -/// -/// A *heterogenous* key policy is one whose equality function expects different -/// argument types, which can be used for so-called heterogenous lookup: finding -/// an element of a table by comparing it to a somewhat different type. If the -/// table element is, for example, a `std::string`[1]-like type, it could still -/// be found via a non-owning version like a `std::string_view`[2]. This is -/// important for making efficient use of a SwissTable. -/// -/// [1]: For non C++ programmers: a growable string type implemented as a -/// `struct { char* ptr; size_t size, capacity; }`. -/// [2]: Similarly, a `std::string_view` is a pointer-length pair to a string -/// *somewhere*; unlike a C-style string, it might be a substring of a -/// larger allocation elsewhere. -typedef struct { - /// Computes the hash of a value. - /// - /// This function must be such that if two elements compare equal, they must - /// have the same hash (but not vice-versa). - /// - /// If this policy is heterogenous, this function must be defined so that - /// given the original key policy of the table's element type, if - /// `hetero->eq(a, b)` holds, then `hetero->hash(a) == original->hash(b)`. - /// In other words, the obvious condition for a hash table to work correctly - /// with this policy. - size_t(*hash)(const void* val); - - /// Compares two values for equality. - /// - /// This function is actually not symmetric: the first argument will always be - /// the value being searched for, and the second will be a pointer to the - /// candidate entry. In particular, this means they can be different types: - /// in C++ parlance, `needle` could be a `std::string_view`, while `candidate` - /// could be a `std::string`. - bool (*eq)(const void* needle, const void* candidate); -} CWISS_KeyPolicy; - -/// A policy for allocation. -/// -/// This type provides access to a custom allocator. -typedef struct { - /// Allocates memory. - /// - /// This function must never fail and never return null, unlike `malloc`. This - /// function does not need to tolerate zero sized allocations. - void* (*alloc)(size_t size, size_t align); - - /// Deallocates memory allocated by `alloc`. - /// - /// This function is passed the same size/alignment as was passed to `alloc`, - /// allowing for sized-delete optimizations. - void (*free)(void* array, size_t size, size_t align); -} CWISS_AllocPolicy; - -/// A policy for allocating space for slots. -/// -/// This allows us to distinguish between inline storage (more cache-friendly) -/// and outline (pointer-stable). -typedef struct { - /// The layout of a slot value. - /// - /// Usually, this will be the same as for the object type, *or* the layout - /// of a pointer (for outline storage). - size_t size, align; - - /// Initializes a new slot at the given location. - /// - /// This function does not initialize the value *in* the slot; it simply sets - /// up the slot so that a value can be `memcpy`'d or otherwise emplaced into - /// the slot. - void (*init)(void* slot); - - /// Destroys a slot, including the destruction of the value it contains. - /// - /// This function may, as an optimization, be null. This will cause it to - /// behave as a no-op. - void (*del)(void* slot); - - /// Transfers a slot. - /// - /// `dst` must be uninitialized; `src` must be initialized. After this - /// function, their roles will be switched: `dst` will be initialized and - /// contain the value from `src`; `src` will be initialized. - /// - /// This function need not actually copy the underlying value. - void (*transfer)(void* dst, void* src); - - /// Extracts a pointer to the value inside the a slot. - /// - /// This function does not need to tolerate nulls. - void* (*get)(void* slot); -} CWISS_SlotPolicy; - -/// A hash table policy. -/// -/// See the header documentation for more information. -typedef struct { - const CWISS_ObjectPolicy* obj; - const CWISS_KeyPolicy* key; - const CWISS_AllocPolicy* alloc; - const CWISS_SlotPolicy* slot; -} CWISS_Policy; - -/// Declares a hash set policy with inline storage for the given type. -/// -/// See the header documentation for more information. -#define CWISS_DECLARE_FLAT_SET_POLICY(kPolicy_, Type_, obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_DECLARE_FLAT_POLICY_(kPolicy_, Type_, Type_, obj_copy, obj_dtor, key_hash, key_eq) - -/// Declares a hash map policy with inline storage for the given key and value -/// types. -/// -/// See the header documentation for more information. - -/// Declares a hash set policy with pointer-stable storage for the given type. -/// -/// See the header documentation for more information. -#define CWISS_DECLARE_NODE_SET_POLICY(kPolicy_, Type_, obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_DECLARE_NODE_POLICY_(kPolicy_, Type_, Type_, obj_copy, obj_dtor, key_hash, key_eq) - -/// Declares a hash map policy with pointer-stable storage for the given key and -/// value types. -/// -/// See the header documentation for more information. -#define CWISS_DECLARE_NODE_MAP_POLICY(kPolicy_, K_, V_, obj_copy, obj_dtor, key_hash, key_eq) \ - typedef struct { \ - K_ k; \ - V_ v; \ - } kPolicy_##_Entry; \ - CWISS_DECLARE_NODE_POLICY_(kPolicy_, kPolicy_##_Entry, K_, obj_copy, obj_dtor, key_hash, key_eq) - -// ---- PUBLIC API ENDS HERE! ---- - - -#define CWISS_DECLARE_FLAT_MAP_POLICY(kPolicy_, K_, V_, obj_copy, obj_dtor, key_hash, key_eq) \ - typedef struct { \ - K_ k; \ - V_ v; \ - } kPolicy_##_Entry; \ - CWISS_DECLARE_FLAT_POLICY_(kPolicy_, kPolicy_##_Entry, K_, obj_copy, obj_dtor, key_hash, key_eq) - -#define CWISS_DECLARE_FLAT_POLICY_(kPolicy_, Type_, Key_, obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_BEGIN \ - static inline void kPolicy_##_DefaultSlotInit(void* slot) {} \ - static inline void kPolicy_##_DefaultSlotTransfer(void* dst, void* src) { \ - memcpy(dst, src, sizeof(Type_)); \ - } \ - static inline void* kPolicy_##_DefaultSlotGet(void* slot) { return slot; } \ - static inline void kPolicy_##_DefaultSlotDtor(void* slot){ \ - obj_dtor (slot); \ - } \ - \ - static const CWISS_ObjectPolicy kPolicy_##_ObjectPolicy = { \ - sizeof(Type_), \ - alignof(Type_), \ - obj_copy, \ - obj_dtor \ - }; \ - static const CWISS_KeyPolicy kPolicy_##_KeyPolicy = { \ - key_hash, key_eq, \ - }; \ - static const CWISS_AllocPolicy kPolicy_##_AllocPolicy = { \ - CWISS_DefaultMalloc, \ - CWISS_DefaultFree, \ - }; \ - static const CWISS_SlotPolicy kPolicy_##_SlotPolicy = { \ - sizeof(Type_), \ - sizeof(Type_), \ - kPolicy_##_DefaultSlotInit, \ - kPolicy_##_DefaultSlotDtor, \ - kPolicy_##_DefaultSlotTransfer, \ - kPolicy_##_DefaultSlotGet, \ - }; \ - CWISS_END \ - static const CWISS_Policy kPolicy_ = { \ - &kPolicy_##_ObjectPolicy, \ - &kPolicy_##_KeyPolicy, \ - &kPolicy_##_AllocPolicy, \ - &kPolicy_##_SlotPolicy, \ - } - -static inline void* CWISS_DefaultMalloc(size_t size, size_t align) { - void* p = malloc(size); // TODO: Check alignment. - CWISS_CHECK(p != NULL, "malloc() returned null"); - return p; -} -static inline void CWISS_DefaultFree(void* array, size_t size, size_t align) { - free(array); -} - -#define CWISS_DECLARE_NODE_POLICY_(kPolicy_, Type_, Key_, obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_BEGIN \ - static inline void kPolicy_##_NodeSlotInit(void* slot) { \ - void* node = CWISS_DefaultMalloc(sizeof(Type_), alignof(Type_)); \ - memcpy(slot, &node, sizeof(node)); \ - } \ - static inline void kPolicy_##_NodeSlotDtor(void* slot) { \ - obj_dtor(*(void**)slot); \ - CWISS_DefaultFree(*(void**)slot, sizeof(Type_), alignof(Type_)); \ - } \ - static inline void kPolicy_##_NodeSlotTransfer(void* dst, void* src) { \ - memcpy(dst, src, sizeof(void*)); \ - } \ - static inline void* kPolicy_##_NodeSlotGet(void* slot) { \ - return *((void**)slot); \ - } \ - static const CWISS_ObjectPolicy kPolicy_##_ObjectPolicy = { \ - sizeof(Type_), \ - alignof(Type_), \ - obj_copy, \ - obj_dtor \ - }; \ - static const CWISS_KeyPolicy kPolicy_##_KeyPolicy = { \ - key_hash, key_eq, \ - }; \ - static const CWISS_AllocPolicy kPolicy_##_AllocPolicy = { \ - CWISS_DefaultMalloc, \ - CWISS_DefaultFree, \ - }; \ - static const CWISS_SlotPolicy kPolicy_##_SlotPolicy = { \ - sizeof(void*), \ - alignof(void*), \ - kPolicy_##_NodeSlotInit, \ - kPolicy_##_NodeSlotDtor, \ - kPolicy_##_NodeSlotTransfer, \ - kPolicy_##_NodeSlotGet, \ - }; \ - CWISS_END \ - static const CWISS_Policy kPolicy_ = { \ - &kPolicy_##_ObjectPolicy, \ - &kPolicy_##_KeyPolicy, \ - &kPolicy_##_AllocPolicy, \ - &kPolicy_##_SlotPolicy, \ - } - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/policy.h //////////////////////////////////////////////////////// - -/// cwisstable/internal/raw_table.h //////////////////////////////////////////// -/// The SwissTable implementation. -/// -/// `CWISS_RawTable` is the core data structure that all SwissTables wrap. -/// -/// All functions in this header take a `const CWISS_Policy*`, which describes -/// how to manipulate the elements in a table. The same pointer (i.e., same -/// address and provenance) passed to the function that created the -/// `CWISS_RawTable` MUST be passed to all subsequent function calls, and it -/// must not be mutated at any point between those calls. Failure to adhere to -/// these requirements is UB. -/// -/// It is STRONGLY recommended that this pointer point to a const global. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// A SwissTable. -/// -/// This is absl::container_internal::raw_hash_set in Abseil. -typedef struct { - /// The control bytes (and, also, a pointer to the base of the backing array). - /// - /// This contains `capacity_ + 1 + CWISS_NumClonedBytes()` entries. - CWISS_ControlByte* ctrl_; - /// The beginning of the slots, located at `CWISS_SlotOffset()` bytes after - /// `ctrl_`. May be null for empty tables. - char* slots_; - /// The number of filled slots. - size_t size_; - /// The total number of available slots. - size_t capacity_; - /// The number of slots we can still fill before a rehash. See - /// `CWISS_CapacityToGrowth()`. - size_t growth_left_; -} CWISS_RawTable; - - -/// An iterator into a SwissTable. -/// -/// Unlike a C++ iterator, there is no "end" to compare to. Instead, -/// `CWISS_RawIter_get()` will yield a null pointer once the iterator is -/// exhausted. -/// -/// Invariants: -/// - `ctrl_` and `slot_` are always in sync (i.e., the pointed to control byte -/// corresponds to the pointed to slot), or both are null. `set_` may be null -/// in the latter case. -/// - `ctrl_` always points to a full slot. -typedef struct { - CWISS_RawTable* set_; - CWISS_ControlByte* ctrl_; - char* slot_; -} CWISS_RawIter; - -/// Fixes up `ctrl_` to point to a full by advancing it and `slot_` until they -/// reach one. -/// -/// If a sentinel is reached, we null both of them out instead. -static inline void CWISS_RawIter_SkipEmptyOrDeleted(const CWISS_Policy* policy, - CWISS_RawIter* self) { - while (CWISS_IsEmptyOrDeleted(*self->ctrl_)) { - CWISS_Group g = CWISS_Group_new(self->ctrl_); - uint32_t shift = CWISS_Group_CountLeadingEmptyOrDeleted(&g); - self->ctrl_ += shift; - self->slot_ += shift * policy->slot->size; - } - - // Not sure why this is a branch rather than a cmov; Abseil uses a branch. - if (CWISS_UNLIKELY(*self->ctrl_ == CWISS_kSentinel)) { - self->ctrl_ = NULL; - self->slot_ = NULL; - } -} - -/// Creates a valid iterator starting at the `index`th slot. -static inline CWISS_RawIter CWISS_RawTable_iter_at(const CWISS_Policy* policy, - CWISS_RawTable* self, - size_t index) { - CWISS_RawIter iter = { - self, - self->ctrl_ + index, - self->slots_ + index * policy->slot->size, - }; - CWISS_RawIter_SkipEmptyOrDeleted(policy, &iter); - CWISS_AssertIsValid(iter.ctrl_); - return iter; -} - -/// Creates an iterator for `self`. -static inline CWISS_RawIter CWISS_RawTable_iter(const CWISS_Policy* policy, - CWISS_RawTable* self) { - return CWISS_RawTable_iter_at(policy, self, 0); -} - -/// Creates a valid iterator starting at the `index`th slot, accepting a `const` -/// pointer instead. -static inline CWISS_RawIter CWISS_RawTable_citer_at(const CWISS_Policy* policy, - const CWISS_RawTable* self, - size_t index) { - return CWISS_RawTable_iter_at(policy, (CWISS_RawTable*)self, index); -} - -/// Creates an iterator for `self`, accepting a `const` pointer instead. -static inline CWISS_RawIter CWISS_RawTable_citer(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return CWISS_RawTable_iter(policy, (CWISS_RawTable*)self); -} - -/// Returns a pointer into the currently pointed-to slot (*not* to the slot -/// itself, but rather its contents). -/// -/// Returns null if the iterator has been exhausted. -static inline void* CWISS_RawIter_get(const CWISS_Policy* policy, - const CWISS_RawIter* self) { - CWISS_AssertIsValid(self->ctrl_); - if (self->slot_ == NULL) { - return NULL; - } - - return policy->slot->get(self->slot_); -} - -/// Advances the iterator and returns the result of `CWISS_RawIter_get()`. -/// -/// Calling on an empty iterator is UB. -static inline void* CWISS_RawIter_next(const CWISS_Policy* policy, - CWISS_RawIter* self) { - CWISS_AssertIsFull(self->ctrl_); - self->ctrl_++; - self->slot_ += policy->slot->size; - - CWISS_RawIter_SkipEmptyOrDeleted(policy, self); - return CWISS_RawIter_get(policy, self); -} - -/// Erases, but does not destroy, the value pointed to by `it`. -static inline void CWISS_RawTable_EraseMetaOnly(const CWISS_Policy* policy, - CWISS_RawIter it) { - CWISS_DCHECK(CWISS_IsFull(*it.ctrl_), "erasing a dangling iterator"); - --it.set_->size_; - const size_t index = (size_t)(it.ctrl_ - it.set_->ctrl_); - const size_t index_before = (index - CWISS_Group_kWidth) & it.set_->capacity_; - CWISS_Group g_after = CWISS_Group_new(it.ctrl_); - CWISS_BitMask empty_after = CWISS_Group_MatchEmpty(&g_after); - CWISS_Group g_before = CWISS_Group_new(it.set_->ctrl_ + index_before); - CWISS_BitMask empty_before = CWISS_Group_MatchEmpty(&g_before); - - // We count how many consecutive non empties we have to the right and to the - // left of `it`. If the sum is >= kWidth then there is at least one probe - // window that might have seen a full group. - bool was_never_full = - empty_before.mask && empty_after.mask && - (size_t)(CWISS_BitMask_TrailingZeros(&empty_after) + - CWISS_BitMask_LeadingZeros(&empty_before)) < CWISS_Group_kWidth; - - CWISS_SetCtrl(index, was_never_full ? CWISS_kEmpty : CWISS_kDeleted, - it.set_->capacity_, it.set_->ctrl_, it.set_->slots_, - policy->slot->size); - it.set_->growth_left_ += was_never_full; - // infoz().RecordErase(); -} - -/// Computes a lower bound for the expected available growth and applies it to -/// `self_`. -static inline void CWISS_RawTable_ResetGrowthLeft(const CWISS_Policy* policy, - CWISS_RawTable* self) { - self->growth_left_ = CWISS_CapacityToGrowth(self->capacity_) - self->size_; -} - -/// Allocates a backing array for `self` and initializes its control bits. This -/// reads `capacity_` and updates all other fields based on the result of the -/// allocation. -/// -/// This does not free the currently held array; `capacity_` must be nonzero. -static inline void CWISS_RawTable_InitializeSlots(const CWISS_Policy* policy, - CWISS_RawTable* self) { - CWISS_DCHECK(self->capacity_, "capacity should be nonzero"); - // Folks with custom allocators often make unwarranted assumptions about the - // behavior of their classes vis-a-vis trivial destructability and what - // calls they will or wont make. Avoid sampling for people with custom - // allocators to get us out of this mess. This is not a hard guarantee but - // a workaround while we plan the exact guarantee we want to provide. - // - // People are often sloppy with the exact type of their allocator (sometimes - // it has an extra const or is missing the pair, but rebinds made it work - // anyway). To avoid the ambiguity, we work off SlotAlloc which we have - // bound more carefully. - // - // NOTE(mcyoung): Not relevant in C but kept in case we decide to do custom - // alloc. - /*if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && - slots_ == nullptr) { - infoz() = Sample(sizeof(slot_type)); - }*/ - - char* mem = - (char*) // Cast for C++. - policy->alloc->alloc(CWISS_AllocSize(self->capacity_, policy->slot->size, - policy->slot->align), - policy->slot->align); - - self->ctrl_ = (CWISS_ControlByte*)mem; - self->slots_ = mem + CWISS_SlotOffset(self->capacity_, policy->slot->align); - CWISS_ResetCtrl(self->capacity_, self->ctrl_, self->slots_, - policy->slot->size); - CWISS_RawTable_ResetGrowthLeft(policy, self); - - // infoz().RecordStorageChanged(size_, capacity_); -} - -/// Destroys all slots in the backing array, frees the backing array, and clears -/// all top-level book-keeping data. -static inline void CWISS_RawTable_DestroySlots(const CWISS_Policy* policy, - CWISS_RawTable* self) { - if (!self->capacity_) return; - - if (policy->slot->del != NULL) { - size_t i; - for (i = 0; i != self->capacity_; i++) { - if (CWISS_IsFull(self->ctrl_[i])) { - policy->slot->del(self->slots_ + i * policy->slot->size); - } - } - } - - policy->alloc->free( - self->ctrl_, - CWISS_AllocSize(self->capacity_, policy->slot->size, policy->slot->align), - policy->slot->align); - self->ctrl_ = CWISS_EmptyGroup(); - self->slots_ = NULL; - self->size_ = 0; - self->capacity_ = 0; - self->growth_left_ = 0; -} - -/// Grows the table to the given capacity, triggering a rehash. -static inline void CWISS_RawTable_Resize(const CWISS_Policy* policy, - CWISS_RawTable* self, - size_t new_capacity) { - CWISS_DCHECK(CWISS_IsValidCapacity(new_capacity), "invalid capacity: %zu", - new_capacity); - - CWISS_ControlByte* old_ctrl = self->ctrl_; - char* old_slots = self->slots_; - const size_t old_capacity = self->capacity_; - self->capacity_ = new_capacity; - CWISS_RawTable_InitializeSlots(policy, self); - - size_t i; - for (i = 0; i != old_capacity; i++) { - if (CWISS_IsFull(old_ctrl[i])) { - size_t hash = policy->key->hash( - policy->slot->get(old_slots + i * policy->slot->size)); - CWISS_FindInfo target = - CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - size_t new_i = target.offset; - CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - policy->slot->transfer(self->slots_ + new_i * policy->slot->size, - old_slots + i * policy->slot->size); - } - } - if (old_capacity) { - CWISS_UnpoisonMemory(old_slots, policy->slot->size * old_capacity); - policy->alloc->free( - old_ctrl, - CWISS_AllocSize(old_capacity, policy->slot->size, policy->slot->align), - policy->slot->align); - } -} - -/// Prunes control bits to remove as many tombstones as possible. -/// -/// See the comment on `CWISS_RawTable_rehash_and_grow_if_necessary()`. -CWISS_INLINE_NEVER -static void CWISS_RawTable_DropDeletesWithoutResize(const CWISS_Policy* policy, - CWISS_RawTable* self) { - CWISS_DCHECK(CWISS_IsValidCapacity(self->capacity_), "invalid capacity: %zu", - self->capacity_); - CWISS_DCHECK(!CWISS_IsSmall(self->capacity_), - "unexpected small capacity: %zu", self->capacity_); - // Algorithm: - // - mark all DELETED slots as EMPTY - // - mark all FULL slots as DELETED - // - for each slot marked as DELETED - // hash = Hash(element) - // target = find_first_non_full(hash) - // if target is in the same group - // mark slot as FULL - // else if target is EMPTY - // transfer element to target - // mark slot as EMPTY - // mark target as FULL - // else if target is DELETED - // swap current element with target element - // mark target as FULL - // repeat procedure for current slot with moved from element (target) - CWISS_ConvertDeletedToEmptyAndFullToDeleted(self->ctrl_, self->capacity_); - // Unfortunately because we do not know this size statically, we need to take - // a trip to the allocator. Alternatively we could use a variable length - // alloca... - void* slot = policy->alloc->alloc(policy->slot->size, policy->slot->align); - - size_t i; - for (i = 0; i != self->capacity_; i++) { - if (!CWISS_IsDeleted(self->ctrl_[i])) continue; - - char* old_slot = self->slots_ + i * policy->slot->size; - size_t hash = policy->key->hash(policy->slot->get(old_slot)); - - const CWISS_FindInfo target = - CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - const size_t new_i = target.offset; - - char* new_slot = self->slots_ + new_i * policy->slot->size; - - // Verify if the old and new i fall within the same group wrt the hash. - // If they do, we don't need to move the object as it falls already in the - // best probe we can. - const size_t probe_offset = - CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_).offset_; -#define CWISS_ProbeIndex(pos_) \ - (((pos_ - probe_offset) & self->capacity_) / CWISS_Group_kWidth) - - // Element doesn't move. - if (CWISS_LIKELY(CWISS_ProbeIndex(new_i) == CWISS_ProbeIndex(i))) { - CWISS_SetCtrl(i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - continue; - } - if (CWISS_IsEmpty(self->ctrl_[new_i])) { - // Transfer element to the empty spot. - // SetCtrl poisons/unpoisons the slots so we have to call it at the - // right time. - CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - policy->slot->transfer(new_slot, old_slot); - CWISS_SetCtrl(i, CWISS_kEmpty, self->capacity_, self->ctrl_, self->slots_, - policy->slot->size); - } - else { - CWISS_DCHECK(CWISS_IsDeleted(self->ctrl_[new_i]), - "bad ctrl value at %zu: %02x", new_i, self->ctrl_[new_i]); - CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - // Until we are done rehashing, DELETED marks previously FULL slots. - // Swap i and new_i elements. - - policy->slot->transfer(slot, old_slot); - policy->slot->transfer(old_slot, new_slot); - policy->slot->transfer(new_slot, slot); - --i; // repeat - } -#undef CWISS_ProbeSeq_Start_index - } - CWISS_RawTable_ResetGrowthLeft(policy, self); - policy->alloc->free(slot, policy->slot->size, policy->slot->align); -} - -/// Called whenever the table *might* need to conditionally grow. -/// -/// This function is an optimization opportunity to perform a rehash even when -/// growth is unnecessary, because vacating tombstones is beneficial for -/// performance in the long-run. -static inline void CWISS_RawTable_rehash_and_grow_if_necessary( - const CWISS_Policy* policy, CWISS_RawTable* self) { - if (self->capacity_ == 0) { - CWISS_RawTable_Resize(policy, self, 1); - } - else if (self->capacity_ > CWISS_Group_kWidth && - // Do these calculations in 64-bit to avoid overflow. - self->size_ * UINT64_C(32) <= self->capacity_ * UINT64_C(25)) { - // Squash DELETED without growing if there is enough capacity. - // - // Rehash in place if the current size is <= 25/32 of capacity_. - // Rationale for such a high factor: 1) drop_deletes_without_resize() is - // faster than resize, and 2) it takes quite a bit of work to add - // tombstones. In the worst case, seems to take approximately 4 - // insert/erase pairs to create a single tombstone and so if we are - // rehashing because of tombstones, we can afford to rehash-in-place as - // long as we are reclaiming at least 1/8 the capacity without doing more - // than 2X the work. (Where "work" is defined to be size() for rehashing - // or rehashing in place, and 1 for an insert or erase.) But rehashing in - // place is faster per operation than inserting or even doubling the size - // of the table, so we actually afford to reclaim even less space from a - // resize-in-place. The decision is to rehash in place if we can reclaim - // at about 1/8th of the usable capacity (specifically 3/28 of the - // capacity) which means that the total cost of rehashing will be a small - // fraction of the total work. - // - // Here is output of an experiment using the BM_CacheInSteadyState - // benchmark running the old case (where we rehash-in-place only if we can - // reclaim at least 7/16*capacity_) vs. this code (which rehashes in place - // if we can recover 3/32*capacity_). - // - // Note that although in the worst-case number of rehashes jumped up from - // 15 to 190, but the number of operations per second is almost the same. - // - // Abridged output of running BM_CacheInSteadyState benchmark from - // raw_hash_set_benchmark. N is the number of insert/erase operations. - // - // | OLD (recover >= 7/16 | NEW (recover >= 3/32) - // size | N/s LoadFactor NRehashes | N/s LoadFactor NRehashes - // 448 | 145284 0.44 18 | 140118 0.44 19 - // 493 | 152546 0.24 11 | 151417 0.48 28 - // 538 | 151439 0.26 11 | 151152 0.53 38 - // 583 | 151765 0.28 11 | 150572 0.57 50 - // 628 | 150241 0.31 11 | 150853 0.61 66 - // 672 | 149602 0.33 12 | 150110 0.66 90 - // 717 | 149998 0.35 12 | 149531 0.70 129 - // 762 | 149836 0.37 13 | 148559 0.74 190 - // 807 | 149736 0.39 14 | 151107 0.39 14 - // 852 | 150204 0.42 15 | 151019 0.42 15 - CWISS_RawTable_DropDeletesWithoutResize(policy, self); - } - else { - // Otherwise grow the container. - CWISS_RawTable_Resize(policy, self, self->capacity_ * 2 + 1); - } -} - -/// Prefetches the backing array to dodge potential TLB misses. -/// This is intended to overlap with execution of calculating the hash for a -/// key. -static inline void CWISS_RawTable_PrefetchHeapBlock( - const CWISS_Policy* policy, const CWISS_RawTable* self) { - CWISS_PREFETCH(self->ctrl_, 1); -} - -/// Issues CPU prefetch instructions for the memory needed to find or insert -/// a key. -/// -/// NOTE: This is a very low level operation and should not be used without -/// specific benchmarks indicating its importance. -static inline void CWISS_RawTable_Prefetch(const CWISS_Policy* policy, - const CWISS_RawTable* self, - const void* key) { - (void)key; -#if CWISS_HAVE_PREFETCH - CWISS_RawTable_PrefetchHeapBlock(policy, self); - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, policy->key->hash(key), - self->capacity_); - CWISS_PREFETCH(self->ctrl_ + seq.offset_, 3); - CWISS_PREFETCH(self->ctrl_ + seq.offset_ * policy->slot->size, 3); -#endif -} - -/// The return type of `CWISS_RawTable_PrepareInsert()`. -typedef struct { - size_t index; - bool inserted; -} CWISS_PrepareInsert; - -/// Given the hash of a value not currently in the table, finds the next viable -/// slot index to insert it at. -/// -/// If the table does not actually have space, UB. -CWISS_INLINE_NEVER -static size_t CWISS_RawTable_PrepareInsert(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t hash) { - CWISS_FindInfo target = - CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - if (CWISS_UNLIKELY(self->growth_left_ == 0 && - !CWISS_IsDeleted(self->ctrl_[target.offset]))) { - CWISS_RawTable_rehash_and_grow_if_necessary(policy, self); - target = CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - } - self->size_++; - self->growth_left_ -= CWISS_IsEmpty(self->ctrl_[target.offset]); - CWISS_SetCtrl(target.offset, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - // infoz().RecordInsert(hash, target.probe_length); - return target.offset; -} - -/// Attempts to find `key` in the table; if it isn't found, returns where to -/// insert it, instead. -static inline CWISS_PrepareInsert CWISS_RawTable_FindOrPrepareInsert( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - CWISS_RawTable* self, const void* key) { - CWISS_RawTable_PrefetchHeapBlock(policy, self); - size_t hash = key_policy->hash(key); - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_); - while (true) { - CWISS_Group g = CWISS_Group_new(self->ctrl_ + seq.offset_); - CWISS_BitMask match = CWISS_Group_Match(&g, CWISS_H2(hash)); - uint32_t i; - while (CWISS_BitMask_next(&match, &i)) { - size_t idx = CWISS_ProbeSeq_offset(&seq, i); - char* slot = self->slots_ + idx * policy->slot->size; - if (CWISS_LIKELY(key_policy->eq(key, policy->slot->get(slot)))) - return (CWISS_PrepareInsert) { idx, false }; - } - if (CWISS_LIKELY(CWISS_Group_MatchEmpty(&g).mask)) break; - CWISS_ProbeSeq_next(&seq); - CWISS_DCHECK(seq.index_ <= self->capacity_, "full table!"); - } - return (CWISS_PrepareInsert) { - CWISS_RawTable_PrepareInsert(policy, self, hash), - true - }; -} - -/// Prepares a slot to insert an element into. -/// -/// This function does all the work of calling the appropriate policy functions -/// to initialize the slot. -static inline void* CWISS_RawTable_PreInsert(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t i) { - void* dst = self->slots_ + i * policy->slot->size; - policy->slot->init(dst); - return policy->slot->get(dst); -} - -/// Creates a new empty table with the given capacity. -static inline CWISS_RawTable CWISS_RawTable_new(const CWISS_Policy* policy, - size_t capacity) { - CWISS_RawTable self = { - .ctrl_ = CWISS_EmptyGroup(), - }; - - if (capacity != 0) { - self.capacity_ = CWISS_NormalizeCapacity(capacity); - CWISS_RawTable_InitializeSlots(policy, &self); - } - - return self; -} - -/// Ensures that at least `n` more elements can be inserted without a resize -/// (although this function my itself resize and rehash the table). -static inline void CWISS_RawTable_reserve(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t n) { - if (n <= self->size_ + self->growth_left_) { - return; - } - - n = CWISS_NormalizeCapacity(CWISS_GrowthToLowerboundCapacity(n)); - CWISS_RawTable_Resize(policy, self, n); - - // This is after resize, to ensure that we have completed the allocation - // and have potentially sampled the hashtable. - // infoz().RecordReservation(n); -} - -/// Creates a duplicate of this table. -static inline CWISS_RawTable CWISS_RawTable_dup(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - CWISS_RawTable copy = CWISS_RawTable_new(policy, 0); - - CWISS_RawTable_reserve(policy, &copy, self->size_); - // Because the table is guaranteed to be empty, we can do something faster - // than a full `insert`. In particular we do not need to take a trip to - // `CWISS_RawTable_rehash_and_grow_if_necessary()` because we are already - // big enough (since `self` is a priori) and tombstones cannot be created - // during this process. - for (CWISS_RawIter iter = CWISS_RawTable_citer(policy, self); - CWISS_RawIter_get(policy, &iter); CWISS_RawIter_next(policy, &iter)) { - void* v = CWISS_RawIter_get(policy, &iter); - size_t hash = policy->key->hash(v); - - CWISS_FindInfo target = - CWISS_FindFirstNonFull(copy.ctrl_, hash, copy.capacity_); - CWISS_SetCtrl(target.offset, CWISS_H2(hash), copy.capacity_, copy.ctrl_, - copy.slots_, policy->slot->size); - void* slot = CWISS_RawTable_PreInsert(policy, &copy, target.offset); - policy->obj->copy(slot, v); - // infoz().RecordInsert(hash, target.probe_length); - } - copy.size_ = self->size_; - copy.growth_left_ -= self->size_; - return copy; -} - -/// Destroys this table, destroying its elements and freeing the backing array. -static inline void CWISS_RawTable_destroy(const CWISS_Policy* policy, - CWISS_RawTable* self) { - CWISS_RawTable_DestroySlots(policy, self); -} - -/// Returns whether the table is empty. -static inline bool CWISS_RawTable_empty(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return !self->size_; -} - -/// Returns the number of elements in the table. -static inline size_t CWISS_RawTable_size(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return self->size_; -} - -/// Returns the total capacity of the table, which is different from the number -/// of elements that would cause it to get resized. -static inline size_t CWISS_RawTable_capacity(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return self->capacity_; -} - -/// Clears the table, erasing every element contained therein. -static inline void CWISS_RawTable_clear(const CWISS_Policy* policy, CWISS_RawTable* self) { - // Iterating over this container is O(bucket_count()). When bucket_count() - // is much greater than size(), iteration becomes prohibitively expensive. - // For clear() it is more important to reuse the allocated array when the - // container is small because allocation takes comparatively long time - // compared to destruction of the elements of the container. So we pick the - // largest bucket_count() threshold for which iteration is still fast and - // past that we simply deallocate the array. - if (self->capacity_ > 127) { - CWISS_RawTable_DestroySlots(policy, self); - - // infoz().RecordClearedReservation(); - } else if (self->capacity_) { - if (policy->slot->del != NULL) { - size_t i; - for (i = 0; i != self->capacity_; i++) { - if (CWISS_IsFull(self->ctrl_[i])) { - policy->slot->del(self->slots_ + i * policy->slot->size); - } - } - } - - self->size_ = 0; - CWISS_ResetCtrl(self->capacity_, self->ctrl_, self->slots_, - policy->slot->size); - CWISS_RawTable_ResetGrowthLeft(policy, self); - } - CWISS_DCHECK(!self->size_, "size was still nonzero"); - // infoz().RecordStorageChanged(0, capacity_); -} - -/// The return type of `CWISS_RawTable_insert()`. -typedef struct { - /// An iterator referring to the relevant element. - CWISS_RawIter iter; - /// True if insertion actually occurred; false if the element was already - /// present. - bool inserted; -} CWISS_Insert; - -/// "Inserts" `val` into the table if it isn't already present. -/// -/// This function does not perform insertion; it behaves exactly like -/// `CWISS_RawTable_insert()` up until it would copy-initialize the new -/// element, instead returning a valid iterator pointing to uninitialized data. -/// -/// This allows, for example, lazily constructing the parts of the element that -/// do not figure into the hash or equality. -/// -/// If this function returns `true` in `inserted`, the caller has *no choice* -/// but to insert, i.e., they may not change their minds at that point. -/// -/// `key_policy` is a possibly heterogenous key policy for comparing `key`'s -/// type to types in the map. `key_policy` may be `&policy->key`. -static inline CWISS_Insert CWISS_RawTable_deferred_insert( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - CWISS_RawTable* self, const void* key) { - CWISS_PrepareInsert res = - CWISS_RawTable_FindOrPrepareInsert(policy, key_policy, self, key); - - if (res.inserted) { - CWISS_RawTable_PreInsert(policy, self, res.index); - } - return (CWISS_Insert) { - CWISS_RawTable_citer_at(policy, self, res.index), - res.inserted - }; -} - -/// Inserts `val` (by copy) into the table if it isn't already present. -/// -/// Returns an iterator pointing to the element in the map and whether it was -/// just inserted or was already present. -static inline CWISS_Insert CWISS_RawTable_insert(const CWISS_Policy* policy, - CWISS_RawTable* self, - const void* val) { - CWISS_PrepareInsert res = - CWISS_RawTable_FindOrPrepareInsert(policy, policy->key, self, val); - - if (res.inserted) { - void* slot = CWISS_RawTable_PreInsert(policy, self, res.index); - policy->obj->copy(slot, val); - } - return (CWISS_Insert) { - CWISS_RawTable_citer_at(policy, self, res.index), - res.inserted - }; -} - -/// Tries to find the corresponding entry for `key` using `hash` as a hint. -/// If not found, returns a null iterator. -/// -/// `key_policy` is a possibly heterogenous key policy for comparing `key`'s -/// type to types in the map. `key_policy` may be `&policy->key`. -/// -/// If `hash` is not actually the hash of `key`, UB. -static inline CWISS_RawIter CWISS_RawTable_find_hinted( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - const CWISS_RawTable* self, const void* key, size_t hash) { - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_); - while (true) { - CWISS_Group g = CWISS_Group_new(self->ctrl_ + seq.offset_); - CWISS_BitMask match = CWISS_Group_Match(&g, CWISS_H2(hash)); - uint32_t i; - while (CWISS_BitMask_next(&match, &i)) { - char* slot = - self->slots_ + CWISS_ProbeSeq_offset(&seq, i) * policy->slot->size; - if (CWISS_LIKELY(key_policy->eq(key, policy->slot->get(slot)))) - return CWISS_RawTable_citer_at(policy, self, - CWISS_ProbeSeq_offset(&seq, i)); - } - if (CWISS_LIKELY(CWISS_Group_MatchEmpty(&g).mask)) - return (CWISS_RawIter) { 0 }; - CWISS_ProbeSeq_next(&seq); - CWISS_DCHECK(seq.index_ <= self->capacity_, "full table!"); - } -} - -/// Tries to find the corresponding entry for `key`. -/// If not found, returns a null iterator. -/// -/// `key_policy` is a possibly heterogenous key policy for comparing `key`'s -/// type to types in the map. `key_policy` may be `&policy->key`. -static inline CWISS_RawIter CWISS_RawTable_find( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - const CWISS_RawTable* self, const void* key) { - return CWISS_RawTable_find_hinted(policy, key_policy, self, key, - key_policy->hash(key)); -} - -/// Erases the element pointed to by the given valid iterator. -/// This function will invalidate the iterator. -static inline void CWISS_RawTable_erase_at(const CWISS_Policy* policy, - CWISS_RawIter it) { - CWISS_AssertIsFull(it.ctrl_); - if (policy->slot->del != NULL) { - policy->slot->del(it.slot_); - } - CWISS_RawTable_EraseMetaOnly(policy, it); -} - -/// Erases the entry corresponding to `key`, if present. Returns true if -/// deletion occured. -/// -/// `key_policy` is a possibly heterogenous key policy for comparing `key`'s -/// type to types in the map. `key_policy` may be `&policy->key`. -static inline bool CWISS_RawTable_erase(const CWISS_Policy* policy, - const CWISS_KeyPolicy* key_policy, - CWISS_RawTable* self, const void* key) { - CWISS_RawIter it = CWISS_RawTable_find(policy, key_policy, self, key); - if (it.slot_ == NULL) return false; - CWISS_RawTable_erase_at(policy, it); - return true; -} - -/// Triggers a rehash, growing to at least a capacity of `n`. -static inline void CWISS_RawTable_rehash(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t n) { - if (n == 0 && self->capacity_ == 0) return; - if (n == 0 && self->size_ == 0) { - CWISS_RawTable_DestroySlots(policy, self); - // infoz().RecordStorageChanged(0, 0); - // infoz().RecordClearedReservation(); - return; - } - - // bitor is a faster way of doing `max` here. We will round up to the next - // power-of-2-minus-1, so bitor is good enough. - size_t m = CWISS_NormalizeCapacity( - n | CWISS_GrowthToLowerboundCapacity(self->size_)); - // n == 0 unconditionally rehashes as per the standard. - if (n == 0 || m > self->capacity_) { - CWISS_RawTable_Resize(policy, self, m); - - // This is after resize, to ensure that we have completed the allocation - // and have potentially sampled the hashtable. - // infoz().RecordReservation(n); - } -} - -/// Returns whether `key` is contained in this table. -/// -/// `key_policy` is a possibly heterogenous key policy for comparing `key`'s -/// type to types in the map. `key_policy` may be `&policy->key`. -static inline bool CWISS_RawTable_contains(const CWISS_Policy* policy, - const CWISS_KeyPolicy* key_policy, - const CWISS_RawTable* self, - const void* key) { - return CWISS_RawTable_find(policy, key_policy, self, key).slot_ != NULL; -} - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/internal/raw_table.h //////////////////////////////////////////// - -/// cwisstable/declare.h /////////////////////////////////////////////////////// -/// SwissTable code generation macros. -/// -/// This file is the entry-point for users of `cwisstable`. It exports six -/// macros for generating different kinds of tables. Four correspond to Abseil's -/// four SwissTable containers: -/// -/// - `CWISS_DECLARE_FLAT_HASHSET(Set, Type)` -/// - `CWISS_DECLARE_FLAT_HASHMAP(Map, Key, Value)` -/// - `CWISS_DECLARE_NODE_HASHSET(Set, Type)` -/// - `CWISS_DECLARE_NODE_HASHMAP(Map, Key, Value)` -/// -/// These expand to a type (with the same name as the first argument) and and -/// a collection of strongly-typed functions associated to it (the generated -/// API is described below). These macros use the default policy (see policy.h) -/// for each of the four containers; custom policies may be used instead via -/// the following macros: -/// -/// - `CWISS_DECLARE_HASHSET_WITH(Set, Type, kPolicy)` -/// - `CWISS_DECLARE_HASHMAP_WITH(Map, Key, Value, kPolicy)` -/// -/// `kPolicy` must be a constant global variable referring to an appropriate -/// property for the element types of the container. -/// -/// The generated API is safe: the functions are well-typed and automatically -/// pass the correct policy pointer. Because the pointer is a constant -/// expression, it promotes devirtualization when inlining. -/// -/// # Generated API -/// -/// See `set_api.h` and `map_api.h` for detailed listings of what the generated -/// APIs look like. - -CWISS_BEGIN -CWISS_BEGIN_EXTERN - -/// Generates a new hash set type with inline storage and the default -/// plain-old-data policies. -/// -/// See header documentation for examples of generated API. -#define CWISS_DECLARE_FLAT_HASHSET(HashSet_, Type_,obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_DECLARE_FLAT_SET_POLICY(HashSet_##_kPolicy, Type_, obj_copy, obj_dtor, key_hash, key_eq); \ - CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, HashSet_##_kPolicy) - -#define CWISS_DECLARE_FLAT_HASHSET_DEFAULT(HashSet_, Type_) \ - static inline void HashSet_##_default_dtor(void* val) { } \ - static inline void HashSet_##_default_copy(void* dst_, const void* src_) { \ - memcpy(dst_, src_, sizeof(Type_)); \ - } \ - static inline size_t HashSet_##_default_hash(const void* val) { \ - CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ - CWISS_AbslHash_Write(&state, val, sizeof(Type_)); \ - return CWISS_AbslHash_Finish(state); \ - } \ - static inline bool HashSet_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(Type_)) == 0; } \ - CWISS_DECLARE_FLAT_HASHSET(HashSet_, Type_, \ - HashSet_##_default_copy, \ - HashSet_##_default_dtor, \ - HashSet_##_default_hash, \ - HashSet_##_default_eq); - -/// Generates a new hash set type with outline storage and the default -/// plain-old-data policies. -/// -/// See header documentation for examples of generated API. -#define CWISS_DECLARE_NODE_HASHSET(HashSet_, Type_, obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_DECLARE_NODE_SET_POLICY(HashSet_##_kPolicy, Type_, obj_copy, obj_dtor, key_hash, key_eq); \ - CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, HashSet_##_kPolicy) - -#define CWISS_DECLARE_NODE_HASHSET_DEFAULT(HashSet_, Type_) \ - static inline void HashSet_##_default_dtor(void* val) { } \ - static inline void HashSet_##_default_copy(void* dst_, const void* src_) { \ - memcpy(dst_, src_, sizeof(Type_)); \ - } \ - static inline size_t HashSet_##_default_hash(const void* val) { \ - CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ - CWISS_AbslHash_Write(&state, val, sizeof(Type_)); \ - return CWISS_AbslHash_Finish(state); \ - } \ - static inline bool HashSet_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(Type_)) == 0; } \ - CWISS_DECLARE_NODE_HASHSET(HashSet_, Type_, \ - HashSet_##_default_copy, \ - HashSet_##_default_dtor, \ - HashSet_##_default_hash, \ - HashSet_##_default_eq); - -/// Generates a new hash map type with inline storage and the default -/// plain-old-data policies. -/// -/// See header documentation for examples of generated API. -#define CWISS_DECLARE_FLAT_HASHMAP(HashMap_, K_, V_, obj_copy, obj_dtor, key_hash, key_eq) \ - CWISS_DECLARE_FLAT_MAP_POLICY(HashMap_##_kPolicy, K_, V_, obj_copy, obj_dtor, key_hash, key_eq); \ - CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, HashMap_##_kPolicy) - -#define CWISS_DECLARE_FLAT_HASHMAP_DEFAULT(HashMap_, K_, V_) \ - static inline void HashMap_##_default_dtor(void* val) { } \ - typedef struct { \ - K_ k; \ - V_ v; \ - } HashMap_##_EntryInternal; \ - static inline void HashMap_##_default_copy(void* dst_, const void* src_) { \ - memcpy(dst_, src_, sizeof(HashMap_##_EntryInternal)); \ - } \ - static inline size_t HashMap_##_default_hash(const void* val) { \ - CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ - CWISS_AbslHash_Write(&state, val, sizeof(K_)); \ - return CWISS_AbslHash_Finish(state); \ - } \ - static inline bool HashMap_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(K_)) == 0; } \ - CWISS_DECLARE_FLAT_HASHMAP(HashMap_, K_, V_, \ - HashMap_##_default_copy, \ - HashMap_##_default_dtor, \ - HashMap_##_default_hash, \ - HashMap_##_default_eq); - -/// Generates a new hash map type with outline storage and the default -/// plain-old-data policies. -/// -/// See header documentation for examples of generated API. -#define CWISS_DECLARE_NODE_HASHMAP(HashMap_, K_, V_, a,b,c,d) \ - CWISS_DECLARE_NODE_MAP_POLICY(HashMap_##_kPolicy, K_, V_, a,b,c,d); \ -CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, HashMap_##_kPolicy) - -#define CWISS_DECLARE_NODE_HASHMAP_DEFAULT(HashMap_, K_, V_) \ - typedef struct { \ - K_ k; \ - V_ v; \ - } HashMap_##_EntryInternal; \ - static inline void HashMap_##_default_dtor(void* val) { } \ - static inline void HashMap_##_default_copy(void* dst_, const void* src_) { \ - memcpy(dst_, src_, sizeof(HashMap_##_EntryInternal)); \ - } \ - static inline size_t HashMap_##_default_hash(const void* val) { \ - CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ - CWISS_AbslHash_Write(&state, val, sizeof(K_)); \ - return CWISS_AbslHash_Finish(state); \ - } \ - static inline bool HashMap_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(K_)) == 0; } \ - CWISS_DECLARE_NODE_HASHMAP(HashMap_, K_, V_, \ - HashMap_##_default_copy, \ - HashMap_##_default_dtor, \ - HashMap_##_default_hash, \ - HashMap_##_default_eq); - -/// Generates a new hash set type using the given policy. -/// -/// See header documentation for examples of generated API. -#define CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, kPolicy_) \ - typedef Type_ HashSet_##_Entry; \ - typedef Type_ HashSet_##_Key; \ - CWISS_DECLARE_COMMON_(HashSet_, HashSet_##_Entry, HashSet_##_Key, kPolicy_) - -/// Generates a new hash map type using the given policy. -/// -/// See header documentation for examples of generated API. -#define CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, kPolicy_) \ - typedef struct { \ - K_ key; \ - V_ val; \ - } HashMap_##_Entry; \ -typedef K_ HashMap_##_Key; \ -CWISS_DECLARE_COMMON_(HashMap_, HashMap_##_Entry, HashMap_##_Key, kPolicy_) - -/// Declares a heterogenous lookup for an existing SwissTable type. -/// -/// This macro will expect to find the following functions: -/// - size_t <Table>_<Key>_hash(const Key*); -/// - bool <Table>_<Key>_eq(const Key*, const <Table>_Key*); -/// -/// These functions will be used to build the heterogenous key policy. -#define CWISS_DECLARE_LOOKUP(HashSet_, Key_) \ - CWISS_DECLARE_LOOKUP_NAMED(HashSet_, Key_, Key_) - -/// Declares a heterogenous lookup for an existing SwissTable type. -/// -/// This is like `CWISS_DECLARE_LOOKUP`, but allows customizing the name used -/// in the `_by_` prefix on the names, as well as the names of the extension -/// point functions. -#define CWISS_DECLARE_LOOKUP_NAMED(HashSet_, LookupName_, Key_) \ - CWISS_BEGIN \ -static inline size_t HashSet_##_##LookupName_##_SyntheticHash( \ - const void* val) { \ - return HashSet_##_##LookupName_##_hash((const Key_*)val); \ -} \ -static inline bool HashSet_##_##LookupName_##_SyntheticEq(const void* a, \ - const void* b) { \ - return HashSet_##_##LookupName_##_eq((const Key_*)a, \ - (const HashSet_##_Entry*)b); \ -} \ -static const CWISS_KeyPolicy HashSet_##_##LookupName_##_kPolicy = { \ - HashSet_##_##LookupName_##_SyntheticHash, \ - HashSet_##_##LookupName_##_SyntheticEq, \ -}; \ -\ -static inline const CWISS_KeyPolicy* HashSet_##_##LookupName_##_policy( \ - void) { \ - return &HashSet_##_##LookupName_##_kPolicy; \ -} \ -\ -static inline HashSet_##_Insert HashSet_##_deferred_insert_by_##LookupName_( \ - HashSet_* self, const Key_* key) { \ - CWISS_Insert ret = CWISS_RawTable_deferred_insert( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key); \ - return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ -} \ -static inline HashSet_##_CIter HashSet_##_cfind_hinted_by_##LookupName_( \ - const HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_CIter){CWISS_RawTable_find_hinted( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key, hash)}; \ -} \ -static inline HashSet_##_Iter HashSet_##_find_hinted_by_##LookupName_( \ - HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_Iter){CWISS_RawTable_find_hinted( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key, hash)}; \ -} \ -\ -static inline HashSet_##_CIter HashSet_##_cfind_by_##LookupName_( \ - const HashSet_* self, const Key_* key) { \ - return (HashSet_##_CIter){CWISS_RawTable_find( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key)}; \ -} \ -static inline HashSet_##_Iter HashSet_##_find_by_##LookupName_( \ - HashSet_* self, const Key_* key) { \ - return (HashSet_##_Iter){CWISS_RawTable_find( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key)}; \ -} \ -\ -static inline bool HashSet_##_contains_by_##LookupName_( \ - const HashSet_* self, const Key_* key) { \ - return CWISS_RawTable_contains(HashSet_##_policy(), \ - &HashSet_##_##LookupName_##_kPolicy, \ - &self->set_, key); \ -} \ -\ -static inline bool HashSet_##_erase_by_##LookupName_(HashSet_* self, \ - const Key_* key) { \ - return CWISS_RawTable_erase(HashSet_##_policy(), \ - &HashSet_##_##LookupName_##_kPolicy, \ - &self->set_, key); \ -} \ -\ -CWISS_END \ -/* Force a semicolon. */ \ -struct HashSet_##_##LookupName_##_NeedsTrailingSemicolon_ { \ - int x; \ -} - -// ---- PUBLIC API ENDS HERE! ---- - -#define CWISS_DECLARE_COMMON_(HashSet_, Type_, Key_, kPolicy_) \ - CWISS_BEGIN \ -static inline const CWISS_Policy* HashSet_##_policy(void) { \ - return &kPolicy_; \ -} \ -\ -typedef struct { \ - CWISS_RawTable set_; \ -} HashSet_; \ -\ -static inline HashSet_ HashSet_##_new(size_t bucket_count) { \ - return (HashSet_){CWISS_RawTable_new(&kPolicy_, bucket_count)}; \ -} \ -static inline HashSet_ HashSet_##_dup(const HashSet_* that) { \ - return (HashSet_){CWISS_RawTable_dup(&kPolicy_, &that->set_)}; \ -} \ -static inline void HashSet_##_destroy(HashSet_* self) { \ - CWISS_RawTable_destroy(&kPolicy_, &self->set_); \ -} \ -\ -typedef struct { \ - CWISS_RawIter it_; \ -} HashSet_##_Iter; \ -static inline HashSet_##_Iter HashSet_##_iter(HashSet_* self) { \ - return (HashSet_##_Iter){CWISS_RawTable_iter(&kPolicy_, &self->set_)}; \ -} \ -static inline Type_* HashSet_##_Iter_get(const HashSet_##_Iter* it) { \ - return (Type_*)CWISS_RawIter_get(&kPolicy_, &it->it_); \ -} \ -static inline Type_* HashSet_##_Iter_next(HashSet_##_Iter* it) { \ - return (Type_*)CWISS_RawIter_next(&kPolicy_, &it->it_); \ -} \ -\ -typedef struct { \ - CWISS_RawIter it_; \ -} HashSet_##_CIter; \ -static inline HashSet_##_CIter HashSet_##_citer(const HashSet_* self) { \ - return (HashSet_##_CIter){CWISS_RawTable_citer(&kPolicy_, &self->set_)}; \ -} \ -static inline const Type_* HashSet_##_CIter_get( \ - const HashSet_##_CIter* it) { \ - return (const Type_*)CWISS_RawIter_get(&kPolicy_, &it->it_); \ -} \ -static inline const Type_* HashSet_##_CIter_next(HashSet_##_CIter* it) { \ - return (const Type_*)CWISS_RawIter_next(&kPolicy_, &it->it_); \ -} \ -static inline HashSet_##_CIter HashSet_##_Iter_const(HashSet_##_Iter it) { \ - return (HashSet_##_CIter){it.it_}; \ -} \ -\ -static inline void HashSet_##_reserve(HashSet_* self, size_t n) { \ - CWISS_RawTable_reserve(&kPolicy_, &self->set_, n); \ -} \ -static inline void HashSet_##_rehash(HashSet_* self, size_t n) { \ - CWISS_RawTable_rehash(&kPolicy_, &self->set_, n); \ -} \ -\ -static inline bool HashSet_##_empty(const HashSet_* self) { \ - return CWISS_RawTable_empty(&kPolicy_, &self->set_); \ -} \ -static inline size_t HashSet_##_size(const HashSet_* self) { \ - return CWISS_RawTable_size(&kPolicy_, &self->set_); \ -} \ -static inline size_t HashSet_##_capacity(const HashSet_* self) { \ - return CWISS_RawTable_capacity(&kPolicy_, &self->set_); \ -} \ -\ -static inline void HashSet_##_clear(HashSet_* self) { \ - CWISS_RawTable_clear(&kPolicy_, &self->set_); \ -} \ -\ -typedef struct { \ - HashSet_##_Iter iter; \ - bool inserted; \ -} HashSet_##_Insert; \ -static inline HashSet_##_Insert HashSet_##_deferred_insert( \ - HashSet_* self, const Key_* key) { \ - CWISS_Insert ret = CWISS_RawTable_deferred_insert(&kPolicy_, kPolicy_.key, \ - &self->set_, key); \ - return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ -} \ -static inline HashSet_##_Insert HashSet_##_insert(HashSet_* self, \ - const Type_* val) { \ - CWISS_Insert ret = CWISS_RawTable_insert(&kPolicy_, &self->set_, val); \ - return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ -} \ -\ -static inline HashSet_##_CIter HashSet_##_cfind_hinted( \ - const HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_CIter){CWISS_RawTable_find_hinted( \ - &kPolicy_, kPolicy_.key, &self->set_, key, hash)}; \ -} \ -static inline HashSet_##_Iter HashSet_##_find_hinted( \ - HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_Iter){CWISS_RawTable_find_hinted( \ - &kPolicy_, kPolicy_.key, &self->set_, key, hash)}; \ -} \ -static inline HashSet_##_CIter HashSet_##_cfind(const HashSet_* self, \ - const Key_* key) { \ - return (HashSet_##_CIter){ \ - CWISS_RawTable_find(&kPolicy_, kPolicy_.key, &self->set_, key)}; \ -} \ -static inline HashSet_##_Iter HashSet_##_find(HashSet_* self, \ - const Key_* key) { \ - return (HashSet_##_Iter){ \ - CWISS_RawTable_find(&kPolicy_, kPolicy_.key, &self->set_, key)}; \ -} \ -\ -static inline bool HashSet_##_contains(const HashSet_* self, \ - const Key_* key) { \ - return CWISS_RawTable_contains(&kPolicy_, kPolicy_.key, &self->set_, key); \ -} \ -\ -static inline void HashSet_##_erase_at(HashSet_##_Iter it) { \ - CWISS_RawTable_erase_at(&kPolicy_, it.it_); \ -} \ -static inline bool HashSet_##_erase(HashSet_* self, const Key_* key) { \ - return CWISS_RawTable_erase(&kPolicy_, kPolicy_.key, &self->set_, key); \ -} \ -\ -CWISS_END \ -/* Force a semicolon. */ struct HashSet_##_NeedsTrailingSemicolon_ { int x; } - -CWISS_END_EXTERN -CWISS_END -/// cwisstable/declare.h /////////////////////////////////////////////////////// - -#endif // CWISSTABLE_H_ diff --git a/libr/include/gcc_stdatomic.h b/libr/include/gcc_stdatomic.h deleted file mode 100644 index 313feff3af..0000000000 --- a/libr/include/gcc_stdatomic.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Copyright © 2018, VideoLAN and dav1d authors -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, this -* list of conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the documentation -* and/or other materials provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef GCCVER_STDATOMIC_H_ -#define GCCVER_STDATOMIC_H_ - -#if !defined(__cplusplus) - -typedef int atomic_int; -typedef unsigned int atomic_uint; - -#ifndef __ATOMIC_RELAXED -#define __ATOMIC_RELAXED 0 -#endif -#ifndef __ATOMIC_CONSUME -#define __ATOMIC_CONSUME 1 -#endif -#ifndef __ATOMIC_ACQUIRE -#define __ATOMIC_ACQUIRE 2 -#endif -#ifndef __ATOMIC_RELEASE -#define __ATOMIC_RELEASE 3 -#endif -#ifndef __ATOMIC_ACQ_REL -#define __ATOMIC_ACQ_REL 4 -#endif -#ifndef __ATOMIC_SEQ_CST -#define __ATOMIC_SEQ_CST 5 -#endif - -#define memory_order_relaxed __ATOMIC_RELAXED -#define memory_order_acquire __ATOMIC_ACQUIRE - -#define atomic_init(p_a, v) do { *(p_a) = (v); } while(0) -#define atomic_store(p_a, v) __atomic_store_n(p_a, v, __ATOMIC_SEQ_CST) -#define atomic_load(p_a) __atomic_load_n(p_a, __ATOMIC_SEQ_CST) -#define atomic_load_explicit(p_a, mo) __atomic_load_n(p_a, mo) -#define atomic_fetch_add(p_a, inc) __atomic_fetch_add(p_a, inc, __ATOMIC_SEQ_CST) -#define atomic_fetch_add_explicit(p_a, inc, mo) __atomic_fetch_add(p_a, inc, mo) -#define atomic_fetch_sub(p_a, dec) __atomic_fetch_sub(p_a, dec, __ATOMIC_SEQ_CST) -#define atomic_exchange(p_a, v) __atomic_exchange_n(p_a, v, __ATOMIC_SEQ_CST) -#define atomic_fetch_or(p_a, v) __atomic_fetch_or(p_a, v, __ATOMIC_SEQ_CST) -#define atomic_compare_exchange_strong(p_a, expected, desired) __atomic_compare_exchange_n(p_a, expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) - -#endif /* !defined(__cplusplus) */ - -#endif /* GCCVER_STDATOMIC_H_ */ diff --git a/libr/include/msvc_stdatomic.h b/libr/include/msvc_stdatomic.h deleted file mode 100644 index f086bab5d5..0000000000 --- a/libr/include/msvc_stdatomic.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef MSCVER_STDATOMIC_H_ -#define MSCVER_STDATOMIC_H_ - -#if !defined(__cplusplus) && defined(_MSC_VER) - -#pragma warning(push) -#pragma warning(disable:4067) /* newline for __has_include_next */ - -#if defined(__clang__) && __has_include_next(<stdatomic.h>) - /* use the clang stdatomic.h with clang-cl*/ -# include_next <stdatomic.h> -#else /* ! stdatomic.h */ - -#include <windows.h> - -typedef volatile LONG atomic_int; -typedef volatile ULONG atomic_uint; - -typedef enum { - memory_order_relaxed, - memory_order_acquire -} msvc_atomic_memory_order; - -#define atomic_init(p_a, v) do { *(p_a) = (v); } while(0) -#define atomic_store(p_a, v) InterlockedExchange((LONG*)p_a, v) -#define atomic_load(p_a) InterlockedCompareExchange((LONG*)p_a, 0, 0) -#define atomic_exchange(p_a, v) InterlockedExchange(p_a, v) -#define atomic_load_explicit(p_a, mo) atomic_load(p_a) - -static inline int atomic_compare_exchange_strong_int(LONG *obj, LONG *expected, - LONG desired) -{ - LONG orig = *expected; - *expected = InterlockedCompareExchange(obj, desired, orig); - return *expected == orig; -} -#define atomic_compare_exchange_strong(p_a, expected, desired) atomic_compare_exchange_strong_int((LONG *)p_a, (LONG *)expected, (LONG)desired) - -/* - * TODO use a special call to increment/decrement - * using InterlockedIncrement/InterlockedDecrement - */ -#define atomic_fetch_add(p_a, inc) InterlockedExchangeAdd(p_a, inc) -#define atomic_fetch_sub(p_a, dec) InterlockedExchangeAdd(p_a, -(dec)) -#define atomic_fetch_or(p_a, v) InterlockedOr(p_a, v) -#define atomic_fetch_add_explicit(p_a, inc, mo) atomic_fetch_add(p_a, inc) - -#endif /* ! stdatomic.h */ - -#pragma warning(pop) - -#endif /* !defined(__cplusplus) && defined(_MSC_VER) */ - -#endif /* MSCVER_STDATOMIC_H_ */ diff --git a/libr/include/r_bin.h b/libr/include/r_bin.h index 7667936087..65ced72381 100644 --- a/libr/include/r_bin.h +++ b/libr/include/r_bin.h @@ -3,7 +3,6 @@ #include <r_util.h> #include <r_types.h> -#include <sdb/ht_pu.h> #include <r_io.h> #include <r_cons.h> #include <r_list.h> @@ -297,7 +296,7 @@ typedef struct r_bin_section_t { #include <r_vec.h> -// R2_590 only forward declare here for better compile times +// XXX only forward declare here for better compile times R_API void r_bin_symbol_fini(RBinSymbol *sym); R_VEC_TYPE_WITH_FINI (RVecRBinSymbol, RBinSymbol, r_bin_symbol_fini); R_VEC_TYPE(RVecRBinSection, RBinSection); @@ -861,10 +860,12 @@ R_API const char *r_bin_lang_tostring(int type); R_API RList *r_bin_get_mem(RBin *bin); /* filter.c */ +typedef struct HtSU_t HtSU; + R_API void r_bin_load_filter(RBin *bin, ut64 rules); R_API void r_bin_filter_symbols(RBinFile *bf, RList *list); R_API void r_bin_filter_sections(RBinFile *bf, RList *list); -R_API char *r_bin_filter_name(RBinFile *bf, HtPU *db, ut64 addr, char *name); +R_API char *r_bin_filter_name(RBinFile *bf, HtSU *db, ut64 addr, const char *name); R_API void r_bin_filter_sym(RBinFile *bf, HtPP *ht, ut64 vaddr, RBinSymbol *sym); R_API bool r_bin_strpurge(RBin *bin, const char *str, ut64 addr); R_API bool r_bin_string_filter(RBin *bin, const char *str, ut64 addr); diff --git a/libr/include/r_core.h b/libr/include/r_core.h index a890aee86e..412f25b2cb 100644 --- a/libr/include/r_core.h +++ b/libr/include/r_core.h @@ -99,12 +99,7 @@ typedef enum { } RCoreVisualMode; typedef struct r_core_plugin_t { - // R2_590 Use RPluginMeta - const char *name; - const char *desc; - const char *license; - const char *author; - const char *version; + RPluginMeta meta; RCmdCb call; // returns true if command was handled, false otherwise. RCmdCb init; RCmdCb fini; @@ -214,6 +209,37 @@ typedef struct r_core_visual_t { RCoreVisualMode printidx; RList *tabs; int tab; + bool textedit_mode; + int obs; + bool ime; + bool imes; + int nib; + int blocksize; + bool autoblocksize; + int disMode; + int hexMode; + int printMode; + bool snowMode; + RList *snows; + int color; + int zoom; + int currentFormat; + int current0format; + char numbuf[32]; + int numbuf_i; + bool splitView; + ut64 splitPtr; + int current3format; + int current4format; + int current5format; + RConfigHold *hold; // TODO should be a tab-specific var + ut64 oldpc; + ut64 oseek; + char debugstr[512]; + + bool firstRun; + bool fromVisual; + char *menus_Colors[128]; } RCoreVisual; typedef struct { diff --git a/libr/include/r_esil.h b/libr/include/r_esil.h index 9deb6afb4d..37e6fc74fd 100644 --- a/libr/include/r_esil.h +++ b/libr/include/r_esil.h @@ -151,6 +151,8 @@ typedef struct r_esil_t { Sdb *stats; REsilTrace *trace; REsilCallbacks cb; + REsilCallbacks ocb; + bool ocb_set; #if 0 struct r_anal_reil_t *Reil; #endif diff --git a/libr/include/r_io.h b/libr/include/r_io.h index 80099a277b..c84d37f04a 100644 --- a/libr/include/r_io.h +++ b/libr/include/r_io.h @@ -5,6 +5,7 @@ #include <r_list.h> #include <r_util.h> +#include <r_lib.h> #include <r_socket.h> #include <r_vector.h> #include <r_util/r_w32dw.h> @@ -122,8 +123,8 @@ typedef struct r_io_cache_layer_t { typedef struct r_io_cache_t { RList *layers; // a list of cache layers-- must be a vector O(n) - int enabled; // R2_590 bool? ut32 mode; // read, write, exec (enabled) sperm = requires maps + bool enabled; } RIOCache; // -io-cache- @@ -191,12 +192,7 @@ typedef struct { } RIORap; typedef struct r_io_plugin_t { - // RPluginMeta - const char *name; - const char *desc; - const char *version; - const char *author; - const char *license; + const RPluginMeta meta; void *widget; const char *uris; int (*listener)(RIODesc *io); diff --git a/libr/io/io_plugin.c b/libr/io/io_plugin.c index b590e1afa8..c39d5fed07 100644 --- a/libr/io/io_plugin.c +++ b/libr/io/io_plugin.c @@ -9,7 +9,7 @@ static RIOPlugin *io_static_plugins[] = { R_API bool r_io_plugin_add(RIO *io, RIOPlugin *plugin) { r_return_val_if_fail (io && plugin && io->plugins, false); - if (!plugin->name) { + if (!plugin->meta.name) { return false; } ls_append (io->plugins, plugin); @@ -17,7 +17,7 @@ R_API bool r_io_plugin_add(RIO *io, RIOPlugin *plugin) { } R_API bool r_io_plugin_remove(RIO *io, RIOPlugin *plugin) { - // R2_590 TODO + // XXX TODO return true; } @@ -29,7 +29,7 @@ R_API bool r_io_plugin_init(RIO *io) { } io->plugins = ls_newf (free); for (i = 0; io_static_plugins[i]; i++) { - if (!io_static_plugins[i]->name) { + if (!io_static_plugins[i]->meta.name) { continue; } static_plugin = R_NEW0 (RIOPlugin); @@ -66,7 +66,7 @@ R_API RIOPlugin *r_io_plugin_byname(RIO *io, const char *name) { SdbListIter *iter; RIOPlugin *iop; ls_foreach (io->plugins, iter, iop) { - if (!strcmp (name, iop->name)) { + if (!strcmp (name, iop->meta.name)) { return iop; } } @@ -85,7 +85,7 @@ R_API int r_io_plugin_list(RIO *io) { str[2] = plugin->isdbg ? 'd' : '_'; str[3] = 0; io->cb_printf ("%s %-8s %-6s %s.", str, - r_str_get (plugin->name), r_str_get (plugin->license), r_str_get (plugin->desc)); + r_str_get (plugin->meta.name), r_str_get (plugin->meta.license), r_str_get (plugin->meta.desc)); if (plugin->uris) { io->cb_printf (" %s", plugin->uris); } @@ -114,14 +114,14 @@ R_API int r_io_plugin_list_json(RIO *io) { pj_o (pj); pj_ks (pj, "permissions", str); - if (plugin->name) { - pj_ks (pj, "name", plugin->name); + if (plugin->meta.name) { + pj_ks (pj, "name", plugin->meta.name); } - if (plugin->desc) { - pj_ks (pj, "description", plugin->desc); + if (plugin->meta.desc) { + pj_ks (pj, "description", plugin->meta.desc); } - if (plugin->license) { - pj_ks (pj, "license", plugin->license); + if (plugin->meta.license) { + pj_ks (pj, "license", plugin->meta.license); } if (plugin->uris) { char *uri; @@ -137,11 +137,11 @@ R_API int r_io_plugin_list_json(RIO *io) { r_list_free (plist); free (uris); } - if (plugin->version) { - pj_ks (pj, "version", plugin->version); + if (plugin->meta.version) { + pj_ks (pj, "version", plugin->meta.version); } - if (plugin->author) { - pj_ks (pj, "author", plugin->author); + if (plugin->meta.author) { + pj_ks (pj, "author", plugin->meta.author); } pj_end (pj); n++; diff --git a/libr/io/p/io_ar.c b/libr/io/p/io_ar.c index ddd321ce01..d70f5476a0 100644 --- a/libr/io/p/io_ar.c +++ b/libr/io/p/io_ar.c @@ -144,9 +144,11 @@ static int r_io_ar_write(RIO *io, RIODesc *fd, const ut8 *buf, int count) { } RIOPlugin r_io_plugin_ar = { - .name = "ar", - .desc = "Open ar/lib files", - .license = "LGPL3", + .meta = { + .name = "ar", + .desc = "Open ar/lib files", + .license = "LGPL3", + }, .uris = "ar://,lib://,arall://,liball://", .open = r_io_ar_open, .open_many = r_io_ar_open_many, diff --git a/libr/io/p/io_bfdbg.c b/libr/io/p/io_bfdbg.c index d445b73ea5..1c51eb7151 100644 --- a/libr/io/p/io_bfdbg.c +++ b/libr/io/p/io_bfdbg.c @@ -193,9 +193,11 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_bfdbg = { - .name = "bfdbg", - .desc = "Attach to brainFuck Debugger instance", - .license = "LGPL3", + .meta = { + .name = "bfdbg", + .desc = "Attach to brainFuck Debugger instance", + .license = "LGPL3", + }, .uris = "bfdbg://", .open = __open, .close = __close, diff --git a/libr/io/p/io_bochs.c b/libr/io/p/io_bochs.c index 326bbe1205..1b6f8532d7 100644 --- a/libr/io/p/io_bochs.c +++ b/libr/io/p/io_bochs.c @@ -97,9 +97,11 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_bochs = { - .name = "bochs", - .desc = "Attach to a BOCHS debugger instance", - .license = "LGPL3", + .meta = { + .name = "bochs", + .desc = "Attach to a BOCHS debugger instance", + .license = "LGPL3", + }, .uris = "bochs://", .open = __open, .close = __close, diff --git a/libr/io/p/io_debug.c b/libr/io/p/io_debug.c index 94e48ab63e..d77f0ac3c6 100644 --- a/libr/io/p/io_debug.c +++ b/libr/io/p/io_debug.c @@ -555,19 +555,23 @@ static RIODesc *__open(RIO *io, const char *file, int rw, int mode) { } RIOPlugin r_io_plugin_debug = { - .name = "debug", - .desc = "Attach to native debugger instance", - .license = "LGPL3", + .meta = { + .name = "debug", + .desc = "Attach to native debugger instance", + .license = "LGPL3", + .author = "pancake", + }, .uris = "dbg://,pidof://,waitfor://", - .author = "pancake", .open = __open, .check = __plugin_open, .isdbg = true, }; #else RIOPlugin r_io_plugin_debug = { - .name = "debug", - .desc = "Debug a program or pid. (NOT SUPPORTED FOR THIS PLATFORM)", + .meta = { + .name = "debug", + .desc = "Debug a program or pid. (NOT SUPPORTED FOR THIS PLATFORM)", + }, }; #endif diff --git a/libr/io/p/io_default.c b/libr/io/p/io_default.c index 29ccf00b26..ed0a226e8a 100644 --- a/libr/io/p/io_default.c +++ b/libr/io/p/io_default.c @@ -315,9 +315,11 @@ static bool __is_blockdevice(RIODesc *desc) { #endif RIOPlugin r_io_plugin_default = { - .name = "default", - .desc = "Open local files", - .license = "LGPL3", + .meta = { + .name = "default", + .desc = "Open local files", + .license = "LGPL3", + }, .uris = "file://,nocache://", .open = __open_default, .close = __close, diff --git a/libr/io/p/io_fd.c b/libr/io/p/io_fd.c index 6acafb0137..c88e723d77 100644 --- a/libr/io/p/io_fd.c +++ b/libr/io/p/io_fd.c @@ -82,15 +82,17 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_fd = { + .meta = { #if R2__WINDOWS__ - .name = "handle", - .desc = "Local process file handle IO", + .name = "handle", + .desc = "Local process file handle IO", #else - .name = "fd", - .desc = "Local process filedescriptor IO", + .name = "fd", + .desc = "Local process filedescriptor IO", #endif + .license = "MIT", + }, .uris = FDURI, - .license = "MIT", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_gdb.c b/libr/io/p/io_gdb.c index 662f4d6706..523b47289e 100644 --- a/libr/io/p/io_gdb.c +++ b/libr/io/p/io_gdb.c @@ -403,10 +403,12 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_gdb = { + .meta = { + .name = "gdb", + .license = "LGPL3", + .desc = "Attach to gdbserver instance", + }, //void *plugin; - .name = "gdb", - .license = "LGPL3", - .desc = "Attach to gdbserver instance", .uris = "gdb://", .open = __open, .close = __close, diff --git a/libr/io/p/io_gprobe.c b/libr/io/p/io_gprobe.c index 74c8898d63..6622d1a4d5 100644 --- a/libr/io/p/io_gprobe.c +++ b/libr/io/p/io_gprobe.c @@ -1210,9 +1210,11 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_gprobe = { - .name = "gprobe", - .desc = "Open gprobe connection", - .license = "LGPL3", + .meta = { + .name = "gprobe", + .desc = "Open gprobe connection", + .license = "LGPL3", + }, .uris = "gprobe://", .open = __open, .close = __close, diff --git a/libr/io/p/io_gzip.c b/libr/io/p/io_gzip.c index af056b6172..1017fa86ac 100644 --- a/libr/io/p/io_gzip.c +++ b/libr/io/p/io_gzip.c @@ -184,9 +184,11 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_gzip = { - .name = "gzip", - .desc = "Read/write gzipped files", - .license = "LGPL3", + .meta = { + .name = "gzip", + .desc = "Read/write gzipped files", + .license = "LGPL3", + }, .uris = "gzip://", .open = __open, .close = __close, diff --git a/libr/io/p/io_http.c b/libr/io/p/io_http.c index 6bbfedb22b..286631a7c4 100644 --- a/libr/io/p/io_http.c +++ b/libr/io/p/io_http.c @@ -31,10 +31,12 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_http = { - .name = "http", - .desc = "Make http get requests", + .meta = { + .name = "http", + .desc = "Make http get requests", + .license = "LGPL3", + }, .uris = "http://", - .license = "LGPL3", .open = __open, .close = io_memory_close, .read = io_memory_read, diff --git a/libr/io/p/io_ihex.c b/libr/io/p/io_ihex.c index d23aaf704f..9b2420d54d 100644 --- a/libr/io/p/io_ihex.c +++ b/libr/io/p/io_ihex.c @@ -428,10 +428,12 @@ static bool __resize(RIO *io, RIODesc *fd, ut64 size) { } RIOPlugin r_io_plugin_ihex = { - .name = "ihex", - .desc = "Open intel HEX file", + .meta = { + .name = "ihex", + .desc = "Open intel HEX file", + .license = "LGPL", + }, .uris = "ihex://", - .license = "LGPL", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_isotp.c b/libr/io/p/io_isotp.c index cc99574aae..2daa0f6d35 100644 --- a/libr/io/p/io_isotp.c +++ b/libr/io/p/io_isotp.c @@ -131,10 +131,12 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_isotp = { - .name = "isotp", - .desc = "Connect using the ISOTP protocol (isotp://interface/srcid/dstid)", + .meta = { + .name = "isotp", + .desc = "Connect using the ISOTP protocol (isotp://interface/srcid/dstid)", + .license = "MIT", + }, .uris = ISOTPURI, - .license = "MIT", .open = __open, .close = __close, .read = __read, @@ -145,9 +147,11 @@ RIOPlugin r_io_plugin_isotp = { #else RIOPlugin r_io_plugin_isotp = { - .name = "isotp", - .license = "MIT", - .desc = "shared memory resources (not for this platform)", + .meta = { + .name = "isotp", + .license = "MIT", + .desc = "shared memory resources (not for this platform)", + }, }; #endif diff --git a/libr/io/p/io_mach.c b/libr/io/p/io_mach.c index 45bfc0437d..ff2cfc1ba8 100644 --- a/libr/io/p/io_mach.c +++ b/libr/io/p/io_mach.c @@ -559,9 +559,11 @@ static int __get_pid(RIODesc *desc) { // TODO: rename ptrace to io_mach .. err io.ptrace ?? RIOPlugin r_io_plugin_mach = { - .name = "mach", - .desc = "Attach to mach debugger instance", - .license = "LGPL", + .meta = { + .name = "mach", + .desc = "Attach to mach debugger instance", + .license = "LGPL", + }, .uris = "attach://,mach://,smach://", .open = __open, .close = __close, @@ -577,9 +579,11 @@ RIOPlugin r_io_plugin_mach = { #else RIOPlugin r_io_plugin_mach = { - .name = "mach", - .desc = "mach debug io (unsupported in this platform)", - .license = "LGPL" + .meta = { + .name = "mach", + .desc = "mach debug io (unsupported in this platform)", + .license = "LGPL" + }, }; #endif diff --git a/libr/io/p/io_malloc.c b/libr/io/p/io_malloc.c index 23349ab9ee..4235a8c989 100644 --- a/libr/io/p/io_malloc.c +++ b/libr/io/p/io_malloc.c @@ -76,10 +76,12 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_malloc = { - .name = "malloc", - .desc = "Memory allocation plugin", + .meta = { + .name = "malloc", + .desc = "Memory allocation plugin", + .license = "LGPL3", + }, .uris = "malloc://,hex://,slurp://,stdin://", - .license = "LGPL3", .open = __open, .close = io_memory_close, .read = io_memory_read, diff --git a/libr/io/p/io_mmap.c b/libr/io/p/io_mmap.c index 798fc2b83b..c45d4ab054 100644 --- a/libr/io/p/io_mmap.c +++ b/libr/io/p/io_mmap.c @@ -185,10 +185,12 @@ static bool __resize(RIO *io, RIODesc *fd, ut64 size) { } RIOPlugin r_io_plugin_mmap = { - .name = "mmap", - .desc = "Open files using mmap", + .meta = { + .name = "mmap", + .desc = "Open files using mmap", + .license = "LGPL3", + }, .uris = "mmap://", - .license = "LGPL3", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_null.c b/libr/io/p/io_null.c index ccb316e7a9..14341888c5 100644 --- a/libr/io/p/io_null.c +++ b/libr/io/p/io_null.c @@ -100,9 +100,11 @@ static RIODesc* __open(RIO* io, const char* pathname, int rw, int mode) { } RIOPlugin r_io_plugin_null = { - .name = "null", - .desc = "Null plugin", - .license = "LGPL3", + .meta = { + .name = "null", + .desc = "Null plugin", + .license = "LGPL3", + }, .uris = "null://", .open = __open, .close = __close, diff --git a/libr/io/p/io_procpid.c b/libr/io/p/io_procpid.c index ccfe5befb2..167d77960d 100644 --- a/libr/io/p/io_procpid.c +++ b/libr/io/p/io_procpid.c @@ -125,9 +125,11 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_procpid = { - .name = "procpid", - .desc = "Open /proc/[pid]/mem io", - .license = "LGPL3", + .meta = { + .name = "procpid", + .desc = "Open /proc/[pid]/mem io", + .license = "LGPL3", + }, .uris = "procpid://", .open = __open, .close = __close, @@ -140,7 +142,9 @@ RIOPlugin r_io_plugin_procpid = { #else RIOPlugin r_io_plugin_procpid = { - .name = NULL + .meta = { + .name = NULL + }, }; #endif diff --git a/libr/io/p/io_ptrace.c b/libr/io/p/io_ptrace.c index db76d3f13b..f35503450d 100644 --- a/libr/io/p/io_ptrace.c +++ b/libr/io/p/io_ptrace.c @@ -342,9 +342,11 @@ static int __getpid(RIODesc *fd) { // TODO: rename ptrace to io_ptrace .. err io.ptrace ?? RIOPlugin r_io_plugin_ptrace = { - .name = "ptrace", - .desc = "Ptrace and /proc/pid/mem (if available) io plugin", - .license = "LGPL3", + .meta = { + .name = "ptrace", + .desc = "Ptrace and /proc/pid/mem (if available) io plugin", + .license = "LGPL3", + }, .uris = "ptrace://,attach://", .open = __open, .close = __close, @@ -359,7 +361,9 @@ RIOPlugin r_io_plugin_ptrace = { }; #else struct r_io_plugin_t r_io_plugin_ptrace = { - .name = NULL + .meta = { + .name = NULL + }, }; #endif diff --git a/libr/io/p/io_qnx.c b/libr/io/p/io_qnx.c index 44020f47f8..76931bc6d0 100644 --- a/libr/io/p/io_qnx.c +++ b/libr/io/p/io_qnx.c @@ -151,9 +151,11 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_qnx = { - .name = "qnx", - .license = "GPL3", - .desc = "Attach to QNX pdebug instance", + .meta = { + .name = "qnx", + .desc = "Attach to QNX pdebug instance", + .license = "GPL3", + }, .uris = "qnx://", .open = __open, .close = __close, @@ -176,9 +178,11 @@ R_API RLibStruct radare_plugin = { #else RIOPlugin r_io_plugin_qnx = { - .name = "qnx", - .license = "GPL3", - .desc = "Attach to QNX pdebug instance (compiled without GPL)", + .meta = { + .name = "qnx", + .license = "GPL3", + .desc = "Attach to QNX pdebug instance (compiled without GPL)", + }, }; #endif diff --git a/libr/io/p/io_r2k.c b/libr/io/p/io_r2k.c index 3c41abc622..5de17a4d52 100644 --- a/libr/io/p/io_r2k.c +++ b/libr/io/p/io_r2k.c @@ -135,10 +135,12 @@ static RIODesc *r2k__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_r2k = { - .name = "r2k", - .desc = "Kernel access API io", + .meta = { + .name = "r2k", + .desc = "Kernel access API io", + .license = "LGPL3", + }, .uris = "r2k://", - .license = "LGPL3", .open = r2k__open, .close = r2k__close, .read = r2k__read, diff --git a/libr/io/p/io_r2pipe.c b/libr/io/p/io_r2pipe.c index 34cad22eea..7168a9a404 100644 --- a/libr/io/p/io_r2pipe.c +++ b/libr/io/p/io_r2pipe.c @@ -180,9 +180,11 @@ static char *__system(RIO *io, RIODesc *fd, const char *msg) { } RIOPlugin r_io_plugin_r2pipe = { - .name = "r2pipe", - .desc = "r2pipe io plugin", - .license = "MIT", + .meta = { + .name = "r2pipe", + .desc = "r2pipe io plugin", + .license = "MIT", + }, .uris = "r2pipe://", .open = __open, .close = __close, diff --git a/libr/io/p/io_r2web.c b/libr/io/p/io_r2web.c index 9502910f43..c6f3d9f3b2 100644 --- a/libr/io/p/io_r2web.c +++ b/libr/io/p/io_r2web.c @@ -151,10 +151,12 @@ static char *__system(RIO *io, RIODesc *fd, const char *command) { } RIOPlugin r_io_plugin_r2web = { - .name = "r2web", - .desc = "r2web io client plugin", + .meta = { + .name = "r2web", + .desc = "r2web io client plugin", + .license = "LGPL3", + }, .uris = "r2web://", - .license = "LGPL3", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_rap.c b/libr/io/p/io_rap.c index 17f6123336..07584d13fa 100644 --- a/libr/io/p/io_rap.c +++ b/libr/io/p/io_rap.c @@ -274,10 +274,12 @@ static char *__rap_system(RIO *io, RIODesc *fd, const char *command) { } RIOPlugin r_io_plugin_rap = { - .name = "rap", - .desc = "Remote binary protocol plugin", + .meta = { + .name = "rap", + .desc = "Remote binary protocol plugin", + .license = "MIT", + }, .uris = "rap://,raps://", - .license = "MIT", .listener = __rap_listener, .open = __rap_open, .close = __rap_close, diff --git a/libr/io/p/io_rbuf.c b/libr/io/p/io_rbuf.c index d74e208714..73122a9c99 100644 --- a/libr/io/p/io_rbuf.c +++ b/libr/io/p/io_rbuf.c @@ -45,12 +45,14 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_rbuf = { - .name = "rbuf", - .desc = "Unsafe RBuffer IO plugin", + .meta = { + .name = "rbuf", + .desc = "Unsafe RBuffer IO plugin", + .author = "pancake", + .license = "LGPL", + }, .uris = "rbuf://", - .license = "LGPL", .open = __open, - .author = "pancake", .close = __close, .read = __read, .seek = __lseek, diff --git a/libr/io/p/io_reg.c b/libr/io/p/io_reg.c index 7f906aec11..0943ade86f 100644 --- a/libr/io/p/io_reg.c +++ b/libr/io/p/io_reg.c @@ -100,9 +100,11 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_reg = { - .name = "reg", - .desc = "read and write the register arena", - .license = "LGPL3", + .meta = { + .name = "reg", + .desc = "read and write the register arena", + .license = "LGPL3", + }, .uris = "reg://", .open = __open, .close = __close, diff --git a/libr/io/p/io_self.c b/libr/io/p/io_self.c index f39d308100..e259f9455f 100644 --- a/libr/io/p/io_self.c +++ b/libr/io/p/io_self.c @@ -587,10 +587,12 @@ static char *__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_self = { - .name = "self", - .desc = "Read memory from self", + .meta = { + .name = "self", + .desc = "Read memory from self", + .license = "LGPL3", + }, .uris = "self://", - .license = "LGPL3", .open = __open, .read = __read, .check = __plugin_open, @@ -942,8 +944,10 @@ exit: #else // DEBUGGER RIOPlugin r_io_plugin_self = { - .name = "self", - .desc = "read memory from myself using 'self://' (UNSUPPORTED)", + .meta = { + .name = "self", + .desc = "read memory from myself using 'self://' (UNSUPPORTED)", + }, }; #ifndef R2_PLUGIN_INCORE diff --git a/libr/io/p/io_serial.c b/libr/io/p/io_serial.c index d38935f2b9..56850279e3 100644 --- a/libr/io/p/io_serial.c +++ b/libr/io/p/io_serial.c @@ -154,10 +154,12 @@ static char *__system(RIO *io, RIODesc *desc, const char *cmd) { } RIOPlugin r_io_plugin_serial = { - .name = "serial", - .desc = "Connect to a serial port (" SERIALURI_EXAMPLE ")", + .meta = { + .name = "serial", + .desc = "Connect to a serial port (" SERIALURI_EXAMPLE ")", + .license = "MIT", + }, .uris = SERIALURI, - .license = "MIT", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_shm.c b/libr/io/p/io_shm.c index 0de1579bc2..4db56dc6a4 100644 --- a/libr/io/p/io_shm.c +++ b/libr/io/p/io_shm.c @@ -130,11 +130,13 @@ static RIODesc *shm__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_shm = { - .name = "shm", - .desc = "Shared memory resources plugin", + .meta = { + .name = "shm", + .desc = "Shared memory resources plugin", + .license = "MIT", + .author = "pancake", + }, .uris = "shm://", - .license = "MIT", - .author = "pancake", .open = shm__open, .close = shm__close, .read = shm__read, @@ -145,8 +147,10 @@ RIOPlugin r_io_plugin_shm = { #else RIOPlugin r_io_plugin_shm = { - .name = "shm", - .desc = "shared memory resources (not for this platform)", + .meta = { + .name = "shm", + .desc = "shared memory resources (not for this platform)", + } }; #endif diff --git a/libr/io/p/io_socket.c b/libr/io/p/io_socket.c index 65e4c2d906..e718986afb 100644 --- a/libr/io/p/io_socket.c +++ b/libr/io/p/io_socket.c @@ -162,10 +162,12 @@ static char *__system(RIO *io, RIODesc *desc, const char *cmd) { } RIOPlugin r_io_plugin_socket = { - .name = "socket", - .desc = "Connect or listen via TCP on a growing io", + .meta = { + .name = "socket", + .desc = "Connect or listen via TCP on a growing io", + .license = "MIT", + }, .uris = SOCKETURI, - .license = "MIT", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_sparse.c b/libr/io/p/io_sparse.c index e9c2accfed..c8eff5616a 100644 --- a/libr/io/p/io_sparse.c +++ b/libr/io/p/io_sparse.c @@ -96,10 +96,12 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_sparse = { - .name = "sparse", - .desc = "Sparse buffer allocation plugin", + .meta = { + .name = "sparse", + .desc = "Sparse buffer allocation plugin", + .license = "LGPL3", + }, .uris = "sparse://", - .license = "LGPL3", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_tcpslurp.c b/libr/io/p/io_tcpslurp.c index 76eff86870..262142ecf8 100644 --- a/libr/io/p/io_tcpslurp.c +++ b/libr/io/p/io_tcpslurp.c @@ -81,10 +81,12 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_tcpslurp = { - .name = "tcp", - .desc = "Slurp/load remote files via TCP (tcp-slurp://:9999 or tcp-slurp://host:port)", + .meta = { + .name = "tcp", + .desc = "Slurp/load remote files via TCP (tcp-slurp://:9999 or tcp-slurp://host:port)", + .license = "LGPL3", + }, .uris = "tcp-slurp://", - .license = "LGPL3", .open = __open, .close = io_memory_close, .read = io_memory_read, diff --git a/libr/io/p/io_treebuf.c b/libr/io/p/io_treebuf.c index 3fccd4c1a9..d75851de9a 100644 --- a/libr/io/p/io_treebuf.c +++ b/libr/io/p/io_treebuf.c @@ -213,10 +213,12 @@ static int __write(RIO *io, RIODesc *desc, const ut8 *buf, int len) { } RIOPlugin r_io_plugin_treebuf = { - .name = "treebuf", - .desc = "Dynamic sparse like buffer without size restriction", + .meta = { + .name = "treebuf", + .desc = "Dynamic sparse like buffer without size restriction", + .license = "LGPL", + }, .uris = "treebuf://", - .license = "LGPL", .system = __system, .open = __open, .close = __close, diff --git a/libr/io/p/io_w32.c b/libr/io/p/io_w32.c index 17c1e06b72..6d9d311549 100644 --- a/libr/io/p/io_w32.c +++ b/libr/io/p/io_w32.c @@ -73,10 +73,12 @@ static char *w32__system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_w32 = { - .name = "w32", - .desc = "w32 API io", - .license = "LGPL3", - .author = "pancake", + .meta = { + .name = "w32", + .desc = "w32 API io", + .author = "pancake", + .license = "LGPL3", + }, .uris = "w32://", .open = w32__open, .close = w32__close, @@ -97,7 +99,9 @@ R_API RLibStruct radare_plugin = { #else struct r_io_plugin_t r_io_plugin_w32 = { - .name = (void*)0 + .meta = { + .name = (void*)0 + } }; #endif diff --git a/libr/io/p/io_w32dbg.c b/libr/io/p/io_w32dbg.c index 2fd9682e9c..c06866dd8c 100644 --- a/libr/io/p/io_w32dbg.c +++ b/libr/io/p/io_w32dbg.c @@ -274,9 +274,11 @@ static bool __getbase(RIODesc *fd, ut64 *base) { } RIOPlugin r_io_plugin_w32dbg = { - .name = "w32dbg", - .desc = "w32 debugger io plugin", - .license = "LGPL3", + .meta = { + .name = "w32dbg", + .desc = "w32 debugger io plugin", + .license = "LGPL3", + }, .uris = "w32dbg://,attach://", .open = __open, .close = __close, @@ -292,7 +294,9 @@ RIOPlugin r_io_plugin_w32dbg = { }; #else RIOPlugin r_io_plugin_w32dbg = { - .name = NULL + .meta = { + .name = NULL + }, }; #endif diff --git a/libr/io/p/io_windbg.c b/libr/io/p/io_windbg.c index 5b1e4eb78b..aa670e9c99 100644 --- a/libr/io/p/io_windbg.c +++ b/libr/io/p/io_windbg.c @@ -672,9 +672,11 @@ static char *windbg_system(RIO *io, RIODesc *fd, const char *cmd) { } RIOPlugin r_io_plugin_windbg = { - .name = "windbg", - .desc = "WinDBG (DbgEng.dll) based io plugin for Windows", - .license = "LGPL3", + .meta = { + .name = "windbg", + .desc = "WinDBG (DbgEng.dll) based io plugin for Windows", + .license = "LGPL3", + }, .uris = WINDBGURI, .isdbg = true, .init = windbg_init, diff --git a/libr/io/p/io_winedbg.c b/libr/io/p/io_winedbg.c index 91dc8ae5bc..5ab9b1116e 100644 --- a/libr/io/p/io_winedbg.c +++ b/libr/io/p/io_winedbg.c @@ -367,10 +367,12 @@ const char *msg = } RIOPlugin r_io_plugin_winedbg = { - .name = "winedbg", - .desc = "Wine-dbg io and debug.io plugin", + .meta = { + .name = "winedbg", + .desc = "Wine-dbg io and debug.io plugin", + .license = "MIT", + }, .uris = "winedbg://", - .license = "MIT", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_winkd.c b/libr/io/p/io_winkd.c index 0045ef9018..da81eef11d 100644 --- a/libr/io/p/io_winkd.c +++ b/libr/io/p/io_winkd.c @@ -110,10 +110,12 @@ static bool __close(RIODesc *fd) { } RIOPlugin r_io_plugin_winkd = { - .name = "winkd", - .desc = "Attach to a KD debugger via UDP or socket file", + .meta = { + .name = "winkd", + .desc = "Attach to a KD debugger via UDP or socket file", + .license = "LGPL3", + }, .uris = "winkd://", - .license = "LGPL3", .open = __open, .close = __close, .read = __read, diff --git a/libr/io/p/io_xalz.c b/libr/io/p/io_xalz.c index 7ebf576736..d714b85bde 100644 --- a/libr/io/p/io_xalz.c +++ b/libr/io/p/io_xalz.c @@ -41,10 +41,12 @@ static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { } RIOPlugin r_io_plugin_xalz = { - .name = "xalz", - .desc = "XAmarin LZ4 assemblies", + .meta = { + .name = "xalz", + .desc = "XAmarin LZ4 assemblies", + .license = "MIT", + }, .uris = "xalz://", - .license = "MIT", .open = __open, .close = io_memory_close, .read = io_memory_read, diff --git a/libr/io/p/io_xattr.c b/libr/io/p/io_xattr.c index 0f8ee1614d..a52b837b0e 100644 --- a/libr/io/p/io_xattr.c +++ b/libr/io/p/io_xattr.c @@ -116,11 +116,13 @@ static bool __close(RIODesc *fd) { } RIOPlugin r_io_plugin_xattr = { - .name = "xattr", - .desc = "access extended file attribute", - .author = "pancake", + .meta = { + .name = "xattr", + .desc = "access extended file attribute", + .author = "pancake", + .license = "LGPL3", + }, .uris = "xattr://", - .license = "LGPL3", .open = __open, .close = __close, .read = io_memory_read, @@ -133,10 +135,12 @@ RIOPlugin r_io_plugin_xattr = { #else // HAS_XATTR RIOPlugin r_io_plugin_xattr = { - .name = "xattr", - .desc = "access extended file attribute (not supported)", + .meta = { + .name = "xattr", + .desc = "access extended file attribute (not supported)", + .license = "LGPL3", + }, .uris = "xattr://", - .license = "LGPL3", }; #endif diff --git a/libr/io/p/io_zip.c b/libr/io/p/io_zip.c index ce12df8ea7..ef882e3abc 100644 --- a/libr/io/p/io_zip.c +++ b/libr/io/p/io_zip.c @@ -610,10 +610,12 @@ static bool r_io_zip_close(RIODesc *fd) { } RIOPlugin r_io_plugin_zip = { - .name = "zip", - .desc = "Open zip files", + .meta = { + .name = "zip", + .desc = "Open zip files", + .license = "BSD", + }, .uris = "zip://,apk://,ipa://,jar://,zip0://,zipall://,apkall://,ipaall://,jarall://", - .license = "BSD", .open = r_io_zip_open, .open_many = r_io_zip_open_many, .write = r_io_zip_write, diff --git a/libr/lang/p/qjs.c b/libr/lang/p/qjs.c index 704f4f4fe8..ed12d7971a 100644 --- a/libr/lang/p/qjs.c +++ b/libr/lang/p/qjs.c @@ -194,6 +194,7 @@ static bool plugin_manager_remove_plugin(QjsPluginManager *pm, const char *type, static void plugin_manager_fini (QjsPluginManager *pm) { RVecCorePlugin_fini (&pm->core_plugins); RVecArchPlugin_fini (&pm->arch_plugins); + RVecIoPlugin_fini (&pm->io_plugins); // XXX leaks, but calling it causes crash because not all JS objects are freed // JS_FreeRuntime (pm->rt); pm->rt = NULL; diff --git a/libr/lang/p/qjs/core.c b/libr/lang/p/qjs/core.c index 09d324b74f..dc04378ad9 100644 --- a/libr/lang/p/qjs/core.c +++ b/libr/lang/p/qjs/core.c @@ -124,12 +124,12 @@ static JSValue r2plugin_core_load(JSContext *ctx, JSValueConst this_val, int arg const char *descptr = JS_ToCStringLen2 (ctx, &namelen, desc, false); const char *licenseptr = JS_ToCStringLen2 (ctx, &namelen, license, false); - ap->name = nameptr; // TODO no strdup here? + ap->meta.name = strdup (nameptr); if (descptr) { - ap->desc = strdup (descptr); + ap->meta.desc = strdup (descptr); } if (licenseptr) { - ap->license = strdup (licenseptr); + ap->meta.license = strdup (licenseptr); } ap->call = r_cmd_qjs_call; // Technically this could all be handled by a single generic plugin @@ -145,6 +145,6 @@ static JSValue r2plugin_core_load(JSContext *ctx, JSValueConst this_val, int arg lib->type = R_LIB_TYPE_CORE; lib->data = ap; lib->version = R2_VERSION; - int ret = r_lib_open_ptr (pm->core->lib, ap->name, NULL, lib); + int ret = r_lib_open_ptr (pm->core->lib, ap->meta.name, NULL, lib); return JS_NewBool (ctx, ret == 1); } diff --git a/libr/lang/p/qjs/io.c b/libr/lang/p/qjs/io.c index 3705d3e8e2..5ba272f7b1 100644 --- a/libr/lang/p/qjs/io.c +++ b/libr/lang/p/qjs/io.c @@ -246,13 +246,12 @@ static JSValue r2plugin_io(JSContext *ctx, JSValueConst this_val, int argc, JSVa const char *descptr = JS_ToCStringLen2 (ctx, &namelen, desc, false); const char *licenseptr = JS_ToCStringLen2 (ctx, &namelen, license, false); - ap->name = nameptr; // TODO no strdup here? - if (descptr) { - ap->desc = strdup (descptr); - } - if (licenseptr) { - ap->license = strdup (licenseptr); - } + RPluginMeta meta = { + .name = strdup (nameptr), + .desc = descptr ? strdup (descptr) : NULL, + .license = descptr ? strdup (licenseptr) : NULL, + }; + memcpy ((void*)&ap->meta, &meta, sizeof (RPluginMeta)); ap->check = qjs_io_check; ap->open = qjs_io_open; @@ -277,6 +276,6 @@ static JSValue r2plugin_io(JSContext *ctx, JSValueConst this_val, int argc, JSVa lib->type = R_LIB_TYPE_IO; lib->data = ap; lib->version = R2_VERSION; - int ret = r_lib_open_ptr (pm->core->lib, ap->name, NULL, lib); + int ret = r_lib_open_ptr (pm->core->lib, ap->meta.name, NULL, lib); return JS_NewBool (ctx, ret == 1); } diff --git a/libr/main/rasm2.c b/libr/main/rasm2.c index 2dd260b1ee..9efb9a0f1a 100644 --- a/libr/main/rasm2.c +++ b/libr/main/rasm2.c @@ -241,77 +241,6 @@ static void rarch2_list(RAsmState *as, const char *arch) { pj_free (pj); } -#if 0 -// R2_590 - deprecate this -static void ranal2_list(RAsmState *as, const char *arch) { - char bits[32]; - RAnalPlugin *h; - RListIter *iter; - PJ *pj = NULL; - if (as->json) { - pj = pj_new (); - pj_a (pj); - } - r_list_foreach (as->anal->plugins, iter, h) { - bits[0] = 0; - if (h->bits == 27) { - strcat (bits, "27"); - } else if (h->bits == 0) { - strcat (bits, "any"); - } else { - if (h->bits & 4) { - strcat (bits, "4 "); - } - if (h->bits & 8) { - strcat (bits, "8 "); - } - if (h->bits & 16) { - strcat (bits, "16 "); - } - if (h->bits & 32) { - strcat (bits, "32 "); - } - if (h->bits & 64) { - strcat (bits, "64 "); - } - } - const char *feat = h->opasm? "ad": "_d"; - const char *feat2 = has_esil (as, h->name); - if (as->quiet) { - printf ("%s\n", h->name); - } else if (as->json) { - pj_o (pj); - pj_ks (pj, "name", h->name); - pj_k (pj, "bits"); - pj_a (pj); - pj_i (pj, 32); - pj_i (pj, 64); - pj_end (pj); - pj_ks (pj, "license", r_str_get_fail (h->license, "unknown")); - pj_ks (pj, "description", h->desc); - pj_ks (pj, "features", feat); - pj_end (pj); - } else { - printf ("%s%s %-11s %-11s %-7s %s", - feat, feat2, bits, h->name, - r_str_get_fail (h->license, "unknown"), h->desc); - if (h->author) { - printf (" (by %s)", h->author); - } - if (h->version) { - printf (" v%s", h->version); - } - printf ("\n"); - } - } - if (as->json) { - pj_end (pj); - printf ("%s\n", pj_string (pj)); - } - pj_free (pj); -} -#endif - static int rasm_show_help(int v) { if (v < 2) { printf ("Usage: rasm2 [-ACdDehLBvw] [-a arch] [-b bits] [-o addr] [-s syntax]\n" diff --git a/libr/meson.build b/libr/meson.build index eaf09654a5..1bab9d7642 100644 --- a/libr/meson.build +++ b/libr/meson.build @@ -420,9 +420,6 @@ include_files = [ 'include/rvc.h', 'include/r_agraph.h', 'include/r_anal.h', - 'include/gcc_stdatomic.h', - 'include/msvc_stdatomic.h', - 'include/cwisstable.h', 'include/r_arch.h', 'include/r_esil.h', 'include/r_asm.h', diff --git a/libr/util/sdb.mk b/libr/util/sdb.mk index 7eacd92f53..db949f630c 100644 --- a/libr/util/sdb.mk +++ b/libr/util/sdb.mk @@ -18,6 +18,7 @@ SDB_OBJS+=ht_uu.o SDB_OBJS+=ht_up.o SDB_OBJS+=ht_pp.o SDB_OBJS+=ht_pu.o +SDB_OBJS+=ht_su.o SDB_OBJS+=ht.o SDB_OBJS+=json.o SDB_OBJS+=text.o diff --git a/meson.build b/meson.build index 10fe540289..749d2f3e98 100644 --- a/meson.build +++ b/meson.build @@ -473,6 +473,7 @@ sdb_files = [ 'shlr/sdb/src/ht_up.c', 'shlr/sdb/src/ht_pp.c', 'shlr/sdb/src/ht_pu.c', + 'shlr/sdb/src/ht_su.c', 'shlr/sdb/src/journal.c', 'shlr/sdb/src/json.c', 'shlr/sdb/src/lock.c', diff --git a/shlr/sdb/include/sdb/cwisstable.h b/shlr/sdb/include/sdb/cwisstable.h index 989cb2782c..0add77a246 100644 --- a/shlr/sdb/include/sdb/cwisstable.h +++ b/shlr/sdb/include/sdb/cwisstable.h @@ -21,7 +21,6 @@ // #include "cwisstable/internal/probe.h" // #include "cwisstable/internal/absl_hash.h" // #include "cwisstable/hash.h" -// #include "cwisstable/internal/extract.h" // #include "cwisstable/policy.h" // #include "cwisstable/internal/raw_table.h" // #include "cwisstable/declare.h" @@ -54,28 +53,23 @@ /// `extern "C"` support via `CWISS_END_EXTERN` and `CWISS_END_EXTERN`, /// which open and close an `extern "C"` block in C++ mode. #ifdef __cplusplus - #include <atomic> - #define CWISS_ATOMIC_T(Type_) std::atomic<Type_> - #define CWISS_ATOMIC_INC(val_) (val_).fetch_add(1, std::memory_order_relaxed) +#include <atomic> - #define CWISS_BEGIN_EXTERN extern "C" { - #define CWISS_END_EXTERN } +#define CWISS_BEGIN_EXTERN extern "C" { +#define CWISS_END_EXTERN } #else #if _MSC_VER -#include "msvc_stdatomic.h" +// #include "msvc_stdatomic.h" #else #if __STDC_VERSION__ >= 201112L - #include <stdatomic.h> +#include <stdatomic.h> #else - #include "gcc_stdatomic.h" +#include "gcc_stdatomic.h" #endif #endif - #define CWISS_ATOMIC_T(Type_) _Atomic(Type_) - #define CWISS_ATOMIC_INC(val_) \ - atomic_fetch_add_explicit(&(val_), 1, memory_order_relaxed) - #define CWISS_BEGIN_EXTERN - #define CWISS_END_EXTERN +#define CWISS_BEGIN_EXTERN +#define CWISS_END_EXTERN #endif /// Compiler detection macros. @@ -87,19 +81,19 @@ /// - `CWISS_IS_GCCISH` detects GCC and GCC-mode Clang. /// - `CWISS_IS_MSVCISH` detects MSVC and clang-cl. #ifdef __clang__ - #define CWISS_IS_CLANG 1 +#define CWISS_IS_CLANG 1 #else - #define CWISS_IS_CLANG 0 +#define CWISS_IS_CLANG 0 #endif #if defined(__GNUC__) - #define CWISS_IS_GCCISH 1 +#define CWISS_IS_GCCISH 1 #else - #define CWISS_IS_GCCISH 0 +#define CWISS_IS_GCCISH 0 #endif #if defined(_MSC_VER) - #define CWISS_IS_MSVCISH 1 +#define CWISS_IS_MSVCISH 1 #else - #define CWISS_IS_MSVCISH 0 +#define CWISS_IS_MSVCISH 0 #endif #define CWISS_IS_GCC (CWISS_IS_GCCISH && !CWISS_IS_CLANG) #define CWISS_IS_MSVC (CWISS_IS_MSVCISH && !CWISS_IS_CLANG) @@ -107,24 +101,48 @@ #define CWISS_PRAGMA(pragma_) _Pragma(#pragma_) #if CWISS_IS_GCCISH - #define CWISS_GCC_PUSH CWISS_PRAGMA(GCC diagnostic push) - #define CWISS_GCC_ALLOW(w_) CWISS_PRAGMA(GCC diagnostic ignored w_) - #define CWISS_GCC_POP CWISS_PRAGMA(GCC diagnostic pop) +#define CWISS_GCC_PUSH CWISS_PRAGMA(GCC diagnostic push) +#define CWISS_GCC_ALLOW(w_) CWISS_PRAGMA(GCC diagnostic ignored w_) +#define CWISS_GCC_POP CWISS_PRAGMA(GCC diagnostic pop) #else - #define CWISS_GCC_PUSH - #define CWISS_GCC_ALLOW(w_) - #define CWISS_GCC_POP +#define CWISS_GCC_PUSH +#define CWISS_GCC_ALLOW(w_) +#define CWISS_GCC_POP +#endif + +/// Atomic support, due to incompatibilities between C++ and C11 atomic syntax. +/// - `CWISS_ATOMIC_T(Type)` names an atomic version of `Type`. We must use this +/// instead of `_Atomic(Type)` to name an atomic type. +/// - `CWISS_ATOMIC_INC(value)` will atomically increment `value` without +/// performing synchronization. This is used as a weak entropy source +/// elsewhere. +/// +/// MSVC, of course, being that it does not support _Atomic in C mode, forces us +/// into `volatile`. This is *wrong*, but MSVC certainly won't miscompile it any +/// worse than it would a relaxed atomic. It doesn't matter for our use of +/// atomics. +#ifdef __cplusplus +#include <atomic> +#define CWISS_ATOMIC_T(Type_) volatile std::atomic<Type_> +#define CWISS_ATOMIC_INC(val_) (val_).fetch_add(1, std::memory_order_relaxed) +#elif CWISS_IS_MSVC +#define CWISS_ATOMIC_T(Type_) volatile Type_ +#define CWISS_ATOMIC_INC(val_) (val_ += 1) +#else +#define CWISS_ATOMIC_T(Type_) volatile _Atomic(Type_) +#define CWISS_ATOMIC_INC(val_) \ + atomic_fetch_add_explicit(&(val_), 1, memory_order_relaxed) #endif /// Warning control around `CWISS` symbol definitions. These macros will /// disable certain false-positive warnings that `CWISS` definitions tend to /// emit. #define CWISS_BEGIN \ - CWISS_GCC_PUSH \ - CWISS_GCC_ALLOW("-Wunused-function") \ - CWISS_GCC_ALLOW("-Wunused-parameter") \ - CWISS_GCC_ALLOW("-Wcast-qual") \ - CWISS_GCC_ALLOW("-Wmissing-field-initializers") + CWISS_GCC_PUSH \ + CWISS_GCC_ALLOW("-Wunused-function") \ + CWISS_GCC_ALLOW("-Wunused-parameter") \ + CWISS_GCC_ALLOW("-Wcast-qual") \ + CWISS_GCC_ALLOW("-Wmissing-field-initializers") #define CWISS_END CWISS_GCC_POP /// `CWISS_HAVE_SSE2` is nonzero if we have SSE2 support. @@ -132,13 +150,13 @@ /// `-DCWISS_HAVE_SSE2` can be used to override it; it is otherwise detected /// via the usual non-portable feature-detection macros. #ifndef CWISS_HAVE_SSE2 - #if defined(__SSE2__) || \ - (CWISS_IS_MSVCISH && \ - (defined(_M_X64) || (defined(_M_IX86) && _M_IX86_FP >= 2))) - #define CWISS_HAVE_SSE2 1 - #else - #define CWISS_HAVE_SSE2 0 - #endif +#if defined(__SSE2__) || \ + (CWISS_IS_MSVCISH && \ + (defined(_M_X64) || (defined(_M_IX86) && _M_IX86_FP >= 2))) +#define CWISS_HAVE_SSE2 1 +#else +#define CWISS_HAVE_SSE2 0 +#endif #endif /// `CWISS_HAVE_SSSE2` is nonzero if we have SSSE2 support. @@ -146,22 +164,62 @@ /// `-DCWISS_HAVE_SSSE2` can be used to override it; it is otherwise detected /// via the usual non-portable feature-detection macros. #ifndef CWISS_HAVE_SSSE3 - #ifdef __SSSE3__ - #define CWISS_HAVE_SSSE3 1 - #else - #define CWISS_HAVE_SSSE3 0 - #endif +#ifdef __SSSE3__ +#define CWISS_HAVE_SSSE3 1 +#else +#define CWISS_HAVE_SSSE3 0 +#endif #endif #if CWISS_HAVE_SSE2 - #include <emmintrin.h> +#include <emmintrin.h> #endif #if CWISS_HAVE_SSSE3 - #if !CWISS_HAVE_SSE2 - #error "Bad configuration: SSSE3 implies SSE2!" - #endif - #include <tmmintrin.h> +#if !CWISS_HAVE_SSE2 +#error "Bad configuration: SSSE3 implies SSE2!" +#endif +#include <tmmintrin.h> +#endif + +/// `CWISS_HAVE_MUL128` is nonzero if there is compiler-specific +/// intrinsics for 128-bit multiplication. +/// +/// `-DCWISS_HAVE_MUL128=0` can be used to explicitly fall back onto the pure +/// C implementation. +#ifndef DCWISS_HAVE_MUL128 +#if defined(__SIZEOF_INT128__) && \ + ((CWISS_IS_CLANG && !CWISS_IS_MSVC) || CWISS_IS_GCC) +#define DCWISS_HAVE_MUL128 1 +#else +#define DCWISS_HAVE_MUL128 0 +#endif +#endif + +/// `CWISS_ALIGN` is a cross-platform `alignas()`: specifically, MSVC doesn't +/// quite believe in it. +#if CWISS_IS_MSVC +#define CWISS_alignas(align_) __declspec(align(align_)) + +#else +#include <stdalign.h> + +#ifdef alignas +#define CWISS_alignas(align_) alignas(align_) +#else +#define CWISS_alignas(align_) __attribute__((aligned(align_))) +#endif + +#endif + +#ifndef alignof +#define alignof __alignof +#endif + +#ifdef _MSC_VER +#define SDB_MAYBE_UNUSED +#else +#define SDB_MAYBE_UNUSED __attribute__((unused)) #endif /// `CWISS_HAVE_BUILTIN` will, in Clang, detect whether a Clang language @@ -169,9 +227,9 @@ /// /// See https://clang.llvm.org/docs/LanguageExtensions.html. #ifdef __has_builtin - #define CWISS_HAVE_CLANG_BUILTIN(x_) __has_builtin(x_) +#define CWISS_HAVE_CLANG_BUILTIN(x_) __has_builtin(x_) #else - #define CWISS_HAVE_CLANG_BUILTIN(x_) 0 +#define CWISS_HAVE_CLANG_BUILTIN(x_) 0 #endif /// `CWISS_HAVE_GCC_ATTRIBUTE` detects if a particular `__attribute__(())` is @@ -180,21 +238,23 @@ /// GCC: https://gcc.gnu.org/gcc-5/changes.html /// Clang: https://clang.llvm.org/docs/LanguageExtensions.html #ifdef __has_attribute - #define CWISS_HAVE_GCC_ATTRIBUTE(x_) __has_attribute(x_) +#define CWISS_HAVE_GCC_ATTRIBUTE(x_) __has_attribute(x_) #else - #define CWISS_HAVE_GCC_ATTRIBUTE(x_) 0 +#define CWISS_HAVE_GCC_ATTRIBUTE(x_) 0 #endif #ifdef __has_feature - #define CWISS_HAVE_FEATURE(x_) __has_feature(x_) +#define CWISS_HAVE_FEATURE(x_) __has_feature(x_) #else - #define CWISS_HAVE_FEATURE(x_) 0 +#define CWISS_HAVE_FEATURE(x_) 0 #endif /// `CWISS_THREAD_LOCAL` expands to the appropriate TLS annotation, if one is /// available. #if CWISS_IS_GCCISH - #define CWISS_THREAD_LOCAL __thread +#define CWISS_THREAD_LOCAL __thread +#elif CWISS_IS_MSVC +#define CWISS_THREAD_LOCAL #endif /// `CWISS_CHECK` will evaluate `cond_` and, if false, print an error and crash @@ -202,79 +262,79 @@ /// /// This is like `assert()` but unconditional. #define CWISS_CHECK(cond_, ...) \ - do { \ - if (cond_) break; \ - fprintf(stderr, "CWISS_CHECK failed at %s:%d\n", __FILE__, __LINE__); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ - fflush(stderr); \ - abort(); \ - } while (false) + do { \ + if (cond_) break; \ + fprintf(stderr, "CWISS_CHECK failed at %s:%d\n", __FILE__, __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + fflush(stderr); \ + abort(); \ + } while (false) /// `CWISS_DCHECK` is like `CWISS_CHECK` but is disabled by `NDEBUG`. #ifdef NDEBUG - #define CWISS_DCHECK(cond_, ...) ((void)0) +#define CWISS_DCHECK(cond_, ...) ((void)0) #else - #define CWISS_DCHECK CWISS_CHECK +#define CWISS_DCHECK CWISS_CHECK #endif /// `CWISS_LIKELY` and `CWISS_UNLIKELY` provide a prediction hint to the /// compiler to encourage branches to be scheduled in a particular way. #if CWISS_HAVE_CLANG_BUILTIN(__builtin_expect) || CWISS_IS_GCC - #define CWISS_LIKELY(cond_) (__builtin_expect(false || (cond_), true)) - #define CWISS_UNLIKELY(cond_) (__builtin_expect(false || (cond_), false)) +#define CWISS_LIKELY(cond_) (__builtin_expect(false || (cond_), true)) +#define CWISS_UNLIKELY(cond_) (__builtin_expect(false || (cond_), false)) #else - #define CWISS_LIKELY(cond_) (cond_) - #define CWISS_UNLIKELY(cond_) (cond_) +#define CWISS_LIKELY(cond_) (cond_) +#define CWISS_UNLIKELY(cond_) (cond_) #endif /// `CWISS_INLINE_ALWAYS` informs the compiler that it should try really hard /// to inline a function. #if CWISS_HAVE_GCC_ATTRIBUTE(always_inline) - #define CWISS_INLINE_ALWAYS __attribute__((always_inline)) +#define CWISS_INLINE_ALWAYS __attribute__((always_inline)) #else - #define CWISS_INLINE_ALWAYS +#define CWISS_INLINE_ALWAYS #endif /// `CWISS_INLINE_NEVER` informs the compiler that it should avoid inlining a /// function. #if CWISS_HAVE_GCC_ATTRIBUTE(noinline) - #define CWISS_INLINE_NEVER __attribute__((noinline)) +#define CWISS_INLINE_NEVER __attribute__((noinline)) #else - #define CWISS_INLINE_NEVER +#define CWISS_INLINE_NEVER #endif /// `CWISS_PREFETCH` informs the compiler that it should issue prefetch /// instructions. #if CWISS_HAVE_CLANG_BUILTIN(__builtin_prefetch) || CWISS_IS_GCC - #define CWISS_HAVE_PREFETCH 1 - #define CWISS_PREFETCH(addr_, locality_) \ - __builtin_prefetch(addr_, 0, locality_); +#define CWISS_HAVE_PREFETCH 1 +#define CWISS_PREFETCH(addr_, locality_) \ + __builtin_prefetch(addr_, 0, locality_); #else - #define CWISS_HAVE_PREFETCH 0 - #define CWISS_PREFETCH(addr_, locality_) ((void)0) +#define CWISS_HAVE_PREFETCH 0 +#define CWISS_PREFETCH(addr_, locality_) ((void)0) #endif /// `CWISS_HAVE_ASAN` and `CWISS_HAVE_MSAN` detect the presence of some of the /// sanitizers. #if defined(__SANITIZE_ADDRESS__) || CWISS_HAVE_FEATURE(address_sanitizer) - #define CWISS_HAVE_ASAN 1 +#define CWISS_HAVE_ASAN 1 #else - #define CWISS_HAVE_ASAN 0 +#define CWISS_HAVE_ASAN 0 #endif #if defined(__SANITIZE_MEMORY__) || \ - (CWISS_HAVE_FEATURE(memory_sanitizer) && !defined(__native_client__)) - #define CWISS_HAVE_MSAN 1 + (CWISS_HAVE_FEATURE(memory_sanitizer) && !defined(__native_client__)) +#define CWISS_HAVE_MSAN 1 #else - #define CWISS_HAVE_MSAN 0 +#define CWISS_HAVE_MSAN 0 #endif #if CWISS_HAVE_ASAN - #include <sanitizer/asan_interface.h> +#include <sanitizer/asan_interface.h> #endif #if CWISS_HAVE_MSAN - #include <sanitizer/msan_interface.h> +#include <sanitizer/msan_interface.h> #endif CWISS_BEGIN @@ -282,25 +342,25 @@ CWISS_BEGIN_EXTERN /// Informs a sanitizer runtime that this memory is invalid. static inline void CWISS_PoisonMemory(const void* m, size_t s) { #if CWISS_HAVE_ASAN - ASAN_POISON_MEMORY_REGION(m, s); + ASAN_POISON_MEMORY_REGION(m, s); #endif #if CWISS_HAVE_MSAN - __msan_poison(m, s); + __msan_poison(m, s); #endif - (void)m; - (void)s; + (void)m; + (void)s; } /// Informs a sanitizer runtime that this memory is no longer invalid. static inline void CWISS_UnpoisonMemory(const void* m, size_t s) { #if CWISS_HAVE_ASAN - ASAN_UNPOISON_MEMORY_REGION(m, s); + ASAN_UNPOISON_MEMORY_REGION(m, s); #endif #if CWISS_HAVE_MSAN - __msan_unpoison(m, s); + __msan_unpoison(m, s); #endif - (void)m; - (void)s; + (void)m; + (void)s; } CWISS_END_EXTERN CWISS_END @@ -316,31 +376,33 @@ CWISS_BEGIN_EXTERN CWISS_INLINE_ALWAYS static inline uint32_t CWISS_TrailingZeroes64(uint64_t x) { #if CWISS_HAVE_CLANG_BUILTIN(__builtin_ctzll) || CWISS_IS_GCC - static_assert(sizeof(unsigned long long) == sizeof(x), - "__builtin_ctzll does not take 64-bit arg"); - return __builtin_ctzll(x); +#if defined( __STDC_VERSION__ ) && __STDC_VERSION__ >= 201112L + static_assert(sizeof(unsigned long long) == sizeof(x), + "__builtin_ctzll does not take 64-bit arg"); +#endif + return __builtin_ctzll(x); #elif CWISS_IS_MSVC - unsigned long result = 0; - #if defined(_M_X64) || defined(_M_ARM64) - _BitScanForward64(&result, x); - #else - if (((uint32_t)x) == 0) { - _BitScanForward(&result, (unsigned long)(x >> 32)); - return result + 32; - } - _BitScanForward(&result, (unsigned long)(x)); - #endif - return result; + unsigned long result = 0; +#if defined(_M_X64) || defined(_M_ARM64) + _BitScanForward64(&result, x); #else - uint32_t c = 63; - x &= ~x + 1; - if (x & 0x00000000FFFFFFFF) c -= 32; - if (x & 0x0000FFFF0000FFFF) c -= 16; - if (x & 0x00FF00FF00FF00FF) c -= 8; - if (x & 0x0F0F0F0F0F0F0F0F) c -= 4; - if (x & 0x3333333333333333) c -= 2; - if (x & 0x5555555555555555) c -= 1; - return c; + if (((uint32_t)x) == 0) { + _BitScanForward(&result, (unsigned long)(x >> 32)); + return result + 32; + } + _BitScanForward(&result, (unsigned long)(x)); +#endif + return result; +#else + uint32_t c = 63; + x &= ~x + 1; + if (x & 0x00000000FFFFFFFF) c -= 32; + if (x & 0x0000FFFF0000FFFF) c -= 16; + if (x & 0x00FF00FF00FF00FF) c -= 8; + if (x & 0x0F0F0F0F0F0F0F0F) c -= 4; + if (x & 0x3333333333333333) c -= 2; + if (x & 0x5555555555555555) c -= 1; + return c; #endif } @@ -348,45 +410,46 @@ static inline uint32_t CWISS_TrailingZeroes64(uint64_t x) { CWISS_INLINE_ALWAYS static inline uint32_t CWISS_LeadingZeroes64(uint64_t x) { #if CWISS_HAVE_CLANG_BUILTIN(__builtin_clzll) || CWISS_IS_GCC - static_assert(sizeof(unsigned long long) == sizeof(x), - "__builtin_clzll does not take 64-bit arg"); - // Handle 0 as a special case because __builtin_clzll(0) is undefined. - return x == 0 ? 64 : __builtin_clzll(x); +#if defined( __STDC_VERSION__ ) && __STDC_VERSION__ >= 201112L + static_assert(sizeof(unsigned long long) == sizeof(x), + "__builtin_clzll does not take 64-bit arg"); +#endif + // Handle 0 as a special case because __builtin_clzll(0) is undefined. + return x == 0 ? 64 : __builtin_clzll(x); #elif CWISS_IS_MSVC - unsigned long result = 0; - #if defined(_M_X64) || defined(_M_ARM64) - if (_BitScanReverse64(&result, x)) { - return 63 - result; - } - #else - unsigned long result = 0; - if ((x >> 32) && _BitScanReverse(&result, (unsigned long)(x >> 32))) { - return 31 - result; - } - if (_BitScanReverse(&result, static_cast<unsigned long>(x))) { - return 63 - result; - } - #endif - return 64; + unsigned long result = 0; +#if defined(_M_X64) || defined(_M_ARM64) + if (_BitScanReverse64(&result, x)) { + return 63 - result; + } #else - uint32_t zeroes = 60; - if (x >> 32) { - zeroes -= 32; - x >>= 32; - } - if (x >> 16) { - zeroes -= 16; - x >>= 16; - } - if (x >> 8) { - zeroes -= 8; - x >>= 8; - } - if (x >> 4) { - zeroes -= 4; - x >>= 4; - } - return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; + if ((x >> 32) && _BitScanReverse(&result, (unsigned long)(x >> 32))) { + return 31 - result; + } + if (_BitScanReverse(&result, static_cast<unsigned long>(x))) { + return 63 - result; + } +#endif + return 64; +#else + uint32_t zeroes = 60; + if (x >> 32) { + zeroes -= 32; + x >>= 32; + } + if (x >> 16) { + zeroes -= 16; + x >>= 16; + } + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; #endif } @@ -397,91 +460,91 @@ static inline uint32_t CWISS_LeadingZeroes64(uint64_t x) { /// Counts the number of leading zeroes in the binary representation of `x_` in /// a type-generic fashion. #define CWISS_LeadingZeros(x_) \ - (CWISS_LeadingZeroes64(x_) - \ - (uint32_t)((sizeof(unsigned long long) - sizeof(x_)) * 8)) + (CWISS_LeadingZeroes64(x_) - \ + (uint32_t)((sizeof(unsigned long long) - sizeof(x_)) * 8)) /// Computes the number of bits necessary to represent `x_`, i.e., the bit index /// of the most significant one. #define CWISS_BitWidth(x_) \ - (((uint32_t)(sizeof(x_) * 8)) - CWISS_LeadingZeros(x_)) + (((uint32_t)(sizeof(x_) * 8)) - CWISS_LeadingZeros(x_)) #define CWISS_RotateLeft(x_, bits_) \ - (((x_) << bits_) | ((x_) >> (sizeof(x_) * 8 - bits_))) + (((x_) << bits_) | ((x_) >> (sizeof(x_) * 8 - bits_))) /// The return type of `CWISS_Mul128`. typedef struct { - uint64_t lo, hi; + uint64_t lo, hi; } CWISS_U128; /// Computes a double-width multiplication operation. static inline CWISS_U128 CWISS_Mul128(uint64_t a, uint64_t b) { #ifdef __SIZEOF_INT128__ - // TODO: de-intrinsics-ize this. - __uint128_t p = a; - p *= b; - return (CWISS_U128){(uint64_t)p, (uint64_t)(p >> 64)}; + // TODO: de-intrinsics-ize this. + __uint128_t p = a; + p *= b; + return (CWISS_U128) { (uint64_t)p, (uint64_t)(p >> 64) }; #else - /* - * https://stackoverflow.com/questions/25095741/how-can-i-multiply-64-bit-operands-and-get-128-bit-result-portably - * - * Fast yet simple grade school multiply that avoids - * 64-bit carries with the properties of multiplying by 11 - * and takes advantage of UMAAL on ARMv6 to only need 4 - * calculations. - */ - - /* First calculate all of the cross products. */ - const uint64_t lo_lo = (a & 0xFFFFFFFF) * (b & 0xFFFFFFFF); - const uint64_t hi_lo = (a >> 32) * (b & 0xFFFFFFFF); - const uint64_t lo_hi = (a & 0xFFFFFFFF) * (b >> 32); - const uint64_t hi_hi = (a >> 32) * (b >> 32); - - /* Now add the products together. These will never overflow. */ - const uint64_t cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi; - const uint64_t high = (hi_lo >> 32) + (cross >> 32) + hi_hi; - const uint64_t low = (cross << 32) | (lo_lo & 0xFFFFFFFF); - CWISS_U128 result = { .lo = low, .hi = high }; - return result; + /* + * https://stackoverflow.com/questions/25095741/how-can-i-multiply-64-bit-operands-and-get-128-bit-result-portably + * + * Fast yet simple grade school multiply that avoids + * 64-bit carries with the properties of multiplying by 11 + * and takes advantage of UMAAL on ARMv6 to only need 4 + * calculations. + */ + + /* First calculate all of the cross products. */ + const uint64_t lo_lo = (a & 0xFFFFFFFF) * (b & 0xFFFFFFFF); + const uint64_t hi_lo = (a >> 32) * (b & 0xFFFFFFFF); + const uint64_t lo_hi = (a & 0xFFFFFFFF) * (b >> 32); + const uint64_t hi_hi = (a >> 32) * (b >> 32); + + /* Now add the products together. These will never overflow. */ + const uint64_t cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi; + const uint64_t high = (hi_lo >> 32) + (cross >> 32) + hi_hi; + const uint64_t low = (cross << 32) | (lo_lo & 0xFFFFFFFF); + CWISS_U128 result = { .lo = low, .hi = high }; + return result; #endif } /// Loads an unaligned u32. static inline uint32_t CWISS_Load32(const void* p) { - uint32_t v; - memcpy(&v, p, sizeof(v)); - return v; + uint32_t v; + memcpy(&v, p, sizeof(v)); + return v; } /// Loads an unaligned u64. static inline uint64_t CWISS_Load64(const void* p) { - uint64_t v; - memcpy(&v, p, sizeof(v)); - return v; + uint64_t v; + memcpy(&v, p, sizeof(v)); + return v; } /// Reads 9 to 16 bytes from p. static inline CWISS_U128 CWISS_Load9To16(const void* p, size_t len) { - const unsigned char* p8 = (const unsigned char*)p; - uint64_t lo = CWISS_Load64(p8); - uint64_t hi = CWISS_Load64(p8 + len - 8); - return (CWISS_U128){lo, hi >> (128 - len * 8)}; + const unsigned char* p8 = (const unsigned char*)p; + uint64_t lo = CWISS_Load64(p8); + uint64_t hi = CWISS_Load64(p8 + len - 8); + return (CWISS_U128) { lo, hi >> (128 - len * 8) }; } /// Reads 4 to 8 bytes from p. static inline uint64_t CWISS_Load4To8(const void* p, size_t len) { - const unsigned char* p8 = (const unsigned char*)p; - uint64_t lo = CWISS_Load32(p8); - uint64_t hi = CWISS_Load32(p8 + len - 4); - return lo | (hi << (len - 4) * 8); + const unsigned char* p8 = (const unsigned char*)p; + uint64_t lo = CWISS_Load32(p8); + uint64_t hi = CWISS_Load32(p8 + len - 4); + return lo | (hi << (len - 4) * 8); } /// Reads 1 to 3 bytes from p. static inline uint32_t CWISS_Load1To3(const void* p, size_t len) { - const unsigned char* p8 = (const unsigned char*)p; - uint32_t mem0 = p8[0]; - uint32_t mem1 = p8[len / 2]; - uint32_t mem2 = p8[len - 1]; - return (mem0 | (mem1 << (len / 2 * 8)) | (mem2 << ((len - 1) * 8))); + const unsigned char* p8 = (const unsigned char*)p; + uint32_t mem0 = p8[0]; + uint32_t mem1 = p8[len / 2]; + uint32_t mem2 = p8[len - 1]; + return (mem0 | (mem1 << (len / 2 * 8)) | (mem2 << ((len - 1) * 8))); } /// A abstract bitmask, such as that emitted by a SIMD instruction. @@ -496,35 +559,35 @@ static inline uint32_t CWISS_Load1To3(const void* p, size_t len) { /// 8 and `shift` is 3, abstract bits are represented as the bytes `0x00` and /// `0x80`, and it occupies all 64 bits of the bitmask. typedef struct { - /// The mask, in the representation specified by `width` and `shift`. - uint64_t mask; - /// The number of abstract bits in the mask. - uint32_t width; - /// The log-base-two width of an abstract bit. - uint32_t shift; + /// The mask, in the representation specified by `width` and `shift`. + uint64_t mask; + /// The number of abstract bits in the mask. + uint32_t width; + /// The log-base-two width of an abstract bit. + uint32_t shift; } CWISS_BitMask; /// Returns the index of the lowest abstract bit set in `self`. static inline uint32_t CWISS_BitMask_LowestBitSet(const CWISS_BitMask* self) { - return CWISS_TrailingZeros(self->mask) >> self->shift; + return CWISS_TrailingZeros(self->mask) >> self->shift; } /// Returns the index of the highest abstract bit set in `self`. static inline uint32_t CWISS_BitMask_HighestBitSet(const CWISS_BitMask* self) { - return (uint32_t)(CWISS_BitWidth(self->mask) - 1) >> self->shift; + return (uint32_t)(CWISS_BitWidth(self->mask) - 1) >> self->shift; } /// Return the number of trailing zero abstract bits. static inline uint32_t CWISS_BitMask_TrailingZeros(const CWISS_BitMask* self) { - return CWISS_TrailingZeros(self->mask) >> self->shift; + return CWISS_TrailingZeros(self->mask) >> self->shift; } /// Return the number of leading zero abstract bits. static inline uint32_t CWISS_BitMask_LeadingZeros(const CWISS_BitMask* self) { - uint32_t total_significant_bits = self->width << self->shift; - uint32_t extra_bits = sizeof(self->mask) * 8 - total_significant_bits; - return (uint32_t)(CWISS_LeadingZeros(self->mask << extra_bits)) >> - self->shift; + uint32_t total_significant_bits = self->width << self->shift; + uint32_t extra_bits = sizeof(self->mask) * 8 - total_significant_bits; + return (uint32_t)(CWISS_LeadingZeros(self->mask << extra_bits)) >> + self->shift; } /// Iterates over the one bits in the mask. @@ -532,13 +595,13 @@ static inline uint32_t CWISS_BitMask_LeadingZeros(const CWISS_BitMask* self) { /// If the mask is empty, returns `false`; otherwise, returns the index of the /// lowest one bit in the mask, and removes it from the set. static inline bool CWISS_BitMask_next(CWISS_BitMask* self, uint32_t* bit) { - if (self->mask == 0) { - return false; - } + if (self->mask == 0) { + return false; + } - *bit = CWISS_BitMask_LowestBitSet(self); - self->mask &= (self->mask - 1); - return true; + *bit = CWISS_BitMask_LowestBitSet(self); + self->mask &= (self->mask - 1); + return true; } CWISS_END_EXTERN @@ -576,7 +639,7 @@ typedef int8_t CWISS_ControlByte; // TODO: Wrap CWISS_ControlByte in a single-field struct to get strict-aliasing // benefits. -#if 0 +#if defined( __STDC_VERSION__ ) && __STDC_VERSION__ >= 201112L static_assert( (CWISS_kEmpty & CWISS_kDeleted & CWISS_kSentinel & 0x80) != 0, "Special markers need to have the MSB to make checking for them efficient"); @@ -603,18 +666,18 @@ static_assert(CWISS_kDeleted == -2, /// Returns a pointer to a control byte group that can be used by empty tables. static inline CWISS_ControlByte* CWISS_EmptyGroup(void) { - // A single block of empty control bytes for tables without any slots - // allocated. This enables removing a branch in the hot path of find(). - alignas(16) static const CWISS_ControlByte kEmptyGroup[16] = { - CWISS_kSentinel, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, - }; + // A single block of empty control bytes for tables without any slots + // allocated. This enables removing a branch in the hot path of find(). + CWISS_alignas(16) static const CWISS_ControlByte kEmptyGroup[16] = { + CWISS_kSentinel, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, + CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, + CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, + CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, CWISS_kEmpty, + }; - // Const must be cast away here; no uses of this function will actually write - // to it, because it is only used for empty tables. - return (CWISS_ControlByte*)&kEmptyGroup; + // Const must be cast away here; no uses of this function will actually write + // to it, because it is only used for empty tables. + return (CWISS_ControlByte*)&kEmptyGroup; } /// Returns a hash seed. @@ -622,16 +685,16 @@ static inline CWISS_ControlByte* CWISS_EmptyGroup(void) { /// The seed consists of the ctrl_ pointer, which adds enough entropy to ensure /// non-determinism of iteration order in most cases. static inline size_t CWISS_HashSeed(const CWISS_ControlByte* ctrl) { - // The low bits of the pointer have little or no entropy because of - // alignment. We shift the pointer to try to use higher entropy bits. A - // good number seems to be 12 bits, because that aligns with page size. - return ((uintptr_t)ctrl) >> 12; + // The low bits of the pointer have little or no entropy because of + // alignment. We shift the pointer to try to use higher entropy bits. A + // good number seems to be 12 bits, because that aligns with page size. + return ((uintptr_t)ctrl) >> 12; } /// Extracts the H1 portion of a hash: the high 57 bits mixed with a per-table /// salt. static inline size_t CWISS_H1(size_t hash, const CWISS_ControlByte* ctrl) { - return (hash >> 7) ^ CWISS_HashSeed(ctrl); + return (hash >> 7) ^ CWISS_HashSeed(ctrl); } /// Extracts the H2 portion of a hash: the low 7 bits, which can be used as @@ -641,7 +704,7 @@ static inline CWISS_h2_t CWISS_H2(size_t hash) { return hash & 0x7F; } /// Returns whether `c` is empty. static inline bool CWISS_IsEmpty(CWISS_ControlByte c) { - return c == CWISS_kEmpty; + return c == CWISS_kEmpty; } /// Returns whether `c` is full. @@ -649,32 +712,32 @@ static inline bool CWISS_IsFull(CWISS_ControlByte c) { return c >= 0; } /// Returns whether `c` is deleted. static inline bool CWISS_IsDeleted(CWISS_ControlByte c) { - return c == CWISS_kDeleted; + return c == CWISS_kDeleted; } /// Returns whether `c` is empty or deleted. static inline bool CWISS_IsEmptyOrDeleted(CWISS_ControlByte c) { - return c < CWISS_kSentinel; + return c < CWISS_kSentinel; } /// Asserts that `ctrl` points to a full control byte. #define CWISS_AssertIsFull(ctrl) \ - CWISS_CHECK((ctrl) != NULL && CWISS_IsFull(*(ctrl)), \ - "Invalid operation on iterator (%p/%d). The element might have " \ - "been erased, or the table might have rehashed.", \ - (ctrl), (ctrl) ? *(ctrl) : -1) + CWISS_CHECK((ctrl) != NULL && CWISS_IsFull(*(ctrl)), \ + "Invalid operation on iterator (%p/%d). The element might have " \ + "been erased, or the table might have rehashed.", \ + (ctrl), (ctrl) ? *(ctrl) : -1) /// Asserts that `ctrl` is either null OR points to a full control byte. #define CWISS_AssertIsValid(ctrl) \ - CWISS_CHECK((ctrl) == NULL || CWISS_IsFull(*(ctrl)), \ - "Invalid operation on iterator (%p/%d). The element might have " \ - "been erased, or the table might have rehashed.", \ - (ctrl), (ctrl) ? *(ctrl) : -1) + CWISS_CHECK((ctrl) == NULL || CWISS_IsFull(*(ctrl)), \ + "Invalid operation on iterator (%p/%d). The element might have " \ + "been erased, or the table might have rehashed.", \ + (ctrl), (ctrl) ? *(ctrl) : -1) /// Constructs a `BitMask` with the correct parameters for whichever /// implementation of `CWISS_Group` is in use. #define CWISS_Group_BitMask(x) \ - (CWISS_BitMask){(uint64_t)(x), CWISS_Group_kWidth, CWISS_Group_kShift}; + (CWISS_BitMask){(uint64_t)(x), CWISS_Group_kWidth, CWISS_Group_kShift}; // TODO(#4): Port this to NEON. #if CWISS_HAVE_SSE2 @@ -706,8 +769,8 @@ static inline bool CWISS_IsEmptyOrDeleted(CWISS_ControlByte c) { // four bits of each i8 lane in the second argument as // indices. typedef __m128i CWISS_Group; - #define CWISS_Group_kWidth ((size_t)16) - #define CWISS_Group_kShift 0 +#define CWISS_Group_kWidth ((size_t)16) +#define CWISS_Group_kShift 0 // https://github.com/abseil/abseil-cpp/issues/209 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87853 @@ -715,122 +778,118 @@ typedef __m128i CWISS_Group; // Work around this by using the portable implementation of Group // when using -funsigned-char under GCC. static inline CWISS_Group CWISS_mm_cmpgt_epi8_fixed(CWISS_Group a, - CWISS_Group b) { - if (CWISS_IS_GCC && CHAR_MIN == 0) { // std::is_unsigned_v<char> - const CWISS_Group mask = _mm_set1_epi8(0x80); - const CWISS_Group diff = _mm_subs_epi8(b, a); - return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask); - } - return _mm_cmpgt_epi8(a, b); + CWISS_Group b) { + if (CWISS_IS_GCC && CHAR_MIN == 0) { // std::is_unsigned_v<char> + const CWISS_Group mask = _mm_set1_epi8(0x80); + const CWISS_Group diff = _mm_subs_epi8(b, a); + return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask); + } + return _mm_cmpgt_epi8(a, b); } static inline CWISS_Group CWISS_Group_new(const CWISS_ControlByte* pos) { - return _mm_loadu_si128((const CWISS_Group*)pos); + return _mm_loadu_si128((const CWISS_Group*)pos); } // Returns a bitmask representing the positions of slots that match hash. static inline CWISS_BitMask CWISS_Group_Match(const CWISS_Group* self, - CWISS_h2_t hash) { - return CWISS_Group_BitMask( - _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_set1_epi8(hash), *self))) + CWISS_h2_t hash) { + return CWISS_Group_BitMask( + _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_set1_epi8(hash), *self))) } // Returns a bitmask representing the positions of empty slots. static inline CWISS_BitMask CWISS_Group_MatchEmpty(const CWISS_Group* self) { - #if CWISS_HAVE_SSSE3 - // This only works because ctrl_t::kEmpty is -128. - return CWISS_Group_BitMask(_mm_movemask_epi8(_mm_sign_epi8(*self, *self))); - #else - return CWISS_Group_Match(self, CWISS_kEmpty); - #endif +#if CWISS_HAVE_SSSE3 + // This only works because ctrl_t::kEmpty is -128. + return CWISS_Group_BitMask(_mm_movemask_epi8(_mm_sign_epi8(*self, *self))); +#else + return CWISS_Group_Match(self, CWISS_kEmpty); +#endif } // Returns a bitmask representing the positions of empty or deleted slots. -static inline CWISS_BitMask CWISS_Group_MatchEmptyOrDeleted( - const CWISS_Group* self) { - CWISS_Group special = _mm_set1_epi8((uint8_t)CWISS_kSentinel); - return CWISS_Group_BitMask( - _mm_movemask_epi8(CWISS_mm_cmpgt_epi8_fixed(special, *self))); +static inline CWISS_BitMask CWISS_Group_MatchEmptyOrDeleted(const CWISS_Group* self) { + CWISS_Group special = _mm_set1_epi8((uint8_t)CWISS_kSentinel); + return CWISS_Group_BitMask(_mm_movemask_epi8(CWISS_mm_cmpgt_epi8_fixed(special, *self))); } // Returns the number of trailing empty or deleted elements in the group. static inline uint32_t CWISS_Group_CountLeadingEmptyOrDeleted( - const CWISS_Group* self) { - CWISS_Group special = _mm_set1_epi8((uint8_t)CWISS_kSentinel); - return CWISS_TrailingZeros((uint32_t)( - _mm_movemask_epi8(CWISS_mm_cmpgt_epi8_fixed(special, *self)) + 1)); + const CWISS_Group* self) { + CWISS_Group special = _mm_set1_epi8((uint8_t)CWISS_kSentinel); + return CWISS_TrailingZeros((uint32_t)(_mm_movemask_epi8(CWISS_mm_cmpgt_epi8_fixed(special, *self)) + 1)); } -static inline void CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted( - const CWISS_Group* self, CWISS_ControlByte* dst) { - CWISS_Group msbs = _mm_set1_epi8((char)-128); - CWISS_Group x126 = _mm_set1_epi8(126); - #if CWISS_HAVE_SSSE3 - CWISS_Group res = _mm_or_si128(_mm_shuffle_epi8(x126, *self), msbs); - #else - CWISS_Group zero = _mm_setzero_si128(); - CWISS_Group special_mask = CWISS_mm_cmpgt_epi8_fixed(zero, *self); - CWISS_Group res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126)); - #endif - _mm_storeu_si128((CWISS_Group*)dst, res); +static inline void CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted(const CWISS_Group* self, CWISS_ControlByte* dst) { + CWISS_Group msbs = _mm_set1_epi8((char)-128); + CWISS_Group x126 = _mm_set1_epi8(126); +#if CWISS_HAVE_SSSE3 + CWISS_Group res = _mm_or_si128(_mm_shuffle_epi8(x126, *self), msbs); +#else + CWISS_Group zero = _mm_setzero_si128(); + CWISS_Group special_mask = CWISS_mm_cmpgt_epi8_fixed(zero, *self); + CWISS_Group res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126)); +#endif + _mm_storeu_si128((CWISS_Group*)dst, res); } #else // CWISS_HAVE_SSE2 typedef uint64_t CWISS_Group; - #define CWISS_Group_kWidth ((size_t)8) - #define CWISS_Group_kShift 3 +#define CWISS_Group_kWidth ((size_t)8) +#define CWISS_Group_kShift 3 // NOTE: Endian-hostile. static inline CWISS_Group CWISS_Group_new(const CWISS_ControlByte* pos) { - CWISS_Group val; - memcpy(&val, pos, sizeof(val)); - return val; + CWISS_Group val; + memcpy(&val, pos, sizeof(val)); + return val; } static inline CWISS_BitMask CWISS_Group_Match(const CWISS_Group* self, - CWISS_h2_t hash) { - // For the technique, see: - // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord - // (Determine if a word has a byte equal to n). - // - // Caveat: there are false positives but: - // - they only occur if there is a real match - // - they never occur on ctrl_t::kEmpty, ctrl_t::kDeleted, ctrl_t::kSentinel - // - they will be handled gracefully by subsequent checks in code - // - // Example: - // v = 0x1716151413121110 - // hash = 0x12 - // retval = (v - lsbs) & ~v & msbs = 0x0000000080800000 - uint64_t msbs = 0x8080808080808080ULL; - uint64_t lsbs = 0x0101010101010101ULL; - uint64_t x = *self ^ (lsbs * hash); - return CWISS_Group_BitMask((x - lsbs) & ~x & msbs); + CWISS_h2_t hash) { + // For the technique, see: + // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord + // (Determine if a word has a byte equal to n). + // + // Caveat: there are false positives but: + // - they only occur if there is a real match + // - they never occur on ctrl_t::kEmpty, ctrl_t::kDeleted, ctrl_t::kSentinel + // - they will be handled gracefully by subsequent checks in code + // + // Example: + // v = 0x1716151413121110 + // hash = 0x12 + // retval = (v - lsbs) & ~v & msbs = 0x0000000080800000 + uint64_t msbs = 0x8080808080808080ULL; + uint64_t lsbs = 0x0101010101010101ULL; + uint64_t x = *self ^ (lsbs * hash); + return CWISS_Group_BitMask((x - lsbs) & ~x & msbs); } static inline CWISS_BitMask CWISS_Group_MatchEmpty(const CWISS_Group* self) { - uint64_t msbs = 0x8080808080808080ULL; - return CWISS_Group_BitMask((*self & (~*self << 6)) & msbs); + uint64_t msbs = 0x8080808080808080ULL; + return CWISS_Group_BitMask((*self & (~*self << 6)) & msbs); } static inline CWISS_BitMask CWISS_Group_MatchEmptyOrDeleted( - const CWISS_Group* self) { - uint64_t msbs = 0x8080808080808080ULL; - return CWISS_Group_BitMask((*self & (~*self << 7)) & msbs); + const CWISS_Group* self) { + uint64_t msbs = 0x8080808080808080ULL; + return CWISS_Group_BitMask((*self & (~*self << 7)) & msbs); } static inline uint32_t CWISS_Group_CountLeadingEmptyOrDeleted( - const CWISS_Group* self) { - uint64_t gaps = 0x00FEFEFEFEFEFEFEULL; - return (CWISS_TrailingZeros(((~*self & (*self >> 7)) | gaps) + 1) + 7) >> 3; + const CWISS_Group* self) { + uint64_t gaps = 0x00FEFEFEFEFEFEFEULL; + return (CWISS_TrailingZeros(((~*self & (*self >> 7)) | gaps) + 1) + 7) >> 3; } static inline void CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted( - const CWISS_Group* self, CWISS_ControlByte* dst) { - uint64_t msbs = 0x8080808080808080ULL; - uint64_t lsbs = 0x0101010101010101ULL; - uint64_t x = *self & msbs; - uint64_t res = (~x + (x >> 7)) & ~lsbs; - memcpy(dst, &res, sizeof(res)); + const CWISS_Group* self, CWISS_ControlByte* dst) { + uint64_t msbs = 0x8080808080808080ULL; + uint64_t lsbs = 0x0101010101010101ULL; + uint64_t x = *self & msbs; + uint64_t res = (~x + (x >> 7)) & ~lsbs; + memcpy(dst, &res, sizeof(res)); } #endif // CWISS_HAVE_SSE2 @@ -879,14 +938,14 @@ CWISS_BEGIN_EXTERN /// of the control byte array and at the end, such that we can create a /// `CWISS_Group_kWidth`-width probe window starting from any control byte. static inline size_t CWISS_NumClonedBytes(void) { - return CWISS_Group_kWidth - 1; + return CWISS_Group_kWidth - 1; } /// Returns whether `n` is a valid capacity (i.e., number of slots). /// /// A valid capacity is a non-zero integer `2^m - 1`. static inline bool CWISS_IsValidCapacity(size_t n) { - return ((n + 1) & n) == 0 && n > 0; + return ((n + 1) & n) == 0 && n > 0; } /// Returns some per-call entropy. @@ -895,22 +954,22 @@ static inline bool CWISS_IsValidCapacity(size_t n) { /// thread-local) value with a perpetually-incrementing value. static inline size_t RandomSeed(void) { #ifdef CWISS_THREAD_LOCAL - static CWISS_THREAD_LOCAL size_t counter; - size_t value = counter++; + static CWISS_THREAD_LOCAL size_t counter; + size_t value = counter++; #else - static volatile CWISS_ATOMIC_T(size_t) counter; - size_t value = CWISS_ATOMIC_INC(counter); + static CWISS_ATOMIC_T(size_t) counter; + size_t value = CWISS_ATOMIC_INC(counter); #endif - return value ^ ((size_t)&counter); + return value ^ ((size_t)&counter); } /// Mixes a randomly generated per-process seed with `hash` and `ctrl` to /// randomize insertion order within groups. CWISS_INLINE_NEVER static bool CWISS_ShouldInsertBackwards( - size_t hash, const CWISS_ControlByte* ctrl) { - // To avoid problems with weak hashes and single bit tests, we use % 13. - // TODO(kfm,sbenza): revisit after we do unconditional mixing - return (CWISS_H1(hash, ctrl) ^ RandomSeed()) % 13 > 6; + size_t hash, const CWISS_ControlByte* ctrl) { + // To avoid problems with weak hashes and single bit tests, we use % 13. + // TODO(kfm,sbenza): revisit after we do unconditional mixing + return (CWISS_H1(hash, ctrl) ^ RandomSeed()) % 13 > 6; } /// Applies the following mapping to every byte in the control array: @@ -920,61 +979,52 @@ CWISS_INLINE_NEVER static bool CWISS_ShouldInsertBackwards( /// /// Preconditions: `CWISS_IsValidCapacity(capacity)`, /// `ctrl[capacity]` == `kSentinel`, `ctrl[i] != kSentinel for i < capacity`. -CWISS_INLINE_NEVER static void CWISS_ConvertDeletedToEmptyAndFullToDeleted( - CWISS_ControlByte* ctrl, size_t capacity) { - CWISS_DCHECK(ctrl[capacity] == CWISS_kSentinel, "bad ctrl value at %zu: %02x", - capacity, ctrl[capacity]); - CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", - capacity); - - for (CWISS_ControlByte* pos = ctrl; pos < ctrl + capacity; - pos += CWISS_Group_kWidth) { - CWISS_Group g = CWISS_Group_new(pos); - CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted(&g, pos); - } - // Copy the cloned ctrl bytes. - memcpy(ctrl + capacity + 1, ctrl, CWISS_NumClonedBytes()); - ctrl[capacity] = CWISS_kSentinel; +CWISS_INLINE_NEVER static void CWISS_ConvertDeletedToEmptyAndFullToDeleted( CWISS_ControlByte* ctrl, size_t capacity) { + CWISS_DCHECK(ctrl[capacity] == CWISS_kSentinel, "bad ctrl value at %zu: %02x", capacity, ctrl[capacity]); + CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", capacity); + + for (CWISS_ControlByte* pos = ctrl; pos < ctrl + capacity; pos += CWISS_Group_kWidth) { + CWISS_Group g = CWISS_Group_new(pos); + CWISS_Group_ConvertSpecialToEmptyAndFullToDeleted(&g, pos); + } + // Copy the cloned ctrl bytes. + memcpy(ctrl + capacity + 1, ctrl, CWISS_NumClonedBytes()); + ctrl[capacity] = CWISS_kSentinel; } /// Sets `ctrl` to `{kEmpty, ..., kEmpty, kSentinel}`, marking the entire /// array as deleted. -static inline void CWISS_ResetCtrl(size_t capacity, CWISS_ControlByte* ctrl, - const void* slots, size_t slot_size) { - memset(ctrl, CWISS_kEmpty, capacity + 1 + CWISS_NumClonedBytes()); - ctrl[capacity] = CWISS_kSentinel; - CWISS_PoisonMemory(slots, slot_size * capacity); +static inline void CWISS_ResetCtrl(size_t capacity, CWISS_ControlByte* ctrl, const void* slots, size_t slot_size) { + memset(ctrl, CWISS_kEmpty, capacity + 1 + CWISS_NumClonedBytes()); + ctrl[capacity] = CWISS_kSentinel; + CWISS_PoisonMemory(slots, slot_size * capacity); } /// Sets `ctrl[i]` to `h`. /// /// Unlike setting it directly, this function will perform bounds checks and /// mirror the value to the cloned tail if necessary. -static inline void CWISS_SetCtrl(size_t i, CWISS_ControlByte h, size_t capacity, - CWISS_ControlByte* ctrl, const void* slots, - size_t slot_size) { - CWISS_DCHECK(i < capacity, "CWISS_SetCtrl out-of-bounds: %zu >= %zu", i, - capacity); - - const char* slot = ((const char*)slots) + i * slot_size; - if (CWISS_IsFull(h)) { - CWISS_UnpoisonMemory(slot, slot_size); - } else { - CWISS_PoisonMemory(slot, slot_size); - } - - // This is intentionally branchless. If `i < kWidth`, it will write to the - // cloned bytes as well as the "real" byte; otherwise, it will store `h` - // twice. - size_t mirrored_i = ((i - CWISS_NumClonedBytes()) & capacity) + - (CWISS_NumClonedBytes() & capacity); - ctrl[i] = h; - ctrl[mirrored_i] = h; +static inline void CWISS_SetCtrl(size_t i, CWISS_ControlByte h, size_t capacity, CWISS_ControlByte* ctrl, const void* slots, size_t slot_size) { + CWISS_DCHECK(i < capacity, "CWISS_SetCtrl out-of-bounds: %zu >= %zu", i, capacity); + + const char* slot = ((const char*)slots) + i * slot_size; + if (CWISS_IsFull(h)) { + CWISS_UnpoisonMemory(slot, slot_size); + } else { + CWISS_PoisonMemory(slot, slot_size); + } + + // This is intentionally branchless. If `i < kWidth`, it will write to the + // cloned bytes as well as the "real" byte; otherwise, it will store `h` + // twice. + size_t mirrored_i = ((i - CWISS_NumClonedBytes()) & capacity) + (CWISS_NumClonedBytes() & capacity); + ctrl[i] = h; + ctrl[mirrored_i] = h; } /// Converts `n` into the next valid capacity, per `CWISS_IsValidCapacity`. static inline size_t CWISS_NormalizeCapacity(size_t n) { - return n ? SIZE_MAX >> CWISS_LeadingZeros(n) : 1; + return n ? SIZE_MAX >> CWISS_LeadingZeros(n) : 1; } // General notes on capacity/growth methods below: @@ -988,14 +1038,14 @@ static inline size_t CWISS_NormalizeCapacity(size_t n) { /// Given `capacity`, applies the load factor; i.e., it returns the maximum /// number of values we should put into the table before a rehash. static inline size_t CWISS_CapacityToGrowth(size_t capacity) { - CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", - capacity); - // `capacity*7/8` - if (CWISS_Group_kWidth == 8 && capacity == 7) { - // x-x/8 does not work when x==7. - return 6; - } - return capacity - capacity / 8; + CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", + capacity); + // `capacity*7/8` + if (CWISS_Group_kWidth == 8 && capacity == 7) { + // x-x/8 does not work when x==7. + return 6; + } + return capacity - capacity / 8; } /// Given `growth`, "unapplies" the load factor to find how large the capacity @@ -1004,12 +1054,12 @@ static inline size_t CWISS_CapacityToGrowth(size_t capacity) { /// This might not be a valid capacity and `CWISS_NormalizeCapacity()` may be /// necessary. static inline size_t CWISS_GrowthToLowerboundCapacity(size_t growth) { - // `growth*8/7` - if (CWISS_Group_kWidth == 8 && growth == 7) { - // x+(x-1)/7 does not work when x==7. - return 8; - } - return growth + (size_t)((((int64_t)growth) - 1) / 7); + // `growth*8/7` + if (CWISS_Group_kWidth == 8 && growth == 7) { + // x+(x-1)/7 does not work when x==7. + return 8; + } + return growth + (size_t)((((int64_t)growth) - 1) / 7); } // The allocated block consists of `capacity + 1 + NumClonedBytes()` control @@ -1019,17 +1069,17 @@ static inline size_t CWISS_GrowthToLowerboundCapacity(size_t growth) { /// Given the capacity of a table, computes the offset (from the start of the /// backing allocation) at which the slots begin. static inline size_t CWISS_SlotOffset(size_t capacity, size_t slot_align) { - CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", - capacity); - const size_t num_control_bytes = capacity + 1 + CWISS_NumClonedBytes(); - return (num_control_bytes + slot_align - 1) & (~slot_align + 1); + CWISS_DCHECK(CWISS_IsValidCapacity(capacity), "invalid capacity: %zu", + capacity); + const size_t num_control_bytes = capacity + 1 + CWISS_NumClonedBytes(); + return (num_control_bytes + slot_align - 1) & (~slot_align + 1); } /// Given the capacity of a table, computes the total size of the backing /// array. static inline size_t CWISS_AllocSize(size_t capacity, size_t slot_size, - size_t slot_align) { - return CWISS_SlotOffset(capacity, slot_align) + capacity * slot_size; + size_t slot_align) { + return CWISS_SlotOffset(capacity, slot_align) + capacity * slot_size; } /// Whether a table is "small". A small table fits entirely into a probing @@ -1045,7 +1095,7 @@ static inline size_t CWISS_AllocSize(size_t capacity, size_t slot_size, /// `CWISS_FindFirstNonFull()`, where we never try /// `CWISS_ShouldInsertBackwards()` for small tables. static inline bool CWISS_IsSmall(size_t capacity) { - return capacity < CWISS_Group_kWidth - 1; + return capacity < CWISS_Group_kWidth - 1; } CWISS_END_EXTERN @@ -1080,47 +1130,47 @@ CWISS_BEGIN_EXTERN /// actually inspected, there are no corresponding slots for the cloned bytes, /// so we need to make sure we've treated those offsets as "wrapping around". typedef struct { - size_t mask_; - size_t offset_; - size_t index_; + size_t mask_; + size_t offset_; + size_t index_; } CWISS_ProbeSeq; /// Creates a new probe sequence using `hash` as the initial value of the /// sequence and `mask` (usually the capacity of the table) as the mask to /// apply to each value in the progression. static inline CWISS_ProbeSeq CWISS_ProbeSeq_new(size_t hash, size_t mask) { - return (CWISS_ProbeSeq){ - .mask_ = mask, - .offset_ = hash & mask, - }; + return (CWISS_ProbeSeq) { + .mask_ = mask, + .offset_ = hash & mask, + }; } /// Returns the slot `i` indices ahead of `self` within the bounds expressed by /// `mask`. static inline size_t CWISS_ProbeSeq_offset(const CWISS_ProbeSeq* self, - size_t i) { - return (self->offset_ + i) & self->mask_; + size_t i) { + return (self->offset_ + i) & self->mask_; } /// Advances the sequence; the value can be obtained by calling /// `CWISS_ProbeSeq_offset()` or inspecting `offset_`. static inline void CWISS_ProbeSeq_next(CWISS_ProbeSeq* self) { - self->index_ += CWISS_Group_kWidth; - self->offset_ += self->index_; - self->offset_ &= self->mask_; + self->index_ += CWISS_Group_kWidth; + self->offset_ += self->index_; + self->offset_ &= self->mask_; } /// Begins a probing operation on `ctrl`, using `hash`. static inline CWISS_ProbeSeq CWISS_ProbeSeq_Start(const CWISS_ControlByte* ctrl, - size_t hash, - size_t capacity) { - return CWISS_ProbeSeq_new(CWISS_H1(hash, ctrl), capacity); + size_t hash, + size_t capacity) { + return CWISS_ProbeSeq_new(CWISS_H1(hash, ctrl), capacity); } // The return value of `CWISS_FindFirstNonFull()`. typedef struct { - size_t offset; - size_t probe_length; + size_t offset; + size_t probe_length; } CWISS_FindInfo; /// Probes an array of control bits using a probe sequence derived from `hash`, @@ -1132,30 +1182,32 @@ typedef struct { /// slots in the same group. Such tables appear during /// `CWISS_RawTable_DropDeletesWithoutResize()`. static inline CWISS_FindInfo CWISS_FindFirstNonFull( - const CWISS_ControlByte* ctrl, size_t hash, size_t capacity) { - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(ctrl, hash, capacity); - while (true) { - CWISS_Group g = CWISS_Group_new(ctrl + seq.offset_); - CWISS_BitMask mask = CWISS_Group_MatchEmptyOrDeleted(&g); - if (mask.mask) { + const CWISS_ControlByte* ctrl, size_t hash, size_t capacity) { + CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(ctrl, hash, capacity); + while (true) { + CWISS_Group g = CWISS_Group_new(ctrl + seq.offset_); + CWISS_BitMask mask = CWISS_Group_MatchEmptyOrDeleted(&g); + if (mask.mask) { #ifndef NDEBUG - // We want to add entropy even when ASLR is not enabled. - // In debug build we will randomly insert in either the front or back of - // the group. - // TODO(kfm,sbenza): revisit after we do unconditional mixing - if (!CWISS_IsSmall(capacity) && CWISS_ShouldInsertBackwards(hash, ctrl)) { - return (CWISS_FindInfo){ - CWISS_ProbeSeq_offset(&seq, CWISS_BitMask_HighestBitSet(&mask)), - seq.index_}; - } + // We want to add entropy even when ASLR is not enabled. + // In debug build we will randomly insert in either the front or back of + // the group. + // TODO(kfm,sbenza): revisit after we do unconditional mixing + if (!CWISS_IsSmall(capacity) && CWISS_ShouldInsertBackwards(hash, ctrl)) { + return (CWISS_FindInfo) { + CWISS_ProbeSeq_offset(&seq, CWISS_BitMask_HighestBitSet(&mask)), + seq.index_ + }; + } #endif - return (CWISS_FindInfo){ - CWISS_ProbeSeq_offset(&seq, CWISS_BitMask_TrailingZeros(&mask)), - seq.index_}; - } - CWISS_ProbeSeq_next(&seq); - CWISS_DCHECK(seq.index_ <= capacity, "full table!"); - } + return (CWISS_FindInfo) { + CWISS_ProbeSeq_offset(&seq, CWISS_BitMask_TrailingZeros(&mask)), + seq.index_ + }; + } + CWISS_ProbeSeq_next(&seq); + CWISS_DCHECK(seq.index_ <= capacity, "full table!"); + } } CWISS_END_EXTERN @@ -1170,93 +1222,95 @@ CWISS_BEGIN_EXTERN static inline uint64_t CWISS_AbslHash_LowLevelMix(uint64_t v0, uint64_t v1) { #ifndef __aarch64__ - // The default bit-mixer uses 64x64->128-bit multiplication. - CWISS_U128 p = CWISS_Mul128(v0, v1); - return p.hi ^ p.lo; + // The default bit-mixer uses 64x64->128-bit multiplication. + CWISS_U128 p = CWISS_Mul128(v0, v1); + return p.hi ^ p.lo; #else - // The default bit-mixer above would perform poorly on some ARM microarchs, - // where calculating a 128-bit product requires a sequence of two - // instructions with a high combined latency and poor throughput. - // Instead, we mix bits using only 64-bit arithmetic, which is faster. - uint64_t p = v0 ^ CWISS_RotateLeft(v1, 40); - p *= v1 ^ CWISS_RotateLeft(v0, 39); - return p ^ (p >> 11); + // The default bit-mixer above would perform poorly on some ARM microarchs, + // where calculating a 128-bit product requires a sequence of two + // instructions with a high combined latency and poor throughput. + // Instead, we mix bits using only 64-bit arithmetic, which is faster. + uint64_t p = v0 ^ CWISS_RotateLeft(v1, 40); + p *= v1 ^ CWISS_RotateLeft(v0, 39); + return p ^ (p >> 11); #endif } CWISS_INLINE_NEVER static uint64_t CWISS_AbslHash_LowLevelHash(const void* data, size_t len, - uint64_t seed, - const uint64_t salt[5]) { - const char* ptr = (const char*)data; - uint64_t starting_length = (uint64_t)len; - uint64_t current_state = seed ^ salt[0]; - - if (len > 64) { - // If we have more than 64 bytes, we're going to handle chunks of 64 - // bytes at a time. We're going to build up two separate hash states - // which we will then hash together. - uint64_t duplicated_state = current_state; - - do { - uint64_t chunk[8]; - memcpy(chunk, ptr, sizeof(chunk)); - - uint64_t cs0 = CWISS_AbslHash_LowLevelMix(chunk[0] ^ salt[1], - chunk[1] ^ current_state); - uint64_t cs1 = CWISS_AbslHash_LowLevelMix(chunk[2] ^ salt[2], - chunk[3] ^ current_state); - current_state = (cs0 ^ cs1); - - uint64_t ds0 = CWISS_AbslHash_LowLevelMix(chunk[4] ^ salt[3], - chunk[5] ^ duplicated_state); - uint64_t ds1 = CWISS_AbslHash_LowLevelMix(chunk[6] ^ salt[4], - chunk[7] ^ duplicated_state); - duplicated_state = (ds0 ^ ds1); - - ptr += 64; - len -= 64; - } while (len > 64); - - current_state = current_state ^ duplicated_state; - } - - // We now have a data `ptr` with at most 64 bytes and the current state - // of the hashing state machine stored in current_state. - while (len > 16) { - uint64_t a = CWISS_Load64(ptr); - uint64_t b = CWISS_Load64(ptr + 8); - - current_state = CWISS_AbslHash_LowLevelMix(a ^ salt[1], b ^ current_state); - - ptr += 16; - len -= 16; - } - - // We now have a data `ptr` with at most 16 bytes. - uint64_t a = 0; - uint64_t b = 0; - if (len > 8) { - // When we have at least 9 and at most 16 bytes, set A to the first 64 - // bits of the input and B to the last 64 bits of the input. Yes, they will - // overlap in the middle if we are working with less than the full 16 - // bytes. - a = CWISS_Load64(ptr); - b = CWISS_Load64(ptr + len - 8); - } else if (len > 3) { - // If we have at least 4 and at most 8 bytes, set A to the first 32 - // bits and B to the last 32 bits. - a = CWISS_Load32(ptr); - b = CWISS_Load32(ptr + len - 4); - } else if (len > 0) { - // If we have at least 1 and at most 3 bytes, read all of the provided - // bits into A, with some adjustments. - a = CWISS_Load1To3(ptr, len); - } - - uint64_t w = CWISS_AbslHash_LowLevelMix(a ^ salt[1], b ^ current_state); - uint64_t z = salt[1] ^ starting_length; - return CWISS_AbslHash_LowLevelMix(w, z); + uint64_t seed, + const uint64_t salt[5]) { + const char* ptr = (const char*)data; + uint64_t starting_length = (uint64_t)len; + uint64_t current_state = seed ^ salt[0]; + + if (len > 64) { + // If we have more than 64 bytes, we're going to handle chunks of 64 + // bytes at a time. We're going to build up two separate hash states + // which we will then hash together. + uint64_t duplicated_state = current_state; + + do { + uint64_t chunk[8]; + memcpy(chunk, ptr, sizeof(chunk)); + + uint64_t cs0 = CWISS_AbslHash_LowLevelMix(chunk[0] ^ salt[1], + chunk[1] ^ current_state); + uint64_t cs1 = CWISS_AbslHash_LowLevelMix(chunk[2] ^ salt[2], + chunk[3] ^ current_state); + current_state = (cs0 ^ cs1); + + uint64_t ds0 = CWISS_AbslHash_LowLevelMix(chunk[4] ^ salt[3], + chunk[5] ^ duplicated_state); + uint64_t ds1 = CWISS_AbslHash_LowLevelMix(chunk[6] ^ salt[4], + chunk[7] ^ duplicated_state); + duplicated_state = (ds0 ^ ds1); + + ptr += 64; + len -= 64; + } while (len > 64); + + current_state = current_state ^ duplicated_state; + } + + // We now have a data `ptr` with at most 64 bytes and the current state + // of the hashing state machine stored in current_state. + while (len > 16) { + uint64_t a = CWISS_Load64(ptr); + uint64_t b = CWISS_Load64(ptr + 8); + + current_state = CWISS_AbslHash_LowLevelMix(a ^ salt[1], b ^ current_state); + + ptr += 16; + len -= 16; + } + + // We now have a data `ptr` with at most 16 bytes. + uint64_t a = 0; + uint64_t b = 0; + if (len > 8) { + // When we have at least 9 and at most 16 bytes, set A to the first 64 + // bits of the input and B to the last 64 bits of the input. Yes, they will + // overlap in the middle if we are working with less than the full 16 + // bytes. + a = CWISS_Load64(ptr); + b = CWISS_Load64(ptr + len - 8); + } + else if (len > 3) { + // If we have at least 4 and at most 8 bytes, set A to the first 32 + // bits and B to the last 32 bits. + a = CWISS_Load32(ptr); + b = CWISS_Load32(ptr + len - 4); + } + else if (len > 0) { + // If we have at least 1 and at most 3 bytes, read all of the provided + // bits into A, with some adjustments. + a = CWISS_Load1To3(ptr, len); + } + + uint64_t w = CWISS_AbslHash_LowLevelMix(a ^ salt[1], b ^ current_state); + uint64_t z = salt[1] ^ starting_length; + return CWISS_AbslHash_LowLevelMix(w, z); } // A non-deterministic seed. @@ -1283,8 +1337,8 @@ static const void* const CWISS_AbslHash_kSeed = &CWISS_AbslHash_kSeed; // part of pi. // https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number static const uint64_t CWISS_AbslHash_kHashSalt[5] = { - 0x243F6A8885A308D3, 0x13198A2E03707344, 0xA4093822299F31D0, - 0x082EFA98EC4E6C89, 0x452821E638D01377, + 0x243F6A8885A308D3, 0x13198A2E03707344, 0xA4093822299F31D0, + 0x082EFA98EC4E6C89, 0x452821E638D01377, }; #define CWISS_AbslHash_kPiecewiseChunkSize ((size_t)1024) @@ -1293,15 +1347,15 @@ typedef uint64_t CWISS_AbslHash_State_; #define CWISS_AbslHash_kInit_ ((CWISS_AbslHash_State_)(uintptr_t)CWISS_AbslHash_kSeed) static inline void CWISS_AbslHash_Mix(CWISS_AbslHash_State_* state, - uint64_t v) { - const uint64_t kMul = sizeof(size_t) == 4 ? 0xcc9e2d51 : 0x9ddfea08eb382d69; - *state = CWISS_AbslHash_LowLevelMix(*state + v, kMul); + uint64_t v) { + const uint64_t kMul = sizeof(size_t) == 4 ? 0xcc9e2d51 : 0x9ddfea08eb382d69; + *state = CWISS_AbslHash_LowLevelMix(*state + v, kMul); } CWISS_INLINE_NEVER static uint64_t CWISS_AbslHash_Hash64(const void* val, size_t len) { - return CWISS_AbslHash_LowLevelHash(val, len, CWISS_AbslHash_kInit_, - CWISS_AbslHash_kHashSalt); + return CWISS_AbslHash_LowLevelHash(val, len, CWISS_AbslHash_kInit_, + CWISS_AbslHash_kHashSalt); } CWISS_END_EXTERN @@ -1332,488 +1386,77 @@ CWISS_BEGIN_EXTERN typedef size_t CWISS_FxHash_State; #define CWISS_FxHash_kInit ((CWISS_FxHash_State)0) static inline void CWISS_FxHash_Write(CWISS_FxHash_State* state, - const void* val, size_t len) { - const size_t kSeed = (size_t)(UINT64_C(0x517cc1b727220a95)); - const uint32_t kRotate = 5; - - const char* p = (const char*)val; - CWISS_FxHash_State state_ = *state; - while (len > 0) { - size_t word = 0; - size_t to_read = len >= sizeof(state_) ? sizeof(state_) : len; - memcpy(&word, p, to_read); - - state_ = CWISS_RotateLeft(state_, kRotate); - state_ ^= word; - state_ *= kSeed; - - len -= to_read; - p += to_read; - } - *state = state_; + const void* val, size_t len) { + const size_t kSeed = (size_t)(UINT64_C(0x517cc1b727220a95)); + const uint32_t kRotate = 5; + + const char* p = (const char*)val; + CWISS_FxHash_State state_ = *state; + while (len > 0) { + size_t word = 0; + size_t to_read = len >= sizeof(state_) ? sizeof(state_) : len; + memcpy(&word, p, to_read); + + state_ = CWISS_RotateLeft(state_, kRotate); + state_ ^= word; + state_ *= kSeed; + + len -= to_read; + p += to_read; + } + *state = state_; } static inline size_t CWISS_FxHash_Finish(CWISS_FxHash_State state) { - return state; + return state; } typedef CWISS_AbslHash_State_ CWISS_AbslHash_State; #define CWISS_AbslHash_kInit CWISS_AbslHash_kInit_ static inline void CWISS_AbslHash_Write(CWISS_AbslHash_State* state, - const void* val, size_t len) { - const char* val8 = (const char*)val; - if (CWISS_LIKELY(len < CWISS_AbslHash_kPiecewiseChunkSize)) { - goto CWISS_AbslHash_Write_small; - } - - while (len >= CWISS_AbslHash_kPiecewiseChunkSize) { - CWISS_AbslHash_Mix( - state, CWISS_AbslHash_Hash64(val8, CWISS_AbslHash_kPiecewiseChunkSize)); - len -= CWISS_AbslHash_kPiecewiseChunkSize; - val8 += CWISS_AbslHash_kPiecewiseChunkSize; - } + const void* val, size_t len) { + const char* val8 = (const char*)val; + if (CWISS_LIKELY(len < CWISS_AbslHash_kPiecewiseChunkSize)) { + goto CWISS_AbslHash_Write_small; + } + + while (len >= CWISS_AbslHash_kPiecewiseChunkSize) { + CWISS_AbslHash_Mix( + state, CWISS_AbslHash_Hash64(val8, CWISS_AbslHash_kPiecewiseChunkSize)); + len -= CWISS_AbslHash_kPiecewiseChunkSize; + val8 += CWISS_AbslHash_kPiecewiseChunkSize; + } CWISS_AbslHash_Write_small:; - uint64_t v; - if (len > 16) { - v = CWISS_AbslHash_Hash64(val8, len); - } else if (len > 8) { - CWISS_U128 p = CWISS_Load9To16(val8, len); - CWISS_AbslHash_Mix(state, p.lo); - v = p.hi; - } else if (len >= 4) { - v = CWISS_Load4To8(val8, len); - } else if (len > 0) { - v = CWISS_Load1To3(val8, len); - } else { - // Empty ranges have no effect. - return; - } - - CWISS_AbslHash_Mix(state, v); + uint64_t v; + if (len > 16) { + v = CWISS_AbslHash_Hash64(val8, len); + } + else if (len > 8) { + CWISS_U128 p = CWISS_Load9To16(val8, len); + CWISS_AbslHash_Mix(state, p.lo); + v = p.hi; + } + else if (len >= 4) { + v = CWISS_Load4To8(val8, len); + } + else if (len > 0) { + v = CWISS_Load1To3(val8, len); + } + else { + // Empty ranges have no effect. + return; + } + + CWISS_AbslHash_Mix(state, v); } static inline size_t CWISS_AbslHash_Finish(CWISS_AbslHash_State state) { - return state; + return state; } CWISS_END_EXTERN CWISS_END /// cwisstable/hash.h ////////////////////////////////////////////////////////// -/// cwisstable/internal/extract.h ////////////////////////////////////////////// -/// Macro keyword-arguments machinery. -/// -/// This file defines a number of macros used by policy.h to implement its -/// policy construction macros. -/// -/// The way they work is more-or-less like this: -/// -/// `CWISS_EXTRACT(foo, ...)` will find the first parenthesized pair that -/// matches exactly `(foo, whatever)`, where `foo` is part of a small set of -/// tokens defined in this file. To do so, this first expands into -/// -/// ``` -/// CWISS_EXTRACT1(CWISS_EXTRACT_foo, (k, v), ...) -/// ``` -/// -/// where `(k, v)` is the first pair in the macro arguments. This in turn -/// expands into -/// -/// ``` -/// CWISS_SELECT01(CWISS_EXTRACT_foo (k, v), CWISS_EXTRACT_VALUE, (k, v), -/// CWISS_EXTRACT2, (needle, __VA_ARGS__), CWISS_NOTHING) -/// ``` -/// -/// At this point, the preprocessor will expand `CWISS_EXTRACT_foo (k, v)` into -/// `CWISS_EXTRACT_foo_k`, which will be further expanded into `tok,tok,tok` if -/// `k` is the token `foo`, because we've defined `CWISS_EXTRACT_foo_foo` as a -/// macro. -/// -/// `CWISS_SELECT01` will then delete the first three arguments, and the fourth -/// and fifth arguments will be juxtaposed. -/// -/// In the case that `k` does not match, `CWISS_EXTRACT_foo (k, v), IDENT, (k, -/// v),` is deleted from the call, and the rest of the macro expands into -/// `CWISS_EXTRACT2(needle, __VA_ARGS__, _)` repeating the cycle but with a -/// different name. -/// -/// In the case that `k` matches, the `tok,tok,tok` is deleted, and we get -/// `CWISS_EXTRACT_VALUE(k, v)`, which expands to `v`. - -#define CWISS_EXTRACT(needle_, default_, ...) \ - (CWISS_EXTRACT_RAW(needle_, default_, __VA_ARGS__)) - -#define CWISS_EXTRACT_RAW(needle_, default_, ...) \ - CWISS_EXTRACT00(CWISS_EXTRACT_##needle_, __VA_ARGS__, (needle_, default_)) - -#define CWISS_EXTRACT_VALUE(key, val) val - -// NOTE: Everything below this line is generated by cwisstable/extract.py! -// !!! - -#define CWISS_EXTRACT_obj_copy(key_, val_) CWISS_EXTRACT_obj_copyZ##key_ -#define CWISS_EXTRACT_obj_copyZobj_copy \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_obj_dtor(key_, val_) CWISS_EXTRACT_obj_dtorZ##key_ -#define CWISS_EXTRACT_obj_dtorZobj_dtor \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_key_hash(key_, val_) CWISS_EXTRACT_key_hashZ##key_ -#define CWISS_EXTRACT_key_hashZkey_hash \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_key_eq(key_, val_) CWISS_EXTRACT_key_eqZ##key_ -#define CWISS_EXTRACT_key_eqZkey_eq CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_alloc_alloc(key_, val_) CWISS_EXTRACT_alloc_allocZ##key_ -#define CWISS_EXTRACT_alloc_allocZalloc_alloc \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_alloc_free(key_, val_) CWISS_EXTRACT_alloc_freeZ##key_ -#define CWISS_EXTRACT_alloc_freeZalloc_free \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_slot_size(key_, val_) CWISS_EXTRACT_slot_sizeZ##key_ -#define CWISS_EXTRACT_slot_sizeZslot_size \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_slot_align(key_, val_) CWISS_EXTRACT_slot_alignZ##key_ -#define CWISS_EXTRACT_slot_alignZslot_align \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_slot_init(key_, val_) CWISS_EXTRACT_slot_initZ##key_ -#define CWISS_EXTRACT_slot_initZslot_init \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_slot_transfer(key_, val_) \ - CWISS_EXTRACT_slot_transferZ##key_ -#define CWISS_EXTRACT_slot_transferZslot_transfer \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_slot_get(key_, val_) CWISS_EXTRACT_slot_getZ##key_ -#define CWISS_EXTRACT_slot_getZslot_get \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_slot_dtor(key_, val_) CWISS_EXTRACT_slot_dtorZ##key_ -#define CWISS_EXTRACT_slot_dtorZslot_dtor \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING -#define CWISS_EXTRACT_modifiers(key_, val_) CWISS_EXTRACT_modifiersZ##key_ -#define CWISS_EXTRACT_modifiersZmodifiers \ - CWISS_NOTHING, CWISS_NOTHING, CWISS_NOTHING - -#define CWISS_EXTRACT00(needle_, kv_, ...) \ - CWISS_SELECT00(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT01, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT01(needle_, kv_, ...) \ - CWISS_SELECT01(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT02, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT02(needle_, kv_, ...) \ - CWISS_SELECT02(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT03, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT03(needle_, kv_, ...) \ - CWISS_SELECT03(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT04, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT04(needle_, kv_, ...) \ - CWISS_SELECT04(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT05, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT05(needle_, kv_, ...) \ - CWISS_SELECT05(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT06, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT06(needle_, kv_, ...) \ - CWISS_SELECT06(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT07, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT07(needle_, kv_, ...) \ - CWISS_SELECT07(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT08, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT08(needle_, kv_, ...) \ - CWISS_SELECT08(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT09, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT09(needle_, kv_, ...) \ - CWISS_SELECT09(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT0A, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT0A(needle_, kv_, ...) \ - CWISS_SELECT0A(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT0B, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT0B(needle_, kv_, ...) \ - CWISS_SELECT0B(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT0C, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT0C(needle_, kv_, ...) \ - CWISS_SELECT0C(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT0D, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT0D(needle_, kv_, ...) \ - CWISS_SELECT0D(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT0E, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT0E(needle_, kv_, ...) \ - CWISS_SELECT0E(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT0F, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT0F(needle_, kv_, ...) \ - CWISS_SELECT0F(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT10, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT10(needle_, kv_, ...) \ - CWISS_SELECT10(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT11, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT11(needle_, kv_, ...) \ - CWISS_SELECT11(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT12, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT12(needle_, kv_, ...) \ - CWISS_SELECT12(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT13, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT13(needle_, kv_, ...) \ - CWISS_SELECT13(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT14, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT14(needle_, kv_, ...) \ - CWISS_SELECT14(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT15, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT15(needle_, kv_, ...) \ - CWISS_SELECT15(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT16, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT16(needle_, kv_, ...) \ - CWISS_SELECT16(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT17, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT17(needle_, kv_, ...) \ - CWISS_SELECT17(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT18, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT18(needle_, kv_, ...) \ - CWISS_SELECT18(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT19, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT19(needle_, kv_, ...) \ - CWISS_SELECT19(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT1A, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT1A(needle_, kv_, ...) \ - CWISS_SELECT1A(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT1B, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT1B(needle_, kv_, ...) \ - CWISS_SELECT1B(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT1C, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT1C(needle_, kv_, ...) \ - CWISS_SELECT1C(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT1D, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT1D(needle_, kv_, ...) \ - CWISS_SELECT1D(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT1E, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT1E(needle_, kv_, ...) \ - CWISS_SELECT1E(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT1F, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT1F(needle_, kv_, ...) \ - CWISS_SELECT1F(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT20, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT20(needle_, kv_, ...) \ - CWISS_SELECT20(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT21, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT21(needle_, kv_, ...) \ - CWISS_SELECT21(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT22, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT22(needle_, kv_, ...) \ - CWISS_SELECT22(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT23, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT23(needle_, kv_, ...) \ - CWISS_SELECT23(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT24, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT24(needle_, kv_, ...) \ - CWISS_SELECT24(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT25, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT25(needle_, kv_, ...) \ - CWISS_SELECT25(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT26, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT26(needle_, kv_, ...) \ - CWISS_SELECT26(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT27, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT27(needle_, kv_, ...) \ - CWISS_SELECT27(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT28, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT28(needle_, kv_, ...) \ - CWISS_SELECT28(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT29, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT29(needle_, kv_, ...) \ - CWISS_SELECT29(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT2A, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT2A(needle_, kv_, ...) \ - CWISS_SELECT2A(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT2B, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT2B(needle_, kv_, ...) \ - CWISS_SELECT2B(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT2C, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT2C(needle_, kv_, ...) \ - CWISS_SELECT2C(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT2D, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT2D(needle_, kv_, ...) \ - CWISS_SELECT2D(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT2E, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT2E(needle_, kv_, ...) \ - CWISS_SELECT2E(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT2F, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT2F(needle_, kv_, ...) \ - CWISS_SELECT2F(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT30, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT30(needle_, kv_, ...) \ - CWISS_SELECT30(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT31, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT31(needle_, kv_, ...) \ - CWISS_SELECT31(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT32, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT32(needle_, kv_, ...) \ - CWISS_SELECT32(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT33, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT33(needle_, kv_, ...) \ - CWISS_SELECT33(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT34, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT34(needle_, kv_, ...) \ - CWISS_SELECT34(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT35, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT35(needle_, kv_, ...) \ - CWISS_SELECT35(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT36, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT36(needle_, kv_, ...) \ - CWISS_SELECT36(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT37, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT37(needle_, kv_, ...) \ - CWISS_SELECT37(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT38, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT38(needle_, kv_, ...) \ - CWISS_SELECT38(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT39, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT39(needle_, kv_, ...) \ - CWISS_SELECT39(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT3A, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT3A(needle_, kv_, ...) \ - CWISS_SELECT3A(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT3B, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT3B(needle_, kv_, ...) \ - CWISS_SELECT3B(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT3C, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT3C(needle_, kv_, ...) \ - CWISS_SELECT3C(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT3D, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT3D(needle_, kv_, ...) \ - CWISS_SELECT3D(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT3E, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT3E(needle_, kv_, ...) \ - CWISS_SELECT3E(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT3F, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) -#define CWISS_EXTRACT3F(needle_, kv_, ...) \ - CWISS_SELECT3F(needle_ kv_, CWISS_EXTRACT_VALUE, kv_, CWISS_EXTRACT40, \ - (needle_, __VA_ARGS__), CWISS_NOTHING) - -#define CWISS_SELECT00(x_, ...) CWISS_SELECT00_(x_, __VA_ARGS__) -#define CWISS_SELECT01(x_, ...) CWISS_SELECT01_(x_, __VA_ARGS__) -#define CWISS_SELECT02(x_, ...) CWISS_SELECT02_(x_, __VA_ARGS__) -#define CWISS_SELECT03(x_, ...) CWISS_SELECT03_(x_, __VA_ARGS__) -#define CWISS_SELECT04(x_, ...) CWISS_SELECT04_(x_, __VA_ARGS__) -#define CWISS_SELECT05(x_, ...) CWISS_SELECT05_(x_, __VA_ARGS__) -#define CWISS_SELECT06(x_, ...) CWISS_SELECT06_(x_, __VA_ARGS__) -#define CWISS_SELECT07(x_, ...) CWISS_SELECT07_(x_, __VA_ARGS__) -#define CWISS_SELECT08(x_, ...) CWISS_SELECT08_(x_, __VA_ARGS__) -#define CWISS_SELECT09(x_, ...) CWISS_SELECT09_(x_, __VA_ARGS__) -#define CWISS_SELECT0A(x_, ...) CWISS_SELECT0A_(x_, __VA_ARGS__) -#define CWISS_SELECT0B(x_, ...) CWISS_SELECT0B_(x_, __VA_ARGS__) -#define CWISS_SELECT0C(x_, ...) CWISS_SELECT0C_(x_, __VA_ARGS__) -#define CWISS_SELECT0D(x_, ...) CWISS_SELECT0D_(x_, __VA_ARGS__) -#define CWISS_SELECT0E(x_, ...) CWISS_SELECT0E_(x_, __VA_ARGS__) -#define CWISS_SELECT0F(x_, ...) CWISS_SELECT0F_(x_, __VA_ARGS__) -#define CWISS_SELECT10(x_, ...) CWISS_SELECT10_(x_, __VA_ARGS__) -#define CWISS_SELECT11(x_, ...) CWISS_SELECT11_(x_, __VA_ARGS__) -#define CWISS_SELECT12(x_, ...) CWISS_SELECT12_(x_, __VA_ARGS__) -#define CWISS_SELECT13(x_, ...) CWISS_SELECT13_(x_, __VA_ARGS__) -#define CWISS_SELECT14(x_, ...) CWISS_SELECT14_(x_, __VA_ARGS__) -#define CWISS_SELECT15(x_, ...) CWISS_SELECT15_(x_, __VA_ARGS__) -#define CWISS_SELECT16(x_, ...) CWISS_SELECT16_(x_, __VA_ARGS__) -#define CWISS_SELECT17(x_, ...) CWISS_SELECT17_(x_, __VA_ARGS__) -#define CWISS_SELECT18(x_, ...) CWISS_SELECT18_(x_, __VA_ARGS__) -#define CWISS_SELECT19(x_, ...) CWISS_SELECT19_(x_, __VA_ARGS__) -#define CWISS_SELECT1A(x_, ...) CWISS_SELECT1A_(x_, __VA_ARGS__) -#define CWISS_SELECT1B(x_, ...) CWISS_SELECT1B_(x_, __VA_ARGS__) -#define CWISS_SELECT1C(x_, ...) CWISS_SELECT1C_(x_, __VA_ARGS__) -#define CWISS_SELECT1D(x_, ...) CWISS_SELECT1D_(x_, __VA_ARGS__) -#define CWISS_SELECT1E(x_, ...) CWISS_SELECT1E_(x_, __VA_ARGS__) -#define CWISS_SELECT1F(x_, ...) CWISS_SELECT1F_(x_, __VA_ARGS__) -#define CWISS_SELECT20(x_, ...) CWISS_SELECT20_(x_, __VA_ARGS__) -#define CWISS_SELECT21(x_, ...) CWISS_SELECT21_(x_, __VA_ARGS__) -#define CWISS_SELECT22(x_, ...) CWISS_SELECT22_(x_, __VA_ARGS__) -#define CWISS_SELECT23(x_, ...) CWISS_SELECT23_(x_, __VA_ARGS__) -#define CWISS_SELECT24(x_, ...) CWISS_SELECT24_(x_, __VA_ARGS__) -#define CWISS_SELECT25(x_, ...) CWISS_SELECT25_(x_, __VA_ARGS__) -#define CWISS_SELECT26(x_, ...) CWISS_SELECT26_(x_, __VA_ARGS__) -#define CWISS_SELECT27(x_, ...) CWISS_SELECT27_(x_, __VA_ARGS__) -#define CWISS_SELECT28(x_, ...) CWISS_SELECT28_(x_, __VA_ARGS__) -#define CWISS_SELECT29(x_, ...) CWISS_SELECT29_(x_, __VA_ARGS__) -#define CWISS_SELECT2A(x_, ...) CWISS_SELECT2A_(x_, __VA_ARGS__) -#define CWISS_SELECT2B(x_, ...) CWISS_SELECT2B_(x_, __VA_ARGS__) -#define CWISS_SELECT2C(x_, ...) CWISS_SELECT2C_(x_, __VA_ARGS__) -#define CWISS_SELECT2D(x_, ...) CWISS_SELECT2D_(x_, __VA_ARGS__) -#define CWISS_SELECT2E(x_, ...) CWISS_SELECT2E_(x_, __VA_ARGS__) -#define CWISS_SELECT2F(x_, ...) CWISS_SELECT2F_(x_, __VA_ARGS__) -#define CWISS_SELECT30(x_, ...) CWISS_SELECT30_(x_, __VA_ARGS__) -#define CWISS_SELECT31(x_, ...) CWISS_SELECT31_(x_, __VA_ARGS__) -#define CWISS_SELECT32(x_, ...) CWISS_SELECT32_(x_, __VA_ARGS__) -#define CWISS_SELECT33(x_, ...) CWISS_SELECT33_(x_, __VA_ARGS__) -#define CWISS_SELECT34(x_, ...) CWISS_SELECT34_(x_, __VA_ARGS__) -#define CWISS_SELECT35(x_, ...) CWISS_SELECT35_(x_, __VA_ARGS__) -#define CWISS_SELECT36(x_, ...) CWISS_SELECT36_(x_, __VA_ARGS__) -#define CWISS_SELECT37(x_, ...) CWISS_SELECT37_(x_, __VA_ARGS__) -#define CWISS_SELECT38(x_, ...) CWISS_SELECT38_(x_, __VA_ARGS__) -#define CWISS_SELECT39(x_, ...) CWISS_SELECT39_(x_, __VA_ARGS__) -#define CWISS_SELECT3A(x_, ...) CWISS_SELECT3A_(x_, __VA_ARGS__) -#define CWISS_SELECT3B(x_, ...) CWISS_SELECT3B_(x_, __VA_ARGS__) -#define CWISS_SELECT3C(x_, ...) CWISS_SELECT3C_(x_, __VA_ARGS__) -#define CWISS_SELECT3D(x_, ...) CWISS_SELECT3D_(x_, __VA_ARGS__) -#define CWISS_SELECT3E(x_, ...) CWISS_SELECT3E_(x_, __VA_ARGS__) -#define CWISS_SELECT3F(x_, ...) CWISS_SELECT3F_(x_, __VA_ARGS__) - -#define CWISS_SELECT00_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT01_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT02_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT03_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT04_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT05_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT06_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT07_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT08_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT09_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT0A_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT0B_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT0C_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT0D_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT0E_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT0F_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT10_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT11_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT12_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT13_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT14_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT15_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT16_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT17_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT18_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT19_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT1A_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT1B_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT1C_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT1D_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT1E_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT1F_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT20_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT21_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT22_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT23_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT24_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT25_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT26_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT27_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT28_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT29_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT2A_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT2B_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT2C_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT2D_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT2E_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT2F_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT30_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT31_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT32_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT33_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT34_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT35_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT36_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT37_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT38_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT39_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT3A_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT3B_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT3C_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT3D_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT3E_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -#define CWISS_SELECT3F_(ignored_, _call_, _args_, call_, args_, ...) call_ args_ -/// cwisstable/internal/extract.h ////////////////////////////////////////////// - /// cwisstable/policy.h //////////////////////////////////////////////////////// /// Hash table policies. /// @@ -1873,18 +1516,18 @@ CWISS_BEGIN_EXTERN /// /// This type describes how to move values of a particular type around. typedef struct { - /// The layout of the stored object. - size_t size, align; - - /// Performs a deep copy of `src` onto a fresh location `dst`. - void (*copy)(void* dst, const void* src); - - /// Destroys an object. - /// - /// This member may, as an optimization, be null. This will cause it to - /// behave as a no-op, and may be more efficient than making this an empty - /// function. - void (*dtor)(void* val); + /// The layout of the stored object. + size_t size, align; + + /// Performs a deep copy of `src` onto a fresh location `dst`. + void (*copy)(void* dst, const void* src); + + /// Destroys an object. + /// + /// This member may, as an optimization, be null. This will cause it to + /// behave as a no-op, and may be more efficient than making this an empty + /// function. + void (*dtor)(void* val); } CWISS_ObjectPolicy; /// A policy describing the hashing properties of a type. @@ -1905,43 +1548,43 @@ typedef struct { /// *somewhere*; unlike a C-style string, it might be a substring of a /// larger allocation elsewhere. typedef struct { - /// Computes the hash of a value. - /// - /// This function must be such that if two elements compare equal, they must - /// have the same hash (but not vice-versa). - /// - /// If this policy is heterogenous, this function must be defined so that - /// given the original key policy of the table's element type, if - /// `hetero->eq(a, b)` holds, then `hetero->hash(a) == original->hash(b)`. - /// In other words, the obvious condition for a hash table to work correctly - /// with this policy. - size_t (*hash)(const void* val); - - /// Compares two values for equality. - /// - /// This function is actually not symmetric: the first argument will always be - /// the value being searched for, and the second will be a pointer to the - /// candidate entry. In particular, this means they can be different types: - /// in C++ parlance, `needle` could be a `std::string_view`, while `candidate` - /// could be a `std::string`. - bool (*eq)(const void* needle, const void* candidate); + /// Computes the hash of a value. + /// + /// This function must be such that if two elements compare equal, they must + /// have the same hash (but not vice-versa). + /// + /// If this policy is heterogenous, this function must be defined so that + /// given the original key policy of the table's element type, if + /// `hetero->eq(a, b)` holds, then `hetero->hash(a) == original->hash(b)`. + /// In other words, the obvious condition for a hash table to work correctly + /// with this policy. + size_t(*hash)(const void* val); + + /// Compares two values for equality. + /// + /// This function is actually not symmetric: the first argument will always be + /// the value being searched for, and the second will be a pointer to the + /// candidate entry. In particular, this means they can be different types: + /// in C++ parlance, `needle` could be a `std::string_view`, while `candidate` + /// could be a `std::string`. + bool (*eq)(const void* needle, const void* candidate); } CWISS_KeyPolicy; /// A policy for allocation. /// /// This type provides access to a custom allocator. typedef struct { - /// Allocates memory. - /// - /// This function must never fail and never return null, unlike `malloc`. This - /// function does not need to tolerate zero sized allocations. - void* (*alloc)(size_t size, size_t align); - - /// Deallocates memory allocated by `alloc`. - /// - /// This function is passed the same size/alignment as was passed to `alloc`, - /// allowing for sized-delete optimizations. - void (*free)(void* array, size_t size, size_t align); + /// Allocates memory. + /// + /// This function must never fail and never return null, unlike `malloc`. This + /// function does not need to tolerate zero sized allocations. + void* (*alloc)(size_t size, size_t align); + + /// Deallocates memory allocated by `alloc`. + /// + /// This function is passed the same size/alignment as was passed to `alloc`, + /// allowing for sized-delete optimizations. + void (*free)(void* array, size_t size, size_t align); } CWISS_AllocPolicy; /// A policy for allocating space for slots. @@ -1949,195 +1592,179 @@ typedef struct { /// This allows us to distinguish between inline storage (more cache-friendly) /// and outline (pointer-stable). typedef struct { - /// The layout of a slot value. - /// - /// Usually, this will be the same as for the object type, *or* the layout - /// of a pointer (for outline storage). - size_t size, align; - - /// Initializes a new slot at the given location. - /// - /// This function does not initialize the value *in* the slot; it simply sets - /// up the slot so that a value can be `memcpy`'d or otherwise emplaced into - /// the slot. - void (*init)(void* slot); - - /// Destroys a slot, including the destruction of the value it contains. - /// - /// This function may, as an optimization, be null. This will cause it to - /// behave as a no-op. - void (*del)(void* slot); - - /// Transfers a slot. - /// - /// `dst` must be uninitialized; `src` must be initialized. After this - /// function, their roles will be switched: `dst` will be initialized and - /// contain the value from `src`; `src` will be initialized. - /// - /// This function need not actually copy the underlying value. - void (*transfer)(void* dst, void* src); - - /// Extracts a pointer to the value inside the a slot. - /// - /// This function does not need to tolerate nulls. - void* (*get)(void* slot); + /// The layout of a slot value. + /// + /// Usually, this will be the same as for the object type, *or* the layout + /// of a pointer (for outline storage). + size_t size, align; + + /// Initializes a new slot at the given location. + /// + /// This function does not initialize the value *in* the slot; it simply sets + /// up the slot so that a value can be `memcpy`'d or otherwise emplaced into + /// the slot. + void (*init)(void* slot); + + /// Destroys a slot, including the destruction of the value it contains. + /// + /// This function may, as an optimization, be null. This will cause it to + /// behave as a no-op. + void (*del)(void* slot); + + /// Transfers a slot. + /// + /// `dst` must be uninitialized; `src` must be initialized. After this + /// function, their roles will be switched: `dst` will be initialized and + /// contain the value from `src`; `src` will be initialized. + /// + /// This function need not actually copy the underlying value. + void (*transfer)(void* dst, void* src); + + /// Extracts a pointer to the value inside the a slot. + /// + /// This function does not need to tolerate nulls. + void* (*get)(void* slot); } CWISS_SlotPolicy; /// A hash table policy. /// /// See the header documentation for more information. typedef struct { - const CWISS_ObjectPolicy* obj; - const CWISS_KeyPolicy* key; - const CWISS_AllocPolicy* alloc; - const CWISS_SlotPolicy* slot; + const CWISS_ObjectPolicy* obj; + const CWISS_KeyPolicy* key; + const CWISS_AllocPolicy* alloc; + const CWISS_SlotPolicy* slot; } CWISS_Policy; /// Declares a hash set policy with inline storage for the given type. /// /// See the header documentation for more information. -#define CWISS_DECLARE_FLAT_SET_POLICY(kPolicy_, Type_, ...) \ - CWISS_DECLARE_POLICY_(kPolicy_, Type_, Type_, __VA_ARGS__) - -/// Declares a hash map policy with inline storage for the given key and value -/// types. -/// -/// See the header documentation for more information. -#define CWISS_DECLARE_FLAT_MAP_POLICY(kPolicy_, K_, V_, ...) \ - typedef struct { \ - K_ k; \ - V_ v; \ - } kPolicy_##_Entry; \ - CWISS_DECLARE_POLICY_(kPolicy_, kPolicy_##_Entry, K_, __VA_ARGS__) +#define CWISS_DECLARE_FLAT_SET_POLICY(kPolicy_, Type_, obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_DECLARE_FLAT_POLICY_(kPolicy_, Type_, Type_, obj_copy, obj_dtor, key_hash, key_eq) /// Declares a hash set policy with pointer-stable storage for the given type. /// /// See the header documentation for more information. -#define CWISS_DECLARE_NODE_SET_POLICY(kPolicy_, Type_, ...) \ - CWISS_DECLARE_NODE_FUNCTIONS_(kPolicy_, Type_, Type_, __VA_ARGS__) \ - CWISS_DECLARE_POLICY_(kPolicy_, Type_, Type_, __VA_ARGS__, \ - CWISS_NODE_OVERRIDES_(kPolicy_)) +#define CWISS_DECLARE_NODE_SET_POLICY(kPolicy_, Type_, obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_DECLARE_NODE_POLICY_(kPolicy_, Type_, Type_, obj_copy, obj_dtor, key_hash, key_eq) /// Declares a hash map policy with pointer-stable storage for the given key and /// value types. /// /// See the header documentation for more information. -#define CWISS_DECLARE_NODE_MAP_POLICY(kPolicy_, K_, V_, ...) \ - typedef struct { \ - K_ k; \ - V_ v; \ - } kPolicy_##_Entry; \ - CWISS_DECLARE_NODE_FUNCTIONS_(kPolicy_, kPolicy_##_Entry, K_, __VA_ARGS__) \ - CWISS_DECLARE_POLICY_(kPolicy_, kPolicy_##_Entry, K_, __VA_ARGS__, \ - CWISS_NODE_OVERRIDES_(kPolicy_)) +#define CWISS_DECLARE_NODE_MAP_POLICY(kPolicy_, K_, V_, obj_copy, obj_dtor, key_hash, key_eq) \ + typedef struct kPolicy_##_entry_t { \ + K_ k; \ + V_ v; \ + } kPolicy_##_Entry; \ + CWISS_DECLARE_NODE_POLICY_(kPolicy_, kPolicy_##_Entry, K_, obj_copy, obj_dtor, key_hash, key_eq) // ---- PUBLIC API ENDS HERE! ---- -#define CWISS_DECLARE_POLICY_(kPolicy_, Type_, Key_, ...) \ - CWISS_BEGIN \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline void kPolicy_##_DefaultCopy(void* dst, const void* src) { \ - memcpy(dst, src, sizeof(Type_)); \ - } \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline size_t kPolicy_##_DefaultHash(const void* val) { \ - CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ - CWISS_AbslHash_Write(&state, val, sizeof(Key_)); \ - return CWISS_AbslHash_Finish(state); \ - } \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline bool kPolicy_##_DefaultEq(const void* a, const void* b) { \ - return memcmp(a, b, sizeof(Key_)) == 0; \ - } \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline void kPolicy_##_DefaultSlotInit(void* slot) {} \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline void kPolicy_##_DefaultSlotTransfer(void* dst, void* src) { \ - memcpy(dst, src, sizeof(Type_)); \ - } \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline void* kPolicy_##_DefaultSlotGet(void* slot) { return slot; } \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - inline void kPolicy_##_DefaultSlotDtor(void* slot) { \ - if (CWISS_EXTRACT(obj_dtor, NULL, __VA_ARGS__) != NULL) { \ - CWISS_EXTRACT(obj_dtor, (void (*)(void*))NULL, __VA_ARGS__)(slot); \ - } \ - } \ - \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - const CWISS_ObjectPolicy kPolicy_##_ObjectPolicy = { \ - sizeof(Type_), \ - alignof(Type_), \ - CWISS_EXTRACT(obj_copy, kPolicy_##_DefaultCopy, __VA_ARGS__), \ - CWISS_EXTRACT(obj_dtor, NULL, __VA_ARGS__), \ - }; \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - const CWISS_KeyPolicy kPolicy_##_KeyPolicy = { \ - CWISS_EXTRACT(key_hash, kPolicy_##_DefaultHash, __VA_ARGS__), \ - CWISS_EXTRACT(key_eq, kPolicy_##_DefaultEq, __VA_ARGS__), \ - }; \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - const CWISS_AllocPolicy kPolicy_##_AllocPolicy = { \ - CWISS_EXTRACT(alloc_alloc, CWISS_DefaultMalloc, __VA_ARGS__), \ - CWISS_EXTRACT(alloc_free, CWISS_DefaultFree, __VA_ARGS__), \ - }; \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - const CWISS_SlotPolicy kPolicy_##_SlotPolicy = { \ - CWISS_EXTRACT(slot_size, sizeof(Type_), __VA_ARGS__), \ - CWISS_EXTRACT(slot_align, sizeof(Type_), __VA_ARGS__), \ - CWISS_EXTRACT(slot_init, kPolicy_##_DefaultSlotInit, __VA_ARGS__), \ - CWISS_EXTRACT(slot_dtor, kPolicy_##_DefaultSlotDtor, __VA_ARGS__), \ - CWISS_EXTRACT(slot_transfer, kPolicy_##_DefaultSlotTransfer, \ - __VA_ARGS__), \ - CWISS_EXTRACT(slot_get, kPolicy_##_DefaultSlotGet, __VA_ARGS__), \ - }; \ - CWISS_END \ - CWISS_EXTRACT_RAW(modifiers, static, __VA_ARGS__) \ - const CWISS_Policy kPolicy_ = { \ - &kPolicy_##_ObjectPolicy, \ - &kPolicy_##_KeyPolicy, \ - &kPolicy_##_AllocPolicy, \ - &kPolicy_##_SlotPolicy, \ - } - -#define CWISS_DECLARE_NODE_FUNCTIONS_(kPolicy_, Type_, ...) \ - CWISS_BEGIN \ - static inline void kPolicy_##_NodeSlotInit(void* slot) { \ - void* node = CWISS_EXTRACT(alloc_alloc, CWISS_DefaultMalloc, __VA_ARGS__)( \ - sizeof(Type_), alignof(Type_)); \ - memcpy(slot, &node, sizeof(node)); \ - } \ - static inline void kPolicy_##_NodeSlotDtor(void* slot) { \ - if (CWISS_EXTRACT(obj_dtor, NULL, __VA_ARGS__) != NULL) { \ - CWISS_EXTRACT(obj_dtor, (void (*)(void*))NULL, __VA_ARGS__) \ - (*(void**)slot); \ - } \ - CWISS_EXTRACT(alloc_free, CWISS_DefaultFree, __VA_ARGS__) \ - (*(void**)slot, sizeof(Type_), alignof(Type_)); \ - } \ - static inline void kPolicy_##_NodeSlotTransfer(void* dst, void* src) { \ - memcpy(dst, src, sizeof(void*)); \ - } \ - static inline void* kPolicy_##_NodeSlotGet(void* slot) { \ - return *((void**)slot); \ - } \ - CWISS_END - -#define CWISS_NODE_OVERRIDES_(kPolicy_) \ - (slot_size, sizeof(void*)), (slot_align, alignof(void*)), \ - (slot_init, kPolicy_##_NodeSlotInit), \ - (slot_dtor, kPolicy_##_NodeSlotDtor), \ - (slot_transfer, kPolicy_##_NodeSlotTransfer), \ - (slot_get, kPolicy_##_NodeSlotGet) +/// Declares a hash map policy with inline storage for the given key and value +/// types. +/// +/// See the header documentation for more information. +#define CWISS_DECLARE_FLAT_MAP_POLICY(kPolicy_, K_, V_, obj_copy, obj_dtor, key_hash, key_eq) \ + typedef struct kPolicy_##_entry_t { \ + K_ k; \ + V_ v; \ + } kPolicy_##_Entry; \ + CWISS_DECLARE_FLAT_POLICY_(kPolicy_, kPolicy_##_Entry, K_, obj_copy, obj_dtor, key_hash, key_eq) + +#define CWISS_DECLARE_FLAT_POLICY_(kPolicy_, Type_, Key_, obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_BEGIN \ + static inline void kPolicy_##_DefaultSlotInit(void* slot) {} \ + static inline void kPolicy_##_DefaultSlotTransfer(void* dst, void* src) { \ + memcpy(dst, src, sizeof(Type_)); \ + } \ + static inline void* kPolicy_##_DefaultSlotGet(void* slot) { return slot; } \ + static inline void kPolicy_##_DefaultSlotDtor(void* slot){ \ + obj_dtor (slot); \ + } \ + \ + static const CWISS_ObjectPolicy kPolicy_##_ObjectPolicy = { \ + sizeof(Type_), \ + alignof(Type_), \ + obj_copy, \ + obj_dtor \ + }; \ + static const CWISS_KeyPolicy kPolicy_##_KeyPolicy = { \ + key_hash, key_eq, \ + }; \ + static const CWISS_AllocPolicy kPolicy_##_AllocPolicy = { \ + CWISS_DefaultMalloc, \ + CWISS_DefaultFree, \ + }; \ + static const CWISS_SlotPolicy kPolicy_##_SlotPolicy = { \ + sizeof(Type_), \ + sizeof(Type_), \ + kPolicy_##_DefaultSlotInit, \ + kPolicy_##_DefaultSlotDtor, \ + kPolicy_##_DefaultSlotTransfer, \ + kPolicy_##_DefaultSlotGet, \ + }; \ + CWISS_END \ + static const CWISS_Policy kPolicy_ = { \ + &kPolicy_##_ObjectPolicy, \ + &kPolicy_##_KeyPolicy, \ + &kPolicy_##_AllocPolicy, \ + &kPolicy_##_SlotPolicy, \ + } static inline void* CWISS_DefaultMalloc(size_t size, size_t align) { - void* p = malloc(size); // TODO: Check alignment. - CWISS_CHECK(p != NULL, "malloc() returned null"); - return p; + void* p = malloc(size); // TODO: Check alignment. + CWISS_CHECK(p != NULL, "malloc() returned null"); + return p; } static inline void CWISS_DefaultFree(void* array, size_t size, size_t align) { - free(array); -} + free(array); +} + +#define CWISS_DECLARE_NODE_POLICY_(kPolicy_, Type_, Key_, obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_BEGIN \ + static inline void kPolicy_##_NodeSlotInit(void* slot) { \ + void* node = CWISS_DefaultMalloc(sizeof(Type_), alignof(Type_)); \ + memcpy(slot, &node, sizeof(node)); \ + } \ + static inline void kPolicy_##_NodeSlotDtor(void* slot) { \ + obj_dtor(*(void**)slot); \ + CWISS_DefaultFree(*(void**)slot, sizeof(Type_), alignof(Type_)); \ + } \ + static inline void kPolicy_##_NodeSlotTransfer(void* dst, void* src) { \ + memcpy(dst, src, sizeof(void*)); \ + } \ + static inline void* kPolicy_##_NodeSlotGet(void* slot) { \ + return *((void**)slot); \ + } \ + static const CWISS_ObjectPolicy kPolicy_##_ObjectPolicy = { \ + sizeof(Type_), \ + alignof(Type_), \ + obj_copy, \ + obj_dtor \ + }; \ + static const CWISS_KeyPolicy kPolicy_##_KeyPolicy = { \ + key_hash, key_eq, \ + }; \ + static const CWISS_AllocPolicy kPolicy_##_AllocPolicy = { \ + CWISS_DefaultMalloc, \ + CWISS_DefaultFree, \ + }; \ + static const CWISS_SlotPolicy kPolicy_##_SlotPolicy = { \ + sizeof(void*), \ + alignof(void*), \ + kPolicy_##_NodeSlotInit, \ + kPolicy_##_NodeSlotDtor, \ + kPolicy_##_NodeSlotTransfer, \ + kPolicy_##_NodeSlotGet, \ + }; \ + CWISS_END \ + static const CWISS_Policy kPolicy_ = { \ + &kPolicy_##_ObjectPolicy, \ + &kPolicy_##_KeyPolicy, \ + &kPolicy_##_AllocPolicy, \ + &kPolicy_##_SlotPolicy, \ + } CWISS_END_EXTERN CWISS_END @@ -2164,72 +1791,22 @@ CWISS_BEGIN_EXTERN /// /// This is absl::container_internal::raw_hash_set in Abseil. typedef struct { - /// The control bytes (and, also, a pointer to the base of the backing array). - /// - /// This contains `capacity_ + 1 + CWISS_NumClonedBytes()` entries. - CWISS_ControlByte* ctrl_; - /// The beginning of the slots, located at `CWISS_SlotOffset()` bytes after - /// `ctrl_`. May be null for empty tables. - char* slots_; - /// The number of filled slots. - size_t size_; - /// The total number of available slots. - size_t capacity_; - /// The number of slots we can still fill before a rehash. See - /// `CWISS_CapacityToGrowth()`. - size_t growth_left_; + /// The control bytes (and, also, a pointer to the base of the backing array). + /// + /// This contains `capacity_ + 1 + CWISS_NumClonedBytes()` entries. + CWISS_ControlByte* ctrl_; + /// The beginning of the slots, located at `CWISS_SlotOffset()` bytes after + /// `ctrl_`. May be null for empty tables. + char* slots_; + /// The number of filled slots. + size_t size_; + /// The total number of available slots. + size_t capacity_; + /// The number of slots we can still fill before a rehash. See + /// `CWISS_CapacityToGrowth()`. + size_t growth_left_; } CWISS_RawTable; -/// Prints full details about the internal state of `self` to `stderr`. -static inline void CWISS_RawTable_dump(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - fprintf(stderr, "ptr: %p, len: %zu, cap: %zu, growth: %zu\n", self->ctrl_, - self->size_, self->capacity_, self->growth_left_); - if (self->capacity_ == 0) { - return; - } - - size_t ctrl_bytes = self->capacity_ + CWISS_NumClonedBytes(); - size_t i; - for (i = 0; i <= ctrl_bytes; i++) { - fprintf(stderr, "[%4zu] %p / ", i, &self->ctrl_[i]); - switch (self->ctrl_[i]) { - case CWISS_kSentinel: - fprintf(stderr, "kSentinel: //\n"); - continue; - case CWISS_kEmpty: - fprintf(stderr, " kEmpty"); - break; - case CWISS_kDeleted: - fprintf(stderr, " kDeleted"); - break; - default: - fprintf(stderr, " H2(0x%02x)", self->ctrl_[i]); - break; - } - - if (i >= self->capacity_) { - fprintf(stderr, ": <mirrored>\n"); - continue; - } - - char* slot = self->slots_ + i * policy->slot->size; - fprintf(stderr, ": %p /", slot); - size_t j; - for (j = 0; j < policy->slot->size; j++) { - fprintf(stderr, " %02x", (unsigned char)slot[j]); - } - char* elem = (char*)policy->slot->get(slot); - if (elem != slot && CWISS_IsFull(self->ctrl_[i])) { - fprintf(stderr, " ->"); - size_t j; - for (j = 0; j < policy->obj->size; j++) { - fprintf(stderr, " %02x", (unsigned char)elem[j]); - } - } - fprintf(stderr, "\n"); - } -} /// An iterator into a SwissTable. /// @@ -2243,9 +1820,9 @@ static inline void CWISS_RawTable_dump(const CWISS_Policy* policy, /// in the latter case. /// - `ctrl_` always points to a full slot. typedef struct { - CWISS_RawTable* set_; - CWISS_ControlByte* ctrl_; - char* slot_; + CWISS_RawTable* set_; + CWISS_ControlByte* ctrl_; + char* slot_; } CWISS_RawIter; /// Fixes up `ctrl_` to point to a full by advancing it and `slot_` until they @@ -2253,53 +1830,53 @@ typedef struct { /// /// If a sentinel is reached, we null both of them out instead. static inline void CWISS_RawIter_SkipEmptyOrDeleted(const CWISS_Policy* policy, - CWISS_RawIter* self) { - while (CWISS_IsEmptyOrDeleted(*self->ctrl_)) { - CWISS_Group g = CWISS_Group_new(self->ctrl_); - uint32_t shift = CWISS_Group_CountLeadingEmptyOrDeleted(&g); - self->ctrl_ += shift; - self->slot_ += shift * policy->slot->size; - } + CWISS_RawIter* self) { + while (CWISS_IsEmptyOrDeleted(*self->ctrl_)) { + CWISS_Group g = CWISS_Group_new(self->ctrl_); + uint32_t shift = CWISS_Group_CountLeadingEmptyOrDeleted(&g); + self->ctrl_ += shift; + self->slot_ += shift * policy->slot->size; + } - // Not sure why this is a branch rather than a cmov; Abseil uses a branch. - if (CWISS_UNLIKELY(*self->ctrl_ == CWISS_kSentinel)) { - self->ctrl_ = NULL; - self->slot_ = NULL; - } + // Not sure why this is a branch rather than a cmov; Abseil uses a branch. + if (CWISS_UNLIKELY(*self->ctrl_ == CWISS_kSentinel)) { + self->ctrl_ = NULL; + self->slot_ = NULL; + } } /// Creates a valid iterator starting at the `index`th slot. static inline CWISS_RawIter CWISS_RawTable_iter_at(const CWISS_Policy* policy, - CWISS_RawTable* self, - size_t index) { - CWISS_RawIter iter = { - self, - self->ctrl_ + index, - self->slots_ + index * policy->slot->size, - }; - CWISS_RawIter_SkipEmptyOrDeleted(policy, &iter); - CWISS_AssertIsValid(iter.ctrl_); - return iter; + CWISS_RawTable* self, + size_t index) { + CWISS_RawIter iter = { + self, + self->ctrl_ + index, + self->slots_ ? self->slots_ + index * policy->slot->size : NULL, + }; + CWISS_RawIter_SkipEmptyOrDeleted(policy, &iter); + CWISS_AssertIsValid(iter.ctrl_); + return iter; } /// Creates an iterator for `self`. static inline CWISS_RawIter CWISS_RawTable_iter(const CWISS_Policy* policy, - CWISS_RawTable* self) { - return CWISS_RawTable_iter_at(policy, self, 0); + CWISS_RawTable* self) { + return CWISS_RawTable_iter_at(policy, self, 0); } /// Creates a valid iterator starting at the `index`th slot, accepting a `const` /// pointer instead. static inline CWISS_RawIter CWISS_RawTable_citer_at(const CWISS_Policy* policy, - const CWISS_RawTable* self, - size_t index) { - return CWISS_RawTable_iter_at(policy, (CWISS_RawTable*)self, index); + const CWISS_RawTable* self, + size_t index) { + return CWISS_RawTable_iter_at(policy, (CWISS_RawTable*)self, index); } /// Creates an iterator for `self`, accepting a `const` pointer instead. static inline CWISS_RawIter CWISS_RawTable_citer(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return CWISS_RawTable_iter(policy, (CWISS_RawTable*)self); + const CWISS_RawTable* self) { + return CWISS_RawTable_iter(policy, (CWISS_RawTable*)self); } /// Returns a pointer into the currently pointed-to slot (*not* to the slot @@ -2307,60 +1884,60 @@ static inline CWISS_RawIter CWISS_RawTable_citer(const CWISS_Policy* policy, /// /// Returns null if the iterator has been exhausted. static inline void* CWISS_RawIter_get(const CWISS_Policy* policy, - const CWISS_RawIter* self) { - CWISS_AssertIsValid(self->ctrl_); - if (self->slot_ == NULL) { - return NULL; - } + const CWISS_RawIter* self) { + CWISS_AssertIsValid(self->ctrl_); + if (self->slot_ == NULL) { + return NULL; + } - return policy->slot->get(self->slot_); + return policy->slot->get(self->slot_); } /// Advances the iterator and returns the result of `CWISS_RawIter_get()`. /// /// Calling on an empty iterator is UB. static inline void* CWISS_RawIter_next(const CWISS_Policy* policy, - CWISS_RawIter* self) { - CWISS_AssertIsFull(self->ctrl_); - self->ctrl_++; - self->slot_ += policy->slot->size; + CWISS_RawIter* self) { + CWISS_AssertIsFull(self->ctrl_); + self->ctrl_++; + self->slot_ += policy->slot->size; - CWISS_RawIter_SkipEmptyOrDeleted(policy, self); - return CWISS_RawIter_get(policy, self); + CWISS_RawIter_SkipEmptyOrDeleted(policy, self); + return CWISS_RawIter_get(policy, self); } /// Erases, but does not destroy, the value pointed to by `it`. static inline void CWISS_RawTable_EraseMetaOnly(const CWISS_Policy* policy, - CWISS_RawIter it) { - CWISS_DCHECK(CWISS_IsFull(*it.ctrl_), "erasing a dangling iterator"); - --it.set_->size_; - const size_t index = (size_t)(it.ctrl_ - it.set_->ctrl_); - const size_t index_before = (index - CWISS_Group_kWidth) & it.set_->capacity_; - CWISS_Group g_after = CWISS_Group_new(it.ctrl_); - CWISS_BitMask empty_after = CWISS_Group_MatchEmpty(&g_after); - CWISS_Group g_before = CWISS_Group_new(it.set_->ctrl_ + index_before); - CWISS_BitMask empty_before = CWISS_Group_MatchEmpty(&g_before); - - // We count how many consecutive non empties we have to the right and to the - // left of `it`. If the sum is >= kWidth then there is at least one probe - // window that might have seen a full group. - bool was_never_full = - empty_before.mask && empty_after.mask && - (size_t)(CWISS_BitMask_TrailingZeros(&empty_after) + - CWISS_BitMask_LeadingZeros(&empty_before)) < CWISS_Group_kWidth; - - CWISS_SetCtrl(index, was_never_full ? CWISS_kEmpty : CWISS_kDeleted, - it.set_->capacity_, it.set_->ctrl_, it.set_->slots_, - policy->slot->size); - it.set_->growth_left_ += was_never_full; - // infoz().RecordErase(); + CWISS_RawIter it) { + CWISS_DCHECK(CWISS_IsFull(*it.ctrl_), "erasing a dangling iterator"); + --it.set_->size_; + const size_t index = (size_t)(it.ctrl_ - it.set_->ctrl_); + const size_t index_before = (index - CWISS_Group_kWidth) & it.set_->capacity_; + CWISS_Group g_after = CWISS_Group_new(it.ctrl_); + CWISS_BitMask empty_after = CWISS_Group_MatchEmpty(&g_after); + CWISS_Group g_before = CWISS_Group_new(it.set_->ctrl_ + index_before); + CWISS_BitMask empty_before = CWISS_Group_MatchEmpty(&g_before); + + // We count how many consecutive non empties we have to the right and to the + // left of `it`. If the sum is >= kWidth then there is at least one probe + // window that might have seen a full group. + bool was_never_full = + empty_before.mask && empty_after.mask && + (size_t)(CWISS_BitMask_TrailingZeros(&empty_after) + + CWISS_BitMask_LeadingZeros(&empty_before)) < CWISS_Group_kWidth; + + CWISS_SetCtrl(index, was_never_full ? CWISS_kEmpty : CWISS_kDeleted, + it.set_->capacity_, it.set_->ctrl_, it.set_->slots_, + policy->slot->size); + it.set_->growth_left_ += was_never_full; + // infoz().RecordErase(); } /// Computes a lower bound for the expected available growth and applies it to /// `self_`. static inline void CWISS_RawTable_ResetGrowthLeft(const CWISS_Policy* policy, - CWISS_RawTable* self) { - self->growth_left_ = CWISS_CapacityToGrowth(self->capacity_) - self->size_; + CWISS_RawTable* self) { + self->growth_left_ = CWISS_CapacityToGrowth(self->capacity_) - self->size_; } /// Allocates a backing array for `self` and initializes its control bits. This @@ -2369,101 +1946,101 @@ static inline void CWISS_RawTable_ResetGrowthLeft(const CWISS_Policy* policy, /// /// This does not free the currently held array; `capacity_` must be nonzero. static inline void CWISS_RawTable_InitializeSlots(const CWISS_Policy* policy, - CWISS_RawTable* self) { - CWISS_DCHECK(self->capacity_, "capacity should be nonzero"); - // Folks with custom allocators often make unwarranted assumptions about the - // behavior of their classes vis-a-vis trivial destructability and what - // calls they will or wont make. Avoid sampling for people with custom - // allocators to get us out of this mess. This is not a hard guarantee but - // a workaround while we plan the exact guarantee we want to provide. - // - // People are often sloppy with the exact type of their allocator (sometimes - // it has an extra const or is missing the pair, but rebinds made it work - // anyway). To avoid the ambiguity, we work off SlotAlloc which we have - // bound more carefully. - // - // NOTE(mcyoung): Not relevant in C but kept in case we decide to do custom - // alloc. - /*if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && - slots_ == nullptr) { - infoz() = Sample(sizeof(slot_type)); - }*/ - - char* mem = - (char*) // Cast for C++. - policy->alloc->alloc(CWISS_AllocSize(self->capacity_, policy->slot->size, - policy->slot->align), - policy->slot->align); - - self->ctrl_ = (CWISS_ControlByte*)mem; - self->slots_ = mem + CWISS_SlotOffset(self->capacity_, policy->slot->align); - CWISS_ResetCtrl(self->capacity_, self->ctrl_, self->slots_, - policy->slot->size); - CWISS_RawTable_ResetGrowthLeft(policy, self); - - // infoz().RecordStorageChanged(size_, capacity_); + CWISS_RawTable* self) { + CWISS_DCHECK(self->capacity_, "capacity should be nonzero"); + // Folks with custom allocators often make unwarranted assumptions about the + // behavior of their classes vis-a-vis trivial destructability and what + // calls they will or wont make. Avoid sampling for people with custom + // allocators to get us out of this mess. This is not a hard guarantee but + // a workaround while we plan the exact guarantee we want to provide. + // + // People are often sloppy with the exact type of their allocator (sometimes + // it has an extra const or is missing the pair, but rebinds made it work + // anyway). To avoid the ambiguity, we work off SlotAlloc which we have + // bound more carefully. + // + // NOTE(mcyoung): Not relevant in C but kept in case we decide to do custom + // alloc. + /*if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && + slots_ == nullptr) { + infoz() = Sample(sizeof(slot_type)); + }*/ + + char* mem = + (char*) // Cast for C++. + policy->alloc->alloc(CWISS_AllocSize(self->capacity_, policy->slot->size, + policy->slot->align), + policy->slot->align); + + self->ctrl_ = (CWISS_ControlByte*)mem; + self->slots_ = mem + CWISS_SlotOffset(self->capacity_, policy->slot->align); + CWISS_ResetCtrl(self->capacity_, self->ctrl_, self->slots_, + policy->slot->size); + CWISS_RawTable_ResetGrowthLeft(policy, self); + + // infoz().RecordStorageChanged(size_, capacity_); } /// Destroys all slots in the backing array, frees the backing array, and clears /// all top-level book-keeping data. static inline void CWISS_RawTable_DestroySlots(const CWISS_Policy* policy, - CWISS_RawTable* self) { - if (!self->capacity_) return; - - if (policy->slot->del != NULL) { - size_t i; - for (i = 0; i != self->capacity_; i++) { - if (CWISS_IsFull(self->ctrl_[i])) { - policy->slot->del(self->slots_ + i * policy->slot->size); - } - } - } - - policy->alloc->free( - self->ctrl_, - CWISS_AllocSize(self->capacity_, policy->slot->size, policy->slot->align), - policy->slot->align); - self->ctrl_ = CWISS_EmptyGroup(); - self->slots_ = NULL; - self->size_ = 0; - self->capacity_ = 0; - self->growth_left_ = 0; + CWISS_RawTable* self) { + if (!self->capacity_) return; + + if (policy->slot->del != NULL) { + size_t i; + for (i = 0; i != self->capacity_; i++) { + if (CWISS_IsFull(self->ctrl_[i])) { + policy->slot->del(self->slots_ + i * policy->slot->size); + } + } + } + + policy->alloc->free( + self->ctrl_, + CWISS_AllocSize(self->capacity_, policy->slot->size, policy->slot->align), + policy->slot->align); + self->ctrl_ = CWISS_EmptyGroup(); + self->slots_ = NULL; + self->size_ = 0; + self->capacity_ = 0; + self->growth_left_ = 0; } /// Grows the table to the given capacity, triggering a rehash. static inline void CWISS_RawTable_Resize(const CWISS_Policy* policy, - CWISS_RawTable* self, - size_t new_capacity) { - CWISS_DCHECK(CWISS_IsValidCapacity(new_capacity), "invalid capacity: %zu", - new_capacity); - - CWISS_ControlByte* old_ctrl = self->ctrl_; - char* old_slots = self->slots_; - const size_t old_capacity = self->capacity_; - self->capacity_ = new_capacity; - CWISS_RawTable_InitializeSlots(policy, self); - - size_t i; - for (i = 0; i != old_capacity; i++) { - if (CWISS_IsFull(old_ctrl[i])) { - size_t hash = policy->key->hash( - policy->slot->get(old_slots + i * policy->slot->size)); - CWISS_FindInfo target = - CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - size_t new_i = target.offset; - CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - policy->slot->transfer(self->slots_ + new_i * policy->slot->size, - old_slots + i * policy->slot->size); - } - } - if (old_capacity) { - CWISS_UnpoisonMemory(old_slots, policy->slot->size * old_capacity); - policy->alloc->free( - old_ctrl, - CWISS_AllocSize(old_capacity, policy->slot->size, policy->slot->align), - policy->slot->align); - } + CWISS_RawTable* self, + size_t new_capacity) { + CWISS_DCHECK(CWISS_IsValidCapacity(new_capacity), "invalid capacity: %zu", + new_capacity); + + CWISS_ControlByte* old_ctrl = self->ctrl_; + char* old_slots = self->slots_; + const size_t old_capacity = self->capacity_; + self->capacity_ = new_capacity; + CWISS_RawTable_InitializeSlots(policy, self); + + size_t i; + for (i = 0; i != old_capacity; i++) { + if (CWISS_IsFull(old_ctrl[i])) { + size_t hash = policy->key->hash( + policy->slot->get(old_slots + i * policy->slot->size)); + CWISS_FindInfo target = + CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); + size_t new_i = target.offset; + CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, + self->slots_, policy->slot->size); + policy->slot->transfer(self->slots_ + new_i * policy->slot->size, + old_slots + i * policy->slot->size); + } + } + if (old_capacity) { + CWISS_UnpoisonMemory(old_slots, policy->slot->size * old_capacity); + policy->alloc->free( + old_ctrl, + CWISS_AllocSize(old_capacity, policy->slot->size, policy->slot->align), + policy->slot->align); + } } /// Prunes control bits to remove as many tombstones as possible. @@ -2471,86 +2048,87 @@ static inline void CWISS_RawTable_Resize(const CWISS_Policy* policy, /// See the comment on `CWISS_RawTable_rehash_and_grow_if_necessary()`. CWISS_INLINE_NEVER static void CWISS_RawTable_DropDeletesWithoutResize(const CWISS_Policy* policy, - CWISS_RawTable* self) { - CWISS_DCHECK(CWISS_IsValidCapacity(self->capacity_), "invalid capacity: %zu", - self->capacity_); - CWISS_DCHECK(!CWISS_IsSmall(self->capacity_), - "unexpected small capacity: %zu", self->capacity_); - // Algorithm: - // - mark all DELETED slots as EMPTY - // - mark all FULL slots as DELETED - // - for each slot marked as DELETED - // hash = Hash(element) - // target = find_first_non_full(hash) - // if target is in the same group - // mark slot as FULL - // else if target is EMPTY - // transfer element to target - // mark slot as EMPTY - // mark target as FULL - // else if target is DELETED - // swap current element with target element - // mark target as FULL - // repeat procedure for current slot with moved from element (target) - CWISS_ConvertDeletedToEmptyAndFullToDeleted(self->ctrl_, self->capacity_); - // Unfortunately because we do not know this size statically, we need to take - // a trip to the allocator. Alternatively we could use a variable length - // alloca... - void* slot = policy->alloc->alloc(policy->slot->size, policy->slot->align); - - size_t i; - for (i = 0; i != self->capacity_; i++) { - if (!CWISS_IsDeleted(self->ctrl_[i])) continue; - - char* old_slot = self->slots_ + i * policy->slot->size; - size_t hash = policy->key->hash(policy->slot->get(old_slot)); - - const CWISS_FindInfo target = - CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - const size_t new_i = target.offset; - - char* new_slot = self->slots_ + new_i * policy->slot->size; - - // Verify if the old and new i fall within the same group wrt the hash. - // If they do, we don't need to move the object as it falls already in the - // best probe we can. - const size_t probe_offset = - CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_).offset_; + CWISS_RawTable* self) { + CWISS_DCHECK(CWISS_IsValidCapacity(self->capacity_), "invalid capacity: %zu", + self->capacity_); + CWISS_DCHECK(!CWISS_IsSmall(self->capacity_), + "unexpected small capacity: %zu", self->capacity_); + // Algorithm: + // - mark all DELETED slots as EMPTY + // - mark all FULL slots as DELETED + // - for each slot marked as DELETED + // hash = Hash(element) + // target = find_first_non_full(hash) + // if target is in the same group + // mark slot as FULL + // else if target is EMPTY + // transfer element to target + // mark slot as EMPTY + // mark target as FULL + // else if target is DELETED + // swap current element with target element + // mark target as FULL + // repeat procedure for current slot with moved from element (target) + CWISS_ConvertDeletedToEmptyAndFullToDeleted(self->ctrl_, self->capacity_); + // Unfortunately because we do not know this size statically, we need to take + // a trip to the allocator. Alternatively we could use a variable length + // alloca... + void* slot = policy->alloc->alloc(policy->slot->size, policy->slot->align); + + size_t i; + for (i = 0; i != self->capacity_; i++) { + if (!CWISS_IsDeleted(self->ctrl_[i])) continue; + + char* old_slot = self->slots_ + i * policy->slot->size; + size_t hash = policy->key->hash(policy->slot->get(old_slot)); + + const CWISS_FindInfo target = + CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); + const size_t new_i = target.offset; + + char* new_slot = self->slots_ + new_i * policy->slot->size; + + // Verify if the old and new i fall within the same group wrt the hash. + // If they do, we don't need to move the object as it falls already in the + // best probe we can. + const size_t probe_offset = + CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_).offset_; #define CWISS_ProbeIndex(pos_) \ - (((pos_ - probe_offset) & self->capacity_) / CWISS_Group_kWidth) - - // Element doesn't move. - if (CWISS_LIKELY(CWISS_ProbeIndex(new_i) == CWISS_ProbeIndex(i))) { - CWISS_SetCtrl(i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - continue; - } - if (CWISS_IsEmpty(self->ctrl_[new_i])) { - // Transfer element to the empty spot. - // SetCtrl poisons/unpoisons the slots so we have to call it at the - // right time. - CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - policy->slot->transfer(new_slot, old_slot); - CWISS_SetCtrl(i, CWISS_kEmpty, self->capacity_, self->ctrl_, self->slots_, - policy->slot->size); - } else { - CWISS_DCHECK(CWISS_IsDeleted(self->ctrl_[new_i]), - "bad ctrl value at %zu: %02x", new_i, self->ctrl_[new_i]); - CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - // Until we are done rehashing, DELETED marks previously FULL slots. - // Swap i and new_i elements. - - policy->slot->transfer(slot, old_slot); - policy->slot->transfer(old_slot, new_slot); - policy->slot->transfer(new_slot, slot); - --i; // repeat - } + (((pos_ - probe_offset) & self->capacity_) / CWISS_Group_kWidth) + + // Element doesn't move. + if (CWISS_LIKELY(CWISS_ProbeIndex(new_i) == CWISS_ProbeIndex(i))) { + CWISS_SetCtrl(i, CWISS_H2(hash), self->capacity_, self->ctrl_, + self->slots_, policy->slot->size); + continue; + } + if (CWISS_IsEmpty(self->ctrl_[new_i])) { + // Transfer element to the empty spot. + // SetCtrl poisons/unpoisons the slots so we have to call it at the + // right time. + CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, + self->slots_, policy->slot->size); + policy->slot->transfer(new_slot, old_slot); + CWISS_SetCtrl(i, CWISS_kEmpty, self->capacity_, self->ctrl_, self->slots_, + policy->slot->size); + } + else { + CWISS_DCHECK(CWISS_IsDeleted(self->ctrl_[new_i]), + "bad ctrl value at %zu: %02x", new_i, self->ctrl_[new_i]); + CWISS_SetCtrl(new_i, CWISS_H2(hash), self->capacity_, self->ctrl_, + self->slots_, policy->slot->size); + // Until we are done rehashing, DELETED marks previously FULL slots. + // Swap i and new_i elements. + + policy->slot->transfer(slot, old_slot); + policy->slot->transfer(old_slot, new_slot); + policy->slot->transfer(new_slot, slot); + --i; // repeat + } #undef CWISS_ProbeSeq_Start_index - } - CWISS_RawTable_ResetGrowthLeft(policy, self); - policy->alloc->free(slot, policy->slot->size, policy->slot->align); + } + CWISS_RawTable_ResetGrowthLeft(policy, self); + policy->alloc->free(slot, policy->slot->size, policy->slot->align); } /// Called whenever the table *might* need to conditionally grow. @@ -2559,66 +2137,68 @@ static void CWISS_RawTable_DropDeletesWithoutResize(const CWISS_Policy* policy, /// growth is unnecessary, because vacating tombstones is beneficial for /// performance in the long-run. static inline void CWISS_RawTable_rehash_and_grow_if_necessary( - const CWISS_Policy* policy, CWISS_RawTable* self) { - if (self->capacity_ == 0) { - CWISS_RawTable_Resize(policy, self, 1); - } else if (self->capacity_ > CWISS_Group_kWidth && - // Do these calculations in 64-bit to avoid overflow. - self->size_ * UINT64_C(32) <= self->capacity_ * UINT64_C(25)) { - // Squash DELETED without growing if there is enough capacity. - // - // Rehash in place if the current size is <= 25/32 of capacity_. - // Rationale for such a high factor: 1) drop_deletes_without_resize() is - // faster than resize, and 2) it takes quite a bit of work to add - // tombstones. In the worst case, seems to take approximately 4 - // insert/erase pairs to create a single tombstone and so if we are - // rehashing because of tombstones, we can afford to rehash-in-place as - // long as we are reclaiming at least 1/8 the capacity without doing more - // than 2X the work. (Where "work" is defined to be size() for rehashing - // or rehashing in place, and 1 for an insert or erase.) But rehashing in - // place is faster per operation than inserting or even doubling the size - // of the table, so we actually afford to reclaim even less space from a - // resize-in-place. The decision is to rehash in place if we can reclaim - // at about 1/8th of the usable capacity (specifically 3/28 of the - // capacity) which means that the total cost of rehashing will be a small - // fraction of the total work. - // - // Here is output of an experiment using the BM_CacheInSteadyState - // benchmark running the old case (where we rehash-in-place only if we can - // reclaim at least 7/16*capacity_) vs. this code (which rehashes in place - // if we can recover 3/32*capacity_). - // - // Note that although in the worst-case number of rehashes jumped up from - // 15 to 190, but the number of operations per second is almost the same. - // - // Abridged output of running BM_CacheInSteadyState benchmark from - // raw_hash_set_benchmark. N is the number of insert/erase operations. - // - // | OLD (recover >= 7/16 | NEW (recover >= 3/32) - // size | N/s LoadFactor NRehashes | N/s LoadFactor NRehashes - // 448 | 145284 0.44 18 | 140118 0.44 19 - // 493 | 152546 0.24 11 | 151417 0.48 28 - // 538 | 151439 0.26 11 | 151152 0.53 38 - // 583 | 151765 0.28 11 | 150572 0.57 50 - // 628 | 150241 0.31 11 | 150853 0.61 66 - // 672 | 149602 0.33 12 | 150110 0.66 90 - // 717 | 149998 0.35 12 | 149531 0.70 129 - // 762 | 149836 0.37 13 | 148559 0.74 190 - // 807 | 149736 0.39 14 | 151107 0.39 14 - // 852 | 150204 0.42 15 | 151019 0.42 15 - CWISS_RawTable_DropDeletesWithoutResize(policy, self); - } else { - // Otherwise grow the container. - CWISS_RawTable_Resize(policy, self, self->capacity_ * 2 + 1); - } + const CWISS_Policy* policy, CWISS_RawTable* self) { + if (self->capacity_ == 0) { + CWISS_RawTable_Resize(policy, self, 1); + } + else if (self->capacity_ > CWISS_Group_kWidth && + // Do these calculations in 64-bit to avoid overflow. + self->size_ * UINT64_C(32) <= self->capacity_ * UINT64_C(25)) { + // Squash DELETED without growing if there is enough capacity. + // + // Rehash in place if the current size is <= 25/32 of capacity_. + // Rationale for such a high factor: 1) drop_deletes_without_resize() is + // faster than resize, and 2) it takes quite a bit of work to add + // tombstones. In the worst case, seems to take approximately 4 + // insert/erase pairs to create a single tombstone and so if we are + // rehashing because of tombstones, we can afford to rehash-in-place as + // long as we are reclaiming at least 1/8 the capacity without doing more + // than 2X the work. (Where "work" is defined to be size() for rehashing + // or rehashing in place, and 1 for an insert or erase.) But rehashing in + // place is faster per operation than inserting or even doubling the size + // of the table, so we actually afford to reclaim even less space from a + // resize-in-place. The decision is to rehash in place if we can reclaim + // at about 1/8th of the usable capacity (specifically 3/28 of the + // capacity) which means that the total cost of rehashing will be a small + // fraction of the total work. + // + // Here is output of an experiment using the BM_CacheInSteadyState + // benchmark running the old case (where we rehash-in-place only if we can + // reclaim at least 7/16*capacity_) vs. this code (which rehashes in place + // if we can recover 3/32*capacity_). + // + // Note that although in the worst-case number of rehashes jumped up from + // 15 to 190, but the number of operations per second is almost the same. + // + // Abridged output of running BM_CacheInSteadyState benchmark from + // raw_hash_set_benchmark. N is the number of insert/erase operations. + // + // | OLD (recover >= 7/16 | NEW (recover >= 3/32) + // size | N/s LoadFactor NRehashes | N/s LoadFactor NRehashes + // 448 | 145284 0.44 18 | 140118 0.44 19 + // 493 | 152546 0.24 11 | 151417 0.48 28 + // 538 | 151439 0.26 11 | 151152 0.53 38 + // 583 | 151765 0.28 11 | 150572 0.57 50 + // 628 | 150241 0.31 11 | 150853 0.61 66 + // 672 | 149602 0.33 12 | 150110 0.66 90 + // 717 | 149998 0.35 12 | 149531 0.70 129 + // 762 | 149836 0.37 13 | 148559 0.74 190 + // 807 | 149736 0.39 14 | 151107 0.39 14 + // 852 | 150204 0.42 15 | 151019 0.42 15 + CWISS_RawTable_DropDeletesWithoutResize(policy, self); + } + else { + // Otherwise grow the container. + CWISS_RawTable_Resize(policy, self, self->capacity_ * 2 + 1); + } } /// Prefetches the backing array to dodge potential TLB misses. /// This is intended to overlap with execution of calculating the hash for a /// key. static inline void CWISS_RawTable_PrefetchHeapBlock( - const CWISS_Policy* policy, const CWISS_RawTable* self) { - CWISS_PREFETCH(self->ctrl_, 1); + const CWISS_Policy* policy, const CWISS_RawTable* self) { + CWISS_PREFETCH(self->ctrl_, 1); } /// Issues CPU prefetch instructions for the memory needed to find or insert @@ -2627,22 +2207,22 @@ static inline void CWISS_RawTable_PrefetchHeapBlock( /// NOTE: This is a very low level operation and should not be used without /// specific benchmarks indicating its importance. static inline void CWISS_RawTable_Prefetch(const CWISS_Policy* policy, - const CWISS_RawTable* self, - const void* key) { - (void)key; + const CWISS_RawTable* self, + const void* key) { + (void)key; #if CWISS_HAVE_PREFETCH - CWISS_RawTable_PrefetchHeapBlock(policy, self); - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, policy->key->hash(key), - self->capacity_); - CWISS_PREFETCH(self->ctrl_ + seq.offset_, 3); - CWISS_PREFETCH(self->ctrl_ + seq.offset_ * policy->slot->size, 3); + CWISS_RawTable_PrefetchHeapBlock(policy, self); + CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, policy->key->hash(key), + self->capacity_); + CWISS_PREFETCH(self->ctrl_ + seq.offset_, 3); + CWISS_PREFETCH(self->ctrl_ + seq.offset_ * policy->slot->size, 3); #endif } /// The return type of `CWISS_RawTable_PrepareInsert()`. typedef struct { - size_t index; - bool inserted; + size_t index; + bool inserted; } CWISS_PrepareInsert; /// Given the hash of a value not currently in the table, finds the next viable @@ -2651,46 +2231,48 @@ typedef struct { /// If the table does not actually have space, UB. CWISS_INLINE_NEVER static size_t CWISS_RawTable_PrepareInsert(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t hash) { - CWISS_FindInfo target = - CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - if (CWISS_UNLIKELY(self->growth_left_ == 0 && - !CWISS_IsDeleted(self->ctrl_[target.offset]))) { - CWISS_RawTable_rehash_and_grow_if_necessary(policy, self); - target = CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); - } - self->size_++; - self->growth_left_ -= CWISS_IsEmpty(self->ctrl_[target.offset]); - CWISS_SetCtrl(target.offset, CWISS_H2(hash), self->capacity_, self->ctrl_, - self->slots_, policy->slot->size); - // infoz().RecordInsert(hash, target.probe_length); - return target.offset; + CWISS_RawTable* self, size_t hash) { + CWISS_FindInfo target = + CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); + if (CWISS_UNLIKELY(self->growth_left_ == 0 && + !CWISS_IsDeleted(self->ctrl_[target.offset]))) { + CWISS_RawTable_rehash_and_grow_if_necessary(policy, self); + target = CWISS_FindFirstNonFull(self->ctrl_, hash, self->capacity_); + } + self->size_++; + self->growth_left_ -= CWISS_IsEmpty(self->ctrl_[target.offset]); + CWISS_SetCtrl(target.offset, CWISS_H2(hash), self->capacity_, self->ctrl_, + self->slots_, policy->slot->size); + // infoz().RecordInsert(hash, target.probe_length); + return target.offset; } /// Attempts to find `key` in the table; if it isn't found, returns where to /// insert it, instead. static inline CWISS_PrepareInsert CWISS_RawTable_FindOrPrepareInsert( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - CWISS_RawTable* self, const void* key) { - CWISS_RawTable_PrefetchHeapBlock(policy, self); - size_t hash = key_policy->hash(key); - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_); - while (true) { - CWISS_Group g = CWISS_Group_new(self->ctrl_ + seq.offset_); - CWISS_BitMask match = CWISS_Group_Match(&g, CWISS_H2(hash)); - uint32_t i; - while (CWISS_BitMask_next(&match, &i)) { - size_t idx = CWISS_ProbeSeq_offset(&seq, i); - char* slot = self->slots_ + idx * policy->slot->size; - if (CWISS_LIKELY(key_policy->eq(key, policy->slot->get(slot)))) - return (CWISS_PrepareInsert){idx, false}; - } - if (CWISS_LIKELY(CWISS_Group_MatchEmpty(&g).mask)) break; - CWISS_ProbeSeq_next(&seq); - CWISS_DCHECK(seq.index_ <= self->capacity_, "full table!"); - } - return (CWISS_PrepareInsert){CWISS_RawTable_PrepareInsert(policy, self, hash), - true}; + const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, + CWISS_RawTable* self, const void* key) { + CWISS_RawTable_PrefetchHeapBlock(policy, self); + size_t hash = key_policy->hash(key); + CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_); + while (true) { + CWISS_Group g = CWISS_Group_new(self->ctrl_ + seq.offset_); + CWISS_BitMask match = CWISS_Group_Match(&g, CWISS_H2(hash)); + uint32_t i; + while (CWISS_BitMask_next(&match, &i)) { + size_t idx = CWISS_ProbeSeq_offset(&seq, i); + char* slot = self->slots_ + idx * policy->slot->size; + if (CWISS_LIKELY(key_policy->eq(key, policy->slot->get(slot)))) + return (CWISS_PrepareInsert) { idx, false }; + } + if (CWISS_LIKELY(CWISS_Group_MatchEmpty(&g).mask)) break; + CWISS_ProbeSeq_next(&seq); + CWISS_DCHECK(seq.index_ <= self->capacity_, "full table!"); + } + return (CWISS_PrepareInsert) { + CWISS_RawTable_PrepareInsert(policy, self, hash), + true + }; } /// Prepares a slot to insert an element into. @@ -2698,137 +2280,136 @@ static inline CWISS_PrepareInsert CWISS_RawTable_FindOrPrepareInsert( /// This function does all the work of calling the appropriate policy functions /// to initialize the slot. static inline void* CWISS_RawTable_PreInsert(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t i) { - void* dst = self->slots_ + i * policy->slot->size; - policy->slot->init(dst); - return policy->slot->get(dst); + CWISS_RawTable* self, size_t i) { + void* dst = self->slots_ + i * policy->slot->size; + policy->slot->init(dst); + return policy->slot->get(dst); } /// Creates a new empty table with the given capacity. static inline CWISS_RawTable CWISS_RawTable_new(const CWISS_Policy* policy, - size_t capacity) { - CWISS_RawTable self = { - .ctrl_ = CWISS_EmptyGroup(), - }; + size_t capacity) { + CWISS_RawTable self = { + .ctrl_ = CWISS_EmptyGroup(), + }; - if (capacity != 0) { - self.capacity_ = CWISS_NormalizeCapacity(capacity); - CWISS_RawTable_InitializeSlots(policy, &self); - } + if (capacity != 0) { + self.capacity_ = CWISS_NormalizeCapacity(capacity); + CWISS_RawTable_InitializeSlots(policy, &self); + } - return self; + return self; } /// Ensures that at least `n` more elements can be inserted without a resize /// (although this function my itself resize and rehash the table). static inline void CWISS_RawTable_reserve(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t n) { - if (n <= self->size_ + self->growth_left_) { - return; - } + CWISS_RawTable* self, size_t n) { + if (n <= self->size_ + self->growth_left_) { + return; + } - n = CWISS_NormalizeCapacity(CWISS_GrowthToLowerboundCapacity(n)); - CWISS_RawTable_Resize(policy, self, n); + n = CWISS_NormalizeCapacity(CWISS_GrowthToLowerboundCapacity(n)); + CWISS_RawTable_Resize(policy, self, n); - // This is after resize, to ensure that we have completed the allocation - // and have potentially sampled the hashtable. - // infoz().RecordReservation(n); + // This is after resize, to ensure that we have completed the allocation + // and have potentially sampled the hashtable. + // infoz().RecordReservation(n); } /// Creates a duplicate of this table. static inline CWISS_RawTable CWISS_RawTable_dup(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - CWISS_RawTable copy = CWISS_RawTable_new(policy, 0); - - CWISS_RawTable_reserve(policy, &copy, self->size_); - // Because the table is guaranteed to be empty, we can do something faster - // than a full `insert`. In particular we do not need to take a trip to - // `CWISS_RawTable_rehash_and_grow_if_necessary()` because we are already - // big enough (since `self` is a priori) and tombstones cannot be created - // during this process. - for (CWISS_RawIter iter = CWISS_RawTable_citer(policy, self); - CWISS_RawIter_get(policy, &iter); CWISS_RawIter_next(policy, &iter)) { - void* v = CWISS_RawIter_get(policy, &iter); - size_t hash = policy->key->hash(v); - - CWISS_FindInfo target = - CWISS_FindFirstNonFull(copy.ctrl_, hash, copy.capacity_); - CWISS_SetCtrl(target.offset, CWISS_H2(hash), copy.capacity_, copy.ctrl_, - copy.slots_, policy->slot->size); - void* slot = CWISS_RawTable_PreInsert(policy, &copy, target.offset); - policy->obj->copy(slot, v); - // infoz().RecordInsert(hash, target.probe_length); - } - copy.size_ = self->size_; - copy.growth_left_ -= self->size_; - return copy; + const CWISS_RawTable* self) { + CWISS_RawTable copy = CWISS_RawTable_new(policy, 0); + + CWISS_RawTable_reserve(policy, &copy, self->size_); + // Because the table is guaranteed to be empty, we can do something faster + // than a full `insert`. In particular we do not need to take a trip to + // `CWISS_RawTable_rehash_and_grow_if_necessary()` because we are already + // big enough (since `self` is a priori) and tombstones cannot be created + // during this process. + for (CWISS_RawIter iter = CWISS_RawTable_citer(policy, self); + CWISS_RawIter_get(policy, &iter); CWISS_RawIter_next(policy, &iter)) { + void* v = CWISS_RawIter_get(policy, &iter); + size_t hash = policy->key->hash(v); + + CWISS_FindInfo target = + CWISS_FindFirstNonFull(copy.ctrl_, hash, copy.capacity_); + CWISS_SetCtrl(target.offset, CWISS_H2(hash), copy.capacity_, copy.ctrl_, + copy.slots_, policy->slot->size); + void* slot = CWISS_RawTable_PreInsert(policy, &copy, target.offset); + policy->obj->copy(slot, v); + // infoz().RecordInsert(hash, target.probe_length); + } + copy.size_ = self->size_; + copy.growth_left_ -= self->size_; + return copy; } /// Destroys this table, destroying its elements and freeing the backing array. static inline void CWISS_RawTable_destroy(const CWISS_Policy* policy, - CWISS_RawTable* self) { - CWISS_RawTable_DestroySlots(policy, self); + CWISS_RawTable* self) { + CWISS_RawTable_DestroySlots(policy, self); } /// Returns whether the table is empty. static inline bool CWISS_RawTable_empty(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return !self->size_; + const CWISS_RawTable* self) { + return !self->size_; } /// Returns the number of elements in the table. static inline size_t CWISS_RawTable_size(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return self->size_; + const CWISS_RawTable* self) { + return self->size_; } /// Returns the total capacity of the table, which is different from the number /// of elements that would cause it to get resized. static inline size_t CWISS_RawTable_capacity(const CWISS_Policy* policy, - const CWISS_RawTable* self) { - return self->capacity_; + const CWISS_RawTable* self) { + return self->capacity_; } /// Clears the table, erasing every element contained therein. -static inline void CWISS_RawTable_clear(const CWISS_Policy* policy, - CWISS_RawTable* self) { - // Iterating over this container is O(bucket_count()). When bucket_count() - // is much greater than size(), iteration becomes prohibitively expensive. - // For clear() it is more important to reuse the allocated array when the - // container is small because allocation takes comparatively long time - // compared to destruction of the elements of the container. So we pick the - // largest bucket_count() threshold for which iteration is still fast and - // past that we simply deallocate the array. - if (self->capacity_ > 127) { - CWISS_RawTable_DestroySlots(policy, self); - - // infoz().RecordClearedReservation(); - } else if (self->capacity_) { - if (policy->slot->del != NULL) { - size_t i; - for (i = 0; i != self->capacity_; i++) { - if (CWISS_IsFull(self->ctrl_[i])) { - policy->slot->del(self->slots_ + i * policy->slot->size); - } - } - } - - self->size_ = 0; - CWISS_ResetCtrl(self->capacity_, self->ctrl_, self->slots_, - policy->slot->size); - CWISS_RawTable_ResetGrowthLeft(policy, self); - } - CWISS_DCHECK(!self->size_, "size was still nonzero"); - // infoz().RecordStorageChanged(0, capacity_); +static inline void CWISS_RawTable_clear(const CWISS_Policy* policy, CWISS_RawTable* self) { + // Iterating over this container is O(bucket_count()). When bucket_count() + // is much greater than size(), iteration becomes prohibitively expensive. + // For clear() it is more important to reuse the allocated array when the + // container is small because allocation takes comparatively long time + // compared to destruction of the elements of the container. So we pick the + // largest bucket_count() threshold for which iteration is still fast and + // past that we simply deallocate the array. + if (self->capacity_ > 127) { + CWISS_RawTable_DestroySlots(policy, self); + + // infoz().RecordClearedReservation(); + } else if (self->capacity_) { + if (policy->slot->del != NULL) { + size_t i; + for (i = 0; i != self->capacity_; i++) { + if (CWISS_IsFull(self->ctrl_[i])) { + policy->slot->del(self->slots_ + i * policy->slot->size); + } + } + } + + self->size_ = 0; + CWISS_ResetCtrl(self->capacity_, self->ctrl_, self->slots_, + policy->slot->size); + CWISS_RawTable_ResetGrowthLeft(policy, self); + } + CWISS_DCHECK(!self->size_, "size was still nonzero"); + // infoz().RecordStorageChanged(0, capacity_); } /// The return type of `CWISS_RawTable_insert()`. typedef struct { - /// An iterator referring to the relevant element. - CWISS_RawIter iter; - /// True if insertion actually occurred; false if the element was already - /// present. - bool inserted; + /// An iterator referring to the relevant element. + CWISS_RawIter iter; + /// True if insertion actually occurred; false if the element was already + /// present. + bool inserted; } CWISS_Insert; /// "Inserts" `val` into the table if it isn't already present. @@ -2846,16 +2427,18 @@ typedef struct { /// `key_policy` is a possibly heterogenous key policy for comparing `key`'s /// type to types in the map. `key_policy` may be `&policy->key`. static inline CWISS_Insert CWISS_RawTable_deferred_insert( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - CWISS_RawTable* self, const void* key) { - CWISS_PrepareInsert res = - CWISS_RawTable_FindOrPrepareInsert(policy, key_policy, self, key); + const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, + CWISS_RawTable* self, const void* key) { + CWISS_PrepareInsert res = + CWISS_RawTable_FindOrPrepareInsert(policy, key_policy, self, key); - if (res.inserted) { - CWISS_RawTable_PreInsert(policy, self, res.index); - } - return (CWISS_Insert){CWISS_RawTable_citer_at(policy, self, res.index), - res.inserted}; + if (res.inserted) { + CWISS_RawTable_PreInsert(policy, self, res.index); + } + return (CWISS_Insert) { + CWISS_RawTable_citer_at(policy, self, res.index), + res.inserted + }; } /// Inserts `val` (by copy) into the table if it isn't already present. @@ -2863,17 +2446,19 @@ static inline CWISS_Insert CWISS_RawTable_deferred_insert( /// Returns an iterator pointing to the element in the map and whether it was /// just inserted or was already present. static inline CWISS_Insert CWISS_RawTable_insert(const CWISS_Policy* policy, - CWISS_RawTable* self, - const void* val) { - CWISS_PrepareInsert res = - CWISS_RawTable_FindOrPrepareInsert(policy, policy->key, self, val); + CWISS_RawTable* self, + const void* val) { + CWISS_PrepareInsert res = + CWISS_RawTable_FindOrPrepareInsert(policy, policy->key, self, val); - if (res.inserted) { - void* slot = CWISS_RawTable_PreInsert(policy, self, res.index); - policy->obj->copy(slot, val); - } - return (CWISS_Insert){CWISS_RawTable_citer_at(policy, self, res.index), - res.inserted}; + if (res.inserted) { + void* slot = CWISS_RawTable_PreInsert(policy, self, res.index); + policy->obj->copy(slot, val); + } + return (CWISS_Insert) { + CWISS_RawTable_citer_at(policy, self, res.index), + res.inserted + }; } /// Tries to find the corresponding entry for `key` using `hash` as a hint. @@ -2884,25 +2469,25 @@ static inline CWISS_Insert CWISS_RawTable_insert(const CWISS_Policy* policy, /// /// If `hash` is not actually the hash of `key`, UB. static inline CWISS_RawIter CWISS_RawTable_find_hinted( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - const CWISS_RawTable* self, const void* key, size_t hash) { - CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_); - while (true) { - CWISS_Group g = CWISS_Group_new(self->ctrl_ + seq.offset_); - CWISS_BitMask match = CWISS_Group_Match(&g, CWISS_H2(hash)); - uint32_t i; - while (CWISS_BitMask_next(&match, &i)) { - char* slot = - self->slots_ + CWISS_ProbeSeq_offset(&seq, i) * policy->slot->size; - if (CWISS_LIKELY(key_policy->eq(key, policy->slot->get(slot)))) - return CWISS_RawTable_citer_at(policy, self, - CWISS_ProbeSeq_offset(&seq, i)); - } - if (CWISS_LIKELY(CWISS_Group_MatchEmpty(&g).mask)) - return (CWISS_RawIter){0}; - CWISS_ProbeSeq_next(&seq); - CWISS_DCHECK(seq.index_ <= self->capacity_, "full table!"); - } + const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, + const CWISS_RawTable* self, const void* key, size_t hash) { + CWISS_ProbeSeq seq = CWISS_ProbeSeq_Start(self->ctrl_, hash, self->capacity_); + while (true) { + CWISS_Group g = CWISS_Group_new(self->ctrl_ + seq.offset_); + CWISS_BitMask match = CWISS_Group_Match(&g, CWISS_H2(hash)); + uint32_t i; + while (CWISS_BitMask_next(&match, &i)) { + char* slot = + self->slots_ + CWISS_ProbeSeq_offset(&seq, i) * policy->slot->size; + if (CWISS_LIKELY(key_policy->eq(key, policy->slot->get(slot)))) + return CWISS_RawTable_citer_at(policy, self, + CWISS_ProbeSeq_offset(&seq, i)); + } + if (CWISS_LIKELY(CWISS_Group_MatchEmpty(&g).mask)) + return (CWISS_RawIter) { 0 }; + CWISS_ProbeSeq_next(&seq); + CWISS_DCHECK(seq.index_ <= self->capacity_, "full table!"); + } } /// Tries to find the corresponding entry for `key`. @@ -2911,21 +2496,21 @@ static inline CWISS_RawIter CWISS_RawTable_find_hinted( /// `key_policy` is a possibly heterogenous key policy for comparing `key`'s /// type to types in the map. `key_policy` may be `&policy->key`. static inline CWISS_RawIter CWISS_RawTable_find( - const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, - const CWISS_RawTable* self, const void* key) { - return CWISS_RawTable_find_hinted(policy, key_policy, self, key, - key_policy->hash(key)); + const CWISS_Policy* policy, const CWISS_KeyPolicy* key_policy, + const CWISS_RawTable* self, const void* key) { + return CWISS_RawTable_find_hinted(policy, key_policy, self, key, + key_policy->hash(key)); } /// Erases the element pointed to by the given valid iterator. /// This function will invalidate the iterator. static inline void CWISS_RawTable_erase_at(const CWISS_Policy* policy, - CWISS_RawIter it) { - CWISS_AssertIsFull(it.ctrl_); - if (policy->slot->del != NULL) { - policy->slot->del(it.slot_); - } - CWISS_RawTable_EraseMetaOnly(policy, it); + CWISS_RawIter it) { + CWISS_AssertIsFull(it.ctrl_); + if (policy->slot->del != NULL) { + policy->slot->del(it.slot_); + } + CWISS_RawTable_EraseMetaOnly(policy, it); } /// Erases the entry corresponding to `key`, if present. Returns true if @@ -2934,37 +2519,37 @@ static inline void CWISS_RawTable_erase_at(const CWISS_Policy* policy, /// `key_policy` is a possibly heterogenous key policy for comparing `key`'s /// type to types in the map. `key_policy` may be `&policy->key`. static inline bool CWISS_RawTable_erase(const CWISS_Policy* policy, - const CWISS_KeyPolicy* key_policy, - CWISS_RawTable* self, const void* key) { - CWISS_RawIter it = CWISS_RawTable_find(policy, key_policy, self, key); - if (it.slot_ == NULL) return false; - CWISS_RawTable_erase_at(policy, it); - return true; + const CWISS_KeyPolicy* key_policy, + CWISS_RawTable* self, const void* key) { + CWISS_RawIter it = CWISS_RawTable_find(policy, key_policy, self, key); + if (it.slot_ == NULL) return false; + CWISS_RawTable_erase_at(policy, it); + return true; } /// Triggers a rehash, growing to at least a capacity of `n`. static inline void CWISS_RawTable_rehash(const CWISS_Policy* policy, - CWISS_RawTable* self, size_t n) { - if (n == 0 && self->capacity_ == 0) return; - if (n == 0 && self->size_ == 0) { - CWISS_RawTable_DestroySlots(policy, self); - // infoz().RecordStorageChanged(0, 0); - // infoz().RecordClearedReservation(); - return; - } - - // bitor is a faster way of doing `max` here. We will round up to the next - // power-of-2-minus-1, so bitor is good enough. - size_t m = CWISS_NormalizeCapacity( - n | CWISS_GrowthToLowerboundCapacity(self->size_)); - // n == 0 unconditionally rehashes as per the standard. - if (n == 0 || m > self->capacity_) { - CWISS_RawTable_Resize(policy, self, m); - - // This is after resize, to ensure that we have completed the allocation - // and have potentially sampled the hashtable. - // infoz().RecordReservation(n); - } + CWISS_RawTable* self, size_t n) { + if (n == 0 && self->capacity_ == 0) return; + if (n == 0 && self->size_ == 0) { + CWISS_RawTable_DestroySlots(policy, self); + // infoz().RecordStorageChanged(0, 0); + // infoz().RecordClearedReservation(); + return; + } + + // bitor is a faster way of doing `max` here. We will round up to the next + // power-of-2-minus-1, so bitor is good enough. + size_t m = CWISS_NormalizeCapacity( + n | CWISS_GrowthToLowerboundCapacity(self->size_)); + // n == 0 unconditionally rehashes as per the standard. + if (n == 0 || m > self->capacity_) { + CWISS_RawTable_Resize(policy, self, m); + + // This is after resize, to ensure that we have completed the allocation + // and have potentially sampled the hashtable. + // infoz().RecordReservation(n); + } } /// Returns whether `key` is contained in this table. @@ -2972,10 +2557,10 @@ static inline void CWISS_RawTable_rehash(const CWISS_Policy* policy, /// `key_policy` is a possibly heterogenous key policy for comparing `key`'s /// type to types in the map. `key_policy` may be `&policy->key`. static inline bool CWISS_RawTable_contains(const CWISS_Policy* policy, - const CWISS_KeyPolicy* key_policy, - const CWISS_RawTable* self, - const void* key) { - return CWISS_RawTable_find(policy, key_policy, self, key).slot_ != NULL; + const CWISS_KeyPolicy* key_policy, + const CWISS_RawTable* self, + const void* key) { + return CWISS_RawTable_find(policy, key_policy, self, key).slot_ != NULL; } CWISS_END_EXTERN @@ -3022,52 +2607,128 @@ CWISS_BEGIN_EXTERN /// plain-old-data policies. /// /// See header documentation for examples of generated API. -#define CWISS_DECLARE_FLAT_HASHSET(HashSet_, Type_) \ - CWISS_DECLARE_FLAT_SET_POLICY(HashSet_##_kPolicy, Type_, (_, _)); \ - CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, HashSet_##_kPolicy) +#define CWISS_DECLARE_FLAT_HASHSET(HashSet_, Type_,obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_DECLARE_FLAT_SET_POLICY(HashSet_##_kPolicy, Type_, obj_copy, obj_dtor, key_hash, key_eq); \ + CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, HashSet_##_kPolicy) + +#define CWISS_DECLARE_FLAT_HASHSET_DEFAULT(HashSet_, Type_) \ + static inline void HashSet_##_default_dtor(void* val) { } \ + static inline void HashSet_##_default_copy(void* dst_, const void* src_) { \ + memcpy(dst_, src_, sizeof(Type_)); \ + } \ + static inline size_t HashSet_##_default_hash(const void* val) { \ + CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ + CWISS_AbslHash_Write(&state, val, sizeof(Type_)); \ + return CWISS_AbslHash_Finish(state); \ + } \ + static inline bool HashSet_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(Type_)) == 0; } \ + CWISS_DECLARE_FLAT_HASHSET(HashSet_, Type_, \ + HashSet_##_default_copy, \ + HashSet_##_default_dtor, \ + HashSet_##_default_hash, \ + HashSet_##_default_eq); /// Generates a new hash set type with outline storage and the default /// plain-old-data policies. /// /// See header documentation for examples of generated API. -#define CWISS_DECLARE_NODE_HASHSET(HashSet_, Type_) \ - CWISS_DECLARE_NODE_SET_POLICY(HashSet_##_kPolicy, Type_, (_, _)); \ - CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, HashSet_##_kPolicy) +#define CWISS_DECLARE_NODE_HASHSET(HashSet_, Type_, obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_DECLARE_NODE_SET_POLICY(HashSet_##_kPolicy, Type_, obj_copy, obj_dtor, key_hash, key_eq); \ + CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, HashSet_##_kPolicy) + +#define CWISS_DECLARE_NODE_HASHSET_DEFAULT(HashSet_, Type_) \ + static inline void HashSet_##_default_dtor(void* val) { } \ + static inline void HashSet_##_default_copy(void* dst_, const void* src_) { \ + memcpy(dst_, src_, sizeof(Type_)); \ + } \ + static inline size_t HashSet_##_default_hash(const void* val) { \ + CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ + CWISS_AbslHash_Write(&state, val, sizeof(Type_)); \ + return CWISS_AbslHash_Finish(state); \ + } \ + static inline bool HashSet_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(Type_)) == 0; } \ + CWISS_DECLARE_NODE_HASHSET(HashSet_, Type_, \ + HashSet_##_default_copy, \ + HashSet_##_default_dtor, \ + HashSet_##_default_hash, \ + HashSet_##_default_eq); /// Generates a new hash map type with inline storage and the default /// plain-old-data policies. /// /// See header documentation for examples of generated API. -#define CWISS_DECLARE_FLAT_HASHMAP(HashMap_, K_, V_) \ - CWISS_DECLARE_FLAT_MAP_POLICY(HashMap_##_kPolicy, K_, V_, (_, _)); \ - CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, HashMap_##_kPolicy) +#define CWISS_DECLARE_FLAT_HASHMAP(HashMap_, K_, V_, obj_copy, obj_dtor, key_hash, key_eq) \ + CWISS_DECLARE_FLAT_MAP_POLICY(HashMap_##_kPolicy, K_, V_, obj_copy, obj_dtor, key_hash, key_eq); \ + CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, HashMap_##_kPolicy) + +#define CWISS_DECLARE_FLAT_HASHMAP_DEFAULT(HashMap_, K_, V_) \ + static inline void HashMap_##_default_dtor(void* val) { } \ + typedef struct { \ + K_ k; \ + V_ v; \ + } HashMap_##_EntryInternal; \ + static inline void HashMap_##_default_copy(void* dst_, const void* src_) { \ + memcpy(dst_, src_, sizeof(HashMap_##_EntryInternal)); \ + } \ + static inline size_t HashMap_##_default_hash(const void* val) { \ + CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ + CWISS_AbslHash_Write(&state, val, sizeof(K_)); \ + return CWISS_AbslHash_Finish(state); \ + } \ + static inline bool HashMap_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(K_)) == 0; } \ + CWISS_DECLARE_FLAT_HASHMAP(HashMap_, K_, V_, \ + HashMap_##_default_copy, \ + HashMap_##_default_dtor, \ + HashMap_##_default_hash, \ + HashMap_##_default_eq); /// Generates a new hash map type with outline storage and the default /// plain-old-data policies. /// /// See header documentation for examples of generated API. -#define CWISS_DECLARE_NODE_HASHMAP(HashMap_, K_, V_) \ - CWISS_DECLARE_NODE_MAP_POLICY(HashMap_##_kPolicy, K_, V_, (_, _)); \ - CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, HashMap_##_kPolicy) +#define CWISS_DECLARE_NODE_HASHMAP(HashMap_, K_, V_, a,b,c,d) \ + CWISS_DECLARE_NODE_MAP_POLICY(HashMap_##_kPolicy, K_, V_, a,b,c,d); \ + CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, HashMap_##_kPolicy) + +#define CWISS_DECLARE_NODE_HASHMAP_DEFAULT(HashMap_, K_, V_) \ + typedef struct { \ + K_ k; \ + V_ v; \ + } HashMap_##_EntryInternal; \ + static inline void HashMap_##_default_dtor(void* val) { } \ + static inline void HashMap_##_default_copy(void* dst_, const void* src_) { \ + memcpy(dst_, src_, sizeof(HashMap_##_EntryInternal)); \ + } \ + static inline size_t HashMap_##_default_hash(const void* val) { \ + CWISS_AbslHash_State state = CWISS_AbslHash_kInit; \ + CWISS_AbslHash_Write(&state, val, sizeof(K_)); \ + return CWISS_AbslHash_Finish(state); \ + } \ + static inline bool HashMap_##_default_eq(const void* a, const void* b) { return memcmp (a,b,sizeof(K_)) == 0; } \ + CWISS_DECLARE_NODE_HASHMAP(HashMap_, K_, V_, \ + HashMap_##_default_copy, \ + HashMap_##_default_dtor, \ + HashMap_##_default_hash, \ + HashMap_##_default_eq); /// Generates a new hash set type using the given policy. /// /// See header documentation for examples of generated API. #define CWISS_DECLARE_HASHSET_WITH(HashSet_, Type_, kPolicy_) \ - typedef Type_ HashSet_##_Entry; \ - typedef Type_ HashSet_##_Key; \ - CWISS_DECLARE_COMMON_(HashSet_, HashSet_##_Entry, HashSet_##_Key, kPolicy_) + typedef Type_ HashSet_##_Entry; \ + typedef Type_ HashSet_##_Key; \ + CWISS_DECLARE_COMMON_(HashSet_, HashSet_##_Entry, HashSet_##_Key, kPolicy_) /// Generates a new hash map type using the given policy. /// /// See header documentation for examples of generated API. #define CWISS_DECLARE_HASHMAP_WITH(HashMap_, K_, V_, kPolicy_) \ - typedef struct { \ - K_ key; \ - V_ val; \ - } HashMap_##_Entry; \ - typedef K_ HashMap_##_Key; \ - CWISS_DECLARE_COMMON_(HashMap_, HashMap_##_Entry, HashMap_##_Key, kPolicy_) + typedef struct HashMap_##_entry_t { \ + K_ key; \ + V_ val; \ + } HashMap_##_Entry; \ + typedef K_ HashMap_##_Key; \ + CWISS_DECLARE_COMMON_(HashMap_, HashMap_##_Entry, HashMap_##_Key, kPolicy_) /// Declares a heterogenous lookup for an existing SwissTable type. /// @@ -3077,7 +2738,7 @@ CWISS_BEGIN_EXTERN /// /// These functions will be used to build the heterogenous key policy. #define CWISS_DECLARE_LOOKUP(HashSet_, Key_) \ - CWISS_DECLARE_LOOKUP_NAMED(HashSet_, Key_, Key_) + CWISS_DECLARE_LOOKUP_NAMED(HashSet_, Key_, Key_) /// Declares a heterogenous lookup for an existing SwissTable type. /// @@ -3085,206 +2746,203 @@ CWISS_BEGIN_EXTERN /// in the `_by_` prefix on the names, as well as the names of the extension /// point functions. #define CWISS_DECLARE_LOOKUP_NAMED(HashSet_, LookupName_, Key_) \ - CWISS_BEGIN \ - static inline size_t HashSet_##_##LookupName_##_SyntheticHash( \ - const void* val) { \ - return HashSet_##_##LookupName_##_hash((const Key_*)val); \ - } \ - static inline bool HashSet_##_##LookupName_##_SyntheticEq(const void* a, \ - const void* b) { \ - return HashSet_##_##LookupName_##_eq((const Key_*)a, \ - (const HashSet_##_Entry*)b); \ - } \ - static const CWISS_KeyPolicy HashSet_##_##LookupName_##_kPolicy = { \ - HashSet_##_##LookupName_##_SyntheticHash, \ - HashSet_##_##LookupName_##_SyntheticEq, \ - }; \ - \ - static inline const CWISS_KeyPolicy* HashSet_##_##LookupName_##_policy( \ - void) { \ - return &HashSet_##_##LookupName_##_kPolicy; \ - } \ - \ - static inline HashSet_##_Insert HashSet_##_deferred_insert_by_##LookupName_( \ - HashSet_* self, const Key_* key) { \ - CWISS_Insert ret = CWISS_RawTable_deferred_insert( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key); \ - return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ - } \ - static inline HashSet_##_CIter HashSet_##_cfind_hinted_by_##LookupName_( \ - const HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_CIter){CWISS_RawTable_find_hinted( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key, hash)}; \ - } \ - static inline HashSet_##_Iter HashSet_##_find_hinted_by_##LookupName_( \ - HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_Iter){CWISS_RawTable_find_hinted( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key, hash)}; \ - } \ - \ - static inline HashSet_##_CIter HashSet_##_cfind_by_##LookupName_( \ - const HashSet_* self, const Key_* key) { \ - return (HashSet_##_CIter){CWISS_RawTable_find( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key)}; \ - } \ - static inline HashSet_##_Iter HashSet_##_find_by_##LookupName_( \ - HashSet_* self, const Key_* key) { \ - return (HashSet_##_Iter){CWISS_RawTable_find( \ - HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ - key)}; \ - } \ - \ - static inline bool HashSet_##_contains_by_##LookupName_( \ - const HashSet_* self, const Key_* key) { \ - return CWISS_RawTable_contains(HashSet_##_policy(), \ - &HashSet_##_##LookupName_##_kPolicy, \ - &self->set_, key); \ - } \ - \ - static inline bool HashSet_##_erase_by_##LookupName_(HashSet_* self, \ - const Key_* key) { \ - return CWISS_RawTable_erase(HashSet_##_policy(), \ - &HashSet_##_##LookupName_##_kPolicy, \ - &self->set_, key); \ - } \ - \ - CWISS_END \ - /* Force a semicolon. */ \ - struct HashSet_##_##LookupName_##_NeedsTrailingSemicolon_ { \ - int x; \ - } + CWISS_BEGIN \ +static inline size_t HashSet_##_##LookupName_##_SyntheticHash( \ + const void* val) { \ + return HashSet_##_##LookupName_##_hash((const Key_*)val); \ + } \ + static inline bool HashSet_##_##LookupName_##_SyntheticEq(const void* a, \ + const void* b) { \ + return HashSet_##_##LookupName_##_eq((const Key_*)a, \ + (const HashSet_##_Entry*)b); \ + } \ + static const CWISS_KeyPolicy HashSet_##_##LookupName_##_kPolicy = { \ + HashSet_##_##LookupName_##_SyntheticHash, \ + HashSet_##_##LookupName_##_SyntheticEq, \ + }; \ + \ + static inline const CWISS_KeyPolicy* HashSet_##_##LookupName_##_policy( \ + void) { \ + return &HashSet_##_##LookupName_##_kPolicy; \ + } \ + \ + static inline HashSet_##_Insert HashSet_##_deferred_insert_by_##LookupName_( \ + HashSet_* self, const Key_* key) { \ + CWISS_Insert ret = CWISS_RawTable_deferred_insert( \ + HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ + key); \ + return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ + } \ + static inline HashSet_##_CIter HashSet_##_cfind_hinted_by_##LookupName_( \ + const HashSet_* self, const Key_* key, size_t hash) { \ + return (HashSet_##_CIter){CWISS_RawTable_find_hinted( \ + HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ + key, hash)}; \ + } \ + static inline HashSet_##_Iter HashSet_##_find_hinted_by_##LookupName_( \ + HashSet_* self, const Key_* key, size_t hash) { \ + return (HashSet_##_Iter){CWISS_RawTable_find_hinted( \ + HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ + key, hash)}; \ + } \ + \ + static inline HashSet_##_CIter HashSet_##_cfind_by_##LookupName_( \ + const HashSet_* self, const Key_* key) { \ + return (HashSet_##_CIter){CWISS_RawTable_find( \ + HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ + key)}; \ + } \ + static inline HashSet_##_Iter HashSet_##_find_by_##LookupName_( \ + HashSet_* self, const Key_* key) { \ + return (HashSet_##_Iter){CWISS_RawTable_find( \ + HashSet_##_policy(), &HashSet_##_##LookupName_##_kPolicy, &self->set_, \ + key)}; \ + } \ + \ + static inline bool HashSet_##_contains_by_##LookupName_( \ + const HashSet_* self, const Key_* key) { \ + return CWISS_RawTable_contains(HashSet_##_policy(), \ + &HashSet_##_##LookupName_##_kPolicy, \ + &self->set_, key); \ + } \ + \ + static inline bool HashSet_##_erase_by_##LookupName_(HashSet_* self, \ + const Key_* key) { \ + return CWISS_RawTable_erase(HashSet_##_policy(), \ + &HashSet_##_##LookupName_##_kPolicy, \ + &self->set_, key); \ + } \ + \ + CWISS_END \ + /* Force a semicolon. */ \ + struct HashSet_##_##LookupName_##_NeedsTrailingSemicolon_ { \ + int x; \ + } // ---- PUBLIC API ENDS HERE! ---- #define CWISS_DECLARE_COMMON_(HashSet_, Type_, Key_, kPolicy_) \ - CWISS_BEGIN \ - static inline const CWISS_Policy* HashSet_##_policy(void) { \ - return &kPolicy_; \ - } \ - \ - typedef struct { \ - CWISS_RawTable set_; \ - } HashSet_; \ - static inline void HashSet_##_dump(const HashSet_* self) { \ - CWISS_RawTable_dump(&kPolicy_, &self->set_); \ - } \ - \ - static inline HashSet_ HashSet_##_new(size_t bucket_count) { \ - return (HashSet_){CWISS_RawTable_new(&kPolicy_, bucket_count)}; \ - } \ - static inline HashSet_ HashSet_##_dup(const HashSet_* that) { \ - return (HashSet_){CWISS_RawTable_dup(&kPolicy_, &that->set_)}; \ - } \ - static inline void HashSet_##_destroy(HashSet_* self) { \ - CWISS_RawTable_destroy(&kPolicy_, &self->set_); \ - } \ - \ - typedef struct { \ - CWISS_RawIter it_; \ - } HashSet_##_Iter; \ - static inline HashSet_##_Iter HashSet_##_iter(HashSet_* self) { \ - return (HashSet_##_Iter){CWISS_RawTable_iter(&kPolicy_, &self->set_)}; \ - } \ - static inline Type_* HashSet_##_Iter_get(const HashSet_##_Iter* it) { \ - return (Type_*)CWISS_RawIter_get(&kPolicy_, &it->it_); \ - } \ - static inline Type_* HashSet_##_Iter_next(HashSet_##_Iter* it) { \ - return (Type_*)CWISS_RawIter_next(&kPolicy_, &it->it_); \ - } \ - \ - typedef struct { \ - CWISS_RawIter it_; \ - } HashSet_##_CIter; \ - static inline HashSet_##_CIter HashSet_##_citer(const HashSet_* self) { \ - return (HashSet_##_CIter){CWISS_RawTable_citer(&kPolicy_, &self->set_)}; \ - } \ - static inline const Type_* HashSet_##_CIter_get( \ - const HashSet_##_CIter* it) { \ - return (const Type_*)CWISS_RawIter_get(&kPolicy_, &it->it_); \ - } \ - static inline const Type_* HashSet_##_CIter_next(HashSet_##_CIter* it) { \ - return (const Type_*)CWISS_RawIter_next(&kPolicy_, &it->it_); \ - } \ - static inline HashSet_##_CIter HashSet_##_Iter_const(HashSet_##_Iter it) { \ - return (HashSet_##_CIter){it.it_}; \ - } \ - \ - static inline void HashSet_##_reserve(HashSet_* self, size_t n) { \ - CWISS_RawTable_reserve(&kPolicy_, &self->set_, n); \ - } \ - static inline void HashSet_##_rehash(HashSet_* self, size_t n) { \ - CWISS_RawTable_rehash(&kPolicy_, &self->set_, n); \ - } \ - \ - static inline bool HashSet_##_empty(const HashSet_* self) { \ - return CWISS_RawTable_empty(&kPolicy_, &self->set_); \ - } \ - static inline size_t HashSet_##_size(const HashSet_* self) { \ - return CWISS_RawTable_size(&kPolicy_, &self->set_); \ - } \ - static inline size_t HashSet_##_capacity(const HashSet_* self) { \ - return CWISS_RawTable_capacity(&kPolicy_, &self->set_); \ - } \ - \ - static inline void HashSet_##_clear(HashSet_* self) { \ - return CWISS_RawTable_clear(&kPolicy_, &self->set_); \ - } \ - \ - typedef struct { \ - HashSet_##_Iter iter; \ - bool inserted; \ - } HashSet_##_Insert; \ - static inline HashSet_##_Insert HashSet_##_deferred_insert( \ - HashSet_* self, const Key_* key) { \ - CWISS_Insert ret = CWISS_RawTable_deferred_insert(&kPolicy_, kPolicy_.key, \ - &self->set_, key); \ - return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ - } \ - static inline HashSet_##_Insert HashSet_##_insert(HashSet_* self, \ - const Type_* val) { \ - CWISS_Insert ret = CWISS_RawTable_insert(&kPolicy_, &self->set_, val); \ - return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ - } \ - \ - static inline HashSet_##_CIter HashSet_##_cfind_hinted( \ - const HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_CIter){CWISS_RawTable_find_hinted( \ - &kPolicy_, kPolicy_.key, &self->set_, key, hash)}; \ - } \ - static inline HashSet_##_Iter HashSet_##_find_hinted( \ - HashSet_* self, const Key_* key, size_t hash) { \ - return (HashSet_##_Iter){CWISS_RawTable_find_hinted( \ - &kPolicy_, kPolicy_.key, &self->set_, key, hash)}; \ - } \ - static inline HashSet_##_CIter HashSet_##_cfind(const HashSet_* self, \ - const Key_* key) { \ - return (HashSet_##_CIter){ \ - CWISS_RawTable_find(&kPolicy_, kPolicy_.key, &self->set_, key)}; \ - } \ - static inline HashSet_##_Iter HashSet_##_find(HashSet_* self, \ - const Key_* key) { \ - return (HashSet_##_Iter){ \ - CWISS_RawTable_find(&kPolicy_, kPolicy_.key, &self->set_, key)}; \ - } \ - \ - static inline bool HashSet_##_contains(const HashSet_* self, \ - const Key_* key) { \ - return CWISS_RawTable_contains(&kPolicy_, kPolicy_.key, &self->set_, key); \ - } \ - \ - static inline void HashSet_##_erase_at(HashSet_##_Iter it) { \ - CWISS_RawTable_erase_at(&kPolicy_, it.it_); \ - } \ - static inline bool HashSet_##_erase(HashSet_* self, const Key_* key) { \ - return CWISS_RawTable_erase(&kPolicy_, kPolicy_.key, &self->set_, key); \ - } \ - \ - CWISS_END \ - /* Force a semicolon. */ struct HashSet_##_NeedsTrailingSemicolon_ { int x; } + CWISS_BEGIN \ + static inline SDB_MAYBE_UNUSED const CWISS_Policy* HashSet_##_policy(void) { \ + return &kPolicy_; \ + } \ + \ + typedef struct HashSet_##_t { \ + CWISS_RawTable set_; \ + } HashSet_; \ + \ + static inline SDB_MAYBE_UNUSED HashSet_ HashSet_##_new(size_t bucket_count) { \ + return (HashSet_){CWISS_RawTable_new(&kPolicy_, bucket_count)}; \ + } \ + static inline SDB_MAYBE_UNUSED HashSet_ HashSet_##_dup(const HashSet_* that) { \ + return (HashSet_){CWISS_RawTable_dup(&kPolicy_, &that->set_)}; \ + } \ + static inline SDB_MAYBE_UNUSED void HashSet_##_destroy(HashSet_* self) { \ + CWISS_RawTable_destroy(&kPolicy_, &self->set_); \ + } \ + \ + typedef struct { \ + CWISS_RawIter it_; \ + } HashSet_##_Iter; \ + static inline SDB_MAYBE_UNUSED HashSet_##_Iter HashSet_##_iter(HashSet_* self) { \ + return (HashSet_##_Iter){CWISS_RawTable_iter(&kPolicy_, &self->set_)}; \ + } \ + static inline SDB_MAYBE_UNUSED Type_* HashSet_##_Iter_get(const HashSet_##_Iter* it) { \ + return (Type_*)CWISS_RawIter_get(&kPolicy_, &it->it_); \ + } \ + static inline SDB_MAYBE_UNUSED Type_* HashSet_##_Iter_next(HashSet_##_Iter* it) { \ + return (Type_*)CWISS_RawIter_next(&kPolicy_, &it->it_); \ + } \ + \ + typedef struct { \ + CWISS_RawIter it_; \ + } HashSet_##_CIter; \ + static inline SDB_MAYBE_UNUSED HashSet_##_CIter HashSet_##_citer(const HashSet_* self) { \ + return (HashSet_##_CIter){CWISS_RawTable_citer(&kPolicy_, &self->set_)}; \ + } \ + static inline SDB_MAYBE_UNUSED const Type_* HashSet_##_CIter_get( \ + const HashSet_##_CIter* it) { \ + return (const Type_*)CWISS_RawIter_get(&kPolicy_, &it->it_); \ + } \ + static inline SDB_MAYBE_UNUSED const Type_* HashSet_##_CIter_next(HashSet_##_CIter* it) { \ + return (const Type_*)CWISS_RawIter_next(&kPolicy_, &it->it_); \ + } \ + static inline SDB_MAYBE_UNUSED HashSet_##_CIter HashSet_##_Iter_const(HashSet_##_Iter it) { \ + return (HashSet_##_CIter){it.it_}; \ + } \ + \ + static inline SDB_MAYBE_UNUSED void HashSet_##_reserve(HashSet_* self, size_t n) { \ + CWISS_RawTable_reserve(&kPolicy_, &self->set_, n); \ + } \ + static inline SDB_MAYBE_UNUSED void HashSet_##_rehash(HashSet_* self, size_t n) { \ + CWISS_RawTable_rehash(&kPolicy_, &self->set_, n); \ + } \ + \ + static inline SDB_MAYBE_UNUSED bool HashSet_##_empty(const HashSet_* self) { \ + return CWISS_RawTable_empty(&kPolicy_, &self->set_); \ + } \ + static inline SDB_MAYBE_UNUSED size_t HashSet_##_size(const HashSet_* self) { \ + return CWISS_RawTable_size(&kPolicy_, &self->set_); \ + } \ + static inline SDB_MAYBE_UNUSED size_t HashSet_##_capacity(const HashSet_* self) { \ + return CWISS_RawTable_capacity(&kPolicy_, &self->set_); \ + } \ + \ + static inline SDB_MAYBE_UNUSED void HashSet_##_clear(HashSet_* self) { \ + CWISS_RawTable_clear(&kPolicy_, &self->set_); \ + } \ + \ + typedef struct { \ + HashSet_##_Iter iter; \ + bool inserted; \ + } HashSet_##_Insert; \ + static inline SDB_MAYBE_UNUSED HashSet_##_Insert HashSet_##_deferred_insert( \ + HashSet_* self, const Key_* key) { \ + CWISS_Insert ret = CWISS_RawTable_deferred_insert(&kPolicy_, kPolicy_.key, \ + &self->set_, key); \ + return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ + } \ + static inline SDB_MAYBE_UNUSED HashSet_##_Insert HashSet_##_insert(HashSet_* self, \ + const Type_* val) { \ + CWISS_Insert ret = CWISS_RawTable_insert(&kPolicy_, &self->set_, val); \ + return (HashSet_##_Insert){{ret.iter}, ret.inserted}; \ + } \ + \ + static inline SDB_MAYBE_UNUSED HashSet_##_CIter HashSet_##_cfind_hinted( \ + const HashSet_* self, const Key_* key, size_t hash) { \ + return (HashSet_##_CIter){CWISS_RawTable_find_hinted( \ + &kPolicy_, kPolicy_.key, &self->set_, key, hash)}; \ + } \ + static inline SDB_MAYBE_UNUSED HashSet_##_Iter HashSet_##_find_hinted( \ + HashSet_* self, const Key_* key, size_t hash) { \ + return (HashSet_##_Iter){CWISS_RawTable_find_hinted( \ + &kPolicy_, kPolicy_.key, &self->set_, key, hash)}; \ + } \ + static inline SDB_MAYBE_UNUSED HashSet_##_CIter HashSet_##_cfind(const HashSet_* self, \ + const Key_* key) { \ + return (HashSet_##_CIter){ \ + CWISS_RawTable_find(&kPolicy_, kPolicy_.key, &self->set_, key)}; \ + } \ + static inline SDB_MAYBE_UNUSED HashSet_##_Iter HashSet_##_find(HashSet_* self, \ + const Key_* key) { \ + return (HashSet_##_Iter){ \ + CWISS_RawTable_find(&kPolicy_, kPolicy_.key, &self->set_, key)}; \ + } \ + \ + static inline bool SDB_MAYBE_UNUSED HashSet_##_contains(const HashSet_* self, \ + const Key_* key) { \ + return CWISS_RawTable_contains(&kPolicy_, kPolicy_.key, &self->set_, key); \ + } \ + \ + static inline void SDB_MAYBE_UNUSED HashSet_##_erase_at(HashSet_##_Iter it) { \ + CWISS_RawTable_erase_at(&kPolicy_, it.it_); \ + } \ + static inline bool SDB_MAYBE_UNUSED HashSet_##_erase(HashSet_* self, const Key_* key) { \ + return CWISS_RawTable_erase(&kPolicy_, kPolicy_.key, &self->set_, key); \ + } \ + \ + CWISS_END \ + /* Force a semicolon. */ struct HashSet_##_NeedsTrailingSemicolon_ { int x; } CWISS_END_EXTERN CWISS_END diff --git a/shlr/sdb/include/sdb/ht_pu.h b/shlr/sdb/include/sdb/ht_pu.h index 28e0def3c3..0e2d80c444 100644 --- a/shlr/sdb/include/sdb/ht_pu.h +++ b/shlr/sdb/include/sdb/ht_pu.h @@ -2,18 +2,31 @@ #define SDB_HT_PU_H /* - * This header provides an hashtable HtPU that has void* as key and ut64 as - * value. The API functions starts with "ht_pu_" and the types starts with "HtPU". + * This header provides a hashtable HtPU that has void* as key and ut64 as + * value. The hashtable does not take ownership of the keys, and so will not + * free the pointers once they are removed from the hashtable. */ -#define HT_TYPE 4 -#include "ht_inc.h" + +#include "sdb/types.h" #ifdef __cplusplus extern "C" { #endif -SDB_API HtName_(Ht)* Ht_(new0)(void); -#undef HT_TYPE +typedef uint64_t ut64; + +typedef struct HtPU_t HtPU; + +typedef bool (*HtPUForEachCallback)(void *user, const void *key, const ut64 value); + +SDB_API HtPU* ht_pu_new0(void); +SDB_API void ht_pu_free(HtPU *hm); +SDB_API bool ht_pu_insert(HtPU *hm, void *key, ut64 value); +SDB_API bool ht_pu_update(HtPU *hm, void *key, ut64 value); +SDB_API bool ht_pu_update_key(HtPU *hm, void *old_key, void *new_key); +SDB_API bool ht_pu_delete(HtPU *hm, void *key); +SDB_API ut64 ht_pu_find(HtPU *hm, void *key, bool* found); +SDB_API void ht_pu_foreach(HtPU *hm, HtPUForEachCallback cb, void *user); #ifdef __cplusplus } diff --git a/shlr/sdb/include/sdb/ht_su.h b/shlr/sdb/include/sdb/ht_su.h new file mode 100644 index 0000000000..7f02fe34d1 --- /dev/null +++ b/shlr/sdb/include/sdb/ht_su.h @@ -0,0 +1,36 @@ +#ifndef SDB_HT_SU_H +#define SDB_HT_SU_H + +/* + * This header provides a hashtable HtSU that has char* as key and ut64 as + * value (a "stringmap"). The hashtable takes ownership of the keys by making a + * copy of the key, and will free the pointers once they are removed from the + * hashtable. + */ + +#include "sdb/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef uint64_t ut64; + +typedef struct HtSU_t HtSU; + +typedef bool (*HtSUForEachCallback)(void *user, const char *key, const ut64 value); + +SDB_API HtSU* ht_su_new0(void); +SDB_API void ht_su_free(HtSU *hm); +SDB_API bool ht_su_insert(HtSU *hm, const char *key, ut64 value); +SDB_API bool ht_su_update(HtSU *hm, const char *key, ut64 value); +SDB_API bool ht_su_update_key(HtSU *hm, const char *old_key, const char *new_key); +SDB_API bool ht_su_delete(HtSU *hm, const char *key); +SDB_API ut64 ht_su_find(HtSU *hm, const char *key, bool* found); +SDB_API void ht_su_foreach(HtSU *hm, HtSUForEachCallback cb, void *user); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/shlr/sdb/include/sdb/ht_uu.h b/shlr/sdb/include/sdb/ht_uu.h index c27facc5e4..cf5f5153cd 100644 --- a/shlr/sdb/include/sdb/ht_uu.h +++ b/shlr/sdb/include/sdb/ht_uu.h @@ -2,19 +2,26 @@ #define SDB_HT_UU_H_ /* - * This header provides an hashtable Ht that has ut64 as key and ut64 as - * value. The API functions starts with "ht_" and the types starts with "Ht". + * This header provides a hashtable Ht that has ut64 as key and ut64 as value. */ -#undef HT_TYPE -#define HT_TYPE 3 -#include "ht_inc.h" -#include "ht.h" + +#include "sdb/types.h" #ifdef __cplusplus extern "C" { #endif -SDB_API HtName_(Ht)* Ht_(new0)(void); +typedef struct HtUU_t HtUU; +typedef bool (*HtUUForEachCallback)(void *user, const ut64 key, const ut64 value); + +SDB_API HtUU* ht_uu_new0(void); +SDB_API void ht_uu_free(HtUU *hm); +SDB_API bool ht_uu_insert(HtUU *hm, const ut64 key, ut64 value); +SDB_API bool ht_uu_update(HtUU *hm, const ut64 key, ut64 value); +SDB_API bool ht_uu_update_key(HtUU *hm, const ut64 old_key, const ut64 new_key); +SDB_API bool ht_uu_delete(HtUU *hm, const ut64 key); +SDB_API ut64 ht_uu_find(HtUU *hm, const ut64 key, bool* found); +SDB_API void ht_uu_foreach(HtUU *hm, HtUUForEachCallback cb, void *user); #ifdef __cplusplus } diff --git a/shlr/sdb/meson.build b/shlr/sdb/meson.build index 422ab6d17c..99f6abb506 100644 --- a/shlr/sdb/meson.build +++ b/shlr/sdb/meson.build @@ -58,6 +58,7 @@ libsdb_sources = [ 'src/ht_up.c', 'src/ht_pp.c', 'src/ht_pu.c', + 'src/ht_su.c', 'src/journal.c', 'src/json.c', 'src/lock.c', @@ -112,7 +113,8 @@ if not meson.is_subproject() 'include/sdb/ht_pp.h', 'include/sdb/ht_up.h', 'include/sdb/ht_uu.h', - 'include/sdb/ht_up.h', + 'include/sdb/ht_pu.h', + 'include/sdb/ht_su.h', 'include/sdb/ls.h', 'include/sdb/sdb.h', 'include/sdb/ht.h', diff --git a/shlr/sdb/src/Makefile b/shlr/sdb/src/Makefile index a87c0f9981..eb5f30995f 100644 --- a/shlr/sdb/src/Makefile +++ b/shlr/sdb/src/Makefile @@ -3,7 +3,7 @@ include ../config.mk # CFLAGS:=-g $(CFLAGS) OBJ=cdb.o buffer.o cdb_make.o ls.o ht.o ht_uu.o sdb.o num.o base64.o match.o OBJ+=json.o ns.o lock.o util.o disk.o query.o array.o fmt.o journal.o text.o -OBJ+=dict.o ht_pp.o ht_up.o ht_pu.o set.o diff.o heap.o main.o +OBJ+=dict.o ht_pp.o ht_up.o ht_pu.o ht_su.o set.o diff.o heap.o main.o SDB_CFLAGS+=-I../include SDB_CXXFLAGS+=-I../include SOBJ=$(subst .o,.o.o,${OBJ}) diff --git a/shlr/sdb/src/ht_pu.c b/shlr/sdb/src/ht_pu.c index 5e00526c46..6ffffab25d 100644 --- a/shlr/sdb/src/ht_pu.c +++ b/shlr/sdb/src/ht_pu.c @@ -1,24 +1,108 @@ -/* sdb - MIT - Copyright 2018-2022 - ret2libc, pancake */ +/* sdb - MIT - Copyright 2018-2023 - ret2libc, pancake, luc-tielen */ -#include "sdb/sdb.h" +#include <stdint.h> #include "sdb/ht_pu.h" -#include "ht.inc.c" - -static void free_kv_key(HT_(Kv) *kv) { - sdb_gh_free (kv->key); -} - -// creates a default HtPU that has strings as keys -SDB_API HtName_(Ht)* Ht_(new0)(void) { - HT_(Options) opt = { - .cmp = (HT_(ListComparator))strcmp, - .hashfn = (HT_(HashFunction))sdb_hash, - .dupkey = (HT_(DupKey))sdb_strdup, - .dupvalue = NULL, - .calcsizeK = (HT_(CalcSizeK))strlen, - .calcsizeV = NULL, - .freefn = free_kv_key, - .elem_size = sizeof (HT_(Kv)), - }; - return Ht_(new_opt) (&opt); +#include "sdb/heap.h" +#include "sdb/cwisstable.h" + +CWISS_DECLARE_FLAT_HASHMAP_DEFAULT(HtPU_, void*, ut64); + +struct HtPU_t { + HtPU_ inner; +}; + +SDB_API HtPU* ht_pu_new0(void) { + HtPU *hm = (HtPU*) sdb_gh_calloc (1, sizeof (HtPU)); + if (hm) { + hm->inner = HtPU__new (0); + } + return hm; +} + +SDB_API void ht_pu_free(HtPU *hm) { + if (hm) { + HtPU__destroy (&hm->inner); + sdb_gh_free (hm); + } +} + +SDB_API bool ht_pu_insert(HtPU *hm, void *key, ut64 value) { + assert (hm); + + HtPU__Entry entry = { .key = key, .val = value }; + HtPU__Insert result = HtPU__insert (&hm->inner, &entry); + return result.inserted; +} + +SDB_API bool ht_pu_update(HtPU *hm, void *key, ut64 value) { + assert (hm); + + HtPU__Entry entry = { .key = key, .val = value }; + HtPU__Insert insert_result = HtPU__insert (&hm->inner, &entry); + const bool should_update = !insert_result.inserted; + if (should_update) { + HtPU__Entry *existing_entry = HtPU__Iter_get (&insert_result.iter); + existing_entry->val = value; + } + + return true; +} + +// Update the key of an element in the hashtable +SDB_API bool ht_pu_update_key(HtPU *hm, void *old_key, void *new_key) { + assert (hm); + + HtPU__Iter iter = HtPU__find (&hm->inner, &old_key); + HtPU__Entry *entry = HtPU__Iter_get (&iter); + if (!entry) { + return false; + } + + // First try inserting the new key + HtPU__Entry new_entry = { .key = new_key, .val = entry->val }; + HtPU__Insert result = HtPU__insert (&hm->inner, &new_entry); + if (!result.inserted) { + return false; + } + + // Then remove entry for the old key + HtPU__erase_at (iter); + return true; +} + +SDB_API bool ht_pu_delete(HtPU *hm, void *key) { + assert (hm); + return HtPU__erase (&hm->inner, &key); +} + +SDB_API ut64 ht_pu_find(HtPU *hm, void *key, bool* found) { + assert (hm); + if (found) { + *found = false; + } + + HtPU__Iter iter = HtPU__find (&hm->inner, &key); + HtPU__Entry *entry = HtPU__Iter_get (&iter); + if (!entry) { + return 0; + } + + if (found) { + *found = true; + } + return entry->val; +} + +// Iterates over all elements in the hashtable, calling the cb function on each Kv. +// If the cb returns false, the iteration is stopped. +// cb should not modify the hashtable. +SDB_API void ht_pu_foreach(HtPU *hm, HtPUForEachCallback cb, void *user) { + assert (hm); + HtPU__CIter iter; + const HtPU__Entry *entry; + for (iter = HtPU__citer (&hm->inner); (entry = HtPU__CIter_get (&iter)) != NULL; HtPU__CIter_next (&iter)) { + if (!cb (user, entry->key, entry->val)) { + return; + } + } } diff --git a/shlr/sdb/src/ht_su.c b/shlr/sdb/src/ht_su.c new file mode 100644 index 0000000000..0bdbec0a08 --- /dev/null +++ b/shlr/sdb/src/ht_su.c @@ -0,0 +1,171 @@ +/* sdb - MIT - Copyright 2018-2023 - ret2libc, pancake, luc-tielen */ + +#include <stdint.h> +#include "sdb/ht_su.h" +#include "sdb/heap.h" +#include "sdb/sdb.h" +#include "sdb/cwisstable.h" + +static inline void string_copy(void *dst, const void *src); +static inline void string_dtor(void *val); +static inline size_t string_hash(const void *val); +static inline bool string_eq(const void *a, const void *b); + +CWISS_DECLARE_FLAT_HASHMAP(HtSU_, char*, ut64, string_copy, string_dtor, string_hash, string_eq); + +struct HtSU_t { + HtSU_ inner; +}; + +static inline void string_copy(void *dst_, const void *src_) { + const HtSU__Entry *src = (const HtSU__Entry *) src_; + HtSU__Entry *dst = (HtSU__Entry *) dst_; + + const size_t len = strlen (src->key); + dst->key = (char*) sdb_gh_malloc (len + 1); + dst->val = src->val; + memcpy (dst->key, src->key, len + 1); +} + +static inline void string_dtor(void *val) { + char *str = *(char**)val; + sdb_gh_free (str); +} + +static inline size_t string_hash(const void *val) { + const char *str = *(const char *const *)val; + const size_t len = strlen (str); + CWISS_FxHash_State state = 0; + CWISS_FxHash_Write (&state, str, len); + return state; +} + +static inline bool string_eq(const void *a, const void *b) { + const char *ap = *(const char* const *)a; + const char *bp = *(const char* const *)b; + return strcmp (ap, bp) == 0; +} + +SDB_API HtSU* ht_su_new0(void) { + HtSU *hm = (HtSU*) sdb_gh_calloc (1, sizeof (HtSU)); + if (hm) { + hm->inner = HtSU__new (0); + } + return hm; +} + +SDB_API void ht_su_free(HtSU *hm) { + if (hm) { + HtSU__destroy (&hm->inner); + sdb_gh_free (hm); + } +} + +SDB_API bool ht_su_insert(HtSU *hm, const char *key, ut64 value) { + assert (hm && key); + + char *key_copy = sdb_strdup (key); + if (!key_copy) { + return false; + } + + HtSU__Entry entry = { .key = key_copy, .val = value }; + HtSU__Insert result = HtSU__insert (&hm->inner, &entry); + if (!result.inserted) { + sdb_gh_free (key_copy); + return false; + } + return true; +} + +SDB_API bool ht_su_update(HtSU *hm, const char *key, ut64 value) { + assert (hm && key); + + char *key_copy = sdb_strdup (key); + if (!key_copy) { + return false; + } + + HtSU__Entry entry = { .key = key_copy, .val = value }; + HtSU__Insert insert_result = HtSU__insert (&hm->inner, &entry); + if (!insert_result.inserted) { + sdb_gh_free (key_copy); + + HtSU__Entry *existing_entry = HtSU__Iter_get (&insert_result.iter); + existing_entry->val = value; + } + + return true; +} + +// Update the key of an element in the hashtable +SDB_API bool ht_su_update_key(HtSU *hm, const char *old_key, const char *new_key) { + assert (hm && old_key && new_key); + + HtSU__Iter iter = HtSU__find (&hm->inner, (const HtSU__Key*) &old_key); + HtSU__Entry *entry = HtSU__Iter_get (&iter); + if (!entry) { + return false; + } + + // Do nothing if keys are the same + if (SDB_UNLIKELY (strcmp (old_key, new_key) == 0)) { + return true; + } + + char *key_copy = sdb_strdup (new_key); + if (!key_copy) { + return false; + } + + // First try inserting the new key + HtSU__Entry new_entry = { .key = key_copy, .val = entry->val }; + HtSU__Insert result = HtSU__insert (&hm->inner, &new_entry); + if (!result.inserted) { + sdb_gh_free (key_copy); + return false; + } + + // Then remove entry for the old key + HtSU__erase_at (iter); + return true; +} + +SDB_API bool ht_su_delete(HtSU *hm, const char *key) { + assert (hm && key); + return HtSU__erase (&hm->inner, (const HtSU__Key*) &key); +} + +SDB_API ut64 ht_su_find(HtSU *hm, const char *key, bool* found) { + assert (hm && key); + + if (found) { + *found = false; + } + + HtSU__Iter iter = HtSU__find (&hm->inner, (const HtSU__Key*) &key); + HtSU__Entry *entry = HtSU__Iter_get (&iter); + if (!entry) { + return 0; + } + + if (found) { + *found = true; + } + return entry->val; +} + +// Iterates over all elements in the hashtable, calling the cb function on each Kv. +// If the cb returns false, the iteration is stopped. +// cb should not modify the hashtable. +SDB_API void ht_su_foreach(HtSU *hm, HtSUForEachCallback cb, void *user) { + assert (hm); + HtSU__CIter iter; + const HtSU__Entry *entry; + + for (iter = HtSU__citer (&hm->inner); (entry = HtSU__CIter_get (&iter)) != NULL; HtSU__CIter_next (&iter)) { + if (!cb (user, entry->key, entry->val)) { + return; + } + } +} diff --git a/shlr/sdb/src/ht_uu.c b/shlr/sdb/src/ht_uu.c index b5851e8920..230814d91e 100644 --- a/shlr/sdb/src/ht_uu.c +++ b/shlr/sdb/src/ht_uu.c @@ -1,19 +1,110 @@ -/* sdb - MIT - Copyright 2018-2022 - ret2libc, pancake */ +/* sdb - MIT - Copyright 2018-2023 - ret2libc, pancake, luc-tielen */ -#include "sdb/sdb.h" +#include <stdint.h> #include "sdb/ht_uu.h" -#include "ht.inc.c" - -// creates a default HtUU that has strings as keys -SDB_API HtName_(Ht)* Ht_(new0)(void) { - HT_(Options) opt = { - .cmp = NULL, - .hashfn = NULL, - .dupkey = NULL, - .dupvalue = NULL, - .calcsizeK = NULL, - .calcsizeV = NULL, - .freefn = NULL - }; - return Ht_(new_opt) (&opt); +#include "sdb/heap.h" +#include "sdb/cwisstable.h" + +typedef uint64_t ut64; + +CWISS_DECLARE_FLAT_HASHMAP_DEFAULT(HtUU_, ut64, ut64); + +struct HtUU_t { + HtUU_ inner; +}; + +SDB_API HtUU* ht_uu_new0(void) { + HtUU *hm = (HtUU*) sdb_gh_calloc (1, sizeof (HtUU)); + if (hm) { + hm->inner = HtUU__new (0); + } + return hm; +} + +SDB_API void ht_uu_free(HtUU *hm) { + if (hm) { + HtUU__destroy (&hm->inner); + sdb_gh_free (hm); + } +} + +SDB_API bool ht_uu_insert(HtUU *hm, const ut64 key, ut64 value) { + assert (hm); + + HtUU__Entry entry = { .key = key, .val = value }; + HtUU__Insert result = HtUU__insert (&hm->inner, &entry); + return result.inserted; +} + +SDB_API bool ht_uu_update(HtUU *hm, const ut64 key, ut64 value) { + assert (hm); + + HtUU__Entry entry = { .key = key, .val = value }; + HtUU__Insert insert_result = HtUU__insert (&hm->inner, &entry); + const bool should_update = !insert_result.inserted; + if (should_update) { + HtUU__Entry *existing_entry = HtUU__Iter_get (&insert_result.iter); + existing_entry->val = value; + } + + return true; +} + +// Update the key of an element in the hashtable +SDB_API bool ht_uu_update_key(HtUU *hm, const ut64 old_key, const ut64 new_key) { + assert (hm); + + HtUU__Iter iter = HtUU__find (&hm->inner, &old_key); + HtUU__Entry *entry = HtUU__Iter_get (&iter); + if (!entry) { + return false; + } + + // First try inserting the new key + HtUU__Entry new_entry = { .key = new_key, .val = entry->val }; + HtUU__Insert result = HtUU__insert (&hm->inner, &new_entry); + if (!result.inserted) { + return false; + } + + // Then remove entry for the old key + HtUU__erase_at (iter); + return true; +} + +SDB_API bool ht_uu_delete(HtUU *hm, const ut64 key) { + assert (hm); + return HtUU__erase (&hm->inner, &key); +} + +SDB_API ut64 ht_uu_find(HtUU *hm, const ut64 key, bool* found) { + assert (hm); + if (found) { + *found = false; + } + + HtUU__Iter iter = HtUU__find (&hm->inner, &key); + HtUU__Entry *entry = HtUU__Iter_get (&iter); + if (!entry) { + return 0; + } + + if (found) { + *found = true; + } + return entry->val; +} + +// Iterates over all elements in the hashtable, calling the cb function on each Kv. +// If the cb returns false, the iteration is stopped. +// cb should not modify the hashtable. +SDB_API void ht_uu_foreach(HtUU *hm, HtUUForEachCallback cb, void *user) { + assert (hm); + HtUU__CIter iter; + const HtUU__Entry *entry; + for (iter = HtUU__citer (&hm->inner); (entry = HtUU__CIter_get (&iter)) != NULL; HtUU__CIter_next (&iter)) { + if (!cb (user, entry->key, entry->val)) { + return; + } + } }
3rdn4/radare2:9650e3c-use_after_free
/workspace/skyset/
radare2
9650e3c-use_after_free
/workspace/skyset/radare2/9650e3c-use_after_free/report.txt
A use after free found in /workspace/skyset/radare2/9650e3c-use_after_free/immutable/
diff --git a/libr/bin/format/pyc/marshal.c b/libr/bin/format/pyc/marshal.c index 4245a17824..728bf73701 100644 --- a/libr/bin/format/pyc/marshal.c +++ b/libr/bin/format/pyc/marshal.c @@ -1098,7 +1098,7 @@ static pyc_object *get_object(RBuffer *buffer) { break; case TYPE_UNKNOWN: eprintf ("Get not implemented for type 0x%x\n", type); - r_list_pop (refs); + // r_list_pop (refs); free_object (ret); return NULL; case 0:
3rdn4/radare2:9bcc98f-heap_out_of_bound
/workspace/skyset/
radare2
9bcc98f-heap_out_of_bound
/workspace/skyset/radare2/9bcc98f-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/9bcc98f-heap_out_of_bound/immutable/
diff --git a/libr/bin/p/bin_symbols.c b/libr/bin/p/bin_symbols.c index 2036dc092b..779e36940f 100644 --- a/libr/bin/p/bin_symbols.c +++ b/libr/bin/p/bin_symbols.c @@ -181,7 +181,7 @@ static RBinSymbol *bin_symbol_from_symbol(RCoreSymCacheElement *element, RCoreSy static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) { D eprintf ("Dragons at 0x%x\n", off); - ut64 size = r_buf_size (buf); + st64 size = r_buf_size (buf); if (off >= size) { return NULL; } @@ -189,6 +189,9 @@ static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, i if (!size) { return NULL; } + if (size < 32) { + return NULL; + } ut8 *b = malloc (size); if (!b) { return NULL;
3rdn4/radare2:a16cb20-heap_out_of_bound
/workspace/skyset/
radare2
a16cb20-heap_out_of_bound
/workspace/skyset/radare2/a16cb20-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/a16cb20-heap_out_of_bound/immutable/
diff --git a/libr/anal/p/anal_msp430.c b/libr/anal/p/anal_msp430.c index fbb51828a4..d8298db578 100644 --- a/libr/anal/p/anal_msp430.c +++ b/libr/anal/p/anal_msp430.c @@ -10,17 +10,13 @@ #include "../arch/msp430/msp430_disas.h" static int msp430_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, RAnalOpMask mask) { - int ret; - struct msp430_cmd cmd; - - memset (&cmd, 0, sizeof (cmd)); - //op->id = ???; + struct msp430_cmd cmd = {0}; op->size = -1; op->nopcode = 1; op->type = R_ANAL_OP_TYPE_UNK; op->family = R_ANAL_OP_FAMILY_CPU; - ret = op->size = msp430_decode_command (buf, len, &cmd); + int ret = op->size = msp430_decode_command (buf, len, &cmd); if (mask & R_ANAL_OP_MASK_DISASM) { if (ret < 1) { op->mnemonic = strdup ("invalid"); @@ -59,7 +55,9 @@ static int msp430_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int le case MSP430_CALL: op->type = R_ANAL_OP_TYPE_CALL; op->fail = addr + op->size; - op->jump = r_read_at_le16 (buf, 2); + if (len > 4) { + op->jump = r_read_at_le16 (buf, 2); + } break; case MSP430_RETI: op->type = R_ANAL_OP_TYPE_RET; @@ -111,6 +109,7 @@ static bool set_reg_profile(RAnal *anal) { const char *p = \ "=PC pc\n" "=SP sp\n" + "=SN r0\n" // this is the "new" ABI, the old was reverse order "=A0 r12\n" "=A1 r13\n" diff --git a/libr/bin/format/elf/elf.c b/libr/bin/format/elf/elf.c index 9239d59e45..40f6566d49 100644 --- a/libr/bin/format/elf/elf.c +++ b/libr/bin/format/elf/elf.c @@ -124,7 +124,7 @@ static bool init_ehdr(ELFOBJ *bin) { ut8 ehdr[sizeof (Elf_(Ehdr))] = {0}; int i, len; if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) { - R_LOG_ERROR ("read (magic)"); + R_LOG_DEBUG ("read (magic)"); return false; } sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1," @@ -188,7 +188,7 @@ static bool init_ehdr(ELFOBJ *bin) { memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr))); len = r_buf_read_at (bin->b, 0, ehdr, sizeof (ehdr)); if (len < 32) { // tinyelf != sizeof (Elf_(Ehdr))) { - R_LOG_ERROR ("read (ehdr)"); + R_LOG_DEBUG ("read (ehdr)"); return false; } // XXX no need to check twice @@ -257,7 +257,7 @@ static bool read_phdr(ELFOBJ *bin, bool linux_kernel_hack) { const size_t rsize = bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)); int len = r_buf_read_at (bin->b, rsize, phdr, sizeof (Elf_(Phdr))); if (len < 1) { - R_LOG_ERROR ("read (phdr)"); + R_LOG_DEBUG ("read (phdr)"); R_FREE (bin->phdr); return false; } @@ -397,7 +397,7 @@ static int init_shdr(ELFOBJ *bin) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr))); if (len < 1) { - R_LOG_ERROR ("read (shdr) at 0x%" PFMT64x, (ut64) bin->ehdr.e_shoff); + R_LOG_DEBUG ("read (shdr) at 0x%" PFMT64x, (ut64) bin->ehdr.e_shoff); R_FREE (bin->shdr); return false; } @@ -475,7 +475,7 @@ static int init_strtab(ELFOBJ *bin) { int res = r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab, bin->shstrtab_section->sh_size); if (res < 1) { - R_LOG_ERROR ("read (shstrtab) at 0x%" PFMT64x, (ut64) bin->shstrtab_section->sh_offset); + R_LOG_DEBUG ("read (shstrtab) at 0x%" PFMT64x, (ut64) bin->shstrtab_section->sh_offset); R_FREE (bin->shstrtab); return false; } @@ -970,7 +970,7 @@ static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) } Elf_(Verdef) *defs = calloc (shdr->sh_size, 1); if (!defs) { - R_LOG_ERROR ("Cannot allocate memory (Check Elf_(Verdef))"); + R_LOG_DEBUG ("Cannot allocate memory (Check Elf_(Verdef))"); return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { @@ -1798,7 +1798,7 @@ ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) { return UT64_MAX; } if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) { - R_LOG_ERROR ("read (init_offset)"); + R_LOG_DEBUG ("read (init_offset)"); return 0; } if (buf[0] == 0x68) { // push // x86 only
3rdn4/radare2:a58b8d4-heap_out_of_bound
/workspace/skyset/
radare2
a58b8d4-heap_out_of_bound
/workspace/skyset/radare2/a58b8d4-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/a58b8d4-heap_out_of_bound/immutable/
diff --git a/libr/bin/format/mach0/coresymbolication.c b/libr/bin/format/mach0/coresymbolication.c index f350199550..f554898c94 100644 --- a/libr/bin/format/mach0/coresymbolication.c +++ b/libr/bin/format/mach0/coresymbolication.c @@ -274,12 +274,12 @@ RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut sect->vaddr += page_zero_size; } cursor += word_size; - if (cursor >= end) { + if (cursor + word_size >= end) { break; } sect->size = r_read_ble (cursor, false, bits); cursor += word_size; - if (cursor >= end) { + if (cursor + word_size >= end) { break; } ut64 sect_name_off = r_read_ble (cursor, false, bits); @@ -291,7 +291,11 @@ RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut cursor += word_size; } string_origin = relative_to_strings? b + start_of_strings : sect_start; - sect->name = str_dup_safe (b, string_origin + (size_t)sect_name_off, end); + if (sect_name_off < (ut64)(size_t)(end - string_origin)) { + sect->name = str_dup_safe (b, string_origin + sect_name_off, end); + } else { + sect->name = strdup (""); + } } } if (hdr->n_symbols) {
3rdn4/radare2:cf780fd-use_after_free
/workspace/skyset/
radare2
cf780fd-use_after_free
/workspace/skyset/radare2/cf780fd-use_after_free/report.txt
A use after free found in /workspace/skyset/radare2/cf780fd-use_after_free/immutable/
diff --git a/libr/core/canal.c b/libr/core/canal.c index 9b4ded95c1..408f3bc0b7 100644 --- a/libr/core/canal.c +++ b/libr/core/canal.c @@ -5188,11 +5188,12 @@ R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) { r_core_cmd0 (core, "aeim"); ESIL = core->anal->esil; } - const char *spname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP); - if (!spname) { + const char *kspname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP); + if (R_STR_ISEMPTY (kspname)) { eprintf ("Error: No =SP defined in the reg profile.\n"); return; } + char *spname = strdup (kspname); EsilBreakCtx ctx = { &op, fcn, @@ -5210,11 +5211,12 @@ R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) { } //eprintf ("Analyzing ESIL refs from 0x%"PFMT64x" - 0x%"PFMT64x"\n", addr, end); // TODO: backup/restore register state before/after analysis - pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC); - if (!pcname || !*pcname) { + const char *kpcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC); + if (!kpcname || !*kpcname) { eprintf ("Cannot find program counter register in the current profile.\n"); return; } + pcname = strdup (kpcname); esil_anal_stop = false; r_cons_break_push (cccb, core); @@ -5544,6 +5544,8 @@ repeat: break; } } while (get_next_i (&ictx, &i)); + free (pcname); + free (spname); r_list_free (ictx.bbl); r_list_free (ictx.path); r_list_free (ictx.switch_path);
3rdn4/radare2:d026503-heap_out_of_bound
/workspace/skyset/
radare2
d026503-heap_out_of_bound
/workspace/skyset/radare2/d026503-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/d026503-heap_out_of_bound/immutable/
diff --git a/shlr/java/code.c b/shlr/java/code.c index 97347eb8d1..efafecf8c9 100644 --- a/shlr/java/code.c +++ b/shlr/java/code.c @@ -206,9 +206,9 @@ R_API int java_print_opcode(RBinJavaObj *obj, ut64 addr, int idx, const ut8 *byt case 0xa6: // if_acmpne case 0xa7: // goto case 0xa8: // jsr - if (len > 1) { - snprintf (output, outlen, "%s 0x%04"PFMT64x, JAVA_OPS[idx].name, - (addr + (short)USHORT (bytes, 1))); + if (len > 3) { + const short delta = USHORT (bytes, 1); + snprintf (output, outlen, "%s 0x%04"PFMT64x, JAVA_OPS[idx].name, addr + delta); output[outlen - 1] = 0; return update_bytes_consumed (JAVA_OPS[idx].size); }
3rdn4/radare2:d17a7bd-use_after_free
/workspace/skyset/
radare2
d17a7bd-use_after_free
/workspace/skyset/radare2/d17a7bd-use_after_free/report.txt
A use after free found in /workspace/skyset/radare2/d17a7bd-use_after_free/immutable/
diff --git a/libr/bin/format/pyc/marshal.c b/libr/bin/format/pyc/marshal.c index 728bf73701..16f297198d 100644 --- a/libr/bin/format/pyc/marshal.c +++ b/libr/bin/format/pyc/marshal.c @@ -1,4 +1,4 @@ -/* radare - LGPL3 - Copyright 2016-2021 - Matthieu (c0riolis) Tardy - l0stb1t*/ +/* radare - LGPL3 - Copyright 2016-2022 - Matthieu (c0riolis) Tardy - l0stb1t */ #include <r_io.h> #include <r_bin.h> @@ -9,9 +9,9 @@ #define if_true_return(cond,ret) if(cond){return(ret);} // TODO: kill globals -static ut32 magic_int; -static ut32 symbols_ordinal = 0; -static RList *refs = NULL; // If you don't have a good reason, do not change this. And also checkout !refs in get_code_object() +static R_TH_LOCAL ut32 magic_int; +static R_TH_LOCAL ut32 symbols_ordinal = 0; +static R_TH_LOCAL RList *refs = NULL; // If you don't have a good reason, do not change this. And also checkout !refs in get_code_object() /* interned_table is used to handle TYPE_INTERNED object */ extern RList *interned_table; @@ -500,13 +500,9 @@ static pyc_object *get_array_object_generic(RBuffer *buffer, ut32 size) { } for (i = 0; i < size; i++) { tmp = get_object (buffer); - if (!tmp) { - r_list_free (ret->data); - R_FREE (ret); - return NULL; - } - if (!r_list_append (ret->data, tmp)) { + if (!tmp || !r_list_append (ret->data, tmp)) { free_object (tmp); + ((RList*)ret->data)->free = NULL; r_list_free (ret->data); free (ret); return NULL; @@ -516,7 +512,6 @@ static pyc_object *get_array_object_generic(RBuffer *buffer, ut32 size) { } /* small TYPE_SMALL_TUPLE doesn't exist in python2 */ -/* */ static pyc_object *get_small_tuple_object(RBuffer *buffer) { pyc_object *ret = NULL; bool error = false; @@ -535,11 +530,8 @@ static pyc_object *get_small_tuple_object(RBuffer *buffer) { } static pyc_object *get_tuple_object(RBuffer *buffer) { - pyc_object *ret = NULL; bool error = false; - ut32 n = 0; - - n = get_ut32 (buffer, &error); + ut32 n = get_ut32 (buffer, &error); if (n > ST32_MAX) { eprintf ("bad marshal data (tuple size out of range)\n"); return NULL; @@ -547,20 +539,17 @@ static pyc_object *get_tuple_object(RBuffer *buffer) { if (error) { return NULL; } - ret = get_array_object_generic (buffer, n); + pyc_object *ret = get_array_object_generic (buffer, n); if (ret) { ret->type = TYPE_TUPLE; - return ret; } - return NULL; + return ret; } static pyc_object *get_list_object(RBuffer *buffer) { pyc_object *ret = NULL; bool error = false; - ut32 n = 0; - - n = get_ut32 (buffer, &error); + ut32 n = get_ut32 (buffer, &error); if (n > ST32_MAX) { eprintf ("bad marshal data (list size out of range)\n"); return NULL; @@ -616,7 +605,6 @@ static pyc_object *get_dict_object(RBuffer *buffer) { } static pyc_object *get_set_object(RBuffer *buffer) { - pyc_object *ret = NULL; bool error = false; ut32 n = get_ut32 (buffer, &error); if (n > ST32_MAX) { @@ -626,11 +614,10 @@ static pyc_object *get_set_object(RBuffer *buffer) { if (error) { return NULL; } - ret = get_array_object_generic (buffer, n); - if (!ret) { - return NULL; + pyc_object *ret = get_array_object_generic (buffer, n); + if (ret) { + ret->type = TYPE_SET; } - ret->type = TYPE_SET; return ret; }
3rdn4/radare2:d22d160-use_after_free
/workspace/skyset/
radare2
d22d160-use_after_free
/workspace/skyset/radare2/d22d160-use_after_free/report.txt
A use after free found in /workspace/skyset/radare2/d22d160-use_after_free/immutable/
diff --git a/libr/anal/fcn.c b/libr/anal/fcn.c index 9780d01046..d159e1ae36 100644 --- a/libr/anal/fcn.c +++ b/libr/anal/fcn.c @@ -815,7 +815,7 @@ repeat: // note, we have still increased size of basic block // (and function) if (anal->verbose) { - eprintf("Enter branch delay at 0x%08"PFMT64x ". bb->sz=%"PFMT64u"\n", at - oplen, bb->size); + eprintf ("Enter branch delay at 0x%08"PFMT64x ". bb->sz=%"PFMT64u"\n", at - oplen, bb->size); } delay.idx = idx - oplen; delay.cnt = op->delay; @@ -882,6 +882,12 @@ repeat: // swapped parameters wtf r_anal_xrefs_set (anal, op->addr, op->ptr, R_ANAL_REF_TYPE_DATA); } + if (anal->opt.vars && !varset) { + // XXX uses op.src/dst and fails because regprofile invalidates the regitems + // lets just call this BEFORE retpoline() to avoid such issue + r_anal_extract_vars (anal, fcn, op); + } + // this call may cause regprofile changes which cause ranalop.regitem references to be invalid analyze_retpoline (anal, op); switch (op->type & R_ANAL_OP_TYPE_MASK) { case R_ANAL_OP_TYPE_CMOV: @@ -973,7 +979,7 @@ repeat: fcn->bp_off = fcn->stack - op->src[0]->delta; } if (op->dst && op->dst->reg && op->dst->reg->name && op->ptr > 0 && op->ptr != UT64_MAX) { - free(last_reg_mov_lea_name); + free (last_reg_mov_lea_name); if ((last_reg_mov_lea_name = strdup(op->dst->reg->name))) { last_reg_mov_lea_val = op->ptr; last_is_reg_mov_lea = true; @@ -1404,10 +1410,13 @@ analopfinish: } } } +#if 0 if (anal->opt.vars && !varset) { // XXX uses op.src/dst and fails because regprofile invalidates the regitems + // we must ranalop in here to avoid uaf r_anal_extract_vars (anal, fcn, op); } +#endif if (op->type != R_ANAL_OP_TYPE_MOV && op->type != R_ANAL_OP_TYPE_CMOV && op->type != R_ANAL_OP_TYPE_LEA) { last_is_reg_mov_lea = false; } diff --git a/libr/anal/var.c b/libr/anal/var.c index 87f6a601c3..575e7bb471 100644 --- a/libr/anal/var.c +++ b/libr/anal/var.c @@ -1048,7 +1048,7 @@ static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char free (vartype); } else { st64 frame_off = -(ptr + fcn->bp_off); - if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) { + if (maxstackframe > 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) { goto beach; } RAnalVar *var = get_stack_var (fcn, frame_off);
3rdn4/radare2:eca58ce-heap_out_of_bound
/workspace/skyset/
radare2
eca58ce-heap_out_of_bound
/workspace/skyset/radare2/eca58ce-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/radare2/eca58ce-heap_out_of_bound/immutable/
diff --git a/libr/bin/bfile.c b/libr/bin/bfile.c index 3216e5b761..bb9663fff1 100644 --- a/libr/bin/bfile.c +++ b/libr/bin/bfile.c @@ -178,19 +178,19 @@ static int string_scan_range(RList *list, RBinFile *bf, int min, free (charset); RConsIsBreaked is_breaked = (bin && bin->consb.is_breaked)? bin->consb.is_breaked: NULL; // may oobread - while (needle < to) { + while (needle < to && needle < UT64_MAX - 4) { if (is_breaked && is_breaked ()) { break; } // smol optimization - if (needle + 4 < to) { - ut32 n1 = r_read_le32 (buf + needle - from); + if (needle < to - 4) { + ut32 n1 = r_read_le32 (buf + (needle - from)); if (!n1) { needle += 4; continue; } } - rc = r_utf8_decode (buf + needle - from, to - needle, NULL); + rc = r_utf8_decode (buf + (needle - from), to - needle, NULL); if (!rc) { needle++; continue; @@ -198,7 +198,7 @@ static int string_scan_range(RList *list, RBinFile *bf, int min, bool addr_aligned = !(needle % 4); if (type == R_STRING_TYPE_DETECT) { - char *w = (char *)buf + needle + rc - from; + char *w = (char *)buf + (needle + rc - from); if (((to - needle) > 8 + rc)) { // TODO: support le and be bool is_wide32le = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]); @@ -248,7 +248,7 @@ static int string_scan_range(RList *list, RBinFile *bf, int min, rc = 2; } } else { - rc = r_utf8_decode (buf + needle - from, to - needle, &r); + rc = r_utf8_decode (buf + (needle - from), to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; }
3rdn4/sleuthkit:34f995d-heap_buffer_overflow_a
/workspace/skyset/
sleuthkit
34f995d-heap_buffer_overflow_a
/workspace/skyset/sleuthkit/34f995d-heap_buffer_overflow_a/report.txt
A heap buffer overflow a found in /workspace/skyset/sleuthkit/34f995d-heap_buffer_overflow_a/immutable/
From 243274a82cc506507bc59083d63a0d3b7ced611e Mon Sep 17 00:00:00 2001 From: Brian Carrier <carrier@sleuthkit.org> Date: Thu, 10 Sep 2020 12:44:24 -0400 Subject: [PATCH] Fix bug that uses wrong value --- tsk/fs/ntfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tsk/fs/ntfs.c b/tsk/fs/ntfs.c index 7db5200e06..631fe2ff38 100755 --- a/tsk/fs/ntfs.c +++ b/tsk/fs/ntfs.c @@ -658,7 +658,7 @@ ntfs_make_data_run(NTFS_INFO * ntfs, TSK_OFF_T start_vcn, * An address offset of more than eight bytes will not fit in the * 64-bit addr_offset field (and is likely corrupt) */ - if (NTFS_RUNL_LENSZ(run) > 8) { + if (NTFS_RUNL_OFFSZ(run) > 8) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_INODE_COR); tsk_error_set_errstr
3rdn4/sleuthkit:34f995d-heap_buffer_overflow_b
/workspace/skyset/
sleuthkit
34f995d-heap_buffer_overflow_b
/workspace/skyset/sleuthkit/34f995d-heap_buffer_overflow_b/report.txt
A heap buffer overflow b found in /workspace/skyset/sleuthkit/34f995d-heap_buffer_overflow_b/immutable/
From 4d379cb12e67f5bc690d2e2e4d6ce752c2b41e67 Mon Sep 17 00:00:00 2001 From: Joachim Metz <joachim.metz@gmail.com> Date: Thu, 22 Apr 2021 05:36:18 +0200 Subject: [PATCH] Fixed integer wrap around --- tsk/fs/ntfs.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/tsk/fs/ntfs.c b/tsk/fs/ntfs.c index 631fe2ff38..d225e5c996 100755 --- a/tsk/fs/ntfs.c +++ b/tsk/fs/ntfs.c @@ -375,9 +375,20 @@ ntfs_dinode_lookup(NTFS_INFO * a_ntfs, char *a_buf, TSK_INUM_T a_mftnum) ("dinode_lookup: More Update Sequence Entries than MFT size"); return TSK_COR; } - if (tsk_getu16(fs->endian, mft->upd_off) + - sizeof(ntfs_upd) + - 2*(tsk_getu16(fs->endian, mft->upd_cnt) - 1) > a_ntfs->mft_rsize_b) { + uint16_t upd_cnt = tsk_getu16(fs->endian, mft->upd_cnt); + uint16_t upd_off = tsk_getu16(fs->endian, mft->upd_off); + + // Make sure upd_cnt > 0 to prevent an integer wrap around. + if ((upd_cnt == 0) || (upd_cnt > (((a_ntfs->mft_rsize_b) / 2) + 1))) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_INODE_COR); + tsk_error_set_errstr + ("dinode_lookup: Invalid update count value out of bounds"); + return TSK_COR; + } + size_t mft_rsize_b = ((size_t) upd_cnt - 1) * 2; + + if ((size_t) upd_off + sizeof(ntfs_upd) > (a_ntfs->mft_rsize_b - mft_rsize_b)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_INODE_COR); tsk_error_set_errstr @@ -386,9 +397,8 @@ ntfs_dinode_lookup(NTFS_INFO * a_ntfs, char *a_buf, TSK_INUM_T a_mftnum) } /* Apply the update sequence structure template */ - upd = - (ntfs_upd *) ((uintptr_t) a_buf + tsk_getu16(fs->endian, - mft->upd_off)); + + upd = (ntfs_upd *) ((uintptr_t) a_buf + upd_off); /* Get the sequence value that each 16-bit value should be */ sig_seq = tsk_getu16(fs->endian, upd->upd_val); /* cycle through each sector */
3rdn4/sleuthkit:38a13f9-heap_buffer_overflow
/workspace/skyset/
sleuthkit
38a13f9-heap_buffer_overflow
/workspace/skyset/sleuthkit/38a13f9-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/sleuthkit/38a13f9-heap_buffer_overflow/immutable/
From 675093ee08b1cc970419946760ca6340edfca272 Mon Sep 17 00:00:00 2001 From: Joachim Metz <joachim.metz@gmail.com> Date: Sat, 18 Sep 2021 09:26:15 +0200 Subject: [PATCH] Fixed integer overflow ext4_load_attrs_inline leading to OOB-read --- tsk/fs/ext2fs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tsk/fs/ext2fs.c b/tsk/fs/ext2fs.c index 9039b696a4..5ca571b274 100755 --- a/tsk/fs/ext2fs.c +++ b/tsk/fs/ext2fs.c @@ -637,7 +637,7 @@ ext4_load_attrs_inline(TSK_FS_FILE *fs_file, const uint8_t * ea_buf, size_t ea_b // The offset is from the beginning of the entries, i.e., four bytes into the buffer. uint16_t offset = tsk_getu16(fs_file->fs_info->endian, ea_entry->val_off); uint32_t size = tsk_getu32(fs_file->fs_info->endian, ea_entry->val_size); - if (4 + offset + size <= ea_buf_len) { + if ((ea_buf_len >= 4) && (offset < ea_buf_len - 4) && (size <= ea_buf_len - 4 - offset)) { ea_inline_data = &(ea_buf[4 + offset]); ea_inline_data_len = size; break;
3rdn4/hostap:703c2b6-heap_buffer_overflow
/workspace/skyset/
hostap
703c2b6-heap_buffer_overflow
/workspace/skyset/hostap/703c2b6-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/hostap/703c2b6-heap_buffer_overflow/immutable/
commit 76162b18280b174cd5e7101c9678f69785409fa3 Author: Jouni Malinen <j@w1.fi> Date: Tue Jan 28 14:17:52 2020 +0200 TLS: Fix bounds checking in certificate policy parser The recent addition of the X.509v3 certificatePolicies parser had a copy-paste issue on the inner SEQUENCE parser that ended up using incorrect length for the remaining buffer. Fix that to calculate the remaining length properly to avoid reading beyond the end of the buffer in case of corrupted input data. Credit to OSS-Fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=20363 Fixes: d165b32f3887 ("TLS: TOD-STRICT and TOD-TOFU certificate policies") Signed-off-by: Jouni Malinen <j@w1.fi> diff --git a/src/tls/x509v3.c b/src/tls/x509v3.c index 2b0743116..5c8ac5676 100644 --- a/src/tls/x509v3.c +++ b/src/tls/x509v3.c @@ -1205,14 +1205,14 @@ static int x509_parse_ext_certificate_policies(struct x509_certificate *cert, struct asn1_oid oid; char buf[80]; - if (asn1_get_next(pos, len, &hdr) < 0 || + if (asn1_get_next(pos, end - pos, &hdr) < 0 || hdr.class != ASN1_CLASS_UNIVERSAL || hdr.tag != ASN1_TAG_SEQUENCE) { wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE (PolicyInformation) - found class %d tag 0x%x", hdr.class, hdr.tag); return -1; } - if (hdr.length > pos + len - hdr.payload) + if (hdr.length > end - hdr.payload) return -1; pos = hdr.payload; pol_end = pos + hdr.length;
3rdn4/hostap:a6ed414-heap_buffer_overflow_a
/workspace/skyset/
hostap
a6ed414-heap_buffer_overflow_a
/workspace/skyset/hostap/a6ed414-heap_buffer_overflow_a/report.txt
A heap buffer overflow a found in /workspace/skyset/hostap/a6ed414-heap_buffer_overflow_a/immutable/
commit ce11c281ad1de25a815d49a29043d127cbc6354d Author: Jouni Malinen <j@w1.fi> Date: Sat Jun 22 18:11:24 2019 +0300 TLS: Fix X.509v3 BasicConstraints parsing Handling of the optional pathLenConstraint after cA was not done properly. The position after cA needs to be compared to the end of the SEQUENCE, not the end of the available buffer, to determine whether the optional pathLenConstraint is present. In addition, when parsing pathLenConstraint, the length of the remaining buffer was calculated incorrectly by not subtracting the length of the header fields needed for cA. This could result in reading couple of octets beyond the end of the buffer before rejecting the ASN.1 data as invalid. Credit to OSS-Fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=15408 Signed-off-by: Jouni Malinen <j@w1.fi> diff --git a/src/tls/x509v3.c b/src/tls/x509v3.c index d74b3a275..71ac6b95b 100644 --- a/src/tls/x509v3.c +++ b/src/tls/x509v3.c @@ -815,6 +815,7 @@ static int x509_parse_ext_basic_constraints(struct x509_certificate *cert, struct asn1_hdr hdr; unsigned long value; size_t left; + const u8 *end_seq; /* * BasicConstraints ::= SEQUENCE { @@ -836,6 +837,7 @@ static int x509_parse_ext_basic_constraints(struct x509_certificate *cert, if (hdr.length == 0) return 0; + end_seq = hdr.payload + hdr.length; if (asn1_get_next(hdr.payload, hdr.length, &hdr) < 0 || hdr.class != ASN1_CLASS_UNIVERSAL) { wpa_printf(MSG_DEBUG, "X509: Failed to parse " @@ -852,14 +854,14 @@ static int x509_parse_ext_basic_constraints(struct x509_certificate *cert, } cert->ca = hdr.payload[0]; - if (hdr.length == pos + len - hdr.payload) { + pos = hdr.payload + hdr.length; + if (pos >= end_seq) { + /* No optional pathLenConstraint */ wpa_printf(MSG_DEBUG, "X509: BasicConstraints - cA=%d", cert->ca); return 0; } - - if (asn1_get_next(hdr.payload + hdr.length, len - hdr.length, - &hdr) < 0 || + if (asn1_get_next(pos, end_seq - pos, &hdr) < 0 || hdr.class != ASN1_CLASS_UNIVERSAL) { wpa_printf(MSG_DEBUG, "X509: Failed to parse " "BasicConstraints");
3rdn4/hostap:a6ed414-heap_buffer_overflow_b
/workspace/skyset/
hostap
a6ed414-heap_buffer_overflow_b
/workspace/skyset/hostap/a6ed414-heap_buffer_overflow_b/report.txt
A heap buffer overflow b found in /workspace/skyset/hostap/a6ed414-heap_buffer_overflow_b/immutable/
commit ce11c281ad1de25a815d49a29043d127cbc6354d Author: Jouni Malinen <j@w1.fi> Date: Sat Jun 22 18:11:24 2019 +0300 TLS: Fix X.509v3 BasicConstraints parsing Handling of the optional pathLenConstraint after cA was not done properly. The position after cA needs to be compared to the end of the SEQUENCE, not the end of the available buffer, to determine whether the optional pathLenConstraint is present. In addition, when parsing pathLenConstraint, the length of the remaining buffer was calculated incorrectly by not subtracting the length of the header fields needed for cA. This could result in reading couple of octets beyond the end of the buffer before rejecting the ASN.1 data as invalid. Credit to OSS-Fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=15408 Signed-off-by: Jouni Malinen <j@w1.fi> diff --git a/src/tls/x509v3.c b/src/tls/x509v3.c index d74b3a275..71ac6b95b 100644 --- a/src/tls/x509v3.c +++ b/src/tls/x509v3.c @@ -815,6 +815,7 @@ static int x509_parse_ext_basic_constraints(struct x509_certificate *cert, struct asn1_hdr hdr; unsigned long value; size_t left; + const u8 *end_seq; /* * BasicConstraints ::= SEQUENCE { @@ -836,6 +837,7 @@ static int x509_parse_ext_basic_constraints(struct x509_certificate *cert, if (hdr.length == 0) return 0; + end_seq = hdr.payload + hdr.length; if (asn1_get_next(hdr.payload, hdr.length, &hdr) < 0 || hdr.class != ASN1_CLASS_UNIVERSAL) { wpa_printf(MSG_DEBUG, "X509: Failed to parse " @@ -852,14 +854,14 @@ static int x509_parse_ext_basic_constraints(struct x509_certificate *cert, } cert->ca = hdr.payload[0]; - if (hdr.length == pos + len - hdr.payload) { + pos = hdr.payload + hdr.length; + if (pos >= end_seq) { + /* No optional pathLenConstraint */ wpa_printf(MSG_DEBUG, "X509: BasicConstraints - cA=%d", cert->ca); return 0; } - - if (asn1_get_next(hdr.payload + hdr.length, len - hdr.length, - &hdr) < 0 || + if (asn1_get_next(pos, end_seq - pos, &hdr) < 0 || hdr.class != ASN1_CLASS_UNIVERSAL) { wpa_printf(MSG_DEBUG, "X509: Failed to parse " "BasicConstraints");
3rdn4/sleuthkit:82d254b-heap_buffer_overflow
/workspace/skyset/
sleuthkit
82d254b-heap_buffer_overflow
/workspace/skyset/sleuthkit/82d254b-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/sleuthkit/82d254b-heap_buffer_overflow/immutable/
From 4d379cb12e67f5bc690d2e2e4d6ce752c2b41e67 Mon Sep 17 00:00:00 2001 From: Joachim Metz <joachim.metz@gmail.com> Date: Thu, 22 Apr 2021 05:36:18 +0200 Subject: [PATCH] Fixed integer wrap around --- tsk/fs/ntfs.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/tsk/fs/ntfs.c b/tsk/fs/ntfs.c index 631fe2ff38..d225e5c996 100755 --- a/tsk/fs/ntfs.c +++ b/tsk/fs/ntfs.c @@ -375,9 +375,20 @@ ntfs_dinode_lookup(NTFS_INFO * a_ntfs, char *a_buf, TSK_INUM_T a_mftnum) ("dinode_lookup: More Update Sequence Entries than MFT size"); return TSK_COR; } - if (tsk_getu16(fs->endian, mft->upd_off) + - sizeof(ntfs_upd) + - 2*(tsk_getu16(fs->endian, mft->upd_cnt) - 1) > a_ntfs->mft_rsize_b) { + uint16_t upd_cnt = tsk_getu16(fs->endian, mft->upd_cnt); + uint16_t upd_off = tsk_getu16(fs->endian, mft->upd_off); + + // Make sure upd_cnt > 0 to prevent an integer wrap around. + if ((upd_cnt == 0) || (upd_cnt > (((a_ntfs->mft_rsize_b) / 2) + 1))) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_INODE_COR); + tsk_error_set_errstr + ("dinode_lookup: Invalid update count value out of bounds"); + return TSK_COR; + } + size_t mft_rsize_b = ((size_t) upd_cnt - 1) * 2; + + if ((size_t) upd_off + sizeof(ntfs_upd) > (a_ntfs->mft_rsize_b - mft_rsize_b)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_INODE_COR); tsk_error_set_errstr @@ -386,9 +397,8 @@ ntfs_dinode_lookup(NTFS_INFO * a_ntfs, char *a_buf, TSK_INUM_T a_mftnum) } /* Apply the update sequence structure template */ - upd = - (ntfs_upd *) ((uintptr_t) a_buf + tsk_getu16(fs->endian, - mft->upd_off)); + + upd = (ntfs_upd *) ((uintptr_t) a_buf + upd_off); /* Get the sequence value that each 16-bit value should be */ sig_seq = tsk_getu16(fs->endian, upd->upd_val); /* cycle through each sector */
3rdn4/sleuthkit:d9b19e1-heap_buffer_overflow
/workspace/skyset/
sleuthkit
d9b19e1-heap_buffer_overflow
/workspace/skyset/sleuthkit/d9b19e1-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/sleuthkit/d9b19e1-heap_buffer_overflow/immutable/
From 4d379cb12e67f5bc690d2e2e4d6ce752c2b41e67 Mon Sep 17 00:00:00 2001 From: Joachim Metz <joachim.metz@gmail.com> Date: Thu, 22 Apr 2021 05:36:18 +0200 Subject: [PATCH] Fixed integer wrap around --- tsk/fs/ntfs.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/tsk/fs/ntfs.c b/tsk/fs/ntfs.c index 631fe2ff38..d225e5c996 100755 --- a/tsk/fs/ntfs.c +++ b/tsk/fs/ntfs.c @@ -375,9 +375,20 @@ ntfs_dinode_lookup(NTFS_INFO * a_ntfs, char *a_buf, TSK_INUM_T a_mftnum) ("dinode_lookup: More Update Sequence Entries than MFT size"); return TSK_COR; } - if (tsk_getu16(fs->endian, mft->upd_off) + - sizeof(ntfs_upd) + - 2*(tsk_getu16(fs->endian, mft->upd_cnt) - 1) > a_ntfs->mft_rsize_b) { + uint16_t upd_cnt = tsk_getu16(fs->endian, mft->upd_cnt); + uint16_t upd_off = tsk_getu16(fs->endian, mft->upd_off); + + // Make sure upd_cnt > 0 to prevent an integer wrap around. + if ((upd_cnt == 0) || (upd_cnt > (((a_ntfs->mft_rsize_b) / 2) + 1))) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_INODE_COR); + tsk_error_set_errstr + ("dinode_lookup: Invalid update count value out of bounds"); + return TSK_COR; + } + size_t mft_rsize_b = ((size_t) upd_cnt - 1) * 2; + + if ((size_t) upd_off + sizeof(ntfs_upd) > (a_ntfs->mft_rsize_b - mft_rsize_b)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_INODE_COR); tsk_error_set_errstr @@ -386,9 +397,8 @@ ntfs_dinode_lookup(NTFS_INFO * a_ntfs, char *a_buf, TSK_INUM_T a_mftnum) } /* Apply the update sequence structure template */ - upd = - (ntfs_upd *) ((uintptr_t) a_buf + tsk_getu16(fs->endian, - mft->upd_off)); + + upd = (ntfs_upd *) ((uintptr_t) a_buf + upd_off); /* Get the sequence value that each 16-bit value should be */ sig_seq = tsk_getu16(fs->endian, upd->upd_val); /* cycle through each sector */
3rdn4/wasm3-harness:0124fd5-heap_buffer_overflow
/workspace/skyset/
wasm3-harness
0124fd5-heap_buffer_overflow
/workspace/skyset/wasm3-harness/0124fd5-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/wasm3-harness/0124fd5-heap_buffer_overflow/immutable/
From 79255ba1dbbb476e57a5f450eb0bbe1b84ef0f01 Mon Sep 17 00:00:00 2001 From: Volodymyr Shymanskyy <vshymanskyi@gmail.com> Date: Mon, 12 Apr 2021 16:24:34 +0300 Subject: [PATCH] Restict opcodes during expression evaluation --- source/m3_compile.c | 19 +++++++++++++++---- source/m3_compile.h | 9 +++++++++ source/m3_env.c | 7 +++++++ source/m3_env.h | 2 ++ source/m3_exec.h | 2 +- source/wasm3.h | 1 + 6 files changed, 35 insertions(+), 5 deletions(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index b9bd21cb..ca0fe830 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -1495,7 +1495,7 @@ _ (ReadLEB_i7 (& reserved, & o->wasm, o->wasmEnd)); _ (PreserveRegisterIfOccupied (o, c_m3Type_i32)); -_ (EmitOp (o, op_MemCurrent)); +_ (EmitOp (o, op_MemSize)); _ (PushRegister (o, c_m3Type_i32)); @@ -1972,7 +1972,7 @@ const M3OpInfo c_operations [] = M3OP( "i64.store16", -2, none, d_binOpList (i64, Store_i16), Compile_Load_Store ), // 0x3d M3OP( "i64.store32", -2, none, d_binOpList (i64, Store_i32), Compile_Load_Store ), // 0x3e - M3OP( "memory.size", 1, i_32, d_logOp (MemCurrent), Compile_Memory_Size ), // 0x3f + M3OP( "memory.size", 1, i_32, d_logOp (MemSize), Compile_Memory_Size ), // 0x3f M3OP( "memory.grow", 1, i_32, d_logOp (MemGrow), Compile_Memory_Grow ), // 0x40 M3OP( "i32.const", 1, i_32, d_logOp (Const32), Compile_Const_i32 ), // 0x41 @@ -2213,6 +2213,17 @@ M3Result Compile_BlockStatements (IM3Compilation o) o->lastOpcodeStart = o->wasm; _ (Read_opcode (& opcode, & o->wasm, o->wasmEnd)); log_opcode (o, opcode); + if (IsCompilingExpressions(o)) { + switch (opcode) { + case c_waOp_i32_const: case c_waOp_i64_const: + case c_waOp_f32_const: case c_waOp_f64_const: + case c_waOp_getGlobal: case c_waOp_end: + break; + default: + _throw(m3Err_restictedOpcode); + } + } + IM3OpInfo opinfo = GetOpInfo(opcode); _throwif (m3Err_unknownOpcode, opinfo == NULL); @@ -2341,9 +2352,9 @@ M3Result Compile_ReserveConstants (IM3Compilation o) { u8 code = * wa++; - if (code == 0x41 or code == 0x43) // i32, f32 + if (code == c_waOp_i32_const or code == c_waOp_f32_const) numConstantSlots += 1; - else if (code == 0x42 or code == 0x44) // i64, f64 + else if (code == c_waOp_i64_const or code == c_waOp_f64_const) numConstantSlots += GetTypeNumSlots (c_m3Type_i64); } diff --git a/source/m3_compile.h b/source/m3_compile.h index db4e0d28..cb61001d 100644 --- a/source/m3_compile.h +++ b/source/m3_compile.h @@ -28,6 +28,13 @@ enum c_waOp_getLocal = 0x20, c_waOp_setLocal = 0x21, c_waOp_teeLocal = 0x22, + + c_waOp_getGlobal = 0x23, + + c_waOp_i32_const = 0x41, + c_waOp_i64_const = 0x42, + c_waOp_f32_const = 0x43, + c_waOp_f64_const = 0x44, }; @@ -82,8 +89,10 @@ typedef struct IM3BranchPatch releasedPatches; +#ifdef DEBUG u32 numEmits; u32 numOpcodes; +#endif u16 stackFirstDynamicIndex; u16 stackIndex; // current stack index diff --git a/source/m3_env.c b/source/m3_env.c index 6b87f661..316f57fd 100644 --- a/source/m3_env.c +++ b/source/m3_env.c @@ -260,6 +260,12 @@ void m3_FreeRuntime (IM3Runtime i_runtime) } } +static char* c_compilingExprsFlag = "m3_exprs"; + +bool IsCompilingExpressions (IM3Compilation i_compilation) +{ + return i_compilation->runtime && i_compilation->runtime->userdata == c_compilingExprsFlag; +} M3Result EvaluateExpression (IM3Module i_module, void * o_expressed, u8 i_type, bytes_t * io_bytes, cbytes_t i_end) { @@ -276,6 +282,7 @@ M3Result EvaluateExpression (IM3Module i_module, void * o_expressed, u8 i_type runtime.environment = i_module->runtime->environment; runtime.numStackSlots = i_module->runtime->numStackSlots; runtime.stack = i_module->runtime->stack; + runtime.userdata = c_compilingExprsFlag; m3stack_t stack = (m3stack_t)runtime.stack; diff --git a/source/m3_env.h b/source/m3_env.h index 9d3a12f7..64cdcf1c 100644 --- a/source/m3_env.h +++ b/source/m3_env.h @@ -190,6 +190,8 @@ M3Runtime; void InitRuntime (IM3Runtime io_runtime, u32 i_stackSizeInBytes); void Runtime_Release (IM3Runtime io_runtime); +bool IsCompilingExpressions (IM3Compilation i_compilation); + M3Result ResizeMemory (IM3Runtime io_runtime, u32 i_numPages); typedef void * (* ModuleVisitor) (IM3Module i_module, void * i_info); diff --git a/source/m3_exec.h b/source/m3_exec.h index cdc8a96b..db007c5e 100644 --- a/source/m3_exec.h +++ b/source/m3_exec.h @@ -653,7 +653,7 @@ d_m3Op (CallRawFunction) } -d_m3Op (MemCurrent) +d_m3Op (MemSize) { IM3Memory memory = m3MemInfo (_mem); diff --git a/source/wasm3.h b/source/wasm3.h index c1097cb8..caf7cbd1 100644 --- a/source/wasm3.h +++ b/source/wasm3.h @@ -144,6 +144,7 @@ d_m3ErrorConst (malformedFunctionSignature, "malformed function signature") // compilation errors d_m3ErrorConst (noCompiler, "no compiler found for opcode") d_m3ErrorConst (unknownOpcode, "unknown opcode") +d_m3ErrorConst (restictedOpcode, "restricted opcode") d_m3ErrorConst (functionStackOverflow, "compiling function overran its stack height limit") d_m3ErrorConst (functionStackUnderrun, "compiling function underran the stack") d_m3ErrorConst (mallocFailedCodePage, "memory allocation failed when acquiring a new M3 code page")
3rdn4/wasm3-harness:355285d-global_buffer_overflow
/workspace/skyset/
wasm3-harness
355285d-global_buffer_overflow
/workspace/skyset/wasm3-harness/355285d-global_buffer_overflow/report.txt
A global buffer overflow found in /workspace/skyset/wasm3-harness/355285d-global_buffer_overflow/immutable/
From 60fdd9ecd84b841351059dbfb962a32f616e376e Mon Sep 17 00:00:00 2001 From: Volodymyr Shymanskyy <vshymanskyi@gmail.com> Date: Sat, 10 Apr 2021 01:21:08 +0300 Subject: [PATCH] Bounds check on opcode decoding --- source/m3_compile.c | 15 +++++++++++++++ source/m3_compile.h | 12 +----------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index a895c496..e525da2f 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -2194,6 +2194,21 @@ const M3OpInfo c_operationsFC [] = # endif }; +const M3OpInfo* GetOpInfo(m3opcode_t opcode) { + switch (opcode >> 8) { + case 0x00: + if (opcode < M3_COUNT_OF(c_operations)) { + return &c_operations[opcode]; + } + case 0xFC: + opcode &= 0xFF; + if (opcode < M3_COUNT_OF(c_operationsFC)) { + return &c_operationsFC[opcode]; + } + } + return NULL; +} + M3Result Compile_BlockStatements (IM3Compilation o) { M3Result result = m3Err_none; diff --git a/source/m3_compile.h b/source/m3_compile.h index ece7ad6b..5bf8e099 100644 --- a/source/m3_compile.h +++ b/source/m3_compile.h @@ -138,17 +138,7 @@ M3OpInfo; typedef const M3OpInfo * IM3OpInfo; -extern const M3OpInfo c_operations []; -extern const M3OpInfo c_operationsFC []; - -static inline -const M3OpInfo* GetOpInfo(m3opcode_t opcode) { - switch (opcode >> 8) { - case 0x00: return &c_operations[opcode]; - case 0xFC: return &c_operationsFC[opcode & 0xFF]; - default: return NULL; - } -} +extern const M3OpInfo* GetOpInfo(m3opcode_t opcode); // TODO: This helper should be removed, when MultiValue is implemented static inline
3rdn4/wasm3-harness:4f0b769-heap_use_after_free
/workspace/skyset/
wasm3-harness
4f0b769-heap_use_after_free
/workspace/skyset/wasm3-harness/4f0b769-heap_use_after_free/report.txt
A heap use after free found in /workspace/skyset/wasm3-harness/4f0b769-heap_use_after_free/immutable/
From 6bb612ccbfd5f8993a07a99092fab534722df1c3 Mon Sep 17 00:00:00 2001 From: Vova <vshymanskyi@gmail.com> Date: Tue, 4 May 2021 23:23:51 +0300 Subject: [PATCH] Disable start func execution for fuzzing builds --- source/m3_compile.c | 5 ++++- source/m3_env.c | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index 835a9a40..76e6ccda 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -1114,7 +1114,10 @@ _ (Read_u8 (& opcode, & o->wasm, o->wasmEnd)); m3log (compile, d_i //printf("Extended opcode: 0x%x\n", i_opcode); - M3Compiler compiler = GetOpInfo (i_opcode)->compiler; + const M3OpInfo* opinfo = GetOpInfo (i_opcode); + _throwif (m3Err_unknownOpcode, not opinfo); + + M3Compiler compiler = opinfo->compiler; _throwif (m3Err_noCompiler, not compiler); _ ((* compiler) (o, i_opcode)); diff --git a/source/m3_env.c b/source/m3_env.c index b6c8e010..dbaca058 100644 --- a/source/m3_env.c +++ b/source/m3_env.c @@ -515,6 +515,11 @@ _ (ReadLEB_u32 (& functionIndex, & bytes, end)); M3Result m3_RunStart (IM3Module io_module) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + // Execution disabled for fuzzing builds + return m3Err_none; +#endif + M3Result result = m3Err_none; if (io_module and io_module->startFunction >= 0)
3rdn4/wasm3-harness:4f0b769-unknown_read
/workspace/skyset/
wasm3-harness
4f0b769-unknown_read
/workspace/skyset/wasm3-harness/4f0b769-unknown_read/report.txt
A unknown read found in /workspace/skyset/wasm3-harness/4f0b769-unknown_read/immutable/
From 6bb612ccbfd5f8993a07a99092fab534722df1c3 Mon Sep 17 00:00:00 2001 From: Vova <vshymanskyi@gmail.com> Date: Tue, 4 May 2021 23:23:51 +0300 Subject: [PATCH] Disable start func execution for fuzzing builds --- source/m3_compile.c | 5 ++++- source/m3_env.c | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index 835a9a40..76e6ccda 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -1114,7 +1114,10 @@ _ (Read_u8 (& opcode, & o->wasm, o->wasmEnd)); m3log (compile, d_i //printf("Extended opcode: 0x%x\n", i_opcode); - M3Compiler compiler = GetOpInfo (i_opcode)->compiler; + const M3OpInfo* opinfo = GetOpInfo (i_opcode); + _throwif (m3Err_unknownOpcode, not opinfo); + + M3Compiler compiler = opinfo->compiler; _throwif (m3Err_noCompiler, not compiler); _ ((* compiler) (o, i_opcode)); diff --git a/source/m3_env.c b/source/m3_env.c index b6c8e010..dbaca058 100644 --- a/source/m3_env.c +++ b/source/m3_env.c @@ -515,6 +515,11 @@ _ (ReadLEB_u32 (& functionIndex, & bytes, end)); M3Result m3_RunStart (IM3Module io_module) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + // Execution disabled for fuzzing builds + return m3Err_none; +#endif + M3Result result = m3Err_none; if (io_module and io_module->startFunction >= 0)
3rdn4/wasm3-harness:4f0b769-unknown_write
/workspace/skyset/
wasm3-harness
4f0b769-unknown_write
/workspace/skyset/wasm3-harness/4f0b769-unknown_write/report.txt
A unknown write found in /workspace/skyset/wasm3-harness/4f0b769-unknown_write/immutable/
From 6bb612ccbfd5f8993a07a99092fab534722df1c3 Mon Sep 17 00:00:00 2001 From: Vova <vshymanskyi@gmail.com> Date: Tue, 4 May 2021 23:23:51 +0300 Subject: [PATCH] Disable start func execution for fuzzing builds --- source/m3_compile.c | 5 ++++- source/m3_env.c | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index 835a9a40..76e6ccda 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -1114,7 +1114,10 @@ _ (Read_u8 (& opcode, & o->wasm, o->wasmEnd)); m3log (compile, d_i //printf("Extended opcode: 0x%x\n", i_opcode); - M3Compiler compiler = GetOpInfo (i_opcode)->compiler; + const M3OpInfo* opinfo = GetOpInfo (i_opcode); + _throwif (m3Err_unknownOpcode, not opinfo); + + M3Compiler compiler = opinfo->compiler; _throwif (m3Err_noCompiler, not compiler); _ ((* compiler) (o, i_opcode)); diff --git a/source/m3_env.c b/source/m3_env.c index b6c8e010..dbaca058 100644 --- a/source/m3_env.c +++ b/source/m3_env.c @@ -515,6 +515,11 @@ _ (ReadLEB_u32 (& functionIndex, & bytes, end)); M3Result m3_RunStart (IM3Module io_module) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + // Execution disabled for fuzzing builds + return m3Err_none; +#endif + M3Result result = m3Err_none; if (io_module and io_module->startFunction >= 0)
3rdn4/wasm3-harness:bc32ee0-segv_on_unknown_address
/workspace/skyset/
wasm3-harness
bc32ee0-segv_on_unknown_address
/workspace/skyset/wasm3-harness/bc32ee0-segv_on_unknown_address/report.txt
A segv on unknown address found in /workspace/skyset/wasm3-harness/bc32ee0-segv_on_unknown_address/immutable/
From 6bb612ccbfd5f8993a07a99092fab534722df1c3 Mon Sep 17 00:00:00 2001 From: Vova <vshymanskyi@gmail.com> Date: Tue, 4 May 2021 23:23:51 +0300 Subject: [PATCH] Disable start func execution for fuzzing builds --- source/m3_compile.c | 5 ++++- source/m3_env.c | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index 835a9a40..76e6ccda 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -1114,7 +1114,10 @@ _ (Read_u8 (& opcode, & o->wasm, o->wasmEnd)); m3log (compile, d_i //printf("Extended opcode: 0x%x\n", i_opcode); - M3Compiler compiler = GetOpInfo (i_opcode)->compiler; + const M3OpInfo* opinfo = GetOpInfo (i_opcode); + _throwif (m3Err_unknownOpcode, not opinfo); + + M3Compiler compiler = opinfo->compiler; _throwif (m3Err_noCompiler, not compiler); _ ((* compiler) (o, i_opcode)); diff --git a/source/m3_env.c b/source/m3_env.c index b6c8e010..dbaca058 100644 --- a/source/m3_env.c +++ b/source/m3_env.c @@ -515,6 +515,11 @@ _ (ReadLEB_u32 (& functionIndex, & bytes, end)); M3Result m3_RunStart (IM3Module io_module) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + // Execution disabled for fuzzing builds + return m3Err_none; +#endif + M3Result result = m3Err_none; if (io_module and io_module->startFunction >= 0)
3rdn4/wasm3-harness:bc32ee0-unknown_read
/workspace/skyset/
wasm3-harness
bc32ee0-unknown_read
/workspace/skyset/wasm3-harness/bc32ee0-unknown_read/report.txt
A unknown read found in /workspace/skyset/wasm3-harness/bc32ee0-unknown_read/immutable/
From 6bb612ccbfd5f8993a07a99092fab534722df1c3 Mon Sep 17 00:00:00 2001 From: Vova <vshymanskyi@gmail.com> Date: Tue, 4 May 2021 23:23:51 +0300 Subject: [PATCH] Disable start func execution for fuzzing builds --- source/m3_compile.c | 5 ++++- source/m3_env.c | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/source/m3_compile.c b/source/m3_compile.c index 835a9a40..76e6ccda 100644 --- a/source/m3_compile.c +++ b/source/m3_compile.c @@ -1114,7 +1114,10 @@ _ (Read_u8 (& opcode, & o->wasm, o->wasmEnd)); m3log (compile, d_i //printf("Extended opcode: 0x%x\n", i_opcode); - M3Compiler compiler = GetOpInfo (i_opcode)->compiler; + const M3OpInfo* opinfo = GetOpInfo (i_opcode); + _throwif (m3Err_unknownOpcode, not opinfo); + + M3Compiler compiler = opinfo->compiler; _throwif (m3Err_noCompiler, not compiler); _ ((* compiler) (o, i_opcode)); diff --git a/source/m3_env.c b/source/m3_env.c index b6c8e010..dbaca058 100644 --- a/source/m3_env.c +++ b/source/m3_env.c @@ -515,6 +515,11 @@ _ (ReadLEB_u32 (& functionIndex, & bytes, end)); M3Result m3_RunStart (IM3Module io_module) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + // Execution disabled for fuzzing builds + return m3Err_none; +#endif + M3Result result = m3Err_none; if (io_module and io_module->startFunction >= 0)
3rdn4/yasm:84be2ee-heap_out_of_bound
/workspace/skyset/
yasm
84be2ee-heap_out_of_bound
/workspace/skyset/yasm/84be2ee-heap_out_of_bound/report.txt
A heap out of bound found in /workspace/skyset/yasm/84be2ee-heap_out_of_bound/immutable/
diff --git a/modules/parsers/nasm/nasm-token.re b/modules/parsers/nasm/nasm-token.re index dba7137e..b2110ce9 100644 --- a/modules/parsers/nasm/nasm-token.re +++ b/modules/parsers/nasm/nasm-token.re @@ -79,7 +79,7 @@ handle_dot_label(YYSTYPE *lvalp, char *tok, size_t toklen, size_t zeropos, lvalp->str_val = yasm__xstrndup(tok+zeropos+(parser_nasm->tasm?2:0), toklen-zeropos-(parser_nasm->tasm?2:0)); /* check for special non-local ..@label */ - if (lvalp->str_val[zeropos+2] == '@') + if (lvalp->str_val[2] == '@') return NONLOCAL_ID; return SPECIAL_ID; }
3rdn4/yasm:ecb47f1-null_pointer_deref
/workspace/skyset/
yasm
ecb47f1-null_pointer_deref
/workspace/skyset/yasm/ecb47f1-null_pointer_deref/report.txt
A null pointer deref found in /workspace/skyset/yasm/ecb47f1-null_pointer_deref/immutable/
diff --git a/libyasm/expr.c b/libyasm/expr.c index 5b0c418b..09ae1121 100644 --- a/libyasm/expr.c +++ b/libyasm/expr.c @@ -1264,7 +1264,7 @@ yasm_expr_get_intnum(yasm_expr **ep, int calc_bc_dist) { *ep = yasm_expr_simplify(*ep, calc_bc_dist); - if ((*ep)->op == YASM_EXPR_IDENT && (*ep)->terms[0].type == YASM_EXPR_INT) + if (*ep && (*ep)->op == YASM_EXPR_IDENT && (*ep)->terms[0].type == YASM_EXPR_INT) return (*ep)->terms[0].data.intn; else return (yasm_intnum *)NULL;
3rdn4/zstd:0a96d00-heap_buffer_overflow
/workspace/skyset/
zstd
0a96d00-heap_buffer_overflow
/workspace/skyset/zstd/0a96d00-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/zstd/0a96d00-heap_buffer_overflow/immutable/
From 05b6773fbcce1075edbe498a821f9a41249cf384 Mon Sep 17 00:00:00 2001 From: Nick Terrell <terrelln@fb.com> Date: Mon, 14 Jun 2021 11:25:55 -0700 Subject: [PATCH] [fix] Add missing bounds checks during compression * The block splitter missed a bounds check, so when the buffer is too small it passes an erroneously large size to `ZSTD_entropyCompressSeqStore()`, which can then write the compressed data past the end of the buffer. This is a new regression in v1.5.0 when the block splitter is enabled. It is either enabled explicitly, or implicitly when using the optimal parser and `ZSTD_compress2()` or `ZSTD_compressStream*()`. * `HUF_writeCTable_wksp()` omits a bounds check when calling `HUF_compressWeights()`. If it is called with `dstCapacity == 0` it will pass an erroneously large size to `HUF_compressWeights()`, which can then write past the end of the buffer. This bug has been present for ages. However, I believe that zstd cannot trigger the bug, because it never calls `HUF_compress*()` with `dstCapacity == 0` because of [this check][1]. Credit to: Oss-Fuzz [1]: https://github.com/facebook/zstd/blob/89127e5ee2f3c1e141668fa6d4ee91245f05d132/lib/compress/zstd_compress_literals.c#L100 --- lib/compress/huf_compress.c | 1 + lib/compress/zstd_compress.c | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/compress/huf_compress.c b/lib/compress/huf_compress.c index 485906e678..e9cb0bd5f5 100644 --- a/lib/compress/huf_compress.c +++ b/lib/compress/huf_compress.c @@ -133,6 +133,7 @@ size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize, wksp->huffWeight[n] = wksp->bitsToWeight[CTable[n].nbBits]; /* attempt weights compression by FSE */ + if (maxDstSize < 1) return ERROR(dstSize_tooSmall); { CHECK_V_F(hSize, HUF_compressWeights(op+1, maxDstSize-1, wksp->huffWeight, maxSymbolValue, &wksp->wksp, sizeof(wksp->wksp)) ); if ((hSize>1) & (hSize < maxSymbolValue/2)) { /* FSE compressed */ op[0] = (BYTE)hSize; diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 70f1693574..9e814e31d1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3486,6 +3486,7 @@ static size_t ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, seqStore_t* const if (isPartition) ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart)); + RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "Block header doesn't fit"); cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore, &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy, &zc->appliedParams,
3rdn4/zstd:2fabd37-global_buffer_overflow
/workspace/skyset/
zstd
2fabd37-global_buffer_overflow
/workspace/skyset/zstd/2fabd37-global_buffer_overflow/report.txt
A global buffer overflow found in /workspace/skyset/zstd/2fabd37-global_buffer_overflow/immutable/
From 4d8a2132d0e453232a46dd448e5137035ba25bee Mon Sep 17 00:00:00 2001 From: Nick Terrell <terrelln@fb.com> Date: Thu, 6 Jan 2022 16:00:02 -0800 Subject: [PATCH] [opt] Fix oss-fuzz bug in optimal parser oss-fuzz uncovered a scenario where we're evaluating the cost of litLength = 131072, which can't be represented in the zstd format, so we accessed 1 beyond LL_bits. Fix the issue by making it cost 1 bit more than litLength = 131071. There are still follow ups: 1. This happened because literals_cost[0] = 0, so the optimal parser chose 36 literals over a match. Should we bound literals_cost[literal] > 0, unless the block truly only has one literal value? 2. When no matches are found, the cost model isn't updated. In this case no matches were found for an entire block. So the literals cost model wasn't updated at all. That made the optimal parser think literals_cost[0] = 0, where it is actually quite high, since the block was entirely random noise. Credit to OSS-Fuzz. --- lib/compress/zstd_opt.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 2fa10816f9..1b1ddad428 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -269,7 +269,16 @@ static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength, * cost of literalLength symbol */ static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel) { - if (optPtr->priceType == zop_predef) return WEIGHT(litLength, optLevel); + assert(litLength <= ZSTD_BLOCKSIZE_MAX); + if (optPtr->priceType == zop_predef) + return WEIGHT(litLength, optLevel); + /* We can't compute the litLength price for sizes >= ZSTD_BLOCKSIZE_MAX + * because it isn't representable in the zstd format. So instead just + * call it 1 bit more than ZSTD_BLOCKSIZE_MAX - 1. In this case the block + * would be all literals. + */ + if (litLength == ZSTD_BLOCKSIZE_MAX) + return BITCOST_MULTIPLIER + ZSTD_litLengthPrice(ZSTD_BLOCKSIZE_MAX - 1, optPtr, optLevel); /* dynamic statistics */ { U32 const llCode = ZSTD_LLcode(litLength);
3rdn4/zstd:3cac061-heap_buffer_overflow
/workspace/skyset/
zstd
3cac061-heap_buffer_overflow
/workspace/skyset/zstd/3cac061-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/zstd/3cac061-heap_buffer_overflow/immutable/
From efd37a64eaff5a0a26ae2566fdb45dc4a0c91673 Mon Sep 17 00:00:00 2001 From: Nick Terrell <terrelln@fb.com> Date: Thu, 19 Sep 2019 13:25:03 -0700 Subject: [PATCH] Optimize decompression and fix wildcopy overread * Bump `WILDCOPY_OVERLENGTH` to 16 to fix the wildcopy overread. * Optimize `ZSTD_wildcopy()` by removing unnecessary branches and unrolling the loop. * Extract `ZSTD_overlapCopy8()` into its own function. * Add `ZSTD_safecopy()` for `ZSTD_execSequenceEnd()`. It is optimized for single long sequences, since that is the important case that can end up in `ZSTD_execSequenceEnd()`. Without this optimization, decompressing a block with 1 long match goes from 5.7 GB/s to 800 MB/s. * Refactor `ZSTD_execSequenceEnd()`. * Increase the literal copy shortcut to 16. * Add a shortcut for offset >= 16. * Simplify `ZSTD_execSequence()` by pushing more cases into `ZSTD_execSequenceEnd()`. * Delete `ZSTD_execSequenceLong()` since it is exactly the same as `ZSTD_execSequence()`. clang-8 seeds +17.5% on silesia and +21.8% on enwik8. gcc-9 sees +12% on silesia and +15.5% on enwik8. TODO: More detailed measurements, and on more datasets. Crdit to OSS-Fuzz for finding the wildcopy overread. --- lib/common/zstd_internal.h | 95 +++------ lib/compress/zstd_compress_internal.h | 5 +- lib/decompress/zstd_decompress_block.c | 284 ++++++++++++------------- 3 files changed, 179 insertions(+), 205 deletions(-) diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index fb6246a1ed..007b03df7a 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -197,8 +197,8 @@ static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); } static void ZSTD_copy16(void* dst, const void* src) { memcpy(dst, src, 16); } #define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; } -#define WILDCOPY_OVERLENGTH 8 -#define VECLEN 16 +#define WILDCOPY_OVERLENGTH 16 +#define WILDCOPY_VECLEN 16 typedef enum { ZSTD_no_overlap, @@ -207,83 +207,58 @@ typedef enum { } ZSTD_overlap_e; /*! ZSTD_wildcopy() : - * custom version of memcpy(), can overwrite up to WILDCOPY_OVERLENGTH bytes (if length==0) */ -MEM_STATIC FORCE_INLINE_ATTR DONT_VECTORIZE -void ZSTD_wildcopy(void* dst, const void* src, BYTE* oend_g, ptrdiff_t length, ZSTD_overlap_e ovtype) -{ - ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src; - const BYTE* ip = (const BYTE*)src; - BYTE* op = (BYTE*)dst; - BYTE* const oend = op + length; - - assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff < -8)); - - if (length < VECLEN || (ovtype == ZSTD_overlap_src_before_dst && diff < VECLEN)) { - do - COPY8(op, ip) - while (op < oend); - } - else { - if (oend < oend_g-16) { - /* common case */ - do { - COPY16(op, ip); - } - while (op < oend); - } - else { - do { - COPY8(op, ip); - } - while (op < oend); - } - } -} - -/*! ZSTD_wildcopy_16min() : - * same semantics as ZSTD_wildcopy() except guaranteed to be able to copy 16 bytes at the start */ + * Custom version of memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0) + * @param ovtype controls the overlap detection + * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart. + * - ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart. + * The src buffer must be before the dst buffer. + */ MEM_STATIC FORCE_INLINE_ATTR DONT_VECTORIZE -void ZSTD_wildcopy_16min(void* dst, const void* src, BYTE* oend_g, ptrdiff_t length, ZSTD_overlap_e ovtype) +void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e ovtype) { ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src; const BYTE* ip = (const BYTE*)src; BYTE* op = (BYTE*)dst; BYTE* const oend = op + length; - assert(length >= 8); - assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff < -8)); + assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff <= -WILDCOPY_VECLEN)); - if (ovtype == ZSTD_overlap_src_before_dst && diff < VECLEN) { - do { - COPY8(op, ip); - } - while (op < oend); - } - else { - if (oend < oend_g-16) { - /* common case */ + if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) { + /* Handle short offset copies. */ do { - COPY16(op, ip); - } - while (op < oend); - } - else { + COPY8(op, ip) + } while (op < oend); + } else { + assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN); + /* Separate out the first two COPY16() calls because the copy length is + * almost certain to be short, so the branches have different + * probabilities. + * On gcc-9 unrolling once is +1.6%, twice is +2%, thrice is +1.8%. + * On clang-8 unrolling once is +1.4%, twice is +3.3%, thrice is +3%. + */ + COPY16(op, ip); + if (op >= oend) return; + COPY16(op, ip); + if (op >= oend) return; do { - COPY8(op, ip); + COPY16(op, ip); } while (op < oend); - } } } -MEM_STATIC void ZSTD_wildcopy_e(void* dst, const void* src, void* dstEnd) /* should be faster for decoding, but strangely, not verified on all platform */ +/*! ZSTD_wildcopy8() : + * The same as ZSTD_wildcopy(), but it can only overwrite 8 bytes, and works for + * overlapping buffers that are at least 8 bytes apart. + */ +MEM_STATIC void ZSTD_wildcopy8(void* dst, const void* src, ptrdiff_t length) { const BYTE* ip = (const BYTE*)src; BYTE* op = (BYTE*)dst; - BYTE* const oend = (BYTE*)dstEnd; - do + BYTE* const oend = (BYTE*)op + length; + do { COPY8(op, ip) - while (op < oend); + } while (op < oend); } diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 208a04c5bb..fefa8aff59 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -359,7 +359,10 @@ MEM_STATIC void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const v /* copy Literals */ assert(seqStorePtr->maxNbLit <= 128 KB); assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit); - ZSTD_wildcopy(seqStorePtr->lit, literals, seqStorePtr->lit + litLength + 8, (ptrdiff_t)litLength, ZSTD_no_overlap); + /* We are guaranteed at least 8 bytes of literals space because of HASH_READ_SIZE and + * MINMATCH. + */ + ZSTD_wildcopy8(seqStorePtr->lit, literals, (ptrdiff_t)litLength); seqStorePtr->lit += litLength; /* literal Length */ diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index bab96fb7db..e799a5c74d 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -573,38 +573,118 @@ typedef struct { size_t pos; } seqState_t; +/*! ZSTD_overlapCopy8() : + * Copies 8 bytes from ip to op and updates op and ip where ip <= op. + * If the offset is < 8 then the offset is spread to at least 8 bytes. + * + * Precondition: *ip <= *op + * Postcondition: *op - *op >= 8 + */ +static void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) { + assert(*ip <= *op); + if (offset < 8) { + /* close range match, overlap */ + static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */ + static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */ + int const sub2 = dec64table[offset]; + (*op)[0] = (*ip)[0]; + (*op)[1] = (*ip)[1]; + (*op)[2] = (*ip)[2]; + (*op)[3] = (*ip)[3]; + *ip += dec32table[offset]; + ZSTD_copy4(*op+4, *ip); + *ip -= sub2; + } else { + ZSTD_copy8(*op, *ip); + } + *ip += 8; + *op += 8; + assert(*op - *ip >= 8); +} + +/*! ZSTD_safecopy() : + * Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer + * and write up to 16 bytes past oend_w (op >= oend_w is allowed). + * This function is only called in the uncommon case where the sequence is near the end of the block. It + * should be fast for a single long sequence, but can be slow for several short sequences. + * + * @param ovtype controls the overlap detection + * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart. + * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart. + * The src buffer must be before the dst buffer. + */ +static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) { + ptrdiff_t const diff = op - ip; + BYTE* const oend = op + length; -/* ZSTD_execSequenceLast7(): - * exceptional case : decompress a match starting within last 7 bytes of output buffer. - * requires more careful checks, to ensure there is no overflow. - * performance does not matter though. - * note : this case is supposed to be never generated "naturally" by reference encoder, - * since in most cases it needs at least 8 bytes to look for a match. - * but it's allowed by the specification. */ + assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8)) || + (ovtype == ZSTD_overlap_src_before_dst && diff >= 0)); + + if (length < 8) { + /* Handle short lengths. */ + while (op < oend) *op++ = *ip++; + return; + } + if (ovtype == ZSTD_overlap_src_before_dst) { + /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */ + assert(length >= 8); + ZSTD_overlapCopy8(&op, &ip, diff); + assert(op - ip >= 8); + assert(op <= oend); + } + + if (oend <= oend_w) { + /* No risk of overwrite. */ + ZSTD_wildcopy(op, ip, length, ovtype); + return; + } + if (op <= oend_w) { + /* Wildcopy until we get close to the end. */ + assert(oend > oend_w); + ZSTD_wildcopy(op, ip, oend_w - op, ovtype); + ip += oend_w - op; + op = oend_w; + } + /* Handle the leftovers. */ + while (op < oend) *op++ = *ip++; +} + +/* ZSTD_execSequenceEnd(): + * This version handles cases that are near the end of the output buffer. It requires + * more careful checks to make sure there is no overflow. By separating out these hard + * and unlikely cases, we can speed up the common cases. + * + * NOTE: This function needs to be fast for a single long sequence, but doesn't need + * to be optimized for many small sequences, since those fall into ZSTD_execSequence(). + */ FORCE_NOINLINE -size_t ZSTD_execSequenceLast7(BYTE* op, - BYTE* const oend, seq_t sequence, - const BYTE** litPtr, const BYTE* const litLimit, - const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd) +size_t ZSTD_execSequenceEnd(BYTE* op, + BYTE* const oend, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) { BYTE* const oLitEnd = op + sequence.litLength; size_t const sequenceLength = sequence.litLength + sequence.matchLength; BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */ const BYTE* const iLitEnd = *litPtr + sequence.litLength; const BYTE* match = oLitEnd - sequence.offset; + BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; - /* check */ - RETURN_ERROR_IF(oMatchEnd>oend, dstSize_tooSmall, "last match must fit within dstBuffer"); + /* bounds checks */ + assert(oLitEnd < oMatchEnd); + RETURN_ERROR_IF(oMatchEnd > oend, dstSize_tooSmall, "last match must fit within dstBuffer"); RETURN_ERROR_IF(iLitEnd > litLimit, corruption_detected, "try to read beyond literal buffer"); /* copy literals */ - while (op < oLitEnd) *op++ = *(*litPtr)++; + ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap); + op = oLitEnd; + *litPtr = iLitEnd; /* copy Match */ - if (sequence.offset > (size_t)(oLitEnd - base)) { + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { /* offset beyond prefix */ - RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - vBase),corruption_detected); - match = dictEnd - (base-match); + RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected); + match = dictEnd - (prefixStart-match); if (match + sequence.matchLength <= dictEnd) { memmove(oLitEnd, match, sequence.matchLength); return sequenceLength; @@ -614,13 +694,12 @@ size_t ZSTD_execSequenceLast7(BYTE* op, memmove(oLitEnd, match, length1); op = oLitEnd + length1; sequence.matchLength -= length1; - match = base; + match = prefixStart; } } - while (op < oMatchEnd) *op++ = *match++; + ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst); return sequenceLength; } - HINT_INLINE size_t ZSTD_execSequence(BYTE* op, BYTE* const oend, seq_t sequence, @@ -634,20 +713,27 @@ size_t ZSTD_execSequence(BYTE* op, const BYTE* const iLitEnd = *litPtr + sequence.litLength; const BYTE* match = oLitEnd - sequence.offset; - /* check */ - RETURN_ERROR_IF(oMatchEnd>oend, dstSize_tooSmall, "last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend"); - RETURN_ERROR_IF(iLitEnd > litLimit, corruption_detected, "over-read beyond lit buffer"); - if (oLitEnd>oend_w) return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd); + /* Errors and uncommon cases handled here. */ + assert(oLitEnd < oMatchEnd); + if (iLitEnd > litLimit || oMatchEnd > oend_w) + return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd); + + /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */ + assert(iLitEnd <= litLimit /* Literal length is in bounds */); + assert(oLitEnd <= oend_w /* Can wildcopy literals */); + assert(oMatchEnd <= oend_w /* Can wildcopy matches */); - /* copy Literals */ - if (sequence.litLength > 8) - ZSTD_wildcopy_16min(op, (*litPtr), oend, sequence.litLength, ZSTD_no_overlap); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */ + /* Copy Literals: + * Split out litLength <= 16 since it is nearly always true. +1% on gcc-9. + */ + if (sequence.litLength <= 16) + ZSTD_copy16(op, *litPtr); else - ZSTD_copy8(op, *litPtr); + ZSTD_wildcopy(op, (*litPtr), sequence.litLength, ZSTD_no_overlap); op = oLitEnd; *litPtr = iLitEnd; /* update for next sequence */ - /* copy Match */ + /* Copy Match */ if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { /* offset beyond prefix -> go into extDict */ RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected); @@ -662,123 +748,33 @@ size_t ZSTD_execSequence(BYTE* op, op = oLitEnd + length1; sequence.matchLength -= length1; match = prefixStart; - if (op > oend_w || sequence.matchLength < MINMATCH) { - U32 i; - for (i = 0; i < sequence.matchLength; ++i) op[i] = match[i]; - return sequenceLength; - } } } - /* Requirement: op <= oend_w && sequence.matchLength >= MINMATCH */ - - /* match within prefix */ - if (sequence.offset < 8) { - /* close range match, overlap */ - static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */ - static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */ - int const sub2 = dec64table[sequence.offset]; - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += dec32table[sequence.offset]; - ZSTD_copy4(op+4, match); - match -= sub2; - } else { - ZSTD_copy8(op, match); - } - op += 8; match += 8; - - if (oMatchEnd > oend-(16-MINMATCH)) { - if (op < oend_w) { - ZSTD_wildcopy(op, match, oend, oend_w - op, ZSTD_overlap_src_before_dst); - match += oend_w - op; - op = oend_w; - } - while (op < oMatchEnd) *op++ = *match++; - } else { - ZSTD_wildcopy(op, match, oend, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst); /* works even if matchLength < 8 */ + /* Match within prefix of 1 or more bytes */ + assert(op <= oMatchEnd); + assert(oMatchEnd <= oend_w); + assert(match >= prefixStart); + assert(sequence.matchLength >= 1); + + /* Nearly all offsets are >= 16 bytes, which means we can use wildcopy + * without overlap checking. + */ + if (sequence.offset >= 16) { + /* Split out matchLength <= 16 since it is nearly always true. +1% on gcc-9. */ + if (sequence.matchLength <= 16) + ZSTD_copy16(op, match); + else + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap); + return sequenceLength; } - return sequenceLength; -} - - -HINT_INLINE -size_t ZSTD_execSequenceLong(BYTE* op, - BYTE* const oend, seq_t sequence, - const BYTE** litPtr, const BYTE* const litLimit, - const BYTE* const prefixStart, const BYTE* const dictStart, const BYTE* const dictEnd) -{ - BYTE* const oLitEnd = op + sequence.litLength; - size_t const sequenceLength = sequence.litLength + sequence.matchLength; - BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */ - BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; - const BYTE* const iLitEnd = *litPtr + sequence.litLength; - const BYTE* match = sequence.match; - - /* check */ - RETURN_ERROR_IF(oMatchEnd > oend, dstSize_tooSmall, "last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend"); - RETURN_ERROR_IF(iLitEnd > litLimit, corruption_detected, "over-read beyond lit buffer"); - if (oLitEnd > oend_w) return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, prefixStart, dictStart, dictEnd); - - /* copy Literals */ - if (sequence.litLength > 8) - ZSTD_wildcopy_16min(op, *litPtr, oend, sequence.litLength, ZSTD_no_overlap); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */ - else - ZSTD_copy8(op, *litPtr); /* note : op <= oLitEnd <= oend_w == oend - 8 */ - - op = oLitEnd; - *litPtr = iLitEnd; /* update for next sequence */ - - /* copy Match */ - if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { - /* offset beyond prefix */ - RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - dictStart), corruption_detected); - if (match + sequence.matchLength <= dictEnd) { - memmove(oLitEnd, match, sequence.matchLength); - return sequenceLength; - } - /* span extDict & currentPrefixSegment */ - { size_t const length1 = dictEnd - match; - memmove(oLitEnd, match, length1); - op = oLitEnd + length1; - sequence.matchLength -= length1; - match = prefixStart; - if (op > oend_w || sequence.matchLength < MINMATCH) { - U32 i; - for (i = 0; i < sequence.matchLength; ++i) op[i] = match[i]; - return sequenceLength; - } - } } - assert(op <= oend_w); - assert(sequence.matchLength >= MINMATCH); + assert(sequence.offset < 16); - /* match within prefix */ - if (sequence.offset < 8) { - /* close range match, overlap */ - static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */ - static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */ - int const sub2 = dec64table[sequence.offset]; - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += dec32table[sequence.offset]; - ZSTD_copy4(op+4, match); - match -= sub2; - } else { - ZSTD_copy8(op, match); - } - op += 8; match += 8; + /* Copy 8 bytes and spread the offset to be >= 8. */ + ZSTD_overlapCopy8(&op, &match, sequence.offset); - if (oMatchEnd > oend-(16-MINMATCH)) { - if (op < oend_w) { - ZSTD_wildcopy(op, match, oend, oend_w - op, ZSTD_overlap_src_before_dst); - match += oend_w - op; - op = oend_w; - } - while (op < oMatchEnd) *op++ = *match++; - } else { - ZSTD_wildcopy(op, match, oend, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst); /* works even if matchLength < 8 */ + /* If the match length is > 8 bytes, then continue with the wildcopy. */ + if (sequence.matchLength > 8) { + assert(op < oMatchEnd); + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst); } return sequenceLength; } @@ -1098,7 +1094,7 @@ ZSTD_decompressSequencesLong_body( /* decode and decompress */ for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) { seq_t const sequence = ZSTD_decodeSequenceLong(&seqState, isLongOffset); - size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd); + size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd); if (ZSTD_isError(oneSeqSize)) return oneSeqSize; PREFETCH_L1(sequence.match); PREFETCH_L1(sequence.match + sequence.matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ sequences[seqNb & STORED_SEQS_MASK] = sequence; @@ -1109,7 +1105,7 @@ ZSTD_decompressSequencesLong_body( /* finish queue */ seqNb -= seqAdvance; for ( ; seqNb<nbSeq ; seqNb++) { - size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd); + size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd); if (ZSTD_isError(oneSeqSize)) return oneSeqSize; op += oneSeqSize; }
3rdn4/zstd:6f40571-unknown_read
/workspace/skyset/
zstd
6f40571-unknown_read
/workspace/skyset/zstd/6f40571-unknown_read/report.txt
A unknown read found in /workspace/skyset/zstd/6f40571-unknown_read/immutable/
From e6c8a5dd40359801bf297dca3be48e38c85ed6c2 Mon Sep 17 00:00:00 2001 From: Sen Huang <senhuang96@fb.com> Date: Tue, 4 May 2021 09:50:44 -0700 Subject: [PATCH] Fix incorrect usages of repIndex across all strategies --- lib/compress/zstd_double_fast.c | 4 ++-- lib/compress/zstd_fast.c | 6 +++--- lib/compress/zstd_lazy.c | 12 ++++++++---- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index b99172e9d2..d0d3a784dd 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -409,7 +409,7 @@ static size_t ZSTD_compressBlock_doubleFast_extDict_generic( hashSmall[hSmall] = hashLong[hLong] = curr; /* update hash table */ if ((((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow : ensure repIndex doesn't overlap dict + prefix */ - & (repIndex > dictStartIndex)) + & (offset_1 < curr+1 - dictStartIndex)) /* note: we are searching at curr+1 */ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) { const BYTE* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixStart) + 4; @@ -477,7 +477,7 @@ static size_t ZSTD_compressBlock_doubleFast_extDict_generic( U32 const repIndex2 = current2 - offset_2; const BYTE* repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2; if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) /* intentional overflow : ensure repIndex2 doesn't overlap dict + prefix */ - & (repIndex2 > dictStartIndex)) + & (offset_2 < current2 - dictStartIndex)) && (MEM_read32(repMatch2) == MEM_read32(ip)) ) { const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixStart) + 4; diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 96b7d48e28..4edc04dccd 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -416,9 +416,9 @@ static size_t ZSTD_compressBlock_fast_extDict_generic( const BYTE* const repMatch = repBase + repIndex; hashTable[h] = curr; /* update hash table */ DEBUGLOG(7, "offset_1 = %u , curr = %u", offset_1, curr); - assert(offset_1 <= curr +1); /* check repIndex */ - if ( (((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow */ & (repIndex > dictStartIndex)) + if ( ( ((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow */ + & (offset_1 < curr+1 - dictStartIndex) ) /* note: we are searching at curr+1 */ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) { const BYTE* const repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; size_t const rLength = ZSTD_count_2segments(ip+1 +4, repMatch +4, iend, repMatchEnd, prefixStart) + 4; @@ -453,7 +453,7 @@ static size_t ZSTD_compressBlock_fast_extDict_generic( U32 const current2 = (U32)(ip-base); U32 const repIndex2 = current2 - offset_2; const BYTE* const repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2; - if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) & (repIndex2 > dictStartIndex)) /* intentional overflow */ + if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) & (offset_2 < curr - dictStartIndex)) /* intentional overflow */ && (MEM_read32(repMatch2) == MEM_read32(ip)) ) { const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixStart) + 4; diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 5d824beed9..3d523e8472 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1994,7 +1994,8 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = (U32)(curr+1 - offset_1); const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > windowLow)) /* intentional overflow */ + if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */ + & (offset_1 < curr+1 - windowLow) ) /* note: we are searching at curr+1 */ if (MEM_read32(ip+1) == MEM_read32(repMatch)) { /* repcode detected we should take it */ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend; @@ -2025,7 +2026,8 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = (U32)(curr - offset_1); const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > windowLow)) /* intentional overflow */ + if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */ + & (offset_1 < curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */ if (MEM_read32(ip) == MEM_read32(repMatch)) { /* repcode detected */ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend; @@ -2056,7 +2058,8 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = (U32)(curr - offset_1); const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > windowLow)) /* intentional overflow */ + if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */ + & (offset_1 < curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */ if (MEM_read32(ip) == MEM_read32(repMatch)) { /* repcode detected */ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend; @@ -2102,7 +2105,8 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = repCurrent - offset_2; const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > windowLow)) /* intentional overflow */ + if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */ + & (offset_2 < repCurrent - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */ if (MEM_read32(ip) == MEM_read32(repMatch)) { /* repcode detected we should take it */ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
3rdn4/zstd:d68aa19-heap_buffer_overflow
/workspace/skyset/
zstd
d68aa19-heap_buffer_overflow
/workspace/skyset/zstd/d68aa19-heap_buffer_overflow/report.txt
A heap buffer overflow found in /workspace/skyset/zstd/d68aa19-heap_buffer_overflow/immutable/
From a7aa2c5df6ced5f3c2019a825cfb08a619cf6851 Mon Sep 17 00:00:00 2001 From: Sen Huang <senhuang96@fb.com> Date: Wed, 15 Sep 2021 09:51:42 -0700 Subject: [PATCH 1/2] Fix NCountWriteBound --- lib/compress/fse_compress.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/compress/fse_compress.c b/lib/compress/fse_compress.c index faca767c5c..5547b4ac09 100644 --- a/lib/compress/fse_compress.c +++ b/lib/compress/fse_compress.c @@ -221,7 +221,11 @@ size_t FSE_buildCTable_wksp(FSE_CTable* ct, ****************************************************************/ size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog) { - size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog) >> 3) + 3; + size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog + + 4 /* bitCount initialized at 4 */ + + 2 /* first two symbols may use one additional bit each */) / 8) + + 1 /* round up to whole nb bytes */ + + 2 /* additional two bytes for bitstream flush */; return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND; /* maxSymbolValue==0 ? use default */ } From 99b5e7b8c28875d0df998be2a4598d2358e37f23 Mon Sep 17 00:00:00 2001 From: senhuang42 <senhuang96@fb.com> Date: Wed, 22 Sep 2021 11:27:56 -0400 Subject: [PATCH 2/2] Add test case for FSE over-write --- tests/fuzzer.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index fff963176f..49f671d170 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3353,6 +3353,23 @@ static int basicUnitTests(U32 const seed, double compressibility) FSE_normalizeCount(norm, tableLog, count, nbSeq, maxSymbolValue, /* useLowProbCount */ 1); } DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3i : testing FSE_writeNCount() PR#2779: ", testNb++); + { + size_t const outBufSize = 9; + short const count[11] = {1, 0, 1, 0, 1, 0, 1, 0, 1, 9, 18}; + unsigned const tableLog = 5; + unsigned const maxSymbolValue = 10; + BYTE* outBuf = (BYTE*)malloc(outBufSize*sizeof(BYTE)); + + /* Ensure that this write doesn't write out of bounds, and that + * FSE_writeNCount_generic() is *not* called with writeIsSafe == 1. + */ + FSE_writeNCount(outBuf, outBufSize, count, maxSymbolValue, tableLog); + free(outBuf); + } + DISPLAYLEVEL(3, "OK \n"); + #ifdef ZSTD_MULTITHREAD DISPLAYLEVEL(3, "test%3i : passing wrong full dict should fail on compressStream2 refPrefix ", testNb++); { ZSTD_CCtx* cctx = ZSTD_createCCtx();