text
stringlengths
486
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: switch (yych) { case 'a': goto yy10; default: goto yy11; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* const context) override { // node_id_range const Tensor* node_id_range_t; OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t)); const auto node_id_range = node_id_range_t->vec<int32>(); const int32_t node_id_first = node_id_range(0); // inclusive const int32_t node_id_last = node_id_range(1); // exclusive const Tensor* stats_summary_t; OP_REQUIRES_OK(context, context->input("stats_summary", &stats_summary_t)); TTypes<float, 4>::ConstTensor stats_summary = stats_summary_t->tensor<float, 4>(); const int32_t feature_dims = stats_summary_t->dim_size(1); // The last bucket is for default/missing value. const int32_t num_buckets = stats_summary_t->dim_size(2) - 1; const int32_t logits_dim = logits_dim_; const int32_t hessian_dim = stats_summary_t->dim_size(3) - logits_dim; DCHECK_GT(hessian_dim, 0); DCHECK_LE(hessian_dim, logits_dim * logits_dim); const Tensor* l1_t; OP_REQUIRES_OK(context, context->input("l1", &l1_t)); const auto l1 = l1_t->scalar<float>()(); DCHECK_GE(l1, 0); if (logits_dim_ > 1) { // Multi-class L1 regularization not supported yet. DCHECK_EQ(l1, 0); } const Tensor* l2_t; OP_REQUIRES_OK(context, context->input("l2", &l2_t)); const auto l2 = l2_t->scalar<float>()(); DCHECK_GE(l2, 0); const Tensor* tree_complexity_t; OP_REQUIRES_OK(context, context->input("tree_complexity", &tree_complexity_t)); const auto tree_complexity = tree_complexity_t->scalar<float>()(); const Tensor* min_node_weight_t; OP_REQUIRES_OK(context, context->input("min_node_weight", &min_node_weight_t)); const auto min_node_weight = min_node_weight_t->scalar<float>()(); std::vector<int32> output_node_ids; std::vector<float> output_gains; std::vector<int32> output_feature_dimensions; std::vector<int32> output_thresholds; std::vector<Eigen::VectorXf> output_left_node_contribs; std::vector<Eigen::VectorXf> output_right_node_contribs; std::vector<string> output_split_types; // TODO(tanzheny) parallelize the computation. // Iterate each node and find the best gain per node. for (int32_t node_id = node_id_first; node_id < node_id_last; ++node_id) { float best_gain = std::numeric_limits<float>::lowest(); int32_t best_bucket = 0; int32_t best_f_dim = 0; string best_split_type; Eigen::VectorXf best_contrib_for_left(logits_dim); Eigen::VectorXf best_contrib_for_right(logits_dim); float parent_gain; // Including default bucket. ConstMatrixMap stats_mat(&stats_summary(node_id, 0, 0, 0), num_buckets + 1, logits_dim + hessian_dim); const Eigen::VectorXf total_grad = stats_mat.leftCols(logits_dim).colwise().sum(); const Eigen::VectorXf total_hess = stats_mat.rightCols(hessian_dim).colwise().sum(); if (total_hess.norm() < min_node_weight) { continue; } Eigen::VectorXf parent_weight(logits_dim); CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &parent_weight, &parent_gain); if (split_type_ == "inequality") { CalculateBestInequalitySplit( stats_summary, node_id, feature_dims, logits_dim, hessian_dim, num_buckets, min_node_weight, l1, l2, &best_gain, &best_bucket, &best_f_dim, &best_split_type, &best_contrib_for_left, &best_contrib_for_right); } else { CalculateBestEqualitySplit( stats_summary, total_grad, total_hess, node_id, feature_dims, logits_dim, hessian_dim, num_buckets, l1, l2, &best_gain, &best_bucket, &best_f_dim, &best_split_type, &best_contrib_for_left, &best_contrib_for_right); } if (best_gain == std::numeric_limits<float>::lowest()) { // Do not add the node if not split if found. continue; } output_node_ids.push_back(node_id); // Remove the parent gain for the parent node. output_gains.push_back(best_gain - parent_gain); output_feature_dimensions.push_back(best_f_dim); // default direction is fixed for dense splits. // TODO(tanzheny) account for default values. output_split_types.push_back(best_split_type); output_thresholds.push_back(best_bucket); output_left_node_contribs.push_back(best_contrib_for_left); output_right_node_contribs.push_back(best_contrib_for_right); } // for node id const int num_nodes = output_node_ids.size(); // output_node_ids Tensor* output_node_ids_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output("node_ids", {num_nodes}, &output_node_ids_t)); auto output_node_ids_vec = output_node_ids_t->vec<int32>(); // output_gains Tensor* output_gains_t; OP_REQUIRES_OK(context, context->allocate_output("gains", {num_nodes}, &output_gains_t)); auto output_gains_vec = output_gains_t->vec<float>(); // output_feature_dimensions Tensor* output_feature_dimension_t; OP_REQUIRES_OK(context, context->allocate_output("feature_dimensions", {num_nodes}, &output_feature_dimension_t)); auto output_feature_dimensions_vec = output_feature_dimension_t->vec<int32>(); // output_thresholds Tensor* output_thresholds_t; OP_REQUIRES_OK(context, context->allocate_output("thresholds", {num_nodes}, &output_thresholds_t)); auto output_thresholds_vec = output_thresholds_t->vec<int32>(); // output_left_node_contribs Tensor* output_left_node_contribs_t; OP_REQUIRES_OK(context, context->allocate_output( "left_node_contribs", {num_nodes, logits_dim}, &output_left_node_contribs_t)); auto output_left_node_contribs_matrix = output_left_node_contribs_t->matrix<float>(); // output_right_node_contribs Tensor* output_right_node_contribs_t; OP_REQUIRES_OK(context, context->allocate_output( "right_node_contribs", {num_nodes, logits_dim}, &output_right_node_contribs_t)); auto output_right_node_contribs_matrix = output_right_node_contribs_t->matrix<float>(); // split type Tensor* output_split_types_t; OP_REQUIRES_OK( context, context->allocate_output("split_with_default_directions", {num_nodes}, &output_split_types_t)); auto output_split_types_vec = output_split_types_t->vec<tstring>(); // Sets output tensors from vectors. for (int i = 0; i < num_nodes; ++i) { output_node_ids_vec(i) = output_node_ids[i]; // Adjust the gains to penalize by tree complexity. output_gains_vec(i) = output_gains[i] - tree_complexity; output_feature_dimensions_vec(i) = output_feature_dimensions[i]; output_thresholds_vec(i) = output_thresholds[i]; for (int j = 0; j < logits_dim; ++j) { output_left_node_contribs_matrix(i, j) = output_left_node_contribs[i][j]; output_right_node_contribs_matrix(i, j) = output_right_node_contribs[i][j]; } output_split_types_vec(i) = output_split_types[i]; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-824'], 'message': 'Add remaining missing validation to `BoostedTreesCalculateBestFeatureSplit` PiperOrigin-RevId: 387423006 Change-Id: I8eaf30efb223011519e60707bfa751b275d3a443'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug if using an undefined member of an object for for..in (fix #1437)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PicContext *s = avctx->priv_data; AVFrame *frame = data; uint32_t *palette; int bits_per_plane, bpp, etype, esize, npal, pos_after_pal; int i, x, y, plane, tmp, ret, val; bytestream2_init(&s->g, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&s->g) < 11) return AVERROR_INVALIDDATA; if (bytestream2_get_le16u(&s->g) != 0x1234) return AVERROR_INVALIDDATA; s->width = bytestream2_get_le16u(&s->g); s->height = bytestream2_get_le16u(&s->g); bytestream2_skip(&s->g, 4); tmp = bytestream2_get_byteu(&s->g); bits_per_plane = tmp & 0xF; s->nb_planes = (tmp >> 4) + 1; bpp = bits_per_plane * s->nb_planes; if (bits_per_plane > 8 || bpp < 1 || bpp > 32) { avpriv_request_sample(avctx, "Unsupported bit depth"); return AVERROR_PATCHWELCOME; } if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) { bytestream2_skip(&s->g, 2); etype = bytestream2_get_le16(&s->g); esize = bytestream2_get_le16(&s->g); if (bytestream2_get_bytes_left(&s->g) < esize) return AVERROR_INVALIDDATA; } else { etype = -1; esize = 0; } avctx->pix_fmt = AV_PIX_FMT_PAL8; if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; if (s->width != avctx->width && s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; } if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; memset(frame->data[0], 0, s->height * frame->linesize[0]); frame->pict_type = AV_PICTURE_TYPE_I; frame->palette_has_changed = 1; pos_after_pal = bytestream2_tell(&s->g) + esize; palette = (uint32_t*)frame->data[1]; if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) { int idx = bytestream2_get_byte(&s->g); npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ]; } else if (etype == 2) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)]; } } else if (etype == 3) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)]; } } else if (etype == 4 || etype == 5) { npal = FFMIN(esize / 3, 256); for (i = 0; i < npal; i++) { palette[i] = bytestream2_get_be24(&s->g) << 2; palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303; } } else { if (bpp == 1) { npal = 2; palette[0] = 0xFF000000; palette[1] = 0xFFFFFFFF; } else if (bpp == 2) { npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ]; } else { npal = 16; memcpy(palette, ff_cga_palette, npal * 4); } } // fill remaining palette entries memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4); // skip remaining palette bytes bytestream2_seek(&s->g, pos_after_pal, SEEK_SET); val = 0; y = s->height - 1; if (bytestream2_get_le16(&s->g)) { x = 0; plane = 0; while (bytestream2_get_bytes_left(&s->g) >= 6) { int stop_size, marker, t1, t2; t1 = bytestream2_get_bytes_left(&s->g); t2 = bytestream2_get_le16(&s->g); stop_size = t1 - FFMIN(t1, t2); // ignore uncompressed block size bytestream2_skip(&s->g, 2); marker = bytestream2_get_byte(&s->g); while (plane < s->nb_planes && bytestream2_get_bytes_left(&s->g) > stop_size) { int run = 1; val = bytestream2_get_byte(&s->g); if (val == marker) { run = bytestream2_get_byte(&s->g); if (run == 0) run = bytestream2_get_le16(&s->g); val = bytestream2_get_byte(&s->g); } if (!bytestream2_get_bytes_left(&s->g)) break; if (bits_per_plane == 8) { picmemset_8bpp(s, frame, val, run, &x, &y); if (y < 0) goto finish; } else { picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane); } } } if (x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); else picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane); } } else { while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) { memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g))); bytestream2_skip(&s->g, avctx->width); y--; } } finish: *got_frame = 1; return avpkt->size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/pictordec: Fix logic error Fixes: 559/clusterfuzz-testcase-6424225917173760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CollationCreate(const char *collname, Oid collnamespace, Oid collowner, char collprovider, int32 collencoding, const char *collcollate, const char *collctype, const char *collversion, bool if_not_exists, bool quiet) { Relation rel; TupleDesc tupDesc; HeapTuple tup; Datum values[Natts_pg_collation]; bool nulls[Natts_pg_collation]; NameData name_name, name_collate, name_ctype; Oid oid; ObjectAddress myself, referenced; AssertArg(collname); AssertArg(collnamespace); AssertArg(collowner); AssertArg(collcollate); AssertArg(collctype); /* * Make sure there is no existing collation of same name & encoding. * * This would be caught by the unique index anyway; we're just giving a * friendlier error message. The unique index provides a backstop against * race conditions. */ if (SearchSysCacheExists3(COLLNAMEENCNSP, PointerGetDatum(collname), Int32GetDatum(collencoding), ObjectIdGetDatum(collnamespace))) { if (quiet) return InvalidOid; else if (if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), collencoding == -1 ? errmsg("collation \"%s\" already exists, skipping", collname) : errmsg("collation \"%s\" for encoding \"%s\" already exists, skipping", collname, pg_encoding_to_char(collencoding)))); return InvalidOid; } else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), collencoding == -1 ? errmsg("collation \"%s\" already exists", collname) : errmsg("collation \"%s\" for encoding \"%s\" already exists", collname, pg_encoding_to_char(collencoding)))); } /* open pg_collation; see below about the lock level */ rel = heap_open(CollationRelationId, ShareRowExclusiveLock); /* * Also forbid a specific-encoding collation shadowing an any-encoding * collation, or an any-encoding collation being shadowed (see * get_collation_name()). This test is not backed up by the unique index, * so we take a ShareRowExclusiveLock earlier, to protect against * concurrent changes fooling this check. */ if ((collencoding == -1 && SearchSysCacheExists3(COLLNAMEENCNSP, PointerGetDatum(collname), Int32GetDatum(GetDatabaseEncoding()), ObjectIdGetDatum(collnamespace))) || (collencoding != -1 && SearchSysCacheExists3(COLLNAMEENCNSP, PointerGetDatum(collname), Int32GetDatum(-1), ObjectIdGetDatum(collnamespace)))) { if (quiet) { heap_close(rel, NoLock); return InvalidOid; } else if (if_not_exists) { heap_close(rel, NoLock); ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("collation \"%s\" already exists, skipping", collname))); return InvalidOid; } else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("collation \"%s\" already exists", collname))); } tupDesc = RelationGetDescr(rel); /* form a tuple */ memset(nulls, 0, sizeof(nulls)); namestrcpy(&name_name, collname); values[Anum_pg_collation_collname - 1] = NameGetDatum(&name_name); values[Anum_pg_collation_collnamespace - 1] = ObjectIdGetDatum(collnamespace); values[Anum_pg_collation_collowner - 1] = ObjectIdGetDatum(collowner); values[Anum_pg_collation_collprovider - 1] = CharGetDatum(collprovider); values[Anum_pg_collation_collencoding - 1] = Int32GetDatum(collencoding); namestrcpy(&name_collate, collcollate); values[Anum_pg_collation_collcollate - 1] = NameGetDatum(&name_collate); namestrcpy(&name_ctype, collctype); values[Anum_pg_collation_collctype - 1] = NameGetDatum(&name_ctype); if (collversion) values[Anum_pg_collation_collversion - 1] = CStringGetTextDatum(collversion); else nulls[Anum_pg_collation_collversion - 1] = true; tup = heap_form_tuple(tupDesc, values, nulls); /* insert a new tuple */ oid = CatalogTupleInsert(rel, tup); Assert(OidIsValid(oid)); /* set up dependencies for the new collation */ myself.classId = CollationRelationId; myself.objectId = oid; myself.objectSubId = 0; /* create dependency on namespace */ referenced.classId = NamespaceRelationId; referenced.objectId = collnamespace; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); /* create dependency on owner */ recordDependencyOnOwner(CollationRelationId, HeapTupleGetOid(tup), collowner); /* dependency on extension */ recordDependencyOnCurrentExtension(&myself, false); /* Post creation hook for new collation */ InvokeObjectPostCreateHook(CollationRelationId, oid, 0); heap_freetuple(tup); heap_close(rel, NoLock); return oid; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void server_real_connect(SERVER_REC *server, IPADDR *ip, const char *unix_socket) { GIOChannel *handle; IPADDR *own_ip = NULL; const char *errmsg; char *errmsg2; char ipaddr[MAX_IP_LEN]; int port; g_return_if_fail(ip != NULL || unix_socket != NULL); signal_emit("server connecting", 2, server, ip); if (server->connrec->no_connect) return; if (ip != NULL) { own_ip = ip == NULL ? NULL : (IPADDR_IS_V6(ip) ? server->connrec->own_ip6 : server->connrec->own_ip4); port = server->connrec->proxy != NULL ? server->connrec->proxy_port : server->connrec->port; handle = server->connrec->use_ssl ? net_connect_ip_ssl(ip, port, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey, server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) : net_connect_ip(ip, port, own_ip); } else { handle = net_connect_unix(unix_socket); } if (handle == NULL) { /* failed */ errmsg = g_strerror(errno); errmsg2 = NULL; if (errno == EADDRNOTAVAIL) { if (own_ip != NULL) { /* show the IP which is causing the error */ net_ip2host(own_ip, ipaddr); errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL); } server->no_reconnect = TRUE; } if (server->connrec->use_ssl && errno == ENOSYS) server->no_reconnect = TRUE; server->connection_lost = TRUE; server_connect_failed(server, errmsg2 ? errmsg2 : errmsg); g_free(errmsg2); } else { server->handle = net_sendbuffer_create(handle, 0); #ifdef HAVE_OPENSSL if (server->connrec->use_ssl) server_connect_callback_init_ssl(server, handle); else #endif server->connect_tag = g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ, (GInputFunction) server_connect_callback_init, server); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Check if an SSL certificate matches the hostname of the server we are connecting to git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* const context) override { // node_id_range const Tensor* node_id_range_t; OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t)); OP_REQUIRES( context, node_id_range_t->dims() == 1, errors::InvalidArgument("node_id_range must be a rank 1 tensor, but " "given node_id_range has dims of ", node_id_range_t->dims())); OP_REQUIRES(context, node_id_range_t->dim_size(0) == 2, errors::InvalidArgument( "node_id_range must be a rank 1 tensor with shape=[2], but " "given node_id_range has shape ", node_id_range_t->dim_size(0), " on its first dim")); const auto node_id_range = node_id_range_t->vec<int32>(); const int32_t node_id_first = node_id_range(0); // inclusive const int32_t node_id_last = node_id_range(1); // exclusive // stats_summary_list OpInputList stats_summary_list; OP_REQUIRES_OK(context, context->input_list("stats_summary_list", &stats_summary_list)); const int64_t num_buckets = stats_summary_list[0].dim_size(1); // Check for single logit: 1 gradient + 1 hessian value. DCHECK_EQ(stats_summary_list[0].dim_size(2), 2); std::vector<TTypes<float, 3>::ConstTensor> stats_summary; stats_summary.reserve(stats_summary_list.size()); for (const auto& tensor : stats_summary_list) { stats_summary.emplace_back(tensor.tensor<float, 3>()); } const Tensor* l1_t; OP_REQUIRES_OK(context, context->input("l1", &l1_t)); const auto l1 = l1_t->scalar<float>()(); const Tensor* l2_t; OP_REQUIRES_OK(context, context->input("l2", &l2_t)); const auto l2 = l2_t->scalar<float>()(); const Tensor* tree_complexity_t; OP_REQUIRES_OK(context, context->input("tree_complexity", &tree_complexity_t)); const auto tree_complexity = tree_complexity_t->scalar<float>()(); const Tensor* min_node_weight_t; OP_REQUIRES_OK(context, context->input("min_node_weight", &min_node_weight_t)); const auto min_node_weight = min_node_weight_t->scalar<float>()(); // Allocate output lists of tensors: OpOutputList output_node_ids_list; OP_REQUIRES_OK( context, context->output_list("node_ids_list", &output_node_ids_list)); OpOutputList output_gains_list; OP_REQUIRES_OK(context, context->output_list("gains_list", &output_gains_list)); OpOutputList output_thresholds_list; OP_REQUIRES_OK(context, context->output_list("thresholds_list", &output_thresholds_list)); OpOutputList output_left_node_contribs_list; OP_REQUIRES_OK(context, context->output_list("left_node_contribs_list", &output_left_node_contribs_list)); OpOutputList output_right_node_contribs_list; OP_REQUIRES_OK(context, context->output_list("right_node_contribs_list", &output_right_node_contribs_list)); // Use identity later to convert float to Eigen::Matrix type for input to // CalculateWeightsAndGains. This op only supports single dimension logits. Eigen::MatrixXf identity; identity.setIdentity(1, 1); // Get the best split info per node for each feature. for (int feature_idx = 0; feature_idx < num_features_; ++feature_idx) { std::vector<float> cum_grad; std::vector<float> cum_hess; cum_grad.reserve(num_buckets); cum_hess.reserve(num_buckets); std::vector<int32> output_node_ids; std::vector<float> output_gains; std::vector<int32> output_thresholds; std::vector<float> output_left_node_contribs; std::vector<float> output_right_node_contribs; for (int node_id = node_id_first; node_id < node_id_last; ++node_id) { // Calculate gains. cum_grad.clear(); cum_hess.clear(); float total_grad = 0.0; float total_hess = 0.0; for (int bucket = 0; bucket < num_buckets; ++bucket) { // TODO(nponomareva): Consider multi-dimensional gradients/hessians. total_grad += stats_summary[feature_idx](node_id, bucket, 0); total_hess += stats_summary[feature_idx](node_id, bucket, 1); cum_grad.push_back(total_grad); cum_hess.push_back(total_hess); } // Check if node has enough of average hessian. if (total_hess < min_node_weight) { // Do not split the node because not enough avg hessian. continue; } float best_gain = std::numeric_limits<float>::lowest(); float best_bucket = 0; float best_contrib_for_left = 0.0; float best_contrib_for_right = 0.0; // Parent gain. float parent_gain; Eigen::VectorXf unused(1); CalculateWeightsAndGains(total_grad * identity, total_hess * identity, l1, l2, &unused, &parent_gain); for (int bucket = 0; bucket < num_buckets; ++bucket) { const float cum_grad_bucket = cum_grad[bucket]; const float cum_hess_bucket = cum_hess[bucket]; // Left child. Eigen::VectorXf contrib_for_left(1); float gain_for_left; CalculateWeightsAndGains(cum_grad_bucket * identity, cum_hess_bucket * identity, l1, l2, &contrib_for_left, &gain_for_left); // Right child. // use contrib_for_right. Eigen::VectorXf contrib_for_right(1); float gain_for_right; CalculateWeightsAndGains((total_grad - cum_grad_bucket) * identity, (total_hess - cum_hess_bucket) * identity, l1, l2, &contrib_for_right, &gain_for_right); if (GainIsLarger(gain_for_left + gain_for_right, best_gain)) { best_gain = gain_for_left + gain_for_right; best_bucket = bucket; best_contrib_for_left = contrib_for_left[0]; best_contrib_for_right = contrib_for_right[0]; } } // for bucket output_node_ids.push_back(node_id); // Remove the parent gain for the parent node. output_gains.push_back(best_gain - parent_gain); output_thresholds.push_back(best_bucket); output_left_node_contribs.push_back(best_contrib_for_left); output_right_node_contribs.push_back(best_contrib_for_right); } // for node_id const int num_nodes = output_node_ids.size(); // output_node_ids Tensor* output_node_ids_t; OP_REQUIRES_OK(context, output_node_ids_list.allocate(feature_idx, {num_nodes}, &output_node_ids_t)); auto output_node_ids_vec = output_node_ids_t->vec<int32>(); // output_gains Tensor* output_gains_t; OP_REQUIRES_OK(context, output_gains_list.allocate( feature_idx, {num_nodes}, &output_gains_t)); auto output_gains_vec = output_gains_t->vec<float>(); // output_thresholds Tensor* output_thresholds_t; OP_REQUIRES_OK(context, output_thresholds_list.allocate(feature_idx, {num_nodes}, &output_thresholds_t)); auto output_thresholds_vec = output_thresholds_t->vec<int32>(); // output_left_node_contribs Tensor* output_left_node_contribs_t; OP_REQUIRES_OK(context, output_left_node_contribs_list.allocate( feature_idx, {num_nodes, 1}, &output_left_node_contribs_t)); auto output_left_node_contribs_matrix = output_left_node_contribs_t->matrix<float>(); // output_right_node_contribs Tensor* output_right_node_contribs_t; OP_REQUIRES_OK(context, output_right_node_contribs_list.allocate( feature_idx, {num_nodes, 1}, &output_right_node_contribs_t)); auto output_right_node_contribs_matrix = output_right_node_contribs_t->matrix<float>(); // Sets output tensors from vectors. for (int i = 0; i < num_nodes; ++i) { output_node_ids_vec(i) = output_node_ids[i]; // Adjust the gains to penalize by tree complexity. output_gains_vec(i) = output_gains[i] - tree_complexity; output_thresholds_vec(i) = output_thresholds[i]; output_left_node_contribs_matrix(i, 0) = output_left_node_contribs[i]; // This op only supports 1-dimensional logits. output_right_node_contribs_matrix(i, 0) = output_right_node_contribs[i]; } } // for f } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-369'], 'message': 'Fixing security fixes in boosted trees ops PiperOrigin-RevId: 405669548 Change-Id: Iae224d240d1779bcc02405c2fff99785644fbd0d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, uint8_t attrtype) { unsigned int attrlenfield = 0; unsigned int attrhdrlen = 0; struct bgp_attr_encap_subtlv *subtlvs; struct bgp_attr_encap_subtlv *st; const char *attrname; if (!attr || (attrtype == BGP_ATTR_ENCAP && (!attr->encap_tunneltype || attr->encap_tunneltype == BGP_ENCAP_TYPE_MPLS))) return; switch (attrtype) { case BGP_ATTR_ENCAP: attrname = "Tunnel Encap"; subtlvs = attr->encap_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; /* * The tunnel encap attr has an "outer" tlv. * T = tunneltype, * L = total length of subtlvs, * V = concatenated subtlvs. */ attrlenfield = 2 + 2; /* T + L */ attrhdrlen = 1 + 1; /* subTLV T + L */ break; #if ENABLE_BGP_VNC case BGP_ATTR_VNC: attrname = "VNC"; subtlvs = attr->vnc_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; attrlenfield = 0; /* no outer T + L */ attrhdrlen = 2 + 2; /* subTLV T + L */ break; #endif default: assert(0); } /* compute attr length */ for (st = subtlvs; st; st = st->next) { attrlenfield += (attrhdrlen + st->length); } if (attrlenfield > 0xffff) { zlog_info("%s attribute is too long (length=%d), can't send it", attrname, attrlenfield); return; } if (attrlenfield > 0xff) { /* 2-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, attrtype); stream_putw(s, attrlenfield & 0xffff); } else { /* 1-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, attrtype); stream_putc(s, attrlenfield & 0xff); } if (attrtype == BGP_ATTR_ENCAP) { /* write outer T+L */ stream_putw(s, attr->encap_tunneltype); stream_putw(s, attrlenfield - 4); } /* write each sub-tlv */ for (st = subtlvs; st; st = st->next) { if (attrtype == BGP_ATTR_ENCAP) { stream_putc(s, st->type); stream_putc(s, st->length); #if ENABLE_BGP_VNC } else { stream_putw(s, st->type); stream_putw(s, st->length); #endif } stream_put(s, st->value, st->length); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-436'], 'message': 'bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <lberger@labn.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err adts_dmx_process(GF_Filter *filter) { GF_ADTSDmxCtx *ctx = gf_filter_get_udta(filter); GF_FilterPacket *pck, *dst_pck; u8 *data, *output; u8 *start; u32 pck_size, remain, prev_pck_size; u64 cts = GF_FILTER_NO_TS; //always reparse duration if (!ctx->duration.num) adts_dmx_check_dur(filter, ctx); if (ctx->opid && !ctx->is_playing) return GF_OK; pck = gf_filter_pid_get_packet(ctx->ipid); if (!pck) { if (gf_filter_pid_is_eos(ctx->ipid)) { if (!ctx->adts_buffer_size) { if (ctx->opid) gf_filter_pid_set_eos(ctx->opid); if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = NULL; return GF_EOS; } } else { return GF_OK; } } prev_pck_size = ctx->adts_buffer_size; if (pck && !ctx->resume_from) { data = (char *) gf_filter_pck_get_data(pck, &pck_size); if (!pck_size) { gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; } if (ctx->byte_offset != GF_FILTER_NO_BO) { u64 byte_offset = gf_filter_pck_get_byte_offset(pck); if (!ctx->adts_buffer_size) { ctx->byte_offset = byte_offset; } else if (ctx->byte_offset + ctx->adts_buffer_size != byte_offset) { ctx->byte_offset = GF_FILTER_NO_BO; if ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->adts_buffer_size) ) { ctx->byte_offset = byte_offset - ctx->adts_buffer_size; } } } if (ctx->adts_buffer_size + pck_size > ctx->adts_buffer_alloc) { ctx->adts_buffer_alloc = ctx->adts_buffer_size + pck_size; ctx->adts_buffer = gf_realloc(ctx->adts_buffer, ctx->adts_buffer_alloc); } memcpy(ctx->adts_buffer + ctx->adts_buffer_size, data, pck_size); ctx->adts_buffer_size += pck_size; } //input pid sets some timescale - we flushed pending data , update cts if (ctx->timescale && pck) { cts = gf_filter_pck_get_cts(pck); } if (cts == GF_FILTER_NO_TS) { //avoids updating cts prev_pck_size = 0; } remain = ctx->adts_buffer_size; start = ctx->adts_buffer; if (ctx->resume_from) { start += ctx->resume_from - 1; remain -= ctx->resume_from - 1; ctx->resume_from = 0; } while (remain) { u8 *sync; u32 sync_pos, size, offset, bytes_to_drop=0, nb_blocks_per_frame; if (!ctx->tag_size && (remain>3)) { /* Did we read an ID3v2 ? */ if (start[0] == 'I' && start[1] == 'D' && start[2] == '3') { if (remain<10) return GF_OK; ctx->tag_size = ((start[9] & 0x7f) + ((start[8] & 0x7f) << 7) + ((start[7] & 0x7f) << 14) + ((start[6] & 0x7f) << 21)); bytes_to_drop = 10; if (ctx->id3_buffer_alloc < ctx->tag_size+10) { ctx->id3_buffer = gf_realloc(ctx->id3_buffer, ctx->tag_size+10); ctx->id3_buffer_alloc = ctx->tag_size+10; } memcpy(ctx->id3_buffer, start, 10); ctx->id3_buffer_size = 10; goto drop_byte; } } if (ctx->tag_size) { if (ctx->tag_size>remain) { bytes_to_drop = remain; ctx->tag_size-=remain; } else { bytes_to_drop = ctx->tag_size; ctx->tag_size = 0; } memcpy(ctx->id3_buffer + ctx->id3_buffer_size, start, bytes_to_drop); ctx->id3_buffer_size += bytes_to_drop; if (!ctx->tag_size && ctx->opid) { id3dmx_flush(filter, ctx->id3_buffer, ctx->id3_buffer_size, ctx->opid, ctx->expart ? &ctx->vpid : NULL); ctx->id3_buffer_size = 0; } goto drop_byte; } sync = memchr(start, 0xFF, remain); sync_pos = (u32) (sync ? sync - start : remain); //couldn't find sync byte in this packet if (remain - sync_pos < 7) { break; } //not sync ! if ((sync[1] & 0xF0) != 0xF0) { GF_LOG(ctx->nb_frames ? GF_LOG_WARNING : GF_LOG_DEBUG, GF_LOG_PARSER, ("[ADTSDmx] invalid ADTS sync bytes, resyncing\n")); ctx->nb_frames = 0; goto drop_byte; } if (!ctx->bs) { ctx->bs = gf_bs_new(sync + 1, remain - sync_pos - 1, GF_BITSTREAM_READ); } else { gf_bs_reassign_buffer(ctx->bs, sync + 1, remain - sync_pos - 1); } //ok parse header gf_bs_read_int(ctx->bs, 4); ctx->hdr.is_mp2 = (Bool)gf_bs_read_int(ctx->bs, 1); //if (ctx->mpeg4) //we deprecate old MPEG-2 signaling for AAC in ISOBMFF, as it is not well supported anyway and we don't write adif_header as //supposed to be for these types ctx->hdr.is_mp2 = 0; gf_bs_read_int(ctx->bs, 2); ctx->hdr.no_crc = (Bool)gf_bs_read_int(ctx->bs, 1); ctx->hdr.profile = 1 + gf_bs_read_int(ctx->bs, 2); ctx->hdr.sr_idx = gf_bs_read_int(ctx->bs, 4); gf_bs_read_int(ctx->bs, 1); ctx->hdr.nb_ch = gf_bs_read_int(ctx->bs, 3); gf_bs_read_int(ctx->bs, 4); ctx->hdr.frame_size = gf_bs_read_int(ctx->bs, 13); gf_bs_read_int(ctx->bs, 11); nb_blocks_per_frame = gf_bs_read_int(ctx->bs, 2); ctx->hdr.hdr_size = 7; if (!ctx->hdr.no_crc) { u32 skip; if (!nb_blocks_per_frame) { skip = 2; } else { skip = 2 + 2*nb_blocks_per_frame; //and we have 2 bytes per raw_data_block } ctx->hdr.hdr_size += skip; gf_bs_skip_bytes(ctx->bs, skip); } if (!ctx->hdr.frame_size || !GF_M4ASampleRates[ctx->hdr.sr_idx]) { GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("[ADTSDmx] Invalid ADTS frame header, resyncing\n")); ctx->nb_frames = 0; goto drop_byte; } if ((nb_blocks_per_frame>2) || (nb_blocks_per_frame && ctx->hdr.nb_ch)) { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[ADTSDmx] Unsupported multi-block ADTS frame header - patch welcome\n")); ctx->nb_frames = 0; goto drop_byte; } else if (!nb_blocks_per_frame) { if (ctx->aacchcfg<0) ctx->hdr.nb_ch = -ctx->aacchcfg; else if (!ctx->hdr.nb_ch) ctx->hdr.nb_ch = ctx->aacchcfg; if (!ctx->hdr.nb_ch) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[ADTSDmx] Missing channel configuration in ADTS frame header, defaulting to stereo - use `--aacchcfg` to force config\n")); ctx->hdr.nb_ch = ctx->aacchcfg = 2; } } if (nb_blocks_per_frame==2) { u32 pos = (u32) gf_bs_get_position(ctx->bs); gf_m4a_parse_program_config_element(ctx->bs, &ctx->acfg); if (!ctx->hdr.no_crc) gf_bs_skip_bytes(ctx->bs, 2); //per block CRC ctx->hdr.hdr_size += (u32) gf_bs_get_position(ctx->bs) - pos; } //value 1->6 match channel number, value 7 is 7.1 if (ctx->hdr.nb_ch==7) ctx->hdr.nb_ch = 8; //ready to send packet if (ctx->hdr.frame_size + 1 < remain) { u32 next_frame = ctx->hdr.frame_size; //make sure we are sync! if ((sync[next_frame] !=0xFF) || ((sync[next_frame+1] & 0xF0) !=0xF0) ) { GF_LOG(ctx->nb_frames ? GF_LOG_WARNING : GF_LOG_DEBUG, GF_LOG_PARSER, ("[ADTSDmx] invalid next ADTS frame sync, resyncing\n")); ctx->nb_frames = 0; goto drop_byte; } } //otherwise wait for next frame, unless if end of stream else if (pck) { if (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) { ctx->cts = cts; } break; } adts_dmx_check_pid(filter, ctx); if (!ctx->is_playing) { ctx->resume_from = 1 + ctx->adts_buffer_size - remain; return GF_OK; } ctx->nb_frames++; size = ctx->hdr.frame_size - ctx->hdr.hdr_size; offset = ctx->hdr.hdr_size; //per raw-block CRC if ((nb_blocks_per_frame==2) && !ctx->hdr.no_crc) size -= 2; if (ctx->in_seek) { u64 nb_samples_at_seek = (u64) (ctx->start_range * GF_M4ASampleRates[ctx->sr_idx]); if (ctx->cts + ctx->dts_inc >= nb_samples_at_seek) { //u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek; ctx->in_seek = GF_FALSE; } } bytes_to_drop = ctx->hdr.frame_size; if (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) { ctx->cts = cts; cts = GF_FILTER_NO_TS; } if (!ctx->in_seek) { dst_pck = gf_filter_pck_new_alloc(ctx->opid, size, &output); if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); memcpy(output, sync + offset, size); gf_filter_pck_set_dts(dst_pck, ctx->cts); gf_filter_pck_set_cts(dst_pck, ctx->cts); gf_filter_pck_set_duration(dst_pck, ctx->dts_inc); gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE); gf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1); if (ctx->byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset + ctx->hdr.hdr_size); } gf_filter_pck_send(dst_pck); } adts_dmx_update_cts(ctx); //truncated last frame if (bytes_to_drop>remain) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[ADTSDmx] truncated ADTS frame!\n")); bytes_to_drop=remain; } drop_byte: if (!bytes_to_drop) { bytes_to_drop = 1; } start += bytes_to_drop; remain -= bytes_to_drop; if (prev_pck_size) { if (prev_pck_size > bytes_to_drop) prev_pck_size -= bytes_to_drop; else { prev_pck_size=0; if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = pck; if (pck) gf_filter_pck_ref_props(&ctx->src_pck); } } if (ctx->byte_offset != GF_FILTER_NO_BO) ctx->byte_offset += bytes_to_drop; } if (!pck) { ctx->adts_buffer_size = 0; return adts_dmx_process(filter); } else { if (remain) { memmove(ctx->adts_buffer, start, remain); } ctx->adts_buffer_size = remain; gf_filter_pid_drop_packet(ctx->ipid); } return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'fixed potential crash in adts reframer with broken streams - cf #1723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline ut8 r_read_le8(const void *src) { return r_read_ble8 (src); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix #6816 - null deref in r_read_*'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk, struct sctp_association *assoc, sctp_socket_type_t type) { struct sctp_sock *oldsp = sctp_sk(oldsk); struct sctp_sock *newsp = sctp_sk(newsk); struct sctp_bind_bucket *pp; /* hash list port iterator */ struct sctp_endpoint *newep = newsp->ep; struct sk_buff *skb, *tmp; struct sctp_ulpevent *event; int flags = 0; /* Migrate socket buffer sizes and all the socket level options to the * new socket. */ newsk->sk_sndbuf = oldsk->sk_sndbuf; newsk->sk_rcvbuf = oldsk->sk_rcvbuf; /* Brute force copy old sctp opt. */ inet_sk_copy_descendant(newsk, oldsk); /* Restore the ep value that was overwritten with the above structure * copy. */ newsp->ep = newep; newsp->hmac = NULL; /* Hook this new socket in to the bind_hash list. */ pp = sctp_sk(oldsk)->bind_hash; sk_add_bind_node(newsk, &pp->owner); sctp_sk(newsk)->bind_hash = pp; inet_sk(newsk)->num = inet_sk(oldsk)->num; /* Copy the bind_addr list from the original endpoint to the new * endpoint so that we can handle restarts properly */ if (PF_INET6 == assoc->base.sk->sk_family) flags = SCTP_ADDR6_ALLOWED; if (assoc->peer.ipv4_address) flags |= SCTP_ADDR4_PEERSUPP; if (assoc->peer.ipv6_address) flags |= SCTP_ADDR6_PEERSUPP; sctp_bind_addr_copy(&newsp->ep->base.bind_addr, &oldsp->ep->base.bind_addr, SCTP_SCOPE_GLOBAL, GFP_KERNEL, flags); /* Move any messages in the old socket's receive queue that are for the * peeled off association to the new socket's receive queue. */ sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { sctp_sock_rfree(skb); __skb_unlink(skb, &oldsk->sk_receive_queue); __skb_queue_tail(&newsk->sk_receive_queue, skb); sctp_skb_set_owner_r(skb, newsk); } } /* Clean up any messages pending delivery due to partial * delivery. Three cases: * 1) No partial deliver; no work. * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby. * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue. */ skb_queue_head_init(&newsp->pd_lobby); sctp_sk(newsk)->pd_mode = assoc->ulpq.pd_mode; if (sctp_sk(oldsk)->pd_mode) { struct sk_buff_head *queue; /* Decide which queue to move pd_lobby skbs to. */ if (assoc->ulpq.pd_mode) { queue = &newsp->pd_lobby; } else queue = &newsk->sk_receive_queue; /* Walk through the pd_lobby, looking for skbs that * need moved to the new socket. */ sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { sctp_sock_rfree(skb); __skb_unlink(skb, &oldsp->pd_lobby); __skb_queue_tail(queue, skb); sctp_skb_set_owner_r(skb, newsk); } } /* Clear up any skbs waiting for the partial * delivery to finish. */ if (assoc->ulpq.pd_mode) sctp_clear_pd(oldsk); } /* Set the type of socket to indicate that it is peeled off from the * original UDP-style socket or created with the accept() call on a * TCP-style socket.. */ newsp->type = type; /* Mark the new socket "in-use" by the user so that any packets * that may arrive on the association after we've moved it are * queued to the backlog. This prevents a potential race between * backlog processing on the old socket and new-packet processing * on the new socket. */ sctp_lock_sock(newsk); sctp_assoc_migrate(assoc, newsk); /* If the association on the newsk is already closed before accept() * is called, set RCV_SHUTDOWN flag. */ if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) newsk->sk_shutdown |= RCV_SHUTDOWN; newsk->sk_state = SCTP_SS_ESTABLISHED; sctp_release_sock(newsk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '[SCTP]: Fix assertion (!atomic_read(&sk->sk_rmem_alloc)) failed message In current implementation, LKSCTP does receive buffer accounting for data in sctp_receive_queue and pd_lobby. However, LKSCTP don't do accounting for data in frag_list when data is fragmented. In addition, LKSCTP doesn't do accounting for data in reasm and lobby queue in structure sctp_ulpq. When there are date in these queue, assertion failed message is printed in inet_sock_destruct because sk_rmem_alloc of oldsk does not become 0 when socket is destroyed. Signed-off-by: Tsutomu Fujii <t-fujii@nb.jp.nec.com> Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: RZ_API void rz_analysis_extract_vars(RzAnalysis *analysis, RzAnalysisFunction *fcn, RzAnalysisOp *op) { rz_return_if_fail(analysis && fcn && op); const char *BP = analysis->reg->name[RZ_REG_NAME_BP]; const char *SP = analysis->reg->name[RZ_REG_NAME_SP]; if (BP) { extract_arg(analysis, fcn, op, BP, "+", RZ_ANALYSIS_VAR_KIND_BPV); extract_arg(analysis, fcn, op, BP, "-", RZ_ANALYSIS_VAR_KIND_BPV); } extract_arg(analysis, fcn, op, SP, "+", RZ_ANALYSIS_VAR_KIND_SPV); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Initialize retctx,ctx before freeing the inner elements In rz_core_analysis_type_match retctx structure was initialized on the stack only after a "goto out_function", where a field of that structure was freed. When the goto path is taken, the field is not properly initialized and it cause cause a crash of Rizin or have other effects. Fixes: CVE-2021-4022'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tg3_read_vpd(struct tg3 *tp) { u8 *vpd_data; unsigned int block_end, rosize, len; u32 vpdlen; int j, i = 0; vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen); if (!vpd_data) goto out_no_vpd; i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA); if (i < 0) goto out_not_found; rosize = pci_vpd_lrdt_size(&vpd_data[i]); block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize; i += PCI_VPD_LRDT_TAG_SIZE; if (block_end > vpdlen) goto out_not_found; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_MFR_ID); if (j > 0) { len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end || len != 4 || memcmp(&vpd_data[j], "1028", 4)) goto partno; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_VENDOR0); if (j < 0) goto partno; len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end) goto partno; memcpy(tp->fw_ver, &vpd_data[j], len); strncat(tp->fw_ver, " bc ", vpdlen - len - 1); } partno: i = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_PARTNO); if (i < 0) goto out_not_found; len = pci_vpd_info_field_size(&vpd_data[i]); i += PCI_VPD_INFO_FLD_HDR_SIZE; if (len > TG3_BPN_SIZE || (len + i) > vpdlen) goto out_not_found; memcpy(tp->board_part_number, &vpd_data[i], len); out_not_found: kfree(vpd_data); if (tp->board_part_number[0]) return; out_no_vpd: if (tg3_asic_rev(tp) == ASIC_REV_5717) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C) strcpy(tp->board_part_number, "BCM5717"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718) strcpy(tp->board_part_number, "BCM5718"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57780) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780) strcpy(tp->board_part_number, "BCM57780"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760) strcpy(tp->board_part_number, "BCM57760"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790) strcpy(tp->board_part_number, "BCM57790"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788) strcpy(tp->board_part_number, "BCM57788"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57765) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761) strcpy(tp->board_part_number, "BCM57761"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765) strcpy(tp->board_part_number, "BCM57765"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781) strcpy(tp->board_part_number, "BCM57781"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785) strcpy(tp->board_part_number, "BCM57785"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791) strcpy(tp->board_part_number, "BCM57791"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795) strcpy(tp->board_part_number, "BCM57795"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762) strcpy(tp->board_part_number, "BCM57762"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766) strcpy(tp->board_part_number, "BCM57766"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782) strcpy(tp->board_part_number, "BCM57782"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786) strcpy(tp->board_part_number, "BCM57786"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) { strcpy(tp->board_part_number, "BCM95906"); } else { nomatch: strcpy(tp->board_part_number, "none"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-119'], 'message': 'tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <keescook@chromium.org> Reported-by: Oded Horovitz <oded@privatecore.com> Reported-by: Brad Spengler <spender@grsecurity.net> Cc: stable@vger.kernel.org Cc: Matt Carlson <mcarlson@broadcom.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: R_API RBinJavaAttrInfo *r_bin_java_code_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) { RBinJavaAttrInfo *attr = NULL, *_attr = NULL; ut32 k = 0, curpos; ut64 offset = 0; attr = r_bin_java_default_attr_new (buffer, sz, buf_offset); if (!attr) { return NULL; } if (sz < 16 || sz > buf_offset) {// sz > buf_offset) { free (attr); return NULL; } offset += 6; attr->type = R_BIN_JAVA_ATTR_TYPE_CODE_ATTR; attr->info.code_attr.max_stack = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.code_attr.max_locals = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.code_attr.code_length = R_BIN_JAVA_UINT (buffer, offset); offset += 4; // BUG: possible unsigned integer overflow here attr->info.code_attr.code_offset = buf_offset + offset; attr->info.code_attr.code = (ut8 *) malloc (attr->info.code_attr.code_length); if (attr->info.code_attr.code == NULL) { eprintf ("Handling Code Attributes: Unable to allocate memory " "(%u bytes) for a code.\n", attr->info.code_attr.code_length); return attr; } R_BIN_JAVA_GLOBAL_BIN->current_code_attr = attr; { int len = attr->info.code_attr.code_length; memset (attr->info.code_attr.code, 0, len); if (offset + len >= sz) { len = sz; return attr; } memcpy (attr->info.code_attr.code, buffer + offset, len); offset += len; } attr->info.code_attr.exception_table_length = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.code_attr.exception_table = r_list_newf (free); for (k = 0; k < attr->info.code_attr.exception_table_length; k++) { curpos = buf_offset + offset; if (curpos + 8 > sz) { return attr; } RBinJavaExceptionEntry *e = R_NEW0 (RBinJavaExceptionEntry); if (!e) { free (attr); return NULL; } e->file_offset = curpos; e->start_pc = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; e->end_pc = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; e->handler_pc = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; e->catch_type = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; r_list_append (attr->info.code_attr.exception_table, e); e->size = 8; } attr->info.code_attr.attributes_count = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; // IFDBG eprintf (" code Attributes_count: %d\n", attr->info.code_attr.attributes_count); // XXX - attr->info.code_attr.attributes is not freed because one of the code attributes is improperly parsed. attr->info.code_attr.attributes = r_list_newf (r_bin_java_attribute_free); if (attr->info.code_attr.attributes_count > 0) { for (k = 0; k < attr->info.code_attr.attributes_count; k++) { int size = (offset < sz) ? sz - offset : 0; if (size > sz || size <= 0) { break; } _attr = r_bin_java_read_next_attr_from_buffer (buffer + offset, size, buf_offset + offset); if (!_attr) { eprintf ("[X] r_bin_java_code_attr_new: Error unable to parse remainder of classfile after Method's Code Attribute: %d.\n", k); break; } IFDBG eprintf("Parsing @ 0x%"PFMT64x " (%s) = 0x%"PFMT64x " bytes, %p\n", _attr->file_offset, _attr->name, _attr->size, _attr); offset += _attr->size; r_list_append (attr->info.code_attr.attributes, _attr); if (_attr->type == R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TABLE_ATTR) { IFDBG eprintf("Parsed the LocalVariableTable, preparing the implicit mthod frame.\n"); // r_bin_java_print_attr_summary(_attr); attr->info.code_attr.implicit_frame = r_bin_java_build_stack_frame_from_local_variable_table (R_BIN_JAVA_GLOBAL_BIN, _attr); attr->info.code_attr.implicit_frame->file_offset = buf_offset; IFDBG r_bin_java_print_stack_map_frame_summary(attr->info.code_attr.implicit_frame); // r_list_append (attr->info.code_attr.attributes, attr->info.code_attr.implicit_frame); } // if (offset > sz) { // eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Attribute: %d.\n", k); // break; // } } } if (attr->info.code_attr.implicit_frame == NULL) { // build a default implicit_frame attr->info.code_attr.implicit_frame = r_bin_java_default_stack_frame (); // r_list_append (attr->info.code_attr.attributes, attr->info.code_attr.implicit_frame); } attr->size = offset; return attr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10498 - Fix crash in fuzzed java files (#10511)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg >= regsz) { //return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #6836 - oob write in dex'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb, struct xfrm_state *x, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; if (dump_one_state(x, 0, &info)) { kfree_skb(skb); return NULL; } return skb; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'xfrm_user: return error pointer instead of NULL When dump_one_state() returns an error, e.g. because of a too small buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL instead of an error pointer. But its callers expect an error pointer and therefore continue to operate on a NULL skbuff. This could lead to a privilege escalation (execution of user code in kernel context) if the attacker has CAP_NET_ADMIN and is able to map address 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Acked-by: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __sys_sendmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned flags, struct used_address *used_address) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __attribute__ ((aligned(sizeof(__kernel_size_t)))); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int err, ctl_len, iov_size, total_len; err = -EFAULT; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr))) return -EFAULT; /* do not move before msg_sys is valid */ err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; /* Check whether to allocate the iovec area */ err = -ENOMEM; iov_size = msg_sys->msg_iovlen * sizeof(struct iovec); if (msg_sys->msg_iovlen > UIO_FASTIOV) { iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL); if (!iov) goto out; } /* This will also move the address data into kernel space */ if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, (struct sockaddr *)&address, VERIFY_READ); } else err = verify_iovec(msg_sys, iov, (struct sockaddr *)&address, VERIFY_READ); if (err < 0) goto out_freeiov; total_len = err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys, total_len); goto out_freectl; } err = sock_sendmsg(sock, msg_sys, total_len); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; memcpy(&used_address->name, msg->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: if (iov != iovstack) sock_kfree_s(sock->sk, iov, iov_size); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'sendmmsg/sendmsg: fix unsafe user pointer access Dereferencing a user pointer directly from kernel-space without going through the copy_from_user family of functions is a bad idea. Two of such usages can be found in the sendmsg code path called from sendmmsg, added by commit c71d8ebe7a4496fb7231151cb70a6baa0cb56f9a upstream. commit 5b47b8038f183b44d2d8ff1c7d11a5c1be706b34 in the 3.0-stable tree. Usages are performed through memcmp() and memcpy() directly. Fix those by using the already copied msg_sys structure instead of the __user *msg structure. Note that msg_sys can be set to NULL by verify_compat_iovec() or verify_iovec(), which requires additional NULL pointer checks. Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Signed-off-by: David Goulet <dgoulet@ev0ke.net> CC: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> CC: Anton Blanchard <anton@samba.org> CC: David S. Miller <davem@davemloft.net> CC: stable <stable@kernel.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; int src_image_len = f->get_len(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); ERR_FAIL_COND_V(src_image_len < (int)sizeof(tga_header_s), ERR_FILE_CORRUPT); src_image.resize(src_image_len); Error err = OK; tga_header_s tga_header; tga_header.id_length = f->get_8(); tga_header.color_map_type = f->get_8(); tga_header.image_type = static_cast<tga_type_e>(f->get_8()); tga_header.first_color_entry = f->get_16(); tga_header.color_map_length = f->get_16(); tga_header.color_map_depth = f->get_8(); tga_header.x_origin = f->get_16(); tga_header.y_origin = f->get_16(); tga_header.image_width = f->get_16(); tga_header.image_height = f->get_16(); tga_header.pixel_depth = f->get_8(); tga_header.image_descriptor = f->get_8(); bool is_encoded = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_RLE_RGB || tga_header.image_type == TGA_TYPE_RLE_MONOCHROME); bool has_color_map = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_INDEXED); bool is_monochrome = (tga_header.image_type == TGA_TYPE_RLE_MONOCHROME || tga_header.image_type == TGA_TYPE_MONOCHROME); if (tga_header.image_type == TGA_TYPE_NO_DATA) { err = FAILED; } if (has_color_map) { if (tga_header.color_map_length > 256 || (tga_header.color_map_depth != 24) || tga_header.color_map_type != 1) { err = FAILED; } } else { if (tga_header.color_map_type) { err = FAILED; } } if (tga_header.image_width <= 0 || tga_header.image_height <= 0) { err = FAILED; } if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) { err = FAILED; } if (err == OK) { f->seek(f->get_position() + tga_header.id_length); Vector<uint8_t> palette; if (has_color_map) { size_t color_map_size = tga_header.color_map_length * (tga_header.color_map_depth >> 3); err = palette.resize(color_map_size); if (err == OK) { uint8_t *palette_w = palette.ptrw(); f->get_buffer(&palette_w[0], color_map_size); } else { return OK; } } uint8_t *src_image_w = src_image.ptrw(); f->get_buffer(&src_image_w[0], src_image_len - f->get_position()); const uint8_t *src_image_r = src_image.ptr(); const size_t pixel_size = tga_header.pixel_depth >> 3; const size_t buffer_size = (tga_header.image_width * tga_header.image_height) * pixel_size; Vector<uint8_t> uncompressed_buffer; uncompressed_buffer.resize(buffer_size); uint8_t *uncompressed_buffer_w = uncompressed_buffer.ptrw(); const uint8_t *uncompressed_buffer_r; const uint8_t *buffer = nullptr; if (is_encoded) { err = decode_tga_rle(src_image_r, pixel_size, uncompressed_buffer_w, buffer_size); if (err == OK) { uncompressed_buffer_r = uncompressed_buffer.ptr(); buffer = uncompressed_buffer_r; } } else { buffer = src_image_r; }; if (err == OK) { const uint8_t *palette_r = palette.ptr(); err = convert_to_image(p_image, buffer, tga_header, palette_r, is_monochrome); } } f->close(); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Fix a crash in the TGA loader with malformed input'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int decode_nal_unit(HEVCContext *s, const uint8_t *nal, int length) { HEVCLocalContext *lc = &s->HEVClc; GetBitContext *gb = &lc->gb; int ctb_addr_ts, ret; ret = init_get_bits8(gb, nal, length); if (ret < 0) return ret; ret = hls_nal_unit(s); if (ret < 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n", s->nal_unit_type); if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; return 0; } else if (!ret) return 0; switch (s->nal_unit_type) { case NAL_VPS: ret = ff_hevc_decode_nal_vps(s); if (ret < 0) return ret; break; case NAL_SPS: ret = ff_hevc_decode_nal_sps(s); if (ret < 0) return ret; break; case NAL_PPS: ret = ff_hevc_decode_nal_pps(s); if (ret < 0) return ret; break; case NAL_SEI_PREFIX: case NAL_SEI_SUFFIX: ret = ff_hevc_decode_nal_sei(s); if (ret < 0) return ret; break; case NAL_TRAIL_R: case NAL_TRAIL_N: case NAL_TSA_N: case NAL_TSA_R: case NAL_STSA_N: case NAL_STSA_R: case NAL_BLA_W_LP: case NAL_BLA_W_RADL: case NAL_BLA_N_LP: case NAL_IDR_W_RADL: case NAL_IDR_N_LP: case NAL_CRA_NUT: case NAL_RADL_N: case NAL_RADL_R: case NAL_RASL_N: case NAL_RASL_R: ret = hls_slice_header(s); if (ret < 0) return ret; if (s->max_ra == INT_MAX) { if (s->nal_unit_type == NAL_CRA_NUT || IS_BLA(s)) { s->max_ra = s->poc; } else { if (IS_IDR(s)) s->max_ra = INT_MIN; } } if ((s->nal_unit_type == NAL_RASL_R || s->nal_unit_type == NAL_RASL_N) && s->poc <= s->max_ra) { s->is_decoded = 0; break; } else { if (s->nal_unit_type == NAL_RASL_R && s->poc > s->max_ra) s->max_ra = INT_MIN; } if (s->sh.first_slice_in_pic_flag) { ret = hevc_frame_start(s); if (ret < 0) return ret; } else if (!s->ref) { av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n"); return AVERROR_INVALIDDATA; } if (!s->sh.dependent_slice_segment_flag && s->sh.slice_type != I_SLICE) { ret = ff_hevc_slice_rpl(s); if (ret < 0) { av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference lists for the current slice.\n"); if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; } } ctb_addr_ts = hls_slice_data(s); if (ctb_addr_ts >= (s->sps->ctb_width * s->sps->ctb_height)) { s->is_decoded = 1; if ((s->pps->transquant_bypass_enable_flag || (s->sps->pcm.loop_filter_disable_flag && s->sps->pcm_enabled_flag)) && s->sps->sao_enabled) restore_tqb_pixels(s); } if (ctb_addr_ts < 0) return ctb_addr_ts; break; case NAL_EOS_NUT: case NAL_EOB_NUT: s->seq_decode = (s->seq_decode + 1) & 0xff; s->max_ra = INT_MAX; break; case NAL_AUD: case NAL_FD_NUT: break; default: av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'hevc: check that the VCL NAL types are the same for all slice segments of a frame Fixes possible invalid memory access for mismatching skipped/non-skipped slice segments. Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Sample-Id: 00001533-google'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool AES_GCM_EncryptContext::Encrypt( const void *pPlaintextData, size_t cbPlaintextData, const void *pIV, void *pEncryptedDataAndTag, uint32 *pcbEncryptedDataAndTag, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { unsigned long long pcbEncryptedDataAndTag_longlong = *pcbEncryptedDataAndTag; crypto_aead_aes256gcm_encrypt_afternm( static_cast<unsigned char*>( pEncryptedDataAndTag ), &pcbEncryptedDataAndTag_longlong, static_cast<const unsigned char*>( pPlaintextData ), cbPlaintextData, static_cast<const unsigned char*>(pAdditionalAuthenticationData), cbAuthenticationData, nullptr, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbEncryptedDataAndTag = pcbEncryptedDataAndTag_longlong; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check if output buffer is too small. It really seems like libsodium (whose entire purpose is to make crypto idiot-proof) making me mess with these details is a flaw in the API design. Also, correct Hungarian.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ssize_t nghttp2_session_mem_recv(nghttp2_session *session, const uint8_t *in, size_t inlen) { const uint8_t *first = in, *last = in + inlen; nghttp2_inbound_frame *iframe = &session->iframe; size_t readlen; ssize_t padlen; int rv; int busy = 0; nghttp2_frame_hd cont_hd; nghttp2_stream *stream; size_t pri_fieldlen; nghttp2_mem *mem; DEBUGF("recv: connection recv_window_size=%d, local_window=%d\n", session->recv_window_size, session->local_window_size); mem = &session->mem; /* We may have idle streams more than we expect (e.g., nghttp2_session_change_stream_priority() or nghttp2_session_create_idle_stream()). Adjust them here. */ rv = nghttp2_session_adjust_idle_stream(session); if (nghttp2_is_fatal(rv)) { return rv; } if (!nghttp2_session_want_read(session)) { return (ssize_t)inlen; } for (;;) { switch (iframe->state) { case NGHTTP2_IB_READ_CLIENT_MAGIC: readlen = nghttp2_min(inlen, iframe->payloadleft); if (memcmp(&NGHTTP2_CLIENT_MAGIC[NGHTTP2_CLIENT_MAGIC_LEN - iframe->payloadleft], in, readlen) != 0) { return NGHTTP2_ERR_BAD_CLIENT_MAGIC; } iframe->payloadleft -= readlen; in += readlen; if (iframe->payloadleft == 0) { session_inbound_frame_reset(session); iframe->state = NGHTTP2_IB_READ_FIRST_SETTINGS; } break; case NGHTTP2_IB_READ_FIRST_SETTINGS: DEBUGF("recv: [IB_READ_FIRST_SETTINGS]\n"); readlen = inbound_frame_buf_read(iframe, in, last); in += readlen; if (nghttp2_buf_mark_avail(&iframe->sbuf)) { return in - first; } if (iframe->sbuf.pos[3] != NGHTTP2_SETTINGS || (iframe->sbuf.pos[4] & NGHTTP2_FLAG_ACK)) { rv = session_call_error_callback( session, NGHTTP2_ERR_SETTINGS_EXPECTED, "Remote peer returned unexpected data while we expected " "SETTINGS frame. Perhaps, peer does not support HTTP/2 " "properly."); if (nghttp2_is_fatal(rv)) { return rv; } rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "SETTINGS expected"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } iframe->state = NGHTTP2_IB_READ_HEAD; /* Fall through */ case NGHTTP2_IB_READ_HEAD: { int on_begin_frame_called = 0; DEBUGF("recv: [IB_READ_HEAD]\n"); readlen = inbound_frame_buf_read(iframe, in, last); in += readlen; if (nghttp2_buf_mark_avail(&iframe->sbuf)) { return in - first; } nghttp2_frame_unpack_frame_hd(&iframe->frame.hd, iframe->sbuf.pos); iframe->payloadleft = iframe->frame.hd.length; DEBUGF("recv: payloadlen=%zu, type=%u, flags=0x%02x, stream_id=%d\n", iframe->frame.hd.length, iframe->frame.hd.type, iframe->frame.hd.flags, iframe->frame.hd.stream_id); if (iframe->frame.hd.length > session->local_settings.max_frame_size) { DEBUGF("recv: length is too large %zu > %u\n", iframe->frame.hd.length, session->local_settings.max_frame_size); rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_FRAME_SIZE_ERROR, "too large frame size"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } switch (iframe->frame.hd.type) { case NGHTTP2_DATA: { DEBUGF("recv: DATA\n"); iframe->frame.hd.flags &= (NGHTTP2_FLAG_END_STREAM | NGHTTP2_FLAG_PADDED); /* Check stream is open. If it is not open or closing, ignore payload. */ busy = 1; rv = session_on_data_received_fail_fast(session); if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } if (rv == NGHTTP2_ERR_IGN_PAYLOAD) { DEBUGF("recv: DATA not allowed stream_id=%d\n", iframe->frame.hd.stream_id); iframe->state = NGHTTP2_IB_IGN_DATA; break; } if (nghttp2_is_fatal(rv)) { return rv; } rv = inbound_frame_handle_pad(iframe, &iframe->frame.hd); if (rv < 0) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "DATA: insufficient padding space"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } if (rv == 1) { iframe->state = NGHTTP2_IB_READ_PAD_DATA; break; } iframe->state = NGHTTP2_IB_READ_DATA; break; } case NGHTTP2_HEADERS: DEBUGF("recv: HEADERS\n"); iframe->frame.hd.flags &= (NGHTTP2_FLAG_END_STREAM | NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_PADDED | NGHTTP2_FLAG_PRIORITY); rv = inbound_frame_handle_pad(iframe, &iframe->frame.hd); if (rv < 0) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "HEADERS: insufficient padding space"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } if (rv == 1) { iframe->state = NGHTTP2_IB_READ_NBYTE; break; } pri_fieldlen = nghttp2_frame_priority_len(iframe->frame.hd.flags); if (pri_fieldlen > 0) { if (iframe->payloadleft < pri_fieldlen) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, pri_fieldlen); break; } /* Call on_begin_frame_callback here because session_process_headers_frame() may call on_begin_headers_callback */ rv = session_call_on_begin_frame(session, &iframe->frame.hd); if (nghttp2_is_fatal(rv)) { return rv; } on_begin_frame_called = 1; rv = session_process_headers_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } busy = 1; if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } if (rv == NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE) { rv = nghttp2_session_add_rst_stream( session, iframe->frame.hd.stream_id, NGHTTP2_INTERNAL_ERROR); if (nghttp2_is_fatal(rv)) { return rv; } iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } if (rv == NGHTTP2_ERR_IGN_HEADER_BLOCK) { iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } iframe->state = NGHTTP2_IB_READ_HEADER_BLOCK; break; case NGHTTP2_PRIORITY: DEBUGF("recv: PRIORITY\n"); iframe->frame.hd.flags = NGHTTP2_FLAG_NONE; if (iframe->payloadleft != NGHTTP2_PRIORITY_SPECLEN) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, NGHTTP2_PRIORITY_SPECLEN); break; case NGHTTP2_RST_STREAM: case NGHTTP2_WINDOW_UPDATE: #ifdef DEBUGBUILD switch (iframe->frame.hd.type) { case NGHTTP2_RST_STREAM: DEBUGF("recv: RST_STREAM\n"); break; case NGHTTP2_WINDOW_UPDATE: DEBUGF("recv: WINDOW_UPDATE\n"); break; } #endif /* DEBUGBUILD */ iframe->frame.hd.flags = NGHTTP2_FLAG_NONE; if (iframe->payloadleft != 4) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, 4); break; case NGHTTP2_SETTINGS: DEBUGF("recv: SETTINGS\n"); iframe->frame.hd.flags &= NGHTTP2_FLAG_ACK; if ((iframe->frame.hd.length % NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH) || ((iframe->frame.hd.flags & NGHTTP2_FLAG_ACK) && iframe->payloadleft > 0)) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_SETTINGS; if (iframe->payloadleft) { nghttp2_settings_entry *min_header_table_size_entry; /* We allocate iv with additional one entry, to store the minimum header table size. */ iframe->max_niv = iframe->frame.hd.length / NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH + 1; if (iframe->max_niv - 1 > session->max_settings) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_ENHANCE_YOUR_CALM, "SETTINGS: too many setting entries"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } iframe->iv = nghttp2_mem_malloc(mem, sizeof(nghttp2_settings_entry) * iframe->max_niv); if (!iframe->iv) { return NGHTTP2_ERR_NOMEM; } min_header_table_size_entry = &iframe->iv[iframe->max_niv - 1]; min_header_table_size_entry->settings_id = NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; min_header_table_size_entry->value = UINT32_MAX; inbound_frame_set_mark(iframe, NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH); break; } busy = 1; inbound_frame_set_mark(iframe, 0); break; case NGHTTP2_PUSH_PROMISE: DEBUGF("recv: PUSH_PROMISE\n"); iframe->frame.hd.flags &= (NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_PADDED); rv = inbound_frame_handle_pad(iframe, &iframe->frame.hd); if (rv < 0) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "PUSH_PROMISE: insufficient padding space"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } if (rv == 1) { iframe->state = NGHTTP2_IB_READ_NBYTE; break; } if (iframe->payloadleft < 4) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, 4); break; case NGHTTP2_PING: DEBUGF("recv: PING\n"); iframe->frame.hd.flags &= NGHTTP2_FLAG_ACK; if (iframe->payloadleft != 8) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, 8); break; case NGHTTP2_GOAWAY: DEBUGF("recv: GOAWAY\n"); iframe->frame.hd.flags = NGHTTP2_FLAG_NONE; if (iframe->payloadleft < 8) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, 8); break; case NGHTTP2_CONTINUATION: DEBUGF("recv: unexpected CONTINUATION\n"); /* Receiving CONTINUATION in this state are subject to connection error of type PROTOCOL_ERROR */ rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "CONTINUATION: unexpected"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; default: DEBUGF("recv: extension frame\n"); if (check_ext_type_set(session->user_recv_ext_types, iframe->frame.hd.type)) { if (!session->callbacks.unpack_extension_callback) { /* Silently ignore unknown frame type. */ busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } busy = 1; iframe->state = NGHTTP2_IB_READ_EXTENSION_PAYLOAD; break; } else { switch (iframe->frame.hd.type) { case NGHTTP2_ALTSVC: if ((session->builtin_recv_ext_types & NGHTTP2_TYPEMASK_ALTSVC) == 0) { busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } DEBUGF("recv: ALTSVC\n"); iframe->frame.hd.flags = NGHTTP2_FLAG_NONE; iframe->frame.ext.payload = &iframe->ext_frame_payload.altsvc; if (session->server) { busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } if (iframe->payloadleft < 2) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } busy = 1; iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, 2); break; case NGHTTP2_ORIGIN: if (!(session->builtin_recv_ext_types & NGHTTP2_TYPEMASK_ORIGIN)) { busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } DEBUGF("recv: ORIGIN\n"); iframe->frame.ext.payload = &iframe->ext_frame_payload.origin; if (session->server || iframe->frame.hd.stream_id || (iframe->frame.hd.flags & 0xf0)) { busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } iframe->frame.hd.flags = NGHTTP2_FLAG_NONE; if (iframe->payloadleft) { iframe->raw_lbuf = nghttp2_mem_malloc(mem, iframe->payloadleft); if (iframe->raw_lbuf == NULL) { return NGHTTP2_ERR_NOMEM; } nghttp2_buf_wrap_init(&iframe->lbuf, iframe->raw_lbuf, iframe->payloadleft); } else { busy = 1; } iframe->state = NGHTTP2_IB_READ_ORIGIN_PAYLOAD; break; default: busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } } } if (!on_begin_frame_called) { switch (iframe->state) { case NGHTTP2_IB_IGN_HEADER_BLOCK: case NGHTTP2_IB_IGN_PAYLOAD: case NGHTTP2_IB_FRAME_SIZE_ERROR: case NGHTTP2_IB_IGN_DATA: case NGHTTP2_IB_IGN_ALL: break; default: rv = session_call_on_begin_frame(session, &iframe->frame.hd); if (nghttp2_is_fatal(rv)) { return rv; } } } break; } case NGHTTP2_IB_READ_NBYTE: DEBUGF("recv: [IB_READ_NBYTE]\n"); readlen = inbound_frame_buf_read(iframe, in, last); in += readlen; iframe->payloadleft -= readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu, left=%zd\n", readlen, iframe->payloadleft, nghttp2_buf_mark_avail(&iframe->sbuf)); if (nghttp2_buf_mark_avail(&iframe->sbuf)) { return in - first; } switch (iframe->frame.hd.type) { case NGHTTP2_HEADERS: if (iframe->padlen == 0 && (iframe->frame.hd.flags & NGHTTP2_FLAG_PADDED)) { pri_fieldlen = nghttp2_frame_priority_len(iframe->frame.hd.flags); padlen = inbound_frame_compute_pad(iframe); if (padlen < 0 || (size_t)padlen + pri_fieldlen > 1 + iframe->payloadleft) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "HEADERS: invalid padding"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } iframe->frame.headers.padlen = (size_t)padlen; if (pri_fieldlen > 0) { if (iframe->payloadleft < pri_fieldlen) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, pri_fieldlen); break; } else { /* Truncate buffers used for padding spec */ inbound_frame_set_mark(iframe, 0); } } rv = session_process_headers_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } busy = 1; if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } if (rv == NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE) { rv = nghttp2_session_add_rst_stream( session, iframe->frame.hd.stream_id, NGHTTP2_INTERNAL_ERROR); if (nghttp2_is_fatal(rv)) { return rv; } iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } if (rv == NGHTTP2_ERR_IGN_HEADER_BLOCK) { iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } iframe->state = NGHTTP2_IB_READ_HEADER_BLOCK; break; case NGHTTP2_PRIORITY: rv = session_process_priority_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; case NGHTTP2_RST_STREAM: rv = session_process_rst_stream_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; case NGHTTP2_PUSH_PROMISE: if (iframe->padlen == 0 && (iframe->frame.hd.flags & NGHTTP2_FLAG_PADDED)) { padlen = inbound_frame_compute_pad(iframe); if (padlen < 0 || (size_t)padlen + 4 /* promised stream id */ > 1 + iframe->payloadleft) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "PUSH_PROMISE: invalid padding"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } iframe->frame.push_promise.padlen = (size_t)padlen; if (iframe->payloadleft < 4) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } iframe->state = NGHTTP2_IB_READ_NBYTE; inbound_frame_set_mark(iframe, 4); break; } rv = session_process_push_promise_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } busy = 1; if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } if (rv == NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE) { rv = nghttp2_session_add_rst_stream( session, iframe->frame.push_promise.promised_stream_id, NGHTTP2_INTERNAL_ERROR); if (nghttp2_is_fatal(rv)) { return rv; } iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } if (rv == NGHTTP2_ERR_IGN_HEADER_BLOCK) { iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } iframe->state = NGHTTP2_IB_READ_HEADER_BLOCK; break; case NGHTTP2_PING: rv = session_process_ping_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; case NGHTTP2_GOAWAY: { size_t debuglen; /* 8 is Last-stream-ID + Error Code */ debuglen = iframe->frame.hd.length - 8; if (debuglen > 0) { iframe->raw_lbuf = nghttp2_mem_malloc(mem, debuglen); if (iframe->raw_lbuf == NULL) { return NGHTTP2_ERR_NOMEM; } nghttp2_buf_wrap_init(&iframe->lbuf, iframe->raw_lbuf, debuglen); } busy = 1; iframe->state = NGHTTP2_IB_READ_GOAWAY_DEBUG; break; } case NGHTTP2_WINDOW_UPDATE: rv = session_process_window_update_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; case NGHTTP2_ALTSVC: { size_t origin_len; origin_len = nghttp2_get_uint16(iframe->sbuf.pos); DEBUGF("recv: origin_len=%zu\n", origin_len); if (origin_len > iframe->payloadleft) { busy = 1; iframe->state = NGHTTP2_IB_FRAME_SIZE_ERROR; break; } if (iframe->frame.hd.length > 2) { iframe->raw_lbuf = nghttp2_mem_malloc(mem, iframe->frame.hd.length - 2); if (iframe->raw_lbuf == NULL) { return NGHTTP2_ERR_NOMEM; } nghttp2_buf_wrap_init(&iframe->lbuf, iframe->raw_lbuf, iframe->frame.hd.length); } busy = 1; iframe->state = NGHTTP2_IB_READ_ALTSVC_PAYLOAD; break; } default: /* This is unknown frame */ session_inbound_frame_reset(session); break; } break; case NGHTTP2_IB_READ_HEADER_BLOCK: case NGHTTP2_IB_IGN_HEADER_BLOCK: { ssize_t data_readlen; size_t trail_padlen; int final; #ifdef DEBUGBUILD if (iframe->state == NGHTTP2_IB_READ_HEADER_BLOCK) { DEBUGF("recv: [IB_READ_HEADER_BLOCK]\n"); } else { DEBUGF("recv: [IB_IGN_HEADER_BLOCK]\n"); } #endif /* DEBUGBUILD */ readlen = inbound_frame_payload_readlen(iframe, in, last); DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft - readlen); data_readlen = inbound_frame_effective_readlen( iframe, iframe->payloadleft - readlen, readlen); if (data_readlen == -1) { /* everything is padding */ data_readlen = 0; } trail_padlen = nghttp2_frame_trail_padlen(&iframe->frame, iframe->padlen); final = (iframe->frame.hd.flags & NGHTTP2_FLAG_END_HEADERS) && iframe->payloadleft - (size_t)data_readlen == trail_padlen; if (data_readlen > 0 || (data_readlen == 0 && final)) { size_t hd_proclen = 0; DEBUGF("recv: block final=%d\n", final); rv = inflate_header_block(session, &iframe->frame, &hd_proclen, (uint8_t *)in, (size_t)data_readlen, final, iframe->state == NGHTTP2_IB_READ_HEADER_BLOCK); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } if (rv == NGHTTP2_ERR_PAUSE) { in += hd_proclen; iframe->payloadleft -= hd_proclen; return in - first; } if (rv == NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE) { /* The application says no more headers. We decompress the rest of the header block but not invoke on_header_callback and on_frame_recv_callback. */ in += hd_proclen; iframe->payloadleft -= hd_proclen; /* Use promised stream ID for PUSH_PROMISE */ rv = nghttp2_session_add_rst_stream( session, iframe->frame.hd.type == NGHTTP2_PUSH_PROMISE ? iframe->frame.push_promise.promised_stream_id : iframe->frame.hd.stream_id, NGHTTP2_INTERNAL_ERROR); if (nghttp2_is_fatal(rv)) { return rv; } busy = 1; iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; break; } in += readlen; iframe->payloadleft -= readlen; if (rv == NGHTTP2_ERR_HEADER_COMP) { /* GOAWAY is already issued */ if (iframe->payloadleft == 0) { session_inbound_frame_reset(session); } else { busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; } break; } } else { in += readlen; iframe->payloadleft -= readlen; } if (iframe->payloadleft) { break; } if ((iframe->frame.hd.flags & NGHTTP2_FLAG_END_HEADERS) == 0) { inbound_frame_set_mark(iframe, NGHTTP2_FRAME_HDLEN); iframe->padlen = 0; if (iframe->state == NGHTTP2_IB_READ_HEADER_BLOCK) { iframe->state = NGHTTP2_IB_EXPECT_CONTINUATION; } else { iframe->state = NGHTTP2_IB_IGN_CONTINUATION; } } else { if (iframe->state == NGHTTP2_IB_READ_HEADER_BLOCK) { rv = session_after_header_block_received(session); if (nghttp2_is_fatal(rv)) { return rv; } } session_inbound_frame_reset(session); } break; } case NGHTTP2_IB_IGN_PAYLOAD: DEBUGF("recv: [IB_IGN_PAYLOAD]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); iframe->payloadleft -= readlen; in += readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (iframe->payloadleft) { break; } switch (iframe->frame.hd.type) { case NGHTTP2_HEADERS: case NGHTTP2_PUSH_PROMISE: case NGHTTP2_CONTINUATION: /* Mark inflater bad so that we won't perform further decoding */ session->hd_inflater.ctx.bad = 1; break; default: break; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_FRAME_SIZE_ERROR: DEBUGF("recv: [IB_FRAME_SIZE_ERROR]\n"); rv = session_handle_frame_size_error(session); if (nghttp2_is_fatal(rv)) { return rv; } assert(iframe->state == NGHTTP2_IB_IGN_ALL); return (ssize_t)inlen; case NGHTTP2_IB_READ_SETTINGS: DEBUGF("recv: [IB_READ_SETTINGS]\n"); readlen = inbound_frame_buf_read(iframe, in, last); iframe->payloadleft -= readlen; in += readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (nghttp2_buf_mark_avail(&iframe->sbuf)) { break; } if (readlen > 0) { inbound_frame_set_settings_entry(iframe); } if (iframe->payloadleft) { inbound_frame_set_mark(iframe, NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH); break; } rv = session_process_settings_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_READ_GOAWAY_DEBUG: DEBUGF("recv: [IB_READ_GOAWAY_DEBUG]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); if (readlen > 0) { iframe->lbuf.last = nghttp2_cpymem(iframe->lbuf.last, in, readlen); iframe->payloadleft -= readlen; in += readlen; } DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (iframe->payloadleft) { assert(nghttp2_buf_avail(&iframe->lbuf) > 0); break; } rv = session_process_goaway_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_EXPECT_CONTINUATION: case NGHTTP2_IB_IGN_CONTINUATION: #ifdef DEBUGBUILD if (iframe->state == NGHTTP2_IB_EXPECT_CONTINUATION) { fprintf(stderr, "recv: [IB_EXPECT_CONTINUATION]\n"); } else { fprintf(stderr, "recv: [IB_IGN_CONTINUATION]\n"); } #endif /* DEBUGBUILD */ readlen = inbound_frame_buf_read(iframe, in, last); in += readlen; if (nghttp2_buf_mark_avail(&iframe->sbuf)) { return in - first; } nghttp2_frame_unpack_frame_hd(&cont_hd, iframe->sbuf.pos); iframe->payloadleft = cont_hd.length; DEBUGF("recv: payloadlen=%zu, type=%u, flags=0x%02x, stream_id=%d\n", cont_hd.length, cont_hd.type, cont_hd.flags, cont_hd.stream_id); if (cont_hd.type != NGHTTP2_CONTINUATION || cont_hd.stream_id != iframe->frame.hd.stream_id) { DEBUGF("recv: expected stream_id=%d, type=%d, but got stream_id=%d, " "type=%u\n", iframe->frame.hd.stream_id, NGHTTP2_CONTINUATION, cont_hd.stream_id, cont_hd.type); rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "unexpected non-CONTINUATION frame or stream_id is invalid"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } /* CONTINUATION won't bear NGHTTP2_PADDED flag */ iframe->frame.hd.flags = (uint8_t)( iframe->frame.hd.flags | (cont_hd.flags & NGHTTP2_FLAG_END_HEADERS)); iframe->frame.hd.length += cont_hd.length; busy = 1; if (iframe->state == NGHTTP2_IB_EXPECT_CONTINUATION) { iframe->state = NGHTTP2_IB_READ_HEADER_BLOCK; rv = session_call_on_begin_frame(session, &cont_hd); if (nghttp2_is_fatal(rv)) { return rv; } } else { iframe->state = NGHTTP2_IB_IGN_HEADER_BLOCK; } break; case NGHTTP2_IB_READ_PAD_DATA: DEBUGF("recv: [IB_READ_PAD_DATA]\n"); readlen = inbound_frame_buf_read(iframe, in, last); in += readlen; iframe->payloadleft -= readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu, left=%zu\n", readlen, iframe->payloadleft, nghttp2_buf_mark_avail(&iframe->sbuf)); if (nghttp2_buf_mark_avail(&iframe->sbuf)) { return in - first; } /* Pad Length field is subject to flow control */ rv = nghttp2_session_update_recv_connection_window_size(session, readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } /* Pad Length field is consumed immediately */ rv = nghttp2_session_consume(session, iframe->frame.hd.stream_id, readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } stream = nghttp2_session_get_stream(session, iframe->frame.hd.stream_id); if (stream) { rv = nghttp2_session_update_recv_stream_window_size( session, stream, readlen, iframe->payloadleft || (iframe->frame.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0); if (nghttp2_is_fatal(rv)) { return rv; } } busy = 1; padlen = inbound_frame_compute_pad(iframe); if (padlen < 0) { rv = nghttp2_session_terminate_session_with_reason( session, NGHTTP2_PROTOCOL_ERROR, "DATA: invalid padding"); if (nghttp2_is_fatal(rv)) { return rv; } return (ssize_t)inlen; } iframe->frame.data.padlen = (size_t)padlen; iframe->state = NGHTTP2_IB_READ_DATA; break; case NGHTTP2_IB_READ_DATA: stream = nghttp2_session_get_stream(session, iframe->frame.hd.stream_id); if (!stream) { busy = 1; iframe->state = NGHTTP2_IB_IGN_DATA; break; } DEBUGF("recv: [IB_READ_DATA]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); iframe->payloadleft -= readlen; in += readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (readlen > 0) { ssize_t data_readlen; rv = nghttp2_session_update_recv_connection_window_size(session, readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } rv = nghttp2_session_update_recv_stream_window_size( session, stream, readlen, iframe->payloadleft || (iframe->frame.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0); if (nghttp2_is_fatal(rv)) { return rv; } data_readlen = inbound_frame_effective_readlen( iframe, iframe->payloadleft, readlen); if (data_readlen == -1) { /* everything is padding */ data_readlen = 0; } padlen = (ssize_t)readlen - data_readlen; if (padlen > 0) { /* Padding is considered as "consumed" immediately */ rv = nghttp2_session_consume(session, iframe->frame.hd.stream_id, (size_t)padlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } } DEBUGF("recv: data_readlen=%zd\n", data_readlen); if (data_readlen > 0) { if (session_enforce_http_messaging(session)) { if (nghttp2_http_on_data_chunk(stream, (size_t)data_readlen) != 0) { if (session->opt_flags & NGHTTP2_OPTMASK_NO_AUTO_WINDOW_UPDATE) { /* Consume all data for connection immediately here */ rv = session_update_connection_consumed_size( session, (size_t)data_readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_DATA) { return (ssize_t)inlen; } } rv = nghttp2_session_add_rst_stream( session, iframe->frame.hd.stream_id, NGHTTP2_PROTOCOL_ERROR); if (nghttp2_is_fatal(rv)) { return rv; } busy = 1; iframe->state = NGHTTP2_IB_IGN_DATA; break; } } if (session->callbacks.on_data_chunk_recv_callback) { rv = session->callbacks.on_data_chunk_recv_callback( session, iframe->frame.hd.flags, iframe->frame.hd.stream_id, in - readlen, (size_t)data_readlen, session->user_data); if (rv == NGHTTP2_ERR_PAUSE) { return in - first; } if (nghttp2_is_fatal(rv)) { return NGHTTP2_ERR_CALLBACK_FAILURE; } } } } if (iframe->payloadleft) { break; } rv = session_process_data_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_IGN_DATA: DEBUGF("recv: [IB_IGN_DATA]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); iframe->payloadleft -= readlen; in += readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (readlen > 0) { /* Update connection-level flow control window for ignored DATA frame too */ rv = nghttp2_session_update_recv_connection_window_size(session, readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } if (session->opt_flags & NGHTTP2_OPTMASK_NO_AUTO_WINDOW_UPDATE) { /* Ignored DATA is considered as "consumed" immediately. */ rv = session_update_connection_consumed_size(session, readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } } } if (iframe->payloadleft) { break; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_IGN_ALL: return (ssize_t)inlen; case NGHTTP2_IB_READ_EXTENSION_PAYLOAD: DEBUGF("recv: [IB_READ_EXTENSION_PAYLOAD]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); iframe->payloadleft -= readlen; in += readlen; DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (readlen > 0) { rv = session_call_on_extension_chunk_recv_callback( session, in - readlen, readlen); if (nghttp2_is_fatal(rv)) { return rv; } if (rv != 0) { busy = 1; iframe->state = NGHTTP2_IB_IGN_PAYLOAD; break; } } if (iframe->payloadleft > 0) { break; } rv = session_process_extension_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_READ_ALTSVC_PAYLOAD: DEBUGF("recv: [IB_READ_ALTSVC_PAYLOAD]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); if (readlen > 0) { iframe->lbuf.last = nghttp2_cpymem(iframe->lbuf.last, in, readlen); iframe->payloadleft -= readlen; in += readlen; } DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (iframe->payloadleft) { assert(nghttp2_buf_avail(&iframe->lbuf) > 0); break; } rv = session_process_altsvc_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } session_inbound_frame_reset(session); break; case NGHTTP2_IB_READ_ORIGIN_PAYLOAD: DEBUGF("recv: [IB_READ_ORIGIN_PAYLOAD]\n"); readlen = inbound_frame_payload_readlen(iframe, in, last); if (readlen > 0) { iframe->lbuf.last = nghttp2_cpymem(iframe->lbuf.last, in, readlen); iframe->payloadleft -= readlen; in += readlen; } DEBUGF("recv: readlen=%zu, payloadleft=%zu\n", readlen, iframe->payloadleft); if (iframe->payloadleft) { assert(nghttp2_buf_avail(&iframe->lbuf) > 0); break; } rv = session_process_origin_frame(session); if (nghttp2_is_fatal(rv)) { return rv; } if (iframe->state == NGHTTP2_IB_IGN_ALL) { return (ssize_t)inlen; } session_inbound_frame_reset(session); break; } if (!busy && in == last) { break; } busy = 0; } assert(in == last); return in - first; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-707'], 'message': 'Earlier check for settings flood'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: NTSTATUS mitkdc_task_init(struct task_server *task) { struct tevent_req *subreq; const char * const *kdc_cmd; struct interface *ifaces; char *kdc_config = NULL; struct kdc_server *kdc; krb5_error_code code; NTSTATUS status; kadm5_ret_t ret; kadm5_config_params config; void *server_handle; int dbglvl = 0; task_server_set_title(task, "task[mitkdc_parent]"); switch (lpcfg_server_role(task->lp_ctx)) { case ROLE_STANDALONE: task_server_terminate(task, "The KDC is not required in standalone " "server configuration, terminate!", false); return NT_STATUS_INVALID_DOMAIN_ROLE; case ROLE_DOMAIN_MEMBER: task_server_terminate(task, "The KDC is not required in member " "server configuration", false); return NT_STATUS_INVALID_DOMAIN_ROLE; case ROLE_ACTIVE_DIRECTORY_DC: /* Yes, we want to start the KDC */ break; } /* Load interfaces for kpasswd */ load_interface_list(task, task->lp_ctx, &ifaces); if (iface_list_count(ifaces) == 0) { task_server_terminate(task, "KDC: no network interfaces configured", false); return NT_STATUS_UNSUCCESSFUL; } kdc_config = talloc_asprintf(task, "%s/kdc.conf", lpcfg_private_dir(task->lp_ctx)); if (kdc_config == NULL) { task_server_terminate(task, "KDC: no memory", false); return NT_STATUS_NO_MEMORY; } setenv("KRB5_KDC_PROFILE", kdc_config, 0); TALLOC_FREE(kdc_config); dbglvl = debuglevel_get_class(DBGC_KERBEROS); if (dbglvl >= 10) { char *kdc_trace_file = talloc_asprintf(task, "%s/mit_kdc_trace.log", get_dyn_LOGFILEBASE()); if (kdc_trace_file == NULL) { task_server_terminate(task, "KDC: no memory", false); return NT_STATUS_NO_MEMORY; } setenv("KRB5_TRACE", kdc_trace_file, 1); } /* start it as a child process */ kdc_cmd = lpcfg_mit_kdc_command(task->lp_ctx); subreq = samba_runcmd_send(task, task->event_ctx, timeval_zero(), 1, /* stdout log level */ 0, /* stderr log level */ kdc_cmd, "-n", /* Don't go into background */ #if 0 "-w 2", /* Start two workers */ #endif NULL); if (subreq == NULL) { DEBUG(0, ("Failed to start MIT KDC as child daemon\n")); task_server_terminate(task, "Failed to startup mitkdc task", true); return NT_STATUS_INTERNAL_ERROR; } tevent_req_set_callback(subreq, mitkdc_server_done, task); DEBUG(5,("Started krb5kdc process\n")); status = samba_setup_mit_kdc_irpc(task); if (!NT_STATUS_IS_OK(status)) { task_server_terminate(task, "Failed to setup kdc irpc service", true); } DEBUG(5,("Started irpc service for kdc_server\n")); kdc = talloc_zero(task, struct kdc_server); if (kdc == NULL) { task_server_terminate(task, "KDC: Out of memory", true); return NT_STATUS_NO_MEMORY; } talloc_set_destructor(kdc, kdc_server_destroy); kdc->task = task; kdc->base_ctx = talloc_zero(kdc, struct samba_kdc_base_context); if (kdc->base_ctx == NULL) { task_server_terminate(task, "KDC: Out of memory", true); return NT_STATUS_NO_MEMORY; } kdc->base_ctx->ev_ctx = task->event_ctx; kdc->base_ctx->lp_ctx = task->lp_ctx; initialize_krb5_error_table(); code = smb_krb5_init_context(kdc, kdc->task->lp_ctx, &kdc->smb_krb5_context); if (code != 0) { task_server_terminate(task, "KDC: Unable to initialize krb5 context", true); return NT_STATUS_INTERNAL_ERROR; } code = kadm5_init_krb5_context(&kdc->smb_krb5_context->krb5_context); if (code != 0) { task_server_terminate(task, "KDC: Unable to init kadm5 krb5_context", true); return NT_STATUS_INTERNAL_ERROR; } ZERO_STRUCT(config); config.mask = KADM5_CONFIG_REALM; config.realm = discard_const_p(char, lpcfg_realm(kdc->task->lp_ctx)); ret = kadm5_init(kdc->smb_krb5_context->krb5_context, discard_const_p(char, "kpasswd"), NULL, /* pass */ discard_const_p(char, "kpasswd"), &config, KADM5_STRUCT_VERSION, KADM5_API_VERSION_4, NULL, &server_handle); if (ret != 0) { task_server_terminate(task, "KDC: Initialize kadm5", true); return NT_STATUS_INTERNAL_ERROR; } kdc->private_data = server_handle; code = krb5_db_register_keytab(kdc->smb_krb5_context->krb5_context); if (code != 0) { task_server_terminate(task, "KDC: Unable to KDB", true); return NT_STATUS_INTERNAL_ERROR; } kdc->keytab_name = talloc_asprintf(kdc, "KDB:"); if (kdc->keytab_name == NULL) { task_server_terminate(task, "KDC: Out of memory", true); return NT_STATUS_NO_MEMORY; } kdc->samdb = samdb_connect(kdc, kdc->task->event_ctx, kdc->task->lp_ctx, system_session(kdc->task->lp_ctx), NULL, 0); if (kdc->samdb == NULL) { task_server_terminate(task, "KDC: Unable to connect to samdb", true); return NT_STATUS_CONNECTION_INVALID; } status = startup_kpasswd_server(kdc, kdc, task->lp_ctx, ifaces); if (!NT_STATUS_IS_OK(status)) { task_server_terminate(task, "KDC: Unable to start kpasswd server", true); return status; } DEBUG(5,("Started kpasswd service for kdc_server\n")); return NT_STATUS_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-288'], 'message': 'CVE-2022-32744 s4:kdc: Rename keytab_name -> kpasswd_keytab_name This makes explicitly clear the purpose of this keytab. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz> Reviewed-by: Andreas Schneider <asn@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PJ_DEF(pj_status_t) pjsip_auth_create_aka_response( pj_pool_t *pool, const pjsip_digest_challenge *chal, const pjsip_cred_info *cred, const pj_str_t *method, pjsip_digest_credential *auth) { pj_str_t nonce_bin; int aka_version; const pj_str_t pjsip_AKAv1_MD5 = { "AKAv1-MD5", 9 }; const pj_str_t pjsip_AKAv2_MD5 = { "AKAv2-MD5", 9 }; pj_uint8_t *chal_rand, *chal_sqnxoraka, *chal_mac; pj_uint8_t k[PJSIP_AKA_KLEN]; pj_uint8_t op[PJSIP_AKA_OPLEN]; pj_uint8_t amf[PJSIP_AKA_AMFLEN]; pj_uint8_t res[PJSIP_AKA_RESLEN]; pj_uint8_t ck[PJSIP_AKA_CKLEN]; pj_uint8_t ik[PJSIP_AKA_IKLEN]; pj_uint8_t ak[PJSIP_AKA_AKLEN]; pj_uint8_t sqn[PJSIP_AKA_SQNLEN]; pj_uint8_t xmac[PJSIP_AKA_MACLEN]; pjsip_cred_info aka_cred; int i, len; pj_status_t status; /* Check the algorithm is supported. */ if (chal->algorithm.slen==0 || pj_stricmp2(&chal->algorithm, "md5") == 0) { /* * A normal MD5 authentication is requested. Fallbackt to the usual * MD5 digest creation. */ pjsip_auth_create_digest(&auth->response, &auth->nonce, &auth->nc, &auth->cnonce, &auth->qop, &auth->uri, &auth->realm, cred, method); return PJ_SUCCESS; } else if (pj_stricmp(&chal->algorithm, &pjsip_AKAv1_MD5) == 0) { /* * AKA version 1 is requested. */ aka_version = 1; } else if (pj_stricmp(&chal->algorithm, &pjsip_AKAv2_MD5) == 0) { /* * AKA version 2 is requested. */ aka_version = 2; } else { /* Unsupported algorithm */ return PJSIP_EINVALIDALGORITHM; } /* Decode nonce */ nonce_bin.slen = len = PJ_BASE64_TO_BASE256_LEN(chal->nonce.slen); nonce_bin.ptr = pj_pool_alloc(pool, nonce_bin.slen + 1); status = pj_base64_decode(&chal->nonce, (pj_uint8_t*)nonce_bin.ptr, &len); nonce_bin.slen = len; if (status != PJ_SUCCESS) return PJSIP_EAUTHINNONCE; if (nonce_bin.slen < PJSIP_AKA_RANDLEN + PJSIP_AKA_AUTNLEN) return PJSIP_EAUTHINNONCE; /* Get RAND, AUTN, and MAC */ chal_rand = (pj_uint8_t*)(nonce_bin.ptr + 0); chal_sqnxoraka = (pj_uint8_t*) (nonce_bin.ptr + PJSIP_AKA_RANDLEN); chal_mac = (pj_uint8_t*) (nonce_bin.ptr + PJSIP_AKA_RANDLEN + PJSIP_AKA_SQNLEN + PJSIP_AKA_AMFLEN); /* Copy k. op, and amf */ pj_bzero(k, sizeof(k)); pj_bzero(op, sizeof(op)); pj_bzero(amf, sizeof(amf)); if (cred->ext.aka.k.slen) pj_memcpy(k, cred->ext.aka.k.ptr, cred->ext.aka.k.slen); if (cred->ext.aka.op.slen) pj_memcpy(op, cred->ext.aka.op.ptr, cred->ext.aka.op.slen); if (cred->ext.aka.amf.slen) pj_memcpy(amf, cred->ext.aka.amf.ptr, cred->ext.aka.amf.slen); /* Given key K and random challenge RAND, compute response RES, * confidentiality key CK, integrity key IK and anonymity key AK. */ f2345(k, chal_rand, res, ck, ik, ak, op); /* Compute sequence number SQN */ for (i=0; i<PJSIP_AKA_SQNLEN; ++i) sqn[i] = (pj_uint8_t) (chal_sqnxoraka[i] ^ ak[i]); /* Verify MAC in the challenge */ /* Compute XMAC */ f1(k, chal_rand, sqn, amf, xmac, op); if (pj_memcmp(chal_mac, xmac, PJSIP_AKA_MACLEN) != 0) { return PJSIP_EAUTHINNONCE; } /* Build a temporary credential info to create MD5 digest, using * "res" as the password. */ pj_memcpy(&aka_cred, cred, sizeof(aka_cred)); aka_cred.data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; /* Create a response */ if (aka_version == 1) { /* * For AKAv1, the password is RES */ aka_cred.data.ptr = (char*)res; aka_cred.data.slen = PJSIP_AKA_RESLEN; pjsip_auth_create_digest(&auth->response, &chal->nonce, &auth->nc, &auth->cnonce, &auth->qop, &auth->uri, &chal->realm, &aka_cred, method); } else if (aka_version == 2) { /* * For AKAv2, password is base64 encoded [1] parameters: * PRF(RES||IK||CK,"http-digest-akav2-password") * * The pseudo-random function (PRF) is HMAC-MD5 in this case. */ pj_str_t resikck; const pj_str_t AKAv2_Passwd = { "http-digest-akav2-password", 26 }; pj_uint8_t hmac_digest[16]; char tmp_buf[48]; int hmac64_len; resikck.slen = PJSIP_AKA_RESLEN + PJSIP_AKA_IKLEN + PJSIP_AKA_CKLEN; pj_assert(resikck.slen <= PJ_ARRAY_SIZE(tmp_buf)); resikck.ptr = tmp_buf; pj_memcpy(resikck.ptr + 0, res, PJSIP_AKA_RESLEN); pj_memcpy(resikck.ptr + PJSIP_AKA_RESLEN, ik, PJSIP_AKA_IKLEN); pj_memcpy(resikck.ptr + PJSIP_AKA_RESLEN + PJSIP_AKA_IKLEN, ck, PJSIP_AKA_CKLEN); pj_hmac_md5((const pj_uint8_t*)AKAv2_Passwd.ptr, AKAv2_Passwd.slen, (const pj_uint8_t*)resikck.ptr, resikck.slen, hmac_digest); aka_cred.data.slen = hmac64_len = PJ_BASE256_TO_BASE64_LEN(PJ_ARRAY_SIZE(hmac_digest)); pj_assert(aka_cred.data.slen+1 <= PJ_ARRAY_SIZE(tmp_buf)); aka_cred.data.ptr = tmp_buf; pj_base64_encode(hmac_digest, PJ_ARRAY_SIZE(hmac_digest), aka_cred.data.ptr, &len); aka_cred.data.slen = hmac64_len; pjsip_auth_create_digest(&auth->response, &chal->nonce, &auth->nc, &auth->cnonce, &auth->qop, &auth->uri, &chal->realm, &aka_cred, method); } else { pj_assert(!"Bug!"); return PJ_EBUG; } /* Done */ return PJ_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Use PJ_ASSERT_RETURN() on pjsip_auth_create_digest() and pjsua_init_tpselector() (#3009) * Use PJ_ASSERT_RETURN on pjsip_auth_create_digest * Use PJ_ASSERT_RETURN on pjsua_init_tpselector() * Fix incorrect check. * Add return value to pjsip_auth_create_digest() and pjsip_auth_create_digestSHA256() * Modification based on comments.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rsa_oaep_sha1_decrypt(const struct rsa_private_key *key, size_t label_length, const uint8_t *label, size_t *length, uint8_t *message, const mpz_t gibberish) { mpz_t m; int res; struct sha1_ctx ctx; mpz_init(m); rsa_compute_root(key, m, gibberish); res = pkcs1_oaep_decrypt (key->size, m, SHA1_DIGEST_SIZE, &ctx, &nettle_sha1, (nettle_hash_init_func*)&sha1_init, (nettle_hash_update_func*)&sha1_update, (nettle_hash_digest_func*)&sha1_digest, label_length, label, length, message); mpz_clear(m); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Fix rsa oaep key length check before decryption'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void launch(OpKernelContext* context, const TensorShape& tensor_in_shape, const Tensor& out_backprop, const std::array<int64, 3>& window, const std::array<int64, 3>& stride, const std::array<int64, 3>& output_shape, const std::array<int64, 3>& padding, TensorFormat data_format, Tensor* output) { output->flat<T>().setZero(); std::array<int64, 3> input_size = {{tensor_in_shape.dim_size(3), tensor_in_shape.dim_size(2), tensor_in_shape.dim_size(1)}}; for (int64 p = 0; p < out_backprop.dim_size(3); ++p) { // Calculate broadcast size for planes/rows/cols. For SAME padding, // current index could be in the padding area, and // p * stride_planes + window_planes // could be beyond the input tensor's boundary. In such cases, change // the starting index and reduce the broadcast size. // // The same procedure is repeated for every spatial dimension in the // nested loops below. int pindex, psize; OP_REQUIRES_OK(context, GetBroadcastSize(p, input_size[0], window[0], stride[0], padding[0], &pindex, &psize)); for (int64 r = 0; r < out_backprop.dim_size(2); ++r) { int rindex, rsize; OP_REQUIRES_OK(context, GetBroadcastSize(r, input_size[1], window[1], stride[1], padding[1], &rindex, &rsize)); for (int64 c = 0; c < out_backprop.dim_size(1); ++c) { int cindex, csize; OP_REQUIRES_OK( context, GetBroadcastSize(c, input_size[2], window[2], stride[2], padding[2], &cindex, &csize)); TensorSlice src{{0, -1}, {c, 1}, {r, 1}, {p, 1}, {0, -1}}; TensorSlice dst{{0, -1}, {cindex, csize}, {rindex, rsize}, {pindex, psize}, {0, -1}}; Eigen::DSizes<Eigen::DenseIndex, 5> src_indices; Eigen::DSizes<Eigen::DenseIndex, 5> src_sizes; Eigen::DSizes<Eigen::DenseIndex, 5> dst_indices; Eigen::DSizes<Eigen::DenseIndex, 5> dst_sizes; src.FillIndicesAndSizes<5>(out_backprop.shape(), &src_indices, &src_sizes); dst.FillIndicesAndSizes<5>(tensor_in_shape, &dst_indices, &dst_sizes); #if !defined(EIGEN_HAS_INDEX_LIST) Eigen::array<int, 5> bcast = {1, csize, rsize, psize, 1}; #else Eigen::IndexList<Eigen::type2index<1>, int, int, int, Eigen::type2index<1>> bcast; bcast.set(1, csize); bcast.set(2, rsize); bcast.set(3, psize); #endif Eigen::Tensor<T, 5, Eigen::RowMajor> slices(src_sizes); slices.device(context->eigen_cpu_device()) = out_backprop.tensor<T, 5>().slice(src_indices, src_sizes); // Divide by the size of the actual patch (psize * rsize * csize). float divide_size = rsize * csize * psize * 1.0f; slices *= slices.constant(1.0f / divide_size); output->tensor<T, 5>() .slice(dst_indices, dst_sizes) .device(context->eigen_cpu_device()) += slices.broadcast(bcast); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix assertion failure in pooling_ops_3d PiperOrigin-RevId: 372364504 Change-Id: Iecde4fe26b47a8fa935d6e2611b5585ed5777781'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int _FVMenuClose(FontView *fv) { int i; SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster:fv->b.sf; if ( !SFCloseAllInstrs(fv->b.sf) ) return( false ); if ( fv->b.nextsame!=NULL || fv->b.sf->fv!=&fv->b ) { /* There's another view, can close this one with no problems */ } else if ( SFAnyChanged(sf) ) { i = AskChanged(fv->b.sf); if ( i==2 ) /* Cancel */ return( false ); if ( i==0 && !_FVMenuSave(fv)) /* Save */ return(false); else SFClearAutoSave(sf); /* if they didn't save it, remove change record */ } _FVCloseWindows(fv); if ( sf->filename!=NULL ) RecentFilesRemember(sf->filename); else if ( sf->origname!=NULL ) RecentFilesRemember(sf->origname); GDrawDestroyWindow(fv->gw); return( true ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Warn users before discarding their unsaved scripts (#3852) * Warn users before discarding their unsaved scripts This closes #3846.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status ComputeConv2DDimension(const Conv2DParameters& params, const Tensor& input, const Tensor& filter, Conv2DDimensions* dimensions) { // Check that 2D convolution input and filter have exactly 4 dimensions. TF_REQUIRES(input.dims() == 4, errors::InvalidArgument("input must be 4-dimensional", input.shape().DebugString())); TF_REQUIRES(filter.dims() == 4, errors::InvalidArgument("filter must be 4-dimensional: ", filter.shape().DebugString())); for (int i = 0; i < 3; i++) { TF_REQUIRES( FastBoundsCheck(filter.dim_size(i), std::numeric_limits<int>::max()), errors::InvalidArgument("filter too large")); } // The last dimension for input is in_depth. Check that it is the same as the // filter's in_depth or it is evenly divisible by filter's in_depth. const int64 in_depth_raw = GetTensorDim(input, params.data_format, 'C'); const int64 patch_depth_raw = filter.dim_size(2); TF_REQUIRES(FastBoundsCheck(in_depth_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("Input depth too large")); TF_REQUIRES(FastBoundsCheck(patch_depth_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("Patch depth too large")); const int in_depth = static_cast<int>(in_depth_raw); const int patch_depth = static_cast<int>(patch_depth_raw); TF_REQUIRES(in_depth % patch_depth == 0, errors::InvalidArgument( "input depth must be evenly divisible by filter depth: ", in_depth, " vs ", patch_depth)); // The last dimension for filter is out_depth. const int out_depth = static_cast<int>(filter.dim_size(3)); // The second dimension for input is rows/height. // The first dimension for filter is rows/height. const int64 input_rows_raw = GetTensorDim(input, params.data_format, 'H'); TF_REQUIRES(FastBoundsCheck(input_rows_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("Input rows too large")); const int input_rows = static_cast<int>(input_rows_raw); const int filter_rows = static_cast<int>(filter.dim_size(0)); // The third dimension for input is columns/width. // The second dimension for filter is columns/width. const int64 input_cols_raw = GetTensorDim(input, params.data_format, 'W'); TF_REQUIRES(FastBoundsCheck(input_cols_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("Input cols too large")); const int input_cols = static_cast<int>(input_cols_raw); const int filter_cols = static_cast<int>(filter.dim_size(1)); // The first dimension for input is batch. const int64 batch_raw = GetTensorDim(input, params.data_format, 'N'); TF_REQUIRES(FastBoundsCheck(batch_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("batch is too large")); const int batch = static_cast<int>(batch_raw); // Take the stride and dilation from the second and third dimensions only (we // do not support striding or dilation on the batch or depth dimension). const int stride_rows = GetTensorDim(params.strides, params.data_format, 'H'); const int stride_cols = GetTensorDim(params.strides, params.data_format, 'W'); const int dilation_rows = GetTensorDim(params.dilations, params.data_format, 'H'); const int dilation_cols = GetTensorDim(params.dilations, params.data_format, 'W'); int64 pad_rows_before, pad_rows_after, pad_cols_before, pad_cols_after; if (params.padding == Padding::EXPLICIT) { GetExplicitPaddingForDim(params.explicit_paddings, params.data_format, 'H', &pad_rows_before, &pad_rows_after); GetExplicitPaddingForDim(params.explicit_paddings, params.data_format, 'W', &pad_cols_before, &pad_cols_after); } // Compute windowed output sizes for rows and columns. int64 out_rows = 0, out_cols = 0; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerboseV2( input_rows, filter_rows, dilation_rows, stride_rows, params.padding, &out_rows, &pad_rows_before, &pad_rows_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerboseV2( input_cols, filter_cols, dilation_cols, stride_cols, params.padding, &out_cols, &pad_cols_before, &pad_cols_after)); dimensions->batch = batch; dimensions->input_rows = input_rows; dimensions->input_cols = input_cols; dimensions->in_depth = in_depth; dimensions->filter_rows = filter_rows; dimensions->filter_cols = filter_cols; dimensions->patch_depth = patch_depth; dimensions->out_depth = out_depth; dimensions->stride_rows = stride_rows; dimensions->stride_cols = stride_cols; dimensions->dilation_rows = dilation_rows; dimensions->dilation_cols = dilation_cols; dimensions->out_rows = out_rows; dimensions->out_cols = out_cols; dimensions->pad_rows_before = pad_rows_before; dimensions->pad_rows_after = pad_rows_after; dimensions->pad_cols_before = pad_cols_before; dimensions->pad_cols_after = pad_cols_after; return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Fix one more FPE. PiperOrigin-RevId: 369346568 Change-Id: I840fd575962adc879713a4c9cc59e6da3331caa7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ff_jpeg2000_init_component(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty, Jpeg2000QuantStyle *qntsty, int cbps, int dx, int dy, AVCodecContext *avctx) { uint8_t log2_band_prec_width, log2_band_prec_height; int reslevelno, bandno, gbandno = 0, ret, i, j; uint32_t csize; if (codsty->nreslevels2decode <= 0) { av_log(avctx, AV_LOG_ERROR, "nreslevels2decode %d invalid or uninitialized\n", codsty->nreslevels2decode); return AVERROR_INVALIDDATA; } if (ret = ff_jpeg2000_dwt_init(&comp->dwt, comp->coord, codsty->nreslevels2decode - 1, codsty->transform)) return ret; // component size comp->coord is uint16_t so ir cannot overflow csize = (comp->coord[0][1] - comp->coord[0][0]) * (comp->coord[1][1] - comp->coord[1][0]); if (codsty->transform == FF_DWT97) { comp->i_data = NULL; comp->f_data = av_malloc_array(csize, sizeof(*comp->f_data)); if (!comp->f_data) return AVERROR(ENOMEM); } else { comp->f_data = NULL; comp->i_data = av_malloc_array(csize, sizeof(*comp->i_data)); if (!comp->i_data) return AVERROR(ENOMEM); } comp->reslevel = av_malloc_array(codsty->nreslevels, sizeof(*comp->reslevel)); if (!comp->reslevel) return AVERROR(ENOMEM); /* LOOP on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) { int declvl = codsty->nreslevels - reslevelno; // N_L -r see ISO/IEC 15444-1:2002 B.5 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; /* Compute borders for each resolution level. * Computation of trx_0, trx_1, try_0 and try_1. * see ISO/IEC 15444-1:2002 eq. B.5 and B-14 */ for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) reslevel->coord[i][j] = ff_jpeg2000_ceildivpow2(comp->coord_o[i][j], declvl - 1); // update precincts size: 2^n value reslevel->log2_prec_width = codsty->log2_prec_widths[reslevelno]; reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno]; /* Number of bands for each resolution level */ if (reslevelno == 0) reslevel->nbands = 1; else reslevel->nbands = 3; /* Number of precincts wich span the tile for resolution level reslevelno * see B.6 in ISO/IEC 15444-1:2002 eq. B-16 * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| - (trx_0 / 2 ^ log2_prec_width) * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| - (try_0 / 2 ^ log2_prec_width) * for Dcinema profiles in JPEG 2000 * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| */ if (reslevel->coord[0][1] == reslevel->coord[0][0]) reslevel->num_precincts_x = 0; else reslevel->num_precincts_x = ff_jpeg2000_ceildivpow2(reslevel->coord[0][1], reslevel->log2_prec_width) - (reslevel->coord[0][0] >> reslevel->log2_prec_width); if (reslevel->coord[1][1] == reslevel->coord[1][0]) reslevel->num_precincts_y = 0; else reslevel->num_precincts_y = ff_jpeg2000_ceildivpow2(reslevel->coord[1][1], reslevel->log2_prec_height) - (reslevel->coord[1][0] >> reslevel->log2_prec_height); reslevel->band = av_malloc_array(reslevel->nbands, sizeof(*reslevel->band)); if (!reslevel->band) return AVERROR(ENOMEM); for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) { Jpeg2000Band *band = reslevel->band + bandno; int cblkno, precno; int nb_precincts; /* TODO: Implementation of quantization step not finished, * see ISO/IEC 15444-1:2002 E.1 and A.6.4. */ switch (qntsty->quantsty) { uint8_t gain; int numbps; case JPEG2000_QSTY_NONE: /* TODO: to verify. No quantization in this case */ band->f_stepsize = 1; break; case JPEG2000_QSTY_SI: /*TODO: Compute formula to implement. */ numbps = cbps + lut_gain[codsty->transform == FF_DWT53][bandno + (reslevelno > 0)]; band->f_stepsize = SHL(2048 + qntsty->mant[gbandno], 2 + numbps - qntsty->expn[gbandno]); break; case JPEG2000_QSTY_SE: /* Exponent quantization step. * Formula: * delta_b = 2 ^ (R_b - expn_b) * (1 + (mant_b / 2 ^ 11)) * R_b = R_I + log2 (gain_b ) * see ISO/IEC 15444-1:2002 E.1.1 eqn. E-3 and E-4 */ /* TODO/WARN: value of log2 (gain_b ) not taken into account * but it works (compared to OpenJPEG). Why? * Further investigation needed. */ gain = cbps; band->f_stepsize = pow(2.0, gain - qntsty->expn[gbandno]); band->f_stepsize *= qntsty->mant[gbandno] / 2048.0 + 1.0; break; default: band->f_stepsize = 0; av_log(avctx, AV_LOG_ERROR, "Unknown quantization format\n"); break; } /* FIXME: In openjepg code stespize = stepsize * 0.5. Why? * If not set output of entropic decoder is not correct. */ if (!av_codec_is_encoder(avctx->codec)) band->f_stepsize *= 0.5; band->i_stepsize = band->f_stepsize * (1 << 15); /* computation of tbx_0, tbx_1, tby_0, tby_1 * see ISO/IEC 15444-1:2002 B.5 eq. B-15 and tbl B.1 * codeblock width and height is computed for * DCI JPEG 2000 codeblock_width = codeblock_width = 32 = 2 ^ 5 */ if (reslevelno == 0) { /* for reslevelno = 0, only one band, x0_b = y0_b = 0 */ for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) band->coord[i][j] = ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0], declvl - 1); log2_band_prec_width = reslevel->log2_prec_width; log2_band_prec_height = reslevel->log2_prec_height; /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */ band->log2_cblk_width = FFMIN(codsty->log2_cblk_width, reslevel->log2_prec_width); band->log2_cblk_height = FFMIN(codsty->log2_cblk_height, reslevel->log2_prec_height); } else { /* 3 bands x0_b = 1 y0_b = 0; x0_b = 0 y0_b = 1; x0_b = y0_b = 1 */ /* x0_b and y0_b are computed with ((bandno + 1 >> i) & 1) */ for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) /* Formula example for tbx_0 = ceildiv((tcx_0 - 2 ^ (declvl - 1) * x0_b) / declvl) */ band->coord[i][j] = ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0] - (((bandno + 1 >> i) & 1) << declvl - 1), declvl); /* TODO: Manage case of 3 band offsets here or * in coding/decoding function? */ /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */ band->log2_cblk_width = FFMIN(codsty->log2_cblk_width, reslevel->log2_prec_width - 1); band->log2_cblk_height = FFMIN(codsty->log2_cblk_height, reslevel->log2_prec_height - 1); log2_band_prec_width = reslevel->log2_prec_width - 1; log2_band_prec_height = reslevel->log2_prec_height - 1; } for (j = 0; j < 2; j++) band->coord[0][j] = ff_jpeg2000_ceildiv(band->coord[0][j], dx); for (j = 0; j < 2; j++) band->coord[1][j] = ff_jpeg2000_ceildiv(band->coord[1][j], dy); band->prec = av_malloc_array(reslevel->num_precincts_x * (uint64_t)reslevel->num_precincts_y, sizeof(*band->prec)); if (!band->prec) return AVERROR(ENOMEM); nb_precincts = reslevel->num_precincts_x * reslevel->num_precincts_y; for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* TODO: Explain formula for JPEG200 DCINEMA. */ /* TODO: Verify with previous count of codeblocks per band */ /* Compute P_x0 */ prec->coord[0][0] = (precno % reslevel->num_precincts_x) * (1 << log2_band_prec_width); prec->coord[0][0] = FFMAX(prec->coord[0][0], band->coord[0][0]); /* Compute P_y0 */ prec->coord[1][0] = (precno / reslevel->num_precincts_x) * (1 << log2_band_prec_height); prec->coord[1][0] = FFMAX(prec->coord[1][0], band->coord[1][0]); /* Compute P_x1 */ prec->coord[0][1] = prec->coord[0][0] + (1 << log2_band_prec_width); prec->coord[0][1] = FFMIN(prec->coord[0][1], band->coord[0][1]); /* Compute P_y1 */ prec->coord[1][1] = prec->coord[1][0] + (1 << log2_band_prec_height); prec->coord[1][1] = FFMIN(prec->coord[1][1], band->coord[1][1]); prec->nb_codeblocks_width = ff_jpeg2000_ceildivpow2(prec->coord[0][1] - prec->coord[0][0], band->log2_cblk_width); prec->nb_codeblocks_height = ff_jpeg2000_ceildivpow2(prec->coord[1][1] - prec->coord[1][0], band->log2_cblk_height); /* Tag trees initialization */ prec->cblkincl = ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width, prec->nb_codeblocks_height); if (!prec->cblkincl) return AVERROR(ENOMEM); prec->zerobits = ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width, prec->nb_codeblocks_height); if (!prec->zerobits) return AVERROR(ENOMEM); prec->cblk = av_mallocz_array(prec->nb_codeblocks_width * (uint64_t)prec->nb_codeblocks_height, sizeof(*prec->cblk)); if (!prec->cblk) return AVERROR(ENOMEM); for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; uint16_t Cx0, Cy0; /* Compute coordinates of codeblocks */ /* Compute Cx0*/ Cx0 = (prec->coord[0][0] >> band->log2_cblk_width) << band->log2_cblk_width; Cx0 = Cx0 + ((cblkno % prec->nb_codeblocks_width) << band->log2_cblk_width); cblk->coord[0][0] = FFMAX(Cx0, prec->coord[0][0]); /* Compute Cy0*/ Cy0 = (prec->coord[1][0] >> band->log2_cblk_height) << band->log2_cblk_height; Cy0 = Cy0 + ((cblkno / prec->nb_codeblocks_width) << band->log2_cblk_height); cblk->coord[1][0] = FFMAX(Cy0, prec->coord[1][0]); /* Compute Cx1 */ cblk->coord[0][1] = FFMIN(Cx0 + (1 << band->log2_cblk_width), prec->coord[0][1]); /* Compute Cy1 */ cblk->coord[1][1] = FFMIN(Cy0 + (1 << band->log2_cblk_height), prec->coord[1][1]); /* Update code-blocks coordinates according sub-band position */ if ((bandno + !!reslevelno) & 1) { cblk->coord[0][0] += comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0]; cblk->coord[0][1] += comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0]; } if ((bandno + !!reslevelno) & 2) { cblk->coord[1][0] += comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0]; cblk->coord[1][1] += comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0]; } cblk->zero = 0; cblk->lblock = 3; cblk->length = 0; cblk->lengthinc = 0; cblk->npasses = 0; } } } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'jpeg2000: fix dereferencing invalid pointers Found-by: Laurent Butti <laurentb@gmail.com> Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err gf_bifs_flush_command_list(GF_BifsDecoder *codec) { GF_BitStream *bs; GF_Err e; CommandBufferItem *cbi; GF_SceneGraph *prev_root = codec->current_graph; u32 NbPass = gf_list_count(codec->command_buffers); GF_List *nextPass = gf_list_new(); while (NbPass) { while (gf_list_count(codec->command_buffers)) { cbi = (CommandBufferItem *)gf_list_get(codec->command_buffers, 0); gf_list_rem(codec->command_buffers, 0); codec->current_graph = gf_node_get_graph(cbi->node); e = GF_OK; if (cbi->cb->bufferSize) { bs = gf_bs_new((char*)cbi->cb->buffer, cbi->cb->bufferSize, GF_BITSTREAM_READ); gf_bs_set_eos_callback(bs, BM_EndOfStream, codec); e = BM_ParseCommand(codec, bs, cbi->cb->commandList); gf_bs_del(bs); } if (!e) { gf_node_unregister(cbi->node, NULL); gf_free(cbi); continue; } /*this may be an error or a dependency pb - reset coimmand list and move to next pass*/ while (gf_list_count(cbi->cb->commandList)) { u32 i; GF_CommandField *cf; GF_Command *com = (GF_Command *)gf_list_get(cbi->cb->commandList, 0); gf_list_rem(cbi->cb->commandList, 0); cf = (GF_CommandField *) gf_list_get(com->command_fields, 0); if (cf && cf->fieldType==GF_SG_VRML_SFCOMMANDBUFFER) { for (i=0; i<gf_list_count(codec->command_buffers); i++) { CommandBufferItem *cbi2 = (CommandBufferItem *)gf_list_get(codec->command_buffers, i); if (cbi2->cb == cf->field_ptr) { gf_node_unregister(cbi2->node, NULL); gf_free(cbi2); gf_list_rem(codec->command_buffers, i); i--; } } } gf_sg_command_del(com); } gf_list_add(nextPass, cbi); } if (!gf_list_count(nextPass)) break; /*prepare next pass*/ while (gf_list_count(nextPass)) { cbi = (CommandBufferItem *)gf_list_get(nextPass, 0); gf_list_rem(nextPass, 0); gf_list_add(codec->command_buffers, cbi); } NbPass --; if (NbPass > gf_list_count(codec->command_buffers)) NbPass = gf_list_count(codec->command_buffers); codec->LastError = GF_OK; } gf_list_del(nextPass); codec->current_graph = prev_root; return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'fixed #2057'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes) { // is_space and is_digit both return false on '\0', so this will // not overrun the null-terminated buffer. char const* p = line.c_str(); char const* start = line.c_str(); // Skip zero or more spaces while (QUtil::is_space(*p)) { ++p; } // Require digit if (! QUtil::is_digit(*p)) { return false; } // Gather digits std::string obj_str; while (QUtil::is_digit(*p)) { obj_str.append(1, *p++); } // Require space if (! QUtil::is_space(*p)) { return false; } // Skip spaces while (QUtil::is_space(*p)) { ++p; } // Require digit if (! QUtil::is_digit(*p)) { return false; } // Gather digits std::string num_str; while (QUtil::is_digit(*p)) { num_str.append(1, *p++); } // Skip any space including line terminators while (QUtil::is_space(*p)) { ++p; } bytes = p - start; obj = QUtil::string_to_int(obj_str.c_str()); num = QUtil::string_to_int(num_str.c_str()); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::compute_data_key(std::string const& encryption_key, int objid, int generation, bool use_aes, int encryption_V, int encryption_R) { // Algorithm 3.1 from the PDF 1.7 Reference Manual std::string result = encryption_key; if (encryption_V >= 5) { // Algorithm 3.1a (PDF 1.7 extension level 3): just use // encryption key straight. return result; } // Append low three bytes of object ID and low two bytes of generation result += static_cast<char>(objid & 0xff); result += static_cast<char>((objid >> 8) & 0xff); result += static_cast<char>((objid >> 16) & 0xff); result += static_cast<char>(generation & 0xff); result += static_cast<char>((generation >> 8) & 0xff); if (use_aes) { result += "sAlT"; } MD5 md5; md5.encodeDataIncrementally(result.c_str(), result.length()); MD5::Digest digest; md5.digest(digest); return std::string(reinterpret_cast<char*>(digest), std::min(result.length(), static_cast<size_t>(16))); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::checkLinearizationInternal() { // All comments referring to the PDF spec refer to the spec for // version 1.4. std::list<std::string> errors; std::list<std::string> warnings; // Check all values in linearization parameter dictionary LinParameters& p = this->m->linp; // L: file size in bytes -- checked by isLinearized // O: object number of first page std::vector<QPDFObjectHandle> const& pages = getAllPages(); if (p.first_page_object != pages.at(0).getObjectID()) { QTC::TC("qpdf", "QPDF err /O mismatch"); errors.push_back("first page object (/O) mismatch"); } // N: number of pages int npages = pages.size(); if (p.npages != npages) { // Not tested in the test suite errors.push_back("page count (/N) mismatch"); } for (int i = 0; i < npages; ++i) { QPDFObjectHandle const& page = pages.at(i); QPDFObjGen og(page.getObjGen()); if (this->m->xref_table[og].getType() == 2) { errors.push_back("page dictionary for page " + QUtil::int_to_string(i) + " is compressed"); } } // T: offset of whitespace character preceding xref entry for object 0 this->m->file->seek(p.xref_zero_offset, SEEK_SET); while (1) { char ch; this->m->file->read(&ch, 1); if (! ((ch == ' ') || (ch == '\r') || (ch == '\n'))) { this->m->file->seek(-1, SEEK_CUR); break; } } if (this->m->file->tell() != this->m->first_xref_item_offset) { QTC::TC("qpdf", "QPDF err /T mismatch"); errors.push_back("space before first xref item (/T) mismatch " "(computed = " + QUtil::int_to_string(this->m->first_xref_item_offset) + "; file = " + QUtil::int_to_string(this->m->file->tell())); } // P: first page number -- Implementation note 124 says Acrobat // ignores this value, so we will too. // Check numbering of compressed objects in each xref section. // For linearized files, all compressed objects are supposed to be // at the end of the containing xref section if any object streams // are in use. if (this->m->uncompressed_after_compressed) { errors.push_back("linearized file contains an uncompressed object" " after a compressed one in a cross-reference stream"); } // Further checking requires optimization and order calculation. // Don't allow optimization to make changes. If it has to, then // the file is not properly linearized. We use the xref table to // figure out which objects are compressed and which are // uncompressed. { // local scope std::map<int, int> object_stream_data; for (std::map<QPDFObjGen, QPDFXRefEntry>::const_iterator iter = this->m->xref_table.begin(); iter != this->m->xref_table.end(); ++iter) { QPDFObjGen const& og = (*iter).first; QPDFXRefEntry const& entry = (*iter).second; if (entry.getType() == 2) { object_stream_data[og.getObj()] = entry.getObjStreamNumber(); } } optimize(object_stream_data, false); calculateLinearizationData(object_stream_data); } // E: offset of end of first page -- Implementation note 123 says // Acrobat includes on extra object here by mistake. pdlin fails // to place thumbnail images in section 9, so when thumbnails are // present, it also gets the wrong value for /E. It also doesn't // count outlines here when it should even though it places them // in part 6. This code fails to put thread information // dictionaries in part 9, so it actually gets the wrong value for // E when threads are present. In that case, it would probably // agree with pdlin. As of this writing, the test suite doesn't // contain any files with threads. if (this->m->part6.empty()) { throw std::logic_error("linearization part 6 unexpectedly empty"); } qpdf_offset_t min_E = -1; qpdf_offset_t max_E = -1; for (std::vector<QPDFObjectHandle>::iterator iter = this->m->part6.begin(); iter != this->m->part6.end(); ++iter) { QPDFObjGen og((*iter).getObjGen()); if (this->m->obj_cache.count(og) == 0) { // All objects have to have been dereferenced to be classified. throw std::logic_error("linearization part6 object not in cache"); } ObjCache const& oc = this->m->obj_cache[og]; min_E = std::max(min_E, oc.end_before_space); max_E = std::max(max_E, oc.end_after_space); } if ((p.first_page_end < min_E) || (p.first_page_end > max_E)) { QTC::TC("qpdf", "QPDF warn /E mismatch"); warnings.push_back("end of first page section (/E) mismatch: /E = " + QUtil::int_to_string(p.first_page_end) + "; computed = " + QUtil::int_to_string(min_E) + ".." + QUtil::int_to_string(max_E)); } // Check hint tables std::map<int, int> shared_idx_to_obj; checkHSharedObject(errors, warnings, pages, shared_idx_to_obj); checkHPageOffset(errors, warnings, pages, shared_idx_to_obj); checkHOutlines(warnings); // Report errors bool result = true; if (! errors.empty()) { result = false; for (std::list<std::string>::iterator iter = errors.begin(); iter != errors.end(); ++iter) { *this->m->out_stream << "ERROR: " << (*iter) << std::endl; } } if (! warnings.empty()) { result = false; for (std::list<std::string>::iterator iter = warnings.begin(); iter != warnings.end(); ++iter) { *this->m->out_stream << "WARNING: " << (*iter) << std::endl; } } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::calculateHPageOffset( std::map<int, QPDFXRefEntry> const& xref, std::map<int, qpdf_offset_t> const& lengths, std::map<int, int> const& obj_renumber) { // Page Offset Hint Table // We are purposely leaving some values set to their initial zero // values. std::vector<QPDFObjectHandle> const& pages = getAllPages(); unsigned int npages = pages.size(); CHPageOffset& cph = this->m->c_page_offset_data; std::vector<CHPageOffsetEntry>& cphe = cph.entries; // Calculate minimum and maximum values for number of objects per // page and page length. int min_nobjects = cphe.at(0).nobjects; int max_nobjects = min_nobjects; int min_length = outputLengthNextN( pages.at(0).getObjectID(), min_nobjects, lengths, obj_renumber); int max_length = min_length; int max_shared = cphe.at(0).nshared_objects; HPageOffset& ph = this->m->page_offset_hints; std::vector<HPageOffsetEntry>& phe = ph.entries; // npages is the size of the existing pages array. phe = std::vector<HPageOffsetEntry>(npages); for (unsigned int i = 0; i < npages; ++i) { // Calculate values for each page, assigning full values to // the delta items. They will be adjusted later. // Repeat calculations for page 0 so we can assign to phe[i] // without duplicating those assignments. int nobjects = cphe.at(i).nobjects; int length = outputLengthNextN( pages.at(i).getObjectID(), nobjects, lengths, obj_renumber); int nshared = cphe.at(i).nshared_objects; min_nobjects = std::min(min_nobjects, nobjects); max_nobjects = std::max(max_nobjects, nobjects); min_length = std::min(min_length, length); max_length = std::max(max_length, length); max_shared = std::max(max_shared, nshared); phe.at(i).delta_nobjects = nobjects; phe.at(i).delta_page_length = length; phe.at(i).nshared_objects = nshared; } ph.min_nobjects = min_nobjects; int in_page0_id = pages.at(0).getObjectID(); int out_page0_id = (*(obj_renumber.find(in_page0_id))).second; ph.first_page_offset = (*(xref.find(out_page0_id))).second.getOffset(); ph.nbits_delta_nobjects = nbits(max_nobjects - min_nobjects); ph.min_page_length = min_length; ph.nbits_delta_page_length = nbits(max_length - min_length); ph.nbits_nshared_objects = nbits(max_shared); ph.nbits_shared_identifier = nbits(this->m->c_shared_object_data.nshared_total); ph.shared_denominator = 4; // doesn't matter // It isn't clear how to compute content offset and content // length. Since we are not interleaving page objects with the // content stream, we'll use the same values for content length as // page length. We will use 0 as content offset because this is // what Adobe does (implementation note 127) and pdlin as well. ph.nbits_delta_content_length = ph.nbits_delta_page_length; ph.min_content_length = ph.min_page_length; for (unsigned int i = 0; i < npages; ++i) { // Adjust delta entries if ((phe.at(i).delta_nobjects < min_nobjects) || (phe.at(i).delta_page_length < min_length)) { stopOnError("found too small delta nobjects or delta page length" " while writing linearization data"); } phe.at(i).delta_nobjects -= min_nobjects; phe.at(i).delta_page_length -= min_length; phe.at(i).delta_content_length = phe.at(i).delta_page_length; for (int j = 0; j < cphe.at(i).nshared_objects; ++j) { phe.at(i).shared_identifiers.push_back( cphe.at(i).shared_identifiers.at(j)); phe.at(i).shared_numerators.push_back(0); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::makeIndirectObject(QPDFObjectHandle oh) { int max_objid = getObjectCount(); QPDFObjGen next(max_objid + 1, 0); this->m->obj_cache[next] = ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), -1, -1); return QPDFObjectHandle::Factory::newIndirect( this, next.getObj(), next.getGen()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::reconstruct_xref(QPDFExc& e) { if (this->m->reconstructed_xref) { // Avoid xref reconstruction infinite loops. This is getting // very hard to reproduce because qpdf is throwing many fewer // exceptions while parsing. Most situations are warnings now. throw e; } this->m->reconstructed_xref = true; warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, "file is damaged")); warn(e); warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, "Attempting to reconstruct cross-reference table")); // Delete all references to type 1 (uncompressed) objects std::set<QPDFObjGen> to_delete; for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter = this->m->xref_table.begin(); iter != this->m->xref_table.end(); ++iter) { if (((*iter).second).getType() == 1) { to_delete.insert((*iter).first); } } for (std::set<QPDFObjGen>::iterator iter = to_delete.begin(); iter != to_delete.end(); ++iter) { this->m->xref_table.erase(*iter); } this->m->file->seek(0, SEEK_END); qpdf_offset_t eof = this->m->file->tell(); this->m->file->seek(0, SEEK_SET); bool in_obj = false; qpdf_offset_t line_start = 0; // Don't allow very long tokens here during recovery. static size_t const MAX_LEN = 100; while (this->m->file->tell() < eof) { this->m->file->findAndSkipNextEOL(); qpdf_offset_t next_line_start = this->m->file->tell(); this->m->file->seek(line_start, SEEK_SET); QPDFTokenizer::Token t1 = readToken(this->m->file, MAX_LEN); qpdf_offset_t token_start = this->m->file->tell() - t1.getValue().length(); if (token_start >= next_line_start) { // don't process yet } else if (in_obj) { if (t1 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj")) { in_obj = false; } } else { if (t1.getType() == QPDFTokenizer::tt_integer) { QPDFTokenizer::Token t2 = readToken(this->m->file, MAX_LEN); QPDFTokenizer::Token t3 = readToken(this->m->file, MAX_LEN); if ((t2.getType() == QPDFTokenizer::tt_integer) && (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj"))) { in_obj = true; int obj = QUtil::string_to_int(t1.getValue().c_str()); int gen = QUtil::string_to_int(t2.getValue().c_str()); insertXrefEntry(obj, 1, token_start, gen, true); } } else if ((! this->m->trailer.isInitialized()) && (t1 == QPDFTokenizer::Token( QPDFTokenizer::tt_word, "trailer"))) { QPDFObjectHandle t = readObject(this->m->file, "trailer", 0, 0, false); if (! t.isDictionary()) { // Oh well. It was worth a try. } else { setTrailer(t); } } } this->m->file->seek(next_line_start, SEEK_SET); line_start = next_line_start; } if (! this->m->trailer.isInitialized()) { // We could check the last encountered object to see if it was // an xref stream. If so, we could try to get the trailer // from there. This may make it possible to recover files // with bad startxref pointers even when they have object // streams. throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, "unable to find trailer " "dictionary while recovering damaged file"); } // We could iterate through the objects looking for streams and // try to find objects inside of them, but it's probably not worth // the trouble. Acrobat can't recover files with any errors in an // xref stream, and this would be a real long shot anyway. If we // wanted to do anything that involved looking at stream contents, // we'd also have to call initializeEncryption() here. It's safe // to call it more than once. } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ArgParser::argOiMinArea(char* parameter) { o.oi_min_area = QUtil::string_to_int(parameter); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ArgParser::handleBashArguments() { // Do a minimal job of parsing bash_line into arguments. This // doesn't do everything the shell does (e.g. $(...), variable // expansion, arithmetic, globs, etc.), but it should be good // enough for purposes of handling completion. As we build up the // new argv, we can't use this->new_argv because this code has to // interoperate with @file arguments, so memory for both ways of // fabricating argv has to be protected. bool last_was_backslash = false; enum { st_top, st_squote, st_dquote } state = st_top; std::string arg; for (std::string::iterator iter = bash_line.begin(); iter != bash_line.end(); ++iter) { char ch = (*iter); if (last_was_backslash) { arg.append(1, ch); last_was_backslash = false; } else if (ch == '\\') { last_was_backslash = true; } else { bool append = false; switch (state) { case st_top: if (QUtil::is_space(ch)) { if (! arg.empty()) { bash_argv.push_back( PointerHolder<char>( true, QUtil::copy_string(arg.c_str()))); arg.clear(); } } else if (ch == '"') { state = st_dquote; } else if (ch == '\'') { state = st_squote; } else { append = true; } break; case st_squote: if (ch == '\'') { state = st_top; } else { append = true; } break; case st_dquote: if (ch == '"') { state = st_top; } else { append = true; } break; } if (append) { arg.append(1, ch); } } } if (bash_argv.empty()) { // This can't happen if properly invoked by bash, but ensure // we have a valid argv[0] regardless. bash_argv.push_back( PointerHolder<char>( true, QUtil::copy_string(argv[0]))); } // Explicitly discard any non-space-terminated word. The "current // word" is handled specially. bash_argv_ph = PointerHolder<char*>(true, new char*[1+bash_argv.size()]); argv = bash_argv_ph.getPointer(); for (size_t i = 0; i < bash_argv.size(); ++i) { argv[i] = bash_argv.at(i).getPointer(); } argc = static_cast<int>(bash_argv.size()); argv[argc] = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_AES_PDF::initializeVector() { if (use_zero_iv) { for (unsigned int i = 0; i < this->buf_size; ++i) { this->cbc_block[i] = 0; } } else if (use_specified_iv) { std::memcpy(this->cbc_block, this->specified_iv, this->buf_size); } else if (use_static_iv) { for (unsigned int i = 0; i < this->buf_size; ++i) { this->cbc_block[i] = 14 * (1 + i); } } else { QUtil::initializeWithRandomBytes(this->cbc_block, this->buf_size); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::optimize(std::map<int, int> const& object_stream_data, bool allow_changes) { if (! this->m->obj_user_to_objects.empty()) { // already optimized return; } // The PDF specification indicates that /Outlines is supposed to // be an indirect reference. Force it to be so if it exists and // is direct. (This has been seen in the wild.) QPDFObjectHandle root = getRoot(); if (root.getKey("/Outlines").isDictionary()) { QPDFObjectHandle outlines = root.getKey("/Outlines"); if (! outlines.isIndirect()) { QTC::TC("qpdf", "QPDF_optimization indirect outlines"); root.replaceKey("/Outlines", makeIndirectObject(outlines)); } } // Traverse pages tree pushing all inherited resources down to the // page level. This also initializes this->m->all_pages. pushInheritedAttributesToPage(allow_changes, false); // Traverse pages int n = this->m->all_pages.size(); for (int pageno = 0; pageno < n; ++pageno) { updateObjectMaps(ObjUser(ObjUser::ou_page, pageno), this->m->all_pages.at(pageno)); } // Traverse document-level items std::set<std::string> keys = this->m->trailer.getKeys(); for (std::set<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { std::string const& key = *iter; if (key == "/Root") { // handled separately } else { updateObjectMaps(ObjUser(ObjUser::ou_trailer_key, key), this->m->trailer.getKey(key)); } } keys = root.getKeys(); for (std::set<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { // Technically, /I keys from /Thread dictionaries are supposed // to be handled separately, but we are going to disregard // that specification for now. There is loads of evidence // that pdlin and Acrobat both disregard things like this from // time to time, so this is almost certain not to cause any // problems. std::string const& key = *iter; updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), root.getKey(key)); } ObjUser root_ou = ObjUser(ObjUser::ou_root); QPDFObjGen root_og = QPDFObjGen(root.getObjGen()); this->m->obj_user_to_objects[root_ou].insert(root_og); this->m->object_to_obj_users[root_og].insert(root_ou); filterCompressedObjects(object_stream_data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::writeHGeneric(BitWriter& w, HGeneric& t) { w.writeBits(t.first_object, 32); // 1 w.writeBits(t.first_object_offset, 32); // 2 w.writeBits(t.nobjects, 32); // 3 w.writeBits(t.group_length, 32); // 4 } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFPageDocumentHelper::flattenAnnotationsForPage( QPDFPageObjectHelper& page, QPDFObjectHandle& resources, QPDFAcroFormDocumentHelper& afdh, int required_flags, int forbidden_flags) { bool need_appearances = afdh.getNeedAppearances(); std::vector<QPDFAnnotationObjectHelper> annots = page.getAnnotations(); std::vector<QPDFObjectHandle> new_annots; std::string new_content; int rotate = 0; QPDFObjectHandle rotate_obj = page.getObjectHandle().getKey("/Rotate"); if (rotate_obj.isInteger() && rotate_obj.getIntValue()) { rotate = rotate_obj.getIntValue(); } int next_fx = 1; for (std::vector<QPDFAnnotationObjectHelper>::iterator iter = annots.begin(); iter != annots.end(); ++iter) { QPDFAnnotationObjectHelper& aoh(*iter); QPDFObjectHandle as = aoh.getAppearanceStream("/N"); bool is_widget = (aoh.getSubtype() == "/Widget"); bool process = true; if (need_appearances && is_widget) { QTC::TC("qpdf", "QPDFPageDocumentHelper skip widget need appearances"); process = false; } if (process && as.isStream()) { if (is_widget) { QTC::TC("qpdf", "QPDFPageDocumentHelper merge DR"); QPDFFormFieldObjectHelper ff = afdh.getFieldForAnnotation(aoh); QPDFObjectHandle as_resources = as.getDict().getKey("/Resources"); if (as_resources.isIndirect()) { QTC::TC("qpdf", "QPDFPageDocumentHelper indirect as resources"); as.getDict().replaceKey( "/Resources", as_resources.shallowCopy()); as_resources = as.getDict().getKey("/Resources"); } as_resources.mergeResources( ff.getInheritableFieldValue("/DR")); } else { QTC::TC("qpdf", "QPDFPageDocumentHelper non-widget annotation"); } std::string name = resources.getUniqueResourceName( "/Fxo", next_fx); std::string content = aoh.getPageContentForAppearance( name, rotate, required_flags, forbidden_flags); if (! content.empty()) { resources.mergeResources( QPDFObjectHandle::parse("<< /XObject << >> >>")); resources.getKey("/XObject").replaceKey(name, as); ++next_fx; } new_content += content; } else if (process) { // If an annotation has no appearance stream, just drop // the annotation when flattening. This can happen for // unchecked checkboxes and radio buttons, popup windows // associated with comments that aren't visible, and other // types of annotations that aren't visible. QTC::TC("qpdf", "QPDFPageDocumentHelper ignore annotation with no appearance"); } else { new_annots.push_back(aoh.getObjectHandle()); } } if (new_annots.size() != annots.size()) { QPDFObjectHandle page_oh = page.getObjectHandle(); if (new_annots.empty()) { QTC::TC("qpdf", "QPDFPageDocumentHelper remove annots"); page_oh.removeKey("/Annots"); } else { QPDFObjectHandle old_annots = page_oh.getKey("/Annots"); QPDFObjectHandle new_annots_oh = QPDFObjectHandle::newArray(new_annots); if (old_annots.isIndirect()) { QTC::TC("qpdf", "QPDFPageDocumentHelper replace indirect annots"); this->qpdf.replaceObject( old_annots.getObjGen(), new_annots_oh); } else { QTC::TC("qpdf", "QPDFPageDocumentHelper replace direct annots"); page_oh.replaceKey("/Annots", new_annots_oh); } } page.addPageContents( QPDFObjectHandle::newStream(&qpdf, "q\n"), true); page.addPageContents( QPDFObjectHandle::newStream(&qpdf, "\nQ\n" + new_content), false); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static QPDFObjectHandle create_page_contents(QPDF& pdf, int pageno) { return QPDFObjectHandle::newStream(&pdf, generate_page_contents(pageno)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFPageData::QPDFPageData(std::string const& filename, QPDF* qpdf, char const* range) : filename(filename), qpdf(qpdf), orig_pages(qpdf->getAllPages()) { try { this->selected_pages = QUtil::parse_numrange(range, this->orig_pages.size()); } catch (std::runtime_error& e) { usageExit("parsing numeric range for " + filename + ": " + e.what()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: compute_O_rc4_key(std::string const& user_password, std::string const& owner_password, QPDF::EncryptionData const& data, unsigned char key[OU_key_bytes_V4]) { if (data.getV() >= 5) { throw std::logic_error( "compute_O_rc4_key called for file with V >= 5"); } std::string password = owner_password; if (password.empty()) { password = user_password; } MD5 md5; md5.encodeDataIncrementally( pad_or_truncate_password_V4(password).c_str(), key_bytes); MD5::Digest digest; int key_len = std::min(static_cast<int>(sizeof(digest)), data.getLengthBytes()); iterate_md5_digest(md5, digest, ((data.getR() >= 3) ? 50 : 0), key_len); memcpy(key, digest, OU_key_bytes_V4); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) { throw std::logic_error("SecureRandomDataProvider::provideRandomData called when support was not compiled in"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::isEncrypted(int& R, int& P, int& V, encryption_method_e& stream_method, encryption_method_e& string_method, encryption_method_e& file_method) { if (this->m->encp->encrypted) { QPDFObjectHandle trailer = getTrailer(); QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); QPDFObjectHandle Pkey = encrypt.getKey("/P"); QPDFObjectHandle Rkey = encrypt.getKey("/R"); QPDFObjectHandle Vkey = encrypt.getKey("/V"); P = Pkey.getIntValue(); R = Rkey.getIntValue(); V = Vkey.getIntValue(); stream_method = this->m->encp->cf_stream; string_method = this->m->encp->cf_string; file_method = this->m->encp->cf_file; return true; } else { return false; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPH_XCAT(sph_, HASH)(void *cc, const void *data, size_t len) { SPH_XCAT(sph_, SPH_XCAT(HASH, _context)) *sc; unsigned current; size_t orig_len; #if !SPH_64 sph_u32 clow, clow2; #endif if (len < (2 * SPH_BLEN)) { SPH_XCAT(HASH, _short)(cc, data, len); return; } sc = cc; #if SPH_64 current = (unsigned)sc->count & (SPH_BLEN - 1U); #else current = (unsigned)sc->count_low & (SPH_BLEN - 1U); #endif if (current > 0) { unsigned t; t = SPH_BLEN - current; SPH_XCAT(HASH, _short)(cc, data, t); data = (const unsigned char *)data + t; len -= t; } #if !SPH_UNALIGNED if (((SPH_UPTR)data & (SPH_WLEN - 1U)) != 0) { SPH_XCAT(HASH, _short)(cc, data, len); return; } #endif orig_len = len; while (len >= SPH_BLEN) { RFUN(data, SPH_VAL); len -= SPH_BLEN; data = (const unsigned char *)data + SPH_BLEN; } if (len > 0) memcpy(sc->buf, data, len); #if SPH_64 sc->count += (sph_u64)orig_len; #else clow = sc->count_low; clow2 = SPH_T32(clow + orig_len); sc->count_low = clow2; if (clow2 < clow) sc->count_high ++; /* * This code handles the improbable situation where "size_t" is * greater than 32 bits, and yet we do not have a 64-bit type. */ orig_len >>= 12; orig_len >>= 10; orig_len >>= 10; sc->count_high += orig_len; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::adjusted_offset(int offset) { // All offsets >= H_offset have to be increased by H_length // since all hint table location values disregard the hint table // itself. if (offset >= this->m->linp.H_offset) { return offset + this->m->linp.H_length; } return offset; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BitStream::getBits(int nbits) { return read_bits(this->p, this->bit_offset, this->bits_available, nbits); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void read_file_into_memory( char const* filename, PointerHolder<char>& file_buf, size_t& size) { FILE* f = QUtil::safe_fopen(filename, "rb"); fseek(f, 0, SEEK_END); size = QUtil::tell(f); fseek(f, 0, SEEK_SET); file_buf = PointerHolder<char>(true, new char[size]); char* buf_p = file_buf.getPointer(); size_t bytes_read = 0; size_t len = 0; while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0) { bytes_read += len; } if (bytes_read != size) { if (ferror(f)) { throw std::runtime_error( std::string("failure reading file ") + filename + " into memory: read " + QUtil::uint_to_string(bytes_read) + "; wanted " + QUtil::uint_to_string(size)); } else { throw std::logic_error( std::string("premature eof reading file ") + filename + " into memory: read " + QUtil::uint_to_string(bytes_read) + "; wanted " + QUtil::uint_to_string(size)); } } fclose(f); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void check_page_contents(int pageno, QPDFObjectHandle page) { PointerHolder<Buffer> buf = page.getKey("/Contents").getStreamData(); std::string actual_contents = std::string(reinterpret_cast<char *>(buf->getBuffer()), buf->getSize()); std::string expected_contents = generate_page_contents(pageno); if (expected_contents != actual_contents) { std::cout << "page contents wrong for page " << pageno << std::endl << "ACTUAL: " << actual_contents << "EXPECTED: " << expected_contents << "----\n"; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFWriter::bytesNeeded(unsigned long long n) { int bytes = 0; while (n) { ++bytes; n >>= 8; } return bytes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::pipeStreamData(int objid, int generation, qpdf_offset_t offset, size_t length, QPDFObjectHandle stream_dict, Pipeline* pipeline, bool suppress_warnings, bool will_retry) { bool is_attachment_stream = this->m->attachment_streams.count( QPDFObjGen(objid, generation)); return pipeStreamData( this->m->encp, this->m->file, *this, objid, generation, offset, length, stream_dict, is_attachment_stream, pipeline, suppress_warnings, will_retry); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) { size_t i, j, k; RBinDwarfDIE *dies; RBinDwarfAttrValue *values; if (!inf || !f) { return; } for (i = 0; i < inf->length; i++) { fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset); fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length); fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version); fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset); fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size); dies = inf->comp_units[i].dies; for (j = 0; j < inf->comp_units[i].length; j++) { fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code); if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type && dwarf_tag_name_encodings[dies[j].tag]) { fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]); } else { fprintf (f, "(Unknown abbrev tag)\n"); } if (!dies[j].abbrev_code) { continue; } values = dies[j].attr_values; for (k = 0; k < dies[j].length; k++) { if (!values[k].name) continue; if (values[k].name < DW_AT_vtable_elem_location && dwarf_attr_encodings[values[k].name]) { fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]); } else { fprintf (f, " TODO\t"); } r_bin_dwarf_dump_attr_value (&values[k], f); fprintf (f, "\n"); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix #8813 - segfault in dwarf parser'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mrb_mod_define_method_m(mrb_state *mrb, struct RClass *c) { struct RProc *p; mrb_method_t m; mrb_sym mid; mrb_value proc = mrb_undef_value(); mrb_value blk; mrb_get_args(mrb, "n|o&", &mid, &proc, &blk); switch (mrb_type(proc)) { case MRB_TT_PROC: blk = proc; break; case MRB_TT_UNDEF: /* ignored */ break; default: mrb_raisef(mrb, E_TYPE_ERROR, "wrong argument type %T (expected Proc)", proc); break; } if (mrb_nil_p(blk)) { mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given"); } p = MRB_OBJ_ALLOC(mrb, MRB_TT_PROC, mrb->proc_class); mrb_proc_copy(p, mrb_proc_ptr(blk)); p->flags |= MRB_PROC_STRICT; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, c, mid, m); mrb_method_added(mrb, c, mid); return mrb_symbol_value(mid); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'proc.c: add `mrb_state` argument to `mrb_proc_copy()`. The function may invoke the garbage collection and it requires `mrb_state` to run.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Subgraph::Invoke() { if (!consistent_) { ReportError("Invoke called on model that is not consistent."); return kTfLiteError; } TfLiteStatus status = kTfLiteOk; if (state_ == kStateUninvokable) { ReportError("Invoke called on model that is not ready."); return kTfLiteError; } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { ReportError("Non-persistent memory is not available."); return kTfLiteError; } TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "Invoke"); // Invocations are always done in node order. // Note that calling Invoke repeatedly will cause the original memory plan to // be reused, unless either ResizeInputTensor() or AllocateTensors() has been // called. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); execution_plan_index++) { if (execution_plan_index == next_execution_plan_index_to_prepare_) { TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >= execution_plan_index); } int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; const char* op_name = nullptr; if (profiler_) op_name = GetTFLiteOpName(registration); TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index); for (int i = 0; i < node.inputs->size; ++i) { int tensor_index = node.inputs->data[i]; if (tensor_index == kTfLiteOptionalTensor) { continue; } TfLiteTensor* tensor = &tensors_[tensor_index]; if (tensor->delegate && tensor->delegate != node.delegate && tensor->data_is_stale) { TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index)); } if (tensor->data.raw == nullptr && tensor->bytes > 0) { if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1 && tensor->dims->size != 1) { // In general, having a tensor here with no buffer will be an error. // However, for the reshape operator, the second input tensor is // sometimes only used for the shape, not for the data. Thus, null // buffer is ok in this situation. // The situation where null buffer is not ok for reshape operator is // only when there are 2 inputs given to the node and the one // corresponding to the shape (i == 1) is a vector that contains all // dimensions. See `GetOutputShape()` function in // `tensorflow/lite/kernels/reshape.cc` continue; } else { // In all other cases, we need to return an error as otherwise we will // trigger a null pointer dereference (likely). ReportError("Input tensor %d lacks data", tensor_index); return kTfLiteError; } } } if (check_cancelled_func_ != nullptr && check_cancelled_func_(cancellation_data_)) { ReportError("Client requested cancel during Invoke()"); return kTfLiteError; } EnsureTensorsVectorCapacity(); tensor_resized_since_op_invoke_ = false; if (OpInvoke(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, "failed to invoke"); } // Force execution prep for downstream ops if the latest op triggered the // resize of a dynamic tensor. if (tensor_resized_since_op_invoke_ && HasDynamicTensor(context_, node.outputs)) { next_execution_plan_index_to_prepare_ = execution_plan_index + 1; // This happens when an intermediate dynamic tensor is resized. // We don't have to prepare all the ops, but we need to recompute // the allocation plan. if (next_execution_plan_index_to_plan_allocation_ > next_execution_plan_index_to_prepare_) { next_execution_plan_index_to_plan_allocation_ = next_execution_plan_index_to_prepare_; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter( next_execution_plan_index_to_plan_allocation_ - 1)); } } } } return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'TFLite: Error out when the graph has a recurion. Recursion is currently unsupported. PiperOrigin-RevId: 371708957 Change-Id: I8dfad0d85cbfe08e39ae8ea7bad21254ddee5003'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& dims = context->input(1); if (TensorShapeUtils::IsScalar(input.shape())) { context->set_output(0, input); } else { const int input_dims = input.dims(); OP_REQUIRES(context, TensorShapeUtils::IsVector(dims.shape()), errors::InvalidArgument("'dims' must be 1-dimension, not ", dims.dims())); OP_REQUIRES( context, input_dims == dims.dim_size(0), errors::InvalidArgument( "'dims' must have the same number of values as 'input' has " "dimensions. 'input' has ", input_dims, "'dims' has ", dims.dim_size(0), " values")); OP_REQUIRES(context, input_dims <= 8, errors::Unimplemented( "reverse is not implemented for tensors of rank > 8.")); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, input.shape(), &output)); #define HANDLE_REVERSE(NDIMS) \ case NDIMS: \ HandleReverseCase<Device, T, NDIMS>(context, dims.vec<bool>(), output); \ return; switch (input_dims) { HANDLE_REVERSE(0); HANDLE_REVERSE(1); HANDLE_REVERSE(2); HANDLE_REVERSE(3); HANDLE_REVERSE(4); HANDLE_REVERSE(5); HANDLE_REVERSE(6); HANDLE_REVERSE(7); HANDLE_REVERSE(8); } #undef HANDLE_REVERSE } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Fix FPE issue with `tf.raw_ops.Reverse`. PiperOrigin-RevId: 371176973 Change-Id: Ic6d483bfc95313ec2299c2d1c956cfe96c96626c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteConcatenationParams*>(node->builtin_data); int axis = params->axis; int num_inputs = node->inputs->size; // The number of dimensions of the input tensors must match, and all // dimensions except 'axis' must be equal. const TfLiteTensor* t0; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0)); TfLiteType input_type = t0->type; if (axis < 0) axis += t0->dims->size; TF_LITE_ENSURE(context, axis >= 0); TF_LITE_ENSURE(context, axis < t0->dims->size); TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone); TF_LITE_ENSURE(context, input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 || input_type == kTfLiteInt8 || input_type == kTfLiteInt16 || input_type == kTfLiteInt32 || input_type == kTfLiteInt64 || input_type == kTfLiteBool); // Output dimensions will match input dimensions, except 'axis', which // will be the sum of inputs int sum_axis = t0->dims->data[axis]; for (int i = 1; i < num_inputs; ++i) { const TfLiteTensor* t; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t)); TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size); TF_LITE_ENSURE_EQ(context, t->type, input_type); for (int d = 0; d < t0->dims->size; ++d) { if (d == axis) { sum_axis += t->dims->data[axis]; } else { TF_LITE_ENSURE_EQ(context, t->dims->data[d], t0->dims->data[d]); } } } TfLiteIntArray* output_size = TfLiteIntArrayCreate(t0->dims->size); for (int d = 0; d < t0->dims->size; ++d) { output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d]; } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type); if (input_type == kTfLiteInt8) { // Make sure there is no re-scaling needed for Int8 quantized kernel. This // is a restriction we introduced to Int8 kernels. VectorOfTensors<int8_t> all_inputs(*context, *node->inputs); for (int i = 0; i < node->inputs->size; ++i) { const TfLiteTensor* t; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t)); TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale); TF_LITE_ENSURE_EQ(context, t->params.zero_point, output->params.zero_point); } } if (input_type == kTfLiteInt16) { // Make sure that all Int16 inputs have a null zero-point. for (int i = 0; i < node->inputs->size; ++i) { const TfLiteTensor* t = GetInput(context, node, i); TF_LITE_ENSURE_EQ(context, t->params.zero_point, 0); } TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); } return context->ResizeTensor(context, output, output_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'Fix integer overflow in TFLite concat PiperOrigin-RevId: 371013841 Change-Id: I6a4782ce7ca753e23ff31e7fb6aeb7f9d412cd29'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, ""); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, "1,$"); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix oobread in avr'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PackLinuxElf64::canPack() { union { unsigned char buf[sizeof(Elf64_Ehdr) + 14*sizeof(Elf64_Phdr)]; //struct { Elf64_Ehdr ehdr; Elf64_Phdr phdr; } e; } u; COMPILE_TIME_ASSERT(sizeof(u) <= 1024) fi->readx(u.buf, sizeof(u.buf)); fi->seek(0, SEEK_SET); Elf64_Ehdr const *const ehdr = (Elf64_Ehdr *) u.buf; // now check the ELF header if (checkEhdr(ehdr) != 0) return false; // additional requirements for linux/elf386 if (get_te16(&ehdr->e_ehsize) != sizeof(*ehdr)) { throwCantPack("invalid Ehdr e_ehsize; try '--force-execve'"); return false; } if (e_phoff != sizeof(*ehdr)) {// Phdrs not contiguous with Ehdr throwCantPack("non-contiguous Ehdr/Phdr; try '--force-execve'"); return false; } // The first PT_LOAD64 must cover the beginning of the file (0==p_offset). Elf64_Phdr const *phdr = phdri; for (unsigned j=0; j < e_phnum; ++phdr, ++j) { if (j >= 14) { throwCantPack("too many ElfXX_Phdr; try '--force-execve'"); return false; } unsigned const p_type = get_te32(&phdr->p_type); if (1!=exetype && PT_LOAD64 == p_type) { // 1st PT_LOAD exetype = 1; load_va = get_te64(&phdr->p_vaddr); // class data member upx_uint64_t const p_offset = get_te64(&phdr->p_offset); upx_uint64_t const off = ~page_mask & load_va; if (off && off == p_offset) { // specific hint throwCantPack("Go-language PT_LOAD: try hemfix.c, or try '--force-execve'"); // Fixing it inside upx fails because packExtent() reads original file. return false; } if (0 != p_offset) { // 1st PT_LOAD must cover Ehdr and Phdr throwCantPack("first PT_LOAD.p_offset != 0; try '--force-execve'"); return false; } hatch_off = ~3ul & (3+ get_te64(&phdr->p_memsz)); break; } } // We want to compress position-independent executable (gcc -pie) // main programs, but compressing a shared library must be avoided // because the result is no longer usable. In theory, there is no way // to tell them apart: both are just ET_DYN. Also in theory, // neither the presence nor the absence of any particular symbol name // can be used to tell them apart; there are counterexamples. // However, we will use the following heuristic suggested by // Peter S. Mazinger <ps.m@gmx.net> September 2005: // If a ET_DYN has __libc_start_main as a global undefined symbol, // then the file is a position-independent executable main program // (that depends on libc.so.6) and is eligible to be compressed. // Otherwise (no __libc_start_main as global undefined): skip it. // Also allow __uClibc_main and __uClibc_start_main . if (Elf64_Ehdr::ET_DYN==get_te16(&ehdr->e_type)) { // The DT_SYMTAB has no designated length. Read the whole file. alloc_file_image(file_image, file_size); fi->seek(0, SEEK_SET); fi->readx(file_image, file_size); memcpy(&ehdri, ehdr, sizeof(Elf64_Ehdr)); phdri= (Elf64_Phdr *)((size_t)e_phoff + file_image); // do not free() !! shdri= (Elf64_Shdr *)((size_t)e_shoff + file_image); // do not free() !! sec_strndx = NULL; shstrtab = NULL; if (e_shnum) { unsigned const e_shstrndx = get_te16(&ehdr->e_shstrndx); if (e_shstrndx) { if (e_shnum <= e_shstrndx) { char msg[40]; snprintf(msg, sizeof(msg), "bad e_shstrndx %#x >= e_shnum %d", e_shstrndx, e_shnum); throwCantPack(msg); } sec_strndx = &shdri[e_shstrndx]; upx_uint64_t sh_offset = get_te64(&sec_strndx->sh_offset); if ((u64_t)file_size <= sh_offset) { char msg[50]; snprintf(msg, sizeof(msg), "bad .e_shstrndx->sh_offset %#lx", (long unsigned)sh_offset); throwCantPack(msg); } shstrtab = (char const *)(sh_offset + file_image); } sec_dynsym = elf_find_section_type(Elf64_Shdr::SHT_DYNSYM); if (sec_dynsym) { upx_uint64_t const sh_link = get_te64(&sec_dynsym->sh_link); if (e_shnum <= sh_link) { char msg[50]; snprintf(msg, sizeof(msg), "bad SHT_DYNSYM.sh_link %#lx", (long unsigned)sh_link); } sec_dynstr = &shdri[sh_link]; } if (sec_strndx) { unsigned const sh_name = get_te32(&sec_strndx->sh_name); if (Elf64_Shdr::SHT_STRTAB != get_te32(&sec_strndx->sh_type) || (u32_t)file_size <= (sizeof(".shstrtab") + sh_name + (shstrtab - (const char *)&file_image[0])) || (sh_name && 0!=strcmp((char const *)".shstrtab", &shstrtab[sh_name])) ) { throwCantPack("bad e_shstrtab"); } } } Elf64_Phdr const *pload_x0(0); // first eXecutable PT_LOAD phdr= phdri; for (int j= e_phnum; --j>=0; ++phdr) if (Elf64_Phdr::PT_DYNAMIC==get_te32(&phdr->p_type)) { dynseg= (Elf64_Dyn const *)(check_pt_dynamic(phdr) + file_image); invert_pt_dynamic(dynseg, get_te64(&phdr->p_filesz)); } else if (PT_LOAD64==get_te32(&phdr->p_type)) { if (!pload_x0 && Elf32_Phdr::PF_X & get_te32(&phdr->p_flags) ) { pload_x0 = phdr; } check_pt_load(phdr); } // elf_find_dynamic() returns 0 if 0==dynseg. dynstr= (char const *)elf_find_dynamic(Elf64_Dyn::DT_STRTAB); dynsym= (Elf64_Sym const *)elf_find_dynamic(Elf64_Dyn::DT_SYMTAB); if (opt->o_unix.force_pie || Elf64_Dyn::DF_1_PIE & elf_unsigned_dynamic(Elf64_Dyn::DT_FLAGS_1) || calls_crt1((Elf64_Rela const *)elf_find_dynamic(Elf64_Dyn::DT_RELA), (int)elf_unsigned_dynamic(Elf64_Dyn::DT_RELASZ)) || calls_crt1((Elf64_Rela const *)elf_find_dynamic(Elf64_Dyn::DT_JMPREL), (int)elf_unsigned_dynamic(Elf64_Dyn::DT_PLTRELSZ))) { is_pie = true; goto proceed; // calls C library init for main program } // Heuristic HACK for shared libraries (compare Darwin (MacOS) Dylib.) // If there is an existing DT_INIT, and if everything that the dynamic // linker ld-linux needs to perform relocations before calling DT_INIT // resides below the first SHT_EXECINSTR Section in one PT_LOAD, then // compress from the first executable Section to the end of that PT_LOAD. // We must not alter anything that ld-linux might touch before it calls // the DT_INIT function. // // Obviously this hack requires that the linker script put pieces // into good positions when building the original shared library, // and also requires ld-linux to behave. if (elf_find_dynamic(upx_dt_init)) { if (elf_has_dynamic(Elf64_Dyn::DT_TEXTREL)) { throwCantPack("DT_TEXTREL found; re-compile with -fPIC"); goto abandon; } if (!(Elf64_Dyn::DF_1_PIE & elf_unsigned_dynamic(Elf64_Dyn::DT_FLAGS_1))) { // not explicitly PIE main program if (Elf64_Ehdr::EM_AARCH64 == e_machine // Android is common && !opt->o_unix.android_shlib // but not explicit ) { opt->info_mode++; info("note: use --android-shlib if appropriate"); opt->info_mode--; } } Elf64_Shdr const *shdr = shdri; xct_va = ~0ull; if (e_shnum) { for (int j= e_shnum; --j>=0; ++shdr) { unsigned const sh_type = get_te32(&shdr->sh_type); if (Elf64_Shdr::SHF_EXECINSTR & get_te64(&shdr->sh_flags)) { xct_va = umin(xct_va, get_te64(&shdr->sh_addr)); } // Hook the first slot of DT_PREINIT_ARRAY or DT_INIT_ARRAY. if (( Elf64_Dyn::DT_PREINIT_ARRAY==upx_dt_init && Elf64_Shdr::SHT_PREINIT_ARRAY==sh_type) || ( Elf64_Dyn::DT_INIT_ARRAY ==upx_dt_init && Elf64_Shdr::SHT_INIT_ARRAY ==sh_type) ) { unsigned user_init_ava = get_te32(&shdr->sh_addr); user_init_off = get_te64(&shdr->sh_offset); if ((u64_t)file_size <= user_init_off) { char msg[70]; snprintf(msg, sizeof(msg), "bad Elf64_Shdr[%d].sh_offset %#x", -1+ e_shnum - j, user_init_off); throwCantPack(msg); } // Check that &file_image[user_init_off] has // *_RELATIVE relocation, and fetch user_init_va. // If Elf64_Rela then the actual value is in Rela.r_addend. int z_rel = dt_table[Elf64_Dyn::DT_RELA]; int z_rsz = dt_table[Elf64_Dyn::DT_RELASZ]; if (z_rel && z_rsz) { unsigned rel_off = get_te64(&dynseg[-1+ z_rel].d_val); Elf64_Rela *rp = (Elf64_Rela *)&file_image[rel_off]; unsigned relsz = get_te64(&dynseg[-1+ z_rsz].d_val); Elf64_Rela *last = (Elf64_Rela *)(relsz + (char *)rp); for (; rp < last; ++rp) { unsigned r_va = get_te64(&rp->r_offset); if (r_va == user_init_ava) { // found the Elf64_Rela unsigned r_info = get_te64(&rp->r_info); unsigned r_type = ELF64_R_TYPE(r_info); if (Elf64_Ehdr::EM_AARCH64 == e_machine && R_AARCH64_RELATIVE == r_type) { user_init_va = get_te64(&rp->r_addend); } else if (Elf64_Ehdr::EM_AARCH64 == e_machine && R_AARCH64_ABS64 == r_type) { user_init_va = get_te64(&file_image[user_init_off]); } else { char msg[50]; snprintf(msg, sizeof(msg), "bad relocation %#x DT_INIT_ARRAY[0]", r_info); throwCantPack(msg); } break; } } } unsigned const p_filesz = get_te64(&pload_x0->p_filesz); if (!((user_init_va - xct_va) < p_filesz)) { // Not in executable portion of first executable PT_LOAD. if (0==user_init_va && opt->o_unix.android_shlib) { // Android allows (0 ==> skip) ? upx_dt_init = 0; // force steal of 'extra' DT_NULL // XXX: FIXME: depends on SHT_DYNAMIC coming later } else { char msg[70]; snprintf(msg, sizeof(msg), "bad init address %#x in Elf64_Shdr[%d].%#x\n", (unsigned)user_init_va, -1+ e_shnum - j, user_init_off); throwCantPack(msg); } } } // By default /usr/bin/ld leaves 4 extra DT_NULL to support pre-linking. // Take one as a last resort. if ((Elf64_Dyn::DT_INIT==upx_dt_init || !upx_dt_init) && Elf64_Shdr::SHT_DYNAMIC == sh_type) { unsigned const n = get_te64(&shdr->sh_size) / sizeof(Elf64_Dyn); Elf64_Dyn *dynp = (Elf64_Dyn *)&file_image[get_te64(&shdr->sh_offset)]; for (; Elf64_Dyn::DT_NULL != dynp->d_tag; ++dynp) { if (upx_dt_init == get_te64(&dynp->d_tag)) { break; // re-found DT_INIT } } if ((1+ dynp) < (n+ dynseg)) { // not the terminator, so take it user_init_va = get_te64(&dynp->d_val); // 0 if (0==upx_dt_init) set_te64(&dynp->d_tag, upx_dt_init = Elf64_Dyn::DT_INIT); user_init_off = (char const *)&dynp->d_val - (char const *)&file_image[0]; } } } } else { // no Sections; use heuristics upx_uint64_t const strsz = elf_unsigned_dynamic(Elf64_Dyn::DT_STRSZ); upx_uint64_t const strtab = elf_unsigned_dynamic(Elf64_Dyn::DT_STRTAB); upx_uint64_t const relsz = elf_unsigned_dynamic(Elf64_Dyn::DT_RELSZ); upx_uint64_t const rel = elf_unsigned_dynamic(Elf64_Dyn::DT_REL); upx_uint64_t const init = elf_unsigned_dynamic(upx_dt_init); if ((init == (relsz + rel ) && rel == (strsz + strtab)) || (init == (strsz + strtab) && strtab == (relsz + rel )) ) { xct_va = init; user_init_va = init; user_init_off = elf_get_offset_from_address(init); } } // Rely on 0==elf_unsigned_dynamic(tag) if no such tag. upx_uint64_t const va_gash = elf_unsigned_dynamic(Elf64_Dyn::DT_GNU_HASH); upx_uint64_t const va_hash = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH); unsigned y = 0; if ((y=1, xct_va < va_gash) || (y=2, (0==va_gash && xct_va < va_hash)) || (y=3, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_STRTAB)) || (y=4, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_SYMTAB)) || (y=5, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_REL)) || (y=6, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_RELA)) || (y=7, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_JMPREL)) || (y=8, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_VERDEF)) || (y=9, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_VERSYM)) || (y=10, xct_va < elf_unsigned_dynamic(Elf64_Dyn::DT_VERNEEDED)) ) { static char const *which[] = { "unknown", "DT_GNU_HASH", "DT_HASH", "DT_STRTAB", "DT_SYMTAB", "DT_REL", "DT_RELA", "DT_JMPREL", "DT_VERDEF", "DT_VERSYM", "DT_VERNEEDED", }; char buf[30]; snprintf(buf, sizeof(buf), "%s above stub", which[y]); throwCantPack(buf); goto abandon; } if (!opt->o_unix.android_shlib) { phdr = phdri; for (unsigned j= 0; j < e_phnum; ++phdr, ++j) { upx_uint64_t const vaddr = get_te64(&phdr->p_vaddr); if (PT_NOTE64 == get_te32(&phdr->p_type) && xct_va < vaddr) { char buf[40]; snprintf(buf, sizeof(buf), "PT_NOTE %#lx above stub", (unsigned long)vaddr); throwCantPack(buf); goto abandon; } } } xct_off = elf_get_offset_from_address(xct_va); if (opt->debug.debug_level) { fprintf(stderr, "shlib canPack: xct_va=%#lx xct_off=%#lx\n", (long)xct_va, (long)xct_off); } goto proceed; // But proper packing depends on checking xct_va. } else throwCantPack("need DT_INIT; try \"void _init(void){}\""); abandon: return false; proceed: ; } // XXX Theoretically the following test should be first, // but PackUnix::canPack() wants 0!=exetype ? if (!super::canPack()) return false; assert(exetype == 1); exetype = 0; // set options opt->o_unix.blocksize = blocksize = file_size; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check .sh_offset and .sh_size in SHT_DYNAMIC and SHT_STRNDX https://github.com/upx/upx/issues/394 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: std::string addEmoji(const Proxy &node, const RegexMatchConfigs &emoji_array, extra_settings &ext) { std::string real_rule, ret; for(const RegexMatchConfig &x : emoji_array) { if(!x.Script.empty()) { std::string result; script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { std::string script = x.Script; if(startsWith(script, "path:")) script = fileGet(script.substr(5), true); try { ctx.eval(script); auto getEmoji = (std::function<std::string(const Proxy&)>) ctx.eval("getEmoji"); ret = getEmoji(node); if(!ret.empty()) result = ret + " " + node.Remark; } catch (qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); if(!result.empty()) return result; continue; } if(x.Replace.empty()) continue; if(applyMatcher(x.Match, real_rule, node) && real_rule.size() && regFind(node.Remark, real_rule)) return x.Replace + " " + node.Remark; } return node.Remark; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-434', 'CWE-94'], 'message': 'Enhancements Add authorization check before loading scripts. Add detailed logs when loading preference settings.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int threaded_has_dirs_only_path(struct cache_def *cache, const char *name, int len, int prefix_len) { return lstat_cache(cache, name, len, FL_DIR|FL_FULLPATH, prefix_len) & FL_DIR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'checkout: fix bug that makes checkout follow symlinks in leading path Before checking out a file, we have to confirm that all of its leading components are real existing directories. And to reduce the number of lstat() calls in this process, we cache the last leading path known to contain only directories. However, when a path collision occurs (e.g. when checking out case-sensitive files in case-insensitive file systems), a cached path might have its file type changed on disk, leaving the cache on an invalid state. Normally, this doesn't bring any bad consequences as we usually check out files in index order, and therefore, by the time the cached path becomes outdated, we no longer need it anyway (because all files in that directory would have already been written). But, there are some users of the checkout machinery that do not always follow the index order. In particular: checkout-index writes the paths in the same order that they appear on the CLI (or stdin); and the delayed checkout feature -- used when a long-running filter process replies with "status=delayed" -- postpones the checkout of some entries, thus modifying the checkout order. When we have to check out an out-of-order entry and the lstat() cache is invalid (due to a previous path collision), checkout_entry() may end up using the invalid data and thrusting that the leading components are real directories when, in reality, they are not. In the best case scenario, where the directory was replaced by a regular file, the user will get an error: "fatal: unable to create file 'foo/bar': Not a directory". But if the directory was replaced by a symlink, checkout could actually end up following the symlink and writing the file at a wrong place, even outside the repository. Since delayed checkout is affected by this bug, it could be used by an attacker to write arbitrary files during the clone of a maliciously crafted repository. Some candidate solutions considered were to disable the lstat() cache during unordered checkouts or sort the entries before passing them to the checkout machinery. But both ideas include some performance penalty and they don't future-proof the code against new unordered use cases. Instead, we now manually reset the lstat cache whenever we successfully remove a directory. Note: We are not even checking whether the directory was the same as the lstat cache points to because we might face a scenario where the paths refer to the same location but differ due to case folding, precomposed UTF-8 issues, or the presence of `..` components in the path. Two regression tests, with case-collisions and utf8-collisions, are also added for both checkout-index and delayed checkout. Note: to make the previously mentioned clone attack unfeasible, it would be sufficient to reset the lstat cache only after the remove_subtree() call inside checkout_entry(). This is the place where we would remove a directory whose path collides with the path of another entry that we are currently trying to check out (possibly a symlink). However, in the interest of a thorough fix that does not leave Git open to similar-but-not-identical attack vectors, we decided to intercept all `rmdir()` calls in one fell swoop. This addresses CVE-2021-21300. Co-authored-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { if (is_guest_mode(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 3; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; vcpu->run->internal.data[2] = error_code; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= dr6 | DR6_RTM; if (!(dr6 & ~DR6_RESERVED)) /* icebp */ skip_emulated_instruction(vcpu); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <digitaleric@google.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, &unmounted); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); umount_mnt(p); } change_mnt_propagation(p, MS_PRIVATE); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: stable@vger.kernel.org Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create) { struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr; struct inet_peer_base *base = family_to_base(daddr->family); struct inet_peer *p; unsigned int sequence; int invalidated, gccnt = 0; /* Attempt a lockless lookup first. * Because of a concurrent writer, we might not find an existing entry. */ rcu_read_lock(); sequence = read_seqbegin(&base->lock); p = lookup_rcu(daddr, base); invalidated = read_seqretry(&base->lock, sequence); rcu_read_unlock(); if (p) return p; /* If no writer did a change during our lookup, we can return early. */ if (!create && !invalidated) return NULL; /* retry an exact lookup, taking the lock before. * At least, nodes should be hot in our cache. */ write_seqlock_bh(&base->lock); relookup: p = lookup(daddr, stack, base); if (p != peer_avl_empty) { atomic_inc(&p->refcnt); write_sequnlock_bh(&base->lock); return p; } if (!gccnt) { gccnt = inet_peer_gc(base, stack, stackptr); if (gccnt && create) goto relookup; } p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL; if (p) { p->daddr = *daddr; atomic_set(&p->refcnt, 1); atomic_set(&p->rid, 0); atomic_set(&p->ip_id_count, secure_ip_id(daddr->addr.a4)); p->tcp_ts_stamp = 0; p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW; p->rate_tokens = 0; p->rate_last = 0; p->pmtu_expires = 0; p->pmtu_orig = 0; memset(&p->redirect_learned, 0, sizeof(p->redirect_learned)); /* Link the node. */ link_to_pool(p, base); base->total++; } write_sequnlock_bh(&base->lock); return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ipv6: make fragment identifications less predictable IPv6 fragment identification generation is way beyond what we use for IPv4 : It uses a single generator. Its not scalable and allows DOS attacks. Now inetpeer is IPv6 aware, we can use it to provide a more secure and scalable frag ident generator (per destination, instead of system wide) This patch : 1) defines a new secure_ipv6_id() helper 2) extends inet_getid() to provide 32bit results 3) extends ipv6_select_ident() with a new dest parameter Reported-by: Fernando Gont <fernando@gont.com.ar> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void stellaris_enet_save(QEMUFile *f, void *opaque) { stellaris_enet_state *s = (stellaris_enet_state *)opaque; int i; qemu_put_be32(f, s->ris); qemu_put_be32(f, s->im); qemu_put_be32(f, s->rctl); qemu_put_be32(f, s->tctl); qemu_put_be32(f, s->thr); qemu_put_be32(f, s->mctl); qemu_put_be32(f, s->mdv); qemu_put_be32(f, s->mtxd); qemu_put_be32(f, s->mrxd); qemu_put_be32(f, s->np); qemu_put_be32(f, s->tx_fifo_len); qemu_put_buffer(f, s->tx_fifo, sizeof(s->tx_fifo)); for (i = 0; i < 31; i++) { qemu_put_be32(f, s->rx[i].len); qemu_put_buffer(f, s->rx[i].data, sizeof(s->rx[i].data)); } qemu_put_be32(f, s->next_packet); qemu_put_be32(f, s->rx_fifo_offset); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'hw/net/stellaris_enet: Convert to vmstate Convert this device to use vmstate for its save/load, including providing a post_load function that sanitizes inbound data to avoid possible buffer overflows if it is malicious. The sanitizing fixes CVE-2013-4532 (though nobody should be relying on the security properties of most of the unmaintained ARM board models anyway, and migration doesn't actually work on this board due to issues in other device models). Signed-off-by: Peter Maydell <peter.maydell@linaro.org> Reviewed-by: Dr. David Alan Gilbert <dgilbert@redhat.com> Reviewed-by: Michael S. Tsirkin <mst@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '[MJ2] Avoid index out of bounds access to pi->include[] Signed-off-by: Young_X <YangX92@hotmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void set_own_dir(const char *argv0) { size_t l = strlen(argv0); while(l && argv0[l - 1] != '/') l--; if(l == 0) memcpy(own_dir, ".", 2); else { memcpy(own_dir, argv0, l - 1); own_dir[l] = 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-426'], 'message': 'fix for CVE-2015-3887 closes #60'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static NTSTATUS idmap_sid_to_xid(struct idmap_context *idmap_ctx, TALLOC_CTX *mem_ctx, const struct dom_sid *sid, struct unixid *unixid) { int ret; NTSTATUS status; struct ldb_context *ldb = idmap_ctx->ldb_ctx; struct ldb_dn *dn; struct ldb_message *hwm_msg, *map_msg, *sam_msg; struct ldb_result *res = NULL; int trans = -1; uint32_t low, high, hwm, new_xid; struct dom_sid_buf sid_string; char *unixid_string, *hwm_string; bool hwm_entry_exists; TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); const char *sam_attrs[] = {"uidNumber", "gidNumber", "samAccountType", NULL}; if (sid_check_is_in_unix_users(sid)) { uint32_t rid; DEBUG(6, ("This is a local unix uid, just calculate that.\n")); status = dom_sid_split_rid(tmp_ctx, sid, NULL, &rid); if (!NT_STATUS_IS_OK(status)) { talloc_free(tmp_ctx); return status; } unixid->id = rid; unixid->type = ID_TYPE_UID; talloc_free(tmp_ctx); return NT_STATUS_OK; } if (sid_check_is_in_unix_groups(sid)) { uint32_t rid; DEBUG(6, ("This is a local unix gid, just calculate that.\n")); status = dom_sid_split_rid(tmp_ctx, sid, NULL, &rid); if (!NT_STATUS_IS_OK(status)) { talloc_free(tmp_ctx); return status; } unixid->id = rid; unixid->type = ID_TYPE_GID; talloc_free(tmp_ctx); return NT_STATUS_OK; } /* * First check against our local DB, to see if this user has a * mapping there. This means that the Samba4 AD DC behaves * much like a winbindd member server running idmap_ad */ if (lpcfg_parm_bool(idmap_ctx->lp_ctx, NULL, "idmap_ldb", "use rfc2307", false)) { struct dom_sid_buf buf; ret = dsdb_search_one(idmap_ctx->samdb, tmp_ctx, &sam_msg, ldb_get_default_basedn(idmap_ctx->samdb), LDB_SCOPE_SUBTREE, sam_attrs, 0, "(&(objectSid=%s)" "(|(sAMaccountType=%u)(sAMaccountType=%u)(sAMaccountType=%u)" "(sAMaccountType=%u)(sAMaccountType=%u))" "(|(uidNumber=*)(gidNumber=*)))", dom_sid_str_buf(sid, &buf), ATYPE_ACCOUNT, ATYPE_WORKSTATION_TRUST, ATYPE_INTERDOMAIN_TRUST, ATYPE_SECURITY_GLOBAL_GROUP, ATYPE_SECURITY_LOCAL_GROUP); } else { /* If we are not to use the rfc2307 attributes, we just emulate a non-match */ ret = LDB_ERR_NO_SUCH_OBJECT; } if (ret == LDB_ERR_CONSTRAINT_VIOLATION) { struct dom_sid_buf buf; DEBUG(1, ("Search for objectSid=%s gave duplicate results, failing to map to a unix ID!\n", dom_sid_str_buf(sid, &buf))); status = NT_STATUS_NONE_MAPPED; goto failed; } else if (ret == LDB_SUCCESS) { uint32_t account_type = ldb_msg_find_attr_as_uint(sam_msg, "sAMaccountType", 0); if ((account_type == ATYPE_ACCOUNT) || (account_type == ATYPE_WORKSTATION_TRUST ) || (account_type == ATYPE_INTERDOMAIN_TRUST )) { const struct ldb_val *v = ldb_msg_find_ldb_val(sam_msg, "uidNumber"); if (v) { unixid->type = ID_TYPE_UID; unixid->id = ldb_msg_find_attr_as_uint(sam_msg, "uidNumber", -1); talloc_free(tmp_ctx); return NT_STATUS_OK; } } else if ((account_type == ATYPE_SECURITY_GLOBAL_GROUP) || (account_type == ATYPE_SECURITY_LOCAL_GROUP)) { const struct ldb_val *v = ldb_msg_find_ldb_val(sam_msg, "gidNumber"); if (v) { unixid->type = ID_TYPE_GID; unixid->id = ldb_msg_find_attr_as_uint(sam_msg, "gidNumber", -1); talloc_free(tmp_ctx); return NT_STATUS_OK; } } } else if (ret != LDB_ERR_NO_SUCH_OBJECT) { struct dom_sid_buf buf; DEBUG(1, ("Search for objectSid=%s gave '%s', failing to map to a SID!\n", dom_sid_str_buf(sid, &buf), ldb_errstring(idmap_ctx->samdb))); status = NT_STATUS_NONE_MAPPED; goto failed; } ret = ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(objectClass=sidMap)(objectSid=%s))", ldap_encode_ndr_dom_sid(tmp_ctx, sid)); if (ret != LDB_SUCCESS) { DEBUG(1, ("Search failed: %s\n", ldb_errstring(ldb))); talloc_free(tmp_ctx); return NT_STATUS_NONE_MAPPED; } if (res->count == 1) { const char *type = ldb_msg_find_attr_as_string(res->msgs[0], "type", NULL); new_xid = ldb_msg_find_attr_as_uint(res->msgs[0], "xidNumber", -1); if (new_xid == (uint32_t) -1) { DEBUG(1, ("Invalid xid mapping.\n")); talloc_free(tmp_ctx); return NT_STATUS_NONE_MAPPED; } if (type == NULL) { DEBUG(1, ("Invalid type for mapping entry.\n")); talloc_free(tmp_ctx); return NT_STATUS_NONE_MAPPED; } unixid->id = new_xid; if (strcmp(type, "ID_TYPE_BOTH") == 0) { unixid->type = ID_TYPE_BOTH; } else if (strcmp(type, "ID_TYPE_UID") == 0) { unixid->type = ID_TYPE_UID; } else { unixid->type = ID_TYPE_GID; } talloc_free(tmp_ctx); return NT_STATUS_OK; } DEBUG(6, ("No existing mapping found, attempting to create one.\n")); trans = ldb_transaction_start(ldb); if (trans != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } /* Redo the search to make sure no one changed the mapping while we * weren't looking */ ret = ldb_search(ldb, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(objectClass=sidMap)(objectSid=%s))", ldap_encode_ndr_dom_sid(tmp_ctx, sid)); if (ret != LDB_SUCCESS) { DEBUG(1, ("Search failed: %s\n", ldb_errstring(ldb))); status = NT_STATUS_NONE_MAPPED; goto failed; } if (res->count > 0) { DEBUG(1, ("Database changed while trying to add a sidmap.\n")); status = NT_STATUS_RETRY; goto failed; } ret = idmap_get_bounds(idmap_ctx, &low, &high); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } dn = ldb_dn_new(tmp_ctx, ldb, "CN=CONFIG"); if (dn == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) { DEBUG(1, ("Search failed: %s\n", ldb_errstring(ldb))); status = NT_STATUS_NONE_MAPPED; goto failed; } if (res->count != 1) { DEBUG(1, ("No CN=CONFIG record, idmap database is broken.\n")); status = NT_STATUS_NONE_MAPPED; goto failed; } hwm = ldb_msg_find_attr_as_uint(res->msgs[0], "xidNumber", -1); if (hwm == (uint32_t)-1) { hwm = low; hwm_entry_exists = false; } else { hwm_entry_exists = true; } if (hwm > high) { DEBUG(1, ("Out of xids to allocate.\n")); status = NT_STATUS_NONE_MAPPED; goto failed; } hwm_msg = ldb_msg_new(tmp_ctx); if (hwm_msg == NULL) { DEBUG(1, ("Out of memory when creating ldb_message\n")); status = NT_STATUS_NO_MEMORY; goto failed; } hwm_msg->dn = dn; new_xid = hwm; hwm++; hwm_string = talloc_asprintf(tmp_ctx, "%u", hwm); if (hwm_string == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } dom_sid_str_buf(sid, &sid_string); unixid_string = talloc_asprintf(tmp_ctx, "%u", new_xid); if (unixid_string == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } if (hwm_entry_exists) { struct ldb_message_element *els; struct ldb_val *vals; /* We're modifying the entry, not just adding a new one. */ els = talloc_array(tmp_ctx, struct ldb_message_element, 2); if (els == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } vals = talloc_array(tmp_ctx, struct ldb_val, 2); if (vals == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } hwm_msg->num_elements = 2; hwm_msg->elements = els; els[0].num_values = 1; els[0].values = &vals[0]; els[0].flags = LDB_FLAG_MOD_DELETE; els[0].name = talloc_strdup(tmp_ctx, "xidNumber"); if (els[0].name == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } els[1].num_values = 1; els[1].values = &vals[1]; els[1].flags = LDB_FLAG_MOD_ADD; els[1].name = els[0].name; vals[0].data = (uint8_t *)unixid_string; vals[0].length = strlen(unixid_string); vals[1].data = (uint8_t *)hwm_string; vals[1].length = strlen(hwm_string); } else { ret = ldb_msg_add_empty(hwm_msg, "xidNumber", LDB_FLAG_MOD_ADD, NULL); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } ret = ldb_msg_add_string(hwm_msg, "xidNumber", hwm_string); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } } ret = ldb_modify(ldb, hwm_msg); if (ret != LDB_SUCCESS) { DEBUG(1, ("Updating the xid high water mark failed: %s\n", ldb_errstring(ldb))); status = NT_STATUS_NONE_MAPPED; goto failed; } map_msg = ldb_msg_new(tmp_ctx); if (map_msg == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } map_msg->dn = ldb_dn_new_fmt(tmp_ctx, ldb, "CN=%s", sid_string.buf); if (map_msg->dn == NULL) { status = NT_STATUS_NO_MEMORY; goto failed; } ret = ldb_msg_add_string(map_msg, "xidNumber", unixid_string); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } ret = idmap_msg_add_dom_sid(idmap_ctx, tmp_ctx, map_msg, "objectSid", sid); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } ret = ldb_msg_add_string(map_msg, "objectClass", "sidMap"); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } ret = ldb_msg_add_string(map_msg, "type", "ID_TYPE_BOTH"); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } ret = ldb_msg_add_string(map_msg, "cn", sid_string.buf); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; goto failed; } ret = ldb_add(ldb, map_msg); if (ret != LDB_SUCCESS) { DEBUG(1, ("Adding a sidmap failed: %s\n", ldb_errstring(ldb))); status = NT_STATUS_NONE_MAPPED; goto failed; } trans = ldb_transaction_commit(ldb); if (trans != LDB_SUCCESS) { DEBUG(1, ("Transaction failed: %s\n", ldb_errstring(ldb))); status = NT_STATUS_NONE_MAPPED; goto failed; } unixid->id = new_xid; unixid->type = ID_TYPE_BOTH; talloc_free(tmp_ctx); return NT_STATUS_OK; failed: if (trans == LDB_SUCCESS) ldb_transaction_cancel(ldb); talloc_free(tmp_ctx); return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int rdn_rename_callback(struct ldb_request *req, struct ldb_reply *ares) { struct ldb_context *ldb; struct rename_context *ac; struct ldb_request *mod_req; const char *rdn_name; const struct ldb_schema_attribute *a = NULL; const struct ldb_val *rdn_val_p; struct ldb_val rdn_val; struct ldb_message *msg; int ret; ac = talloc_get_type(req->context, struct rename_context); ldb = ldb_module_get_ctx(ac->module); if (!ares) { goto error; } if (ares->type == LDB_REPLY_REFERRAL) { return ldb_module_send_referral(ac->req, ares->referral); } if (ares->error != LDB_SUCCESS) { return ldb_module_done(ac->req, ares->controls, ares->response, ares->error); } /* the only supported reply right now is a LDB_REPLY_DONE */ if (ares->type != LDB_REPLY_DONE) { goto error; } /* save reply for caller */ ac->ares = talloc_steal(ac, ares); msg = ldb_msg_new(ac); if (msg == NULL) { goto error; } msg->dn = ldb_dn_copy(msg, ac->req->op.rename.newdn); if (msg->dn == NULL) { goto error; } rdn_name = ldb_dn_get_rdn_name(ac->req->op.rename.newdn); if (rdn_name == NULL) { goto error; } a = ldb_schema_attribute_by_name(ldb, rdn_name); if (a == NULL) { goto error; } if (a->name != NULL && strcmp(a->name, "*") != 0) { rdn_name = a->name; } rdn_val_p = ldb_dn_get_rdn_val(msg->dn); if (rdn_val_p == NULL) { goto error; } if (rdn_val_p->length == 0) { ldb_asprintf_errstring(ldb, "Empty RDN value on %s not permitted!", ldb_dn_get_linearized(req->op.rename.olddn)); return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_NAMING_VIOLATION); } rdn_val = ldb_val_dup(msg, rdn_val_p); if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) { goto error; } if (ldb_msg_add_value(msg, rdn_name, &rdn_val, NULL) != 0) { goto error; } if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) { goto error; } if (ldb_msg_add_value(msg, "name", &rdn_val, NULL) != 0) { goto error; } ret = ldb_build_mod_req(&mod_req, ldb, ac, msg, NULL, ac, rdn_modify_callback, req); if (ret != LDB_SUCCESS) { return ldb_module_done(ac->req, NULL, NULL, ret); } talloc_steal(mod_req, msg); /* go on with the call chain */ return ldb_next_request(ac->module, mod_req); error: return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CreateStatistics(CreateStatsStmt *stmt) { int16 attnums[STATS_MAX_DIMENSIONS]; int nattnums = 0; int numcols; char *namestr; NameData stxname; Oid statoid; Oid namespaceId; Oid stxowner = GetUserId(); HeapTuple htup; Datum values[Natts_pg_statistic_ext]; bool nulls[Natts_pg_statistic_ext]; int2vector *stxkeys; List *stxexprs = NIL; Datum exprsDatum; Relation statrel; Relation rel = NULL; Oid relid; ObjectAddress parentobject, myself; Datum types[4]; /* one for each possible type of statistic */ int ntypes; ArrayType *stxkind; bool build_ndistinct; bool build_dependencies; bool build_mcv; bool build_expressions; bool requested_type = false; int i; ListCell *cell; ListCell *cell2; Assert(IsA(stmt, CreateStatsStmt)); /* * Examine the FROM clause. Currently, we only allow it to be a single * simple table, but later we'll probably allow multiple tables and JOIN * syntax. The grammar is already prepared for that, so we have to check * here that what we got is what we can support. */ if (list_length(stmt->relations) != 1) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only a single relation is allowed in CREATE STATISTICS"))); foreach(cell, stmt->relations) { Node *rln = (Node *) lfirst(cell); if (!IsA(rln, RangeVar)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only a single relation is allowed in CREATE STATISTICS"))); /* * CREATE STATISTICS will influence future execution plans but does * not interfere with currently executing plans. So it should be * enough to take only ShareUpdateExclusiveLock on relation, * conflicting with ANALYZE and other DDL that sets statistical * information, but not with normal queries. */ rel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock); /* Restrict to allowed relation types */ if (rel->rd_rel->relkind != RELKIND_RELATION && rel->rd_rel->relkind != RELKIND_MATVIEW && rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE && rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("cannot define statistics for relation \"%s\"", RelationGetRelationName(rel)), errdetail_relkind_not_supported(rel->rd_rel->relkind))); /* You must own the relation to create stats on it */ if (!pg_class_ownercheck(RelationGetRelid(rel), stxowner)) aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind), RelationGetRelationName(rel)); /* Creating statistics on system catalogs is not allowed */ if (!allowSystemTableMods && IsSystemRelation(rel)) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied: \"%s\" is a system catalog", RelationGetRelationName(rel)))); } Assert(rel); relid = RelationGetRelid(rel); /* * If the node has a name, split it up and determine creation namespace. * If not (a possibility not considered by the grammar, but one which can * occur via the "CREATE TABLE ... (LIKE)" command), then we put the * object in the same namespace as the relation, and cons up a name for * it. */ if (stmt->defnames) namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames, &namestr); else { namespaceId = RelationGetNamespace(rel); namestr = ChooseExtendedStatisticName(RelationGetRelationName(rel), ChooseExtendedStatisticNameAddition(stmt->exprs), "stat", namespaceId); } namestrcpy(&stxname, namestr); /* * Deal with the possibility that the statistics object already exists. */ if (SearchSysCacheExists2(STATEXTNAMENSP, CStringGetDatum(namestr), ObjectIdGetDatum(namespaceId))) { if (stmt->if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("statistics object \"%s\" already exists, skipping", namestr))); relation_close(rel, NoLock); return InvalidObjectAddress; } ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("statistics object \"%s\" already exists", namestr))); } /* * Make sure no more than STATS_MAX_DIMENSIONS columns are used. There * might be duplicates and so on, but we'll deal with those later. */ numcols = list_length(stmt->exprs); if (numcols > STATS_MAX_DIMENSIONS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_COLUMNS), errmsg("cannot have more than %d columns in statistics", STATS_MAX_DIMENSIONS))); /* * Convert the expression list to a simple array of attnums, but also keep * a list of more complex expressions. While at it, enforce some * constraints - we don't allow extended statistics on system attributes, * and we require the data type to have a less-than operator. * * There are many ways to "mask" a simple attribute reference as an * expression, for example "(a+0)" etc. We can't possibly detect all of * them, but we handle at least the simple case with the attribute in * parens. There'll always be a way around this, if the user is determined * (like the "(a+0)" example), but this makes it somewhat consistent with * how indexes treat attributes/expressions. */ foreach(cell, stmt->exprs) { StatsElem *selem = lfirst_node(StatsElem, cell); if (selem->name) /* column reference */ { char *attname; HeapTuple atttuple; Form_pg_attribute attForm; TypeCacheEntry *type; attname = selem->name; atttuple = SearchSysCacheAttName(relid, attname); if (!HeapTupleIsValid(atttuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column \"%s\" does not exist", attname))); attForm = (Form_pg_attribute) GETSTRUCT(atttuple); /* Disallow use of system attributes in extended stats */ if (attForm->attnum <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); /* Disallow data types without a less-than operator */ type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class", attname, format_type_be(attForm->atttypid)))); attnums[nattnums] = attForm->attnum; nattnums++; ReleaseSysCache(atttuple); } else if (IsA(selem->expr, Var)) /* column reference in parens */ { Var *var = (Var *) selem->expr; TypeCacheEntry *type; /* Disallow use of system attributes in extended stats */ if (var->varattno <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); /* Disallow data types without a less-than operator */ type = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class", get_attname(relid, var->varattno, false), format_type_be(var->vartype)))); attnums[nattnums] = var->varattno; nattnums++; } else /* expression */ { Node *expr = selem->expr; Oid atttype; TypeCacheEntry *type; Bitmapset *attnums = NULL; int k; Assert(expr != NULL); /* Disallow expressions referencing system attributes. */ pull_varattnos(expr, 1, &attnums); k = -1; while ((k = bms_next_member(attnums, k)) >= 0) { AttrNumber attnum = k + FirstLowInvalidHeapAttributeNumber; if (attnum <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); } /* * Disallow data types without a less-than operator. * * We ignore this for statistics on a single expression, in which * case we'll build the regular statistics only (and that code can * deal with such data types). */ if (list_length(stmt->exprs) > 1) { atttype = exprType(expr); type = lookup_type_cache(atttype, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("expression cannot be used in multivariate statistics because its type %s has no default btree operator class", format_type_be(atttype)))); } stxexprs = lappend(stxexprs, expr); } } /* * Parse the statistics kinds. * * First check that if this is the case with a single expression, there * are no statistics kinds specified (we don't allow that for the simple * CREATE STATISTICS form). */ if ((list_length(stmt->exprs) == 1) && (list_length(stxexprs) == 1)) { /* statistics kinds not specified */ if (list_length(stmt->stat_types) > 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("when building statistics on a single expression, statistics kinds may not be specified"))); } /* OK, let's check that we recognize the statistics kinds. */ build_ndistinct = false; build_dependencies = false; build_mcv = false; foreach(cell, stmt->stat_types) { char *type = strVal(lfirst(cell)); if (strcmp(type, "ndistinct") == 0) { build_ndistinct = true; requested_type = true; } else if (strcmp(type, "dependencies") == 0) { build_dependencies = true; requested_type = true; } else if (strcmp(type, "mcv") == 0) { build_mcv = true; requested_type = true; } else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("unrecognized statistics kind \"%s\"", type))); } /* * If no statistic type was specified, build them all (but only when the * statistics is defined on more than one column/expression). */ if ((!requested_type) && (numcols >= 2)) { build_ndistinct = true; build_dependencies = true; build_mcv = true; } /* * When there are non-trivial expressions, build the expression stats * automatically. This allows calculating good estimates for stats that * consider per-clause estimates (e.g. functional dependencies). */ build_expressions = (list_length(stxexprs) > 0); /* * Check that at least two columns were specified in the statement, or * that we're building statistics on a single expression. */ if ((numcols < 2) && (list_length(stxexprs) != 1)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("extended statistics require at least 2 columns"))); /* * Sort the attnums, which makes detecting duplicates somewhat easier, and * it does not hurt (it does not matter for the contents, unlike for * indexes, for example). */ qsort(attnums, nattnums, sizeof(int16), compare_int16); /* * Check for duplicates in the list of columns. The attnums are sorted so * just check consecutive elements. */ for (i = 1; i < nattnums; i++) { if (attnums[i] == attnums[i - 1]) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), errmsg("duplicate column name in statistics definition"))); } /* * Check for duplicate expressions. We do two loops, counting the * occurrences of each expression. This is O(N^2) but we only allow small * number of expressions and it's not executed often. * * XXX We don't cross-check attributes and expressions, because it does * not seem worth it. In principle we could check that expressions don't * contain trivial attribute references like "(a)", but the reasoning is * similar to why we don't bother with extracting columns from * expressions. It's either expensive or very easy to defeat for * determined user, and there's no risk if we allow such statistics (the * statistics is useless, but harmless). */ foreach(cell, stxexprs) { Node *expr1 = (Node *) lfirst(cell); int cnt = 0; foreach(cell2, stxexprs) { Node *expr2 = (Node *) lfirst(cell2); if (equal(expr1, expr2)) cnt += 1; } /* every expression should find at least itself */ Assert(cnt >= 1); if (cnt > 1) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), errmsg("duplicate expression in statistics definition"))); } /* Form an int2vector representation of the sorted column list */ stxkeys = buildint2vector(attnums, nattnums); /* construct the char array of enabled statistic types */ ntypes = 0; if (build_ndistinct) types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT); if (build_dependencies) types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES); if (build_mcv) types[ntypes++] = CharGetDatum(STATS_EXT_MCV); if (build_expressions) types[ntypes++] = CharGetDatum(STATS_EXT_EXPRESSIONS); Assert(ntypes > 0 && ntypes <= lengthof(types)); stxkind = construct_array(types, ntypes, CHAROID, 1, true, TYPALIGN_CHAR); /* convert the expressions (if any) to a text datum */ if (stxexprs != NIL) { char *exprsString; exprsString = nodeToString(stxexprs); exprsDatum = CStringGetTextDatum(exprsString); pfree(exprsString); } else exprsDatum = (Datum) 0; statrel = table_open(StatisticExtRelationId, RowExclusiveLock); /* * Everything seems fine, so let's build the pg_statistic_ext tuple. */ memset(values, 0, sizeof(values)); memset(nulls, false, sizeof(nulls)); statoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId, Anum_pg_statistic_ext_oid); values[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid); values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid); values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname); values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId); values[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(-1); values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner); values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys); values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind); values[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum; if (exprsDatum == (Datum) 0) nulls[Anum_pg_statistic_ext_stxexprs - 1] = true; /* insert it into pg_statistic_ext */ htup = heap_form_tuple(statrel->rd_att, values, nulls); CatalogTupleInsert(statrel, htup); heap_freetuple(htup); relation_close(statrel, RowExclusiveLock); /* * We used to create the pg_statistic_ext_data tuple too, but it's not * clear what value should the stxdinherit flag have (it depends on * whether the rel is partitioned, contains data, etc.) */ InvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0); /* * Invalidate relcache so that others see the new statistics object. */ CacheInvalidateRelcache(rel); relation_close(rel, NoLock); /* * Add an AUTO dependency on each column used in the stats, so that the * stats object goes away if any or all of them get dropped. */ ObjectAddressSet(myself, StatisticExtRelationId, statoid); /* add dependencies for plain column references */ for (i = 0; i < nattnums; i++) { ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]); recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO); } /* * If there are no dependencies on a column, give the statistics object an * auto dependency on the whole table. In most cases, this will be * redundant, but it might not be if the statistics expressions contain no * Vars (which might seem strange but possible). This is consistent with * what we do for indexes in index_create. * * XXX We intentionally don't consider the expressions before adding this * dependency, because recordDependencyOnSingleRelExpr may not create any * dependencies for whole-row Vars. */ if (!nattnums) { ObjectAddressSet(parentobject, RelationRelationId, relid); recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO); } /* * Store dependencies on anything mentioned in statistics expressions, * just like we do for index expressions. */ if (stxexprs) recordDependencyOnSingleRelExpr(&myself, (Node *) stxexprs, relid, DEPENDENCY_NORMAL, DEPENDENCY_AUTO, false); /* * Also add dependencies on namespace and owner. These are required * because the stats object might have a different namespace and/or owner * than the underlying table(s). */ ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId); recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL); recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner); /* * XXX probably there should be a recordDependencyOnCurrentExtension call * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP * STATISTICS, which is more work than it seems worth. */ /* Add any requested comment */ if (stmt->stxcomment != NULL) CreateComments(statoid, StatisticExtRelationId, 0, stmt->stxcomment); /* Return stats object's address */ return myself; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int VvcSpsUnit::deserialize() { int rez = VvcUnit::deserialize(); if (rez) return rez; try { sps_id = m_reader.getBits(4); vps_id = m_reader.getBits(4); max_sublayers_minus1 = m_reader.getBits(3); if (max_sublayers_minus1 == 7) return 1; chroma_format_idc = m_reader.getBits(2); unsigned sps_log2_ctu_size_minus5 = m_reader.getBits(2); if (sps_log2_ctu_size_minus5 > 2) return 1; int CtbLog2SizeY = sps_log2_ctu_size_minus5 + 5; unsigned CtbSizeY = 1 << CtbLog2SizeY; bool sps_ptl_dpb_hrd_params_present_flag = m_reader.getBit(); if (sps_id == 0 && !sps_ptl_dpb_hrd_params_present_flag) return 1; if (sps_ptl_dpb_hrd_params_present_flag) profile_tier_level(1, max_sublayers_minus1); m_reader.skipBit(); // sps_gdr_enabled_flag if (m_reader.getBit()) // sps_ref_pic_resampling_enabled_flag m_reader.skipBit(); // sps_res_change_in_clvs_allowed_flag pic_width_max_in_luma_samples = extractUEGolombCode(); pic_height_max_in_luma_samples = extractUEGolombCode(); unsigned tmpWidthVal = (pic_width_max_in_luma_samples + CtbSizeY - 1) / CtbSizeY; unsigned tmpHeightVal = (pic_height_max_in_luma_samples + CtbSizeY - 1) / CtbSizeY; unsigned sps_conf_win_left_offset = 0; unsigned sps_conf_win_right_offset = 0; unsigned sps_conf_win_top_offset = 0; unsigned sps_conf_win_bottom_offset = 0; if (m_reader.getBit()) // sps_conformance_window_flag { sps_conf_win_left_offset = extractUEGolombCode(); sps_conf_win_right_offset = extractUEGolombCode(); sps_conf_win_top_offset = extractUEGolombCode(); sps_conf_win_bottom_offset = extractUEGolombCode(); } if (m_reader.getBit()) // sps_subpic_info_present_flag { unsigned sps_num_subpics_minus1 = extractUEGolombCode(); if (sps_num_subpics_minus1 > 600) return 1; if (sps_num_subpics_minus1 > 0) { bool sps_independent_subpics_flag = m_reader.getBit(); bool sps_subpic_same_size_flag = m_reader.getBit(); for (size_t i = 0; i <= sps_num_subpics_minus1; i++) { if (!sps_subpic_same_size_flag || i == 0) { if (i != 0 && pic_width_max_in_luma_samples > CtbSizeY) m_reader.skipBits(ceil(log2(tmpWidthVal))); // sps_subpic_ctu_top_left_x[i] if (i != 0 && pic_height_max_in_luma_samples > CtbSizeY) m_reader.skipBits(ceil(log2(tmpHeightVal))); // sps_subpic_ctu_top_left_y[i] if (i < sps_num_subpics_minus1 && pic_width_max_in_luma_samples > CtbSizeY) m_reader.skipBits(ceil(log2(tmpWidthVal))); // sps_subpic_width_minus1[i] if (i < sps_num_subpics_minus1 && pic_height_max_in_luma_samples > CtbSizeY) m_reader.skipBits(ceil(log2(tmpHeightVal))); // sps_subpic_height_minus1[i] } if (!sps_independent_subpics_flag) { m_reader.skipBit(); // sps_subpic_treated_as_pic_flag m_reader.skipBit(); // sps_loop_filter_across_subpic_enabled_flag } } } unsigned sps_subpic_id_len = extractUEGolombCode() + 1; if (sps_subpic_id_len > 16 || (unsigned)(1 << sps_subpic_id_len) < (sps_num_subpics_minus1 + 1)) return 1; if (m_reader.getBit()) // sps_subpic_id_mapping_explicitly_signalled_flag { if (m_reader.getBit()) // sps_subpic_id_mapping_present_flag for (size_t i = 0; i <= sps_num_subpics_minus1; i++) m_reader.skipBits(sps_subpic_id_len); // sps_subpic_id[i] } } bitdepth_minus8 = extractUEGolombCode(); if (bitdepth_minus8 > 2) return 1; int QpBdOffset = 6 * bitdepth_minus8; m_reader.skipBit(); // sps_entropy_coding_sync_enabled_flag m_reader.skipBit(); // vsps_entry_point_offsets_present_flag log2_max_pic_order_cnt_lsb = m_reader.getBits(4) + 4; if (log2_max_pic_order_cnt_lsb > 16) return 1; if (m_reader.getBit()) // sps_poc_msb_cycle_flag { if (extractUEGolombCode() /* sps_poc_msb_cycle_len_minus1 */ > 23 - log2_max_pic_order_cnt_lsb) return 1; } int sps_num_extra_ph_bytes = m_reader.getBits(2); for (size_t i = 0; i < sps_num_extra_ph_bytes; i++) m_reader.skipBits(8); // sps_extra_ph_bit_present_flag[i] int sps_num_extra_sh_bytes = m_reader.getBits(2); for (size_t i = 0; i < sps_num_extra_sh_bytes; i++) m_reader.skipBits(8); // sps_extra_sh_bit_present_flag[i] if (sps_ptl_dpb_hrd_params_present_flag) { bool sps_sublayer_dpb_params_flag = (max_sublayers_minus1 > 0) ? m_reader.getBit() : 0; if (dpb_parameters(max_sublayers_minus1, sps_sublayer_dpb_params_flag)) return 1; } unsigned sps_log2_min_luma_coding_block_size_minus2 = extractUEGolombCode(); if (sps_log2_min_luma_coding_block_size_minus2 > (unsigned)min(4, (int)sps_log2_ctu_size_minus5 + 3)) return 1; unsigned MinCbLog2SizeY = sps_log2_min_luma_coding_block_size_minus2 + 2; unsigned MinCbSizeY = 1 << MinCbLog2SizeY; m_reader.skipBit(); // sps_partition_constraints_override_enabled_flag unsigned sps_log2_diff_min_qt_min_cb_intra_slice_luma = extractUEGolombCode(); if (sps_log2_diff_min_qt_min_cb_intra_slice_luma > min(6, CtbLog2SizeY) - MinCbLog2SizeY) return 1; unsigned MinQtLog2SizeIntraY = sps_log2_diff_min_qt_min_cb_intra_slice_luma + MinCbLog2SizeY; unsigned sps_max_mtt_hierarchy_depth_intra_slice_luma = extractUEGolombCode(); if (sps_max_mtt_hierarchy_depth_intra_slice_luma > 2 * (CtbLog2SizeY - MinCbLog2SizeY)) return 1; if (sps_max_mtt_hierarchy_depth_intra_slice_luma != 0) { if (extractUEGolombCode() > CtbLog2SizeY - MinQtLog2SizeIntraY) // sps_log2_diff_max_bt_min_qt_intra_slice_luma return 1; if (extractUEGolombCode() > min(6, CtbLog2SizeY) - MinQtLog2SizeIntraY) // sps_log2_diff_max_tt_min_qt_intra_slice_luma return 1; } bool sps_qtbtt_dual_tree_intra_flag = (chroma_format_idc != 0 ? m_reader.getBit() : 0); if (sps_qtbtt_dual_tree_intra_flag) { unsigned sps_log2_diff_min_qt_min_cb_intra_slice_chroma = extractUEGolombCode(); if (sps_log2_diff_min_qt_min_cb_intra_slice_chroma > min(6, CtbLog2SizeY) - MinCbLog2SizeY) // return 1; unsigned MinQtLog2SizeIntraC = sps_log2_diff_min_qt_min_cb_intra_slice_chroma + MinCbLog2SizeY; unsigned sps_max_mtt_hierarchy_depth_intra_slice_chroma = extractUEGolombCode(); if (sps_max_mtt_hierarchy_depth_intra_slice_chroma > 2 * (CtbLog2SizeY - MinCbLog2SizeY)) return 1; if (sps_max_mtt_hierarchy_depth_intra_slice_chroma != 0) { if (extractUEGolombCode() > min(6, CtbLog2SizeY) - MinQtLog2SizeIntraC) // sps_log2_diff_max_bt_min_qt_intra_slice_chroma return 1; if (extractUEGolombCode() > min(6, CtbLog2SizeY) - MinQtLog2SizeIntraC) // sps_log2_diff_max_tt_min_qt_intra_slice_chroma return 1; } } unsigned sps_log2_diff_min_qt_min_cb_inter_slice = extractUEGolombCode(); if (sps_log2_diff_min_qt_min_cb_inter_slice > min(6, CtbLog2SizeY) - MinCbLog2SizeY) return 1; unsigned MinQtLog2SizeInterY = sps_log2_diff_min_qt_min_cb_inter_slice + MinCbLog2SizeY; unsigned sps_max_mtt_hierarchy_depth_inter_slice = extractUEGolombCode(); if (sps_max_mtt_hierarchy_depth_inter_slice > 2 * (CtbLog2SizeY - MinCbLog2SizeY)) return 1; if (sps_max_mtt_hierarchy_depth_inter_slice != 0) { if (extractUEGolombCode() > CtbLog2SizeY - MinQtLog2SizeInterY) // sps_log2_diff_max_bt_min_qt_inter_slice return 1; if (extractUEGolombCode() > min(6, CtbLog2SizeY) - MinQtLog2SizeInterY) // sps_log2_diff_max_tt_min_qt_inter_slice return 1; } bool sps_max_luma_transform_size_64_flag = (CtbSizeY > 32 ? m_reader.getBit() : 0); bool sps_transform_skip_enabled_flag = m_reader.getBit(); if (sps_transform_skip_enabled_flag) { if (extractUEGolombCode() > 3) // sps_log2_transform_skip_max_size_minus2 return 1; m_reader.skipBit(); // sps_bdpcm_enabled_flag } if (m_reader.getBit()) // sps_mts_enabled_flag { m_reader.skipBit(); // sps_explicit_mts_intra_enabled_flag m_reader.skipBit(); // sps_explicit_mts_inter_enabled_flag } bool sps_lfnst_enabled_flag = m_reader.getBit(); if (chroma_format_idc != 0) { bool sps_joint_cbcr_enabled_flag = m_reader.getBit(); int numQpTables = m_reader.getBit() /* sps_same_qp_table_for_chroma_flag */ ? 1 : (sps_joint_cbcr_enabled_flag ? 3 : 2); for (int i = 0; i < numQpTables; i++) { int sps_qp_table_start_minus26 = extractSEGolombCode(); if (sps_qp_table_start_minus26 < (-26 - QpBdOffset) || sps_qp_table_start_minus26 > 36) return 1; unsigned sps_num_points_in_qp_table_minus1 = extractUEGolombCode(); if (sps_num_points_in_qp_table_minus1 > (unsigned)(36 - sps_qp_table_start_minus26)) return 1; for (size_t j = 0; j <= sps_num_points_in_qp_table_minus1; j++) { extractUEGolombCode(); // sps_delta_qp_in_val_minus1 extractUEGolombCode(); // sps_delta_qp_diff_val } } } m_reader.skipBit(); // sps_sao_enabled_flag if (m_reader.getBit() /* sps_alf_enabled_flag */ && chroma_format_idc != 0) m_reader.skipBit(); // sps_ccalf_enabled_flag m_reader.skipBit(); // sps_lmcs_enabled_flag weighted_pred_flag = m_reader.getBit(); weighted_bipred_flag = m_reader.getBit(); long_term_ref_pics_flag = m_reader.getBit(); inter_layer_prediction_enabled_flag = (sps_id != 0) ? m_reader.getBit() : 0; m_reader.skipBit(); // sps_idr_rpl_present_flag bool sps_rpl1_same_as_rpl0_flag = m_reader.getBit(); for (size_t i = 0; i < (sps_rpl1_same_as_rpl0_flag ? 1 : 2); i++) { sps_num_ref_pic_lists = extractUEGolombCode(); if (sps_num_ref_pic_lists > 64) return 1; for (size_t j = 0; j < sps_num_ref_pic_lists; j++) ref_pic_list_struct(i, j); } m_reader.skipBit(); // sps_ref_wraparound_enabled_flag bool sps_sbtmvp_enabled_flag = (m_reader.getBit()) /* sps_temporal_mvp_enabled_flag */ ? m_reader.getBit() : 0; bool sps_amvr_enabled_flag = m_reader.getBit(); if (m_reader.getBit()) // sps_bdof_enabled_flag m_reader.skipBit(); // sps_bdof_control_present_in_ph_flag m_reader.skipBit(); // sps_smvd_enabled_flag if (m_reader.getBit()) // sps_dmvr_enabled_flag m_reader.skipBit(); // sps_dmvr_control_present_in_ph_flag if (m_reader.getBit()) // sps_mmvd_enabled_flag m_reader.skipBit(); // sps_mmvd_fullpel_only_enabled_flag unsigned sps_six_minus_max_num_merge_cand = extractUEGolombCode(); if (sps_six_minus_max_num_merge_cand > 5) return 1; unsigned MaxNumMergeCand = 6 - sps_six_minus_max_num_merge_cand; m_reader.skipBit(); // sps_sbt_enabled_flag if (m_reader.getBit()) // sps_affine_enabled_flag { unsigned sps_five_minus_max_num_subblock_merge_cand = extractUEGolombCode(); if (sps_five_minus_max_num_subblock_merge_cand + sps_sbtmvp_enabled_flag > 5) return 1; m_reader.skipBit(); // sps_6param_affine_enabled_flag if (sps_amvr_enabled_flag) m_reader.skipBit(); // sps_affine_amvr_enabled_flag if (m_reader.getBit()) // sps_affine_prof_enabled_flag m_reader.skipBit(); // sps_prof_control_present_in_ph_flag } m_reader.skipBit(); // sps_bcw_enabled_flag m_reader.skipBit(); // sps_ciip_enabled_flag if (MaxNumMergeCand >= 2) { if (m_reader.getBit() /* sps_gpm_enabled_flag */ && MaxNumMergeCand >= 3) { unsigned sps_max_num_merge_cand_minus_max_num_gpm_cand = extractUEGolombCode(); if (sps_max_num_merge_cand_minus_max_num_gpm_cand + 2 > MaxNumMergeCand) return 1; } } unsigned sps_log2_parallel_merge_level_minus2 = extractUEGolombCode(); if (sps_log2_parallel_merge_level_minus2 > CtbLog2SizeY - 2) return 1; bool sps_isp_enabled_flag = m_reader.getBit(); bool sps_mrl_enabled_flag = m_reader.getBit(); bool sps_mip_enabled_flag = m_reader.getBit(); if (chroma_format_idc != 0) bool sps_cclm_enabled_flag = m_reader.getBit(); if (chroma_format_idc == 1) { bool sps_chroma_horizontal_collocated_flag = m_reader.getBit(); bool sps_chroma_vertical_collocated_flag = m_reader.getBit(); } bool sps_palette_enabled_flag = m_reader.getBit(); bool sps_act_enabled_flag = (chroma_format_idc == 3 && !sps_max_luma_transform_size_64_flag) ? m_reader.getBit() : 0; if (sps_transform_skip_enabled_flag || sps_palette_enabled_flag) { unsigned sps_min_qp_prime_ts = extractUEGolombCode(); if (sps_min_qp_prime_ts > 8) return 1; } if (m_reader.getBit()) // sps_ibc_enabled_flag { unsigned sps_six_minus_max_num_ibc_merge_cand = extractUEGolombCode(); if (sps_six_minus_max_num_ibc_merge_cand > 5) return 1; } if (m_reader.getBit()) // sps_ladf_enabled_flag { int sps_num_ladf_intervals_minus2 = m_reader.getBits(2); int sps_ladf_lowest_interval_qp_offset = extractSEGolombCode(); for (int i = 0; i < sps_num_ladf_intervals_minus2 + 1; i++) { int sps_ladf_qp_offset = extractSEGolombCode(); unsigned sps_ladf_delta_threshold_minus1 = extractUEGolombCode(); } } bool sps_explicit_scaling_list_enabled_flag = m_reader.getBit(); if (sps_lfnst_enabled_flag && sps_explicit_scaling_list_enabled_flag) bool sps_scaling_matrix_for_lfnst_disabled_flag = m_reader.getBit(); bool sps_scaling_matrix_for_alternative_colour_space_disabled_flag = (sps_act_enabled_flag && sps_explicit_scaling_list_enabled_flag) ? m_reader.getBit() : 0; if (sps_scaling_matrix_for_alternative_colour_space_disabled_flag) bool sps_scaling_matrix_designated_colour_space_flag = m_reader.getBit(); bool sps_dep_quant_enabled_flag = m_reader.getBit(); bool sps_sign_data_hiding_enabled_flag = m_reader.getBit(); if (m_reader.getBit()) // sps_virtual_boundaries_enabled_flag { if (m_reader.getBit()) // sps_virtual_boundaries_present_flag { unsigned sps_num_ver_virtual_boundaries = extractUEGolombCode(); if (sps_num_ver_virtual_boundaries > (pic_width_max_in_luma_samples <= 8 ? 0 : 3)) return 1; for (size_t i = 0; i < sps_num_ver_virtual_boundaries; i++) { unsigned sps_virtual_boundary_pos_x_minus1 = extractUEGolombCode(); if (sps_virtual_boundary_pos_x_minus1 > ceil(pic_width_max_in_luma_samples / 8) - 2) return 1; } unsigned sps_num_hor_virtual_boundaries = extractUEGolombCode(); if (sps_num_hor_virtual_boundaries > (pic_height_max_in_luma_samples <= 8 ? 0 : 3)) return 1; for (size_t i = 0; i < sps_num_hor_virtual_boundaries; i++) { unsigned sps_virtual_boundary_pos_y_minus1 = extractUEGolombCode(); if (sps_virtual_boundary_pos_y_minus1 > ceil(pic_height_max_in_luma_samples / 8) - 2) return 1; } } } if (sps_ptl_dpb_hrd_params_present_flag) { if (m_reader.getBit()) // sps_timing_hrd_params_present_flag { if (m_sps_hrd.general_timing_hrd_parameters()) return 1; int sps_sublayer_cpb_params_present_flag = (max_sublayers_minus1 > 0) ? m_reader.getBit() : 0; int firstSubLayer = sps_sublayer_cpb_params_present_flag ? 0 : max_sublayers_minus1; m_sps_hrd.ols_timing_hrd_parameters(firstSubLayer, max_sublayers_minus1); } } bool sps_field_seq_flag = m_reader.getBit(); if (m_reader.getBit()) // sps_vui_parameters_present_flag { unsigned sps_vui_payload_size_minus1 = extractUEGolombCode(); if (sps_vui_payload_size_minus1 > 1023) return 1; m_reader.skipBits(m_reader.getBitsLeft() % 8); // sps_vui_alignment_zero_bit vui_parameters(); } bool sps_extension_flag = m_reader.getBit(); return 0; } catch (VodCoreException& e) { return NOT_ENOUGH_BUFFER; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fix Buffer Overflow Fixes issue #509.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: export_desktop_file (const char *app, const char *branch, const char *arch, GKeyFile *metadata, const char * const *previous_ids, int parent_fd, const char *name, struct stat *stat_buf, char **target, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; glnx_autofd int desktop_fd = -1; g_autofree char *tmpfile_name = g_strdup_printf ("export-desktop-XXXXXX"); g_autoptr(GOutputStream) out_stream = NULL; g_autofree gchar *data = NULL; gsize data_len; g_autofree gchar *new_data = NULL; gsize new_data_len; g_autoptr(GKeyFile) keyfile = NULL; g_autofree gchar *old_exec = NULL; gint old_argc; g_auto(GStrv) old_argv = NULL; g_auto(GStrv) groups = NULL; GString *new_exec = NULL; g_autofree char *escaped_app = maybe_quote (app); g_autofree char *escaped_branch = maybe_quote (branch); g_autofree char *escaped_arch = maybe_quote (arch); int i; if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error)) goto out; if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error)) goto out; keyfile = g_key_file_new (); if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error)) goto out; if (g_str_has_suffix (name, ".service")) { g_autofree gchar *dbus_name = NULL; g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (".service")); dbus_name = g_key_file_get_string (keyfile, "D-BUS Service", "Name", NULL); if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0) { return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED, _("D-Bus service file '%s' has wrong name"), name); } } if (g_str_has_suffix (name, ".desktop")) { gsize length; g_auto(GStrv) tags = g_key_file_get_string_list (metadata, "Application", "tags", &length, NULL); if (tags != NULL) { g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, "X-Flatpak-Tags", (const char * const *) tags, length); } /* Add a marker so consumers can easily find out that this launches a sandbox */ g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, "X-Flatpak", app); /* If the app has been renamed, add its old .desktop filename to * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to * introduce duplicates. */ if (previous_ids != NULL) { const char *X_FLATPAK_RENAMED_FROM = "X-Flatpak-RenamedFrom"; g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, NULL, NULL); g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free); g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal); const char *new_suffix; for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++) { if (!g_hash_table_contains (seen, renamed_from[i])) { gchar *copy = g_strdup (renamed_from[i]); g_hash_table_insert (seen, copy, copy); g_ptr_array_add (merged, g_steal_pointer (&copy)); } } /* If an app was renamed from com.example.Foo to net.example.Bar, and * the new version exports net.example.Bar-suffix.desktop, we assume the * old version exported com.example.Foo-suffix.desktop. * * This assertion is true because * flatpak_name_matches_one_wildcard_prefix() is called on all * exported files before we get here. */ g_assert (g_str_has_prefix (name, app)); /* ".desktop" for the "main" desktop file; something like * "-suffix.desktop" for extra ones. */ new_suffix = name + strlen (app); for (i = 0; previous_ids[i] != NULL; i++) { g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL); if (!g_hash_table_contains (seen, previous_desktop)) { g_hash_table_insert (seen, previous_desktop, previous_desktop); g_ptr_array_add (merged, g_steal_pointer (&previous_desktop)); } } if (merged->len > 0) { g_ptr_array_add (merged, NULL); g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, (const char * const *) merged->pdata, merged->len - 1); } } } groups = g_key_file_get_groups (keyfile, NULL); for (i = 0; groups[i] != NULL; i++) { g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], "X-Flatpak-RunOptions", NULL, NULL); g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts); g_key_file_remove_key (keyfile, groups[i], "X-Flatpak-RunOptions", NULL); g_key_file_remove_key (keyfile, groups[i], "TryExec", NULL); /* Remove this to make sure nothing tries to execute it outside the sandbox*/ g_key_file_remove_key (keyfile, groups[i], "X-GNOME-Bugzilla-ExtraInfoScript", NULL); new_exec = g_string_new (""); g_string_append_printf (new_exec, FLATPAK_BINDIR "/flatpak run --branch=%s --arch=%s", escaped_branch, escaped_arch); if (flatpak_run_args != NULL) g_string_append_printf (new_exec, "%s", flatpak_run_args); old_exec = g_key_file_get_string (keyfile, groups[i], "Exec", NULL); if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1) { int j; g_autofree char *command = maybe_quote (old_argv[0]); g_string_append_printf (new_exec, " --command=%s", command); for (j = 1; j < old_argc; j++) { if (strcasecmp (old_argv[j], "%f") == 0 || strcasecmp (old_argv[j], "%u") == 0) { g_string_append (new_exec, " --file-forwarding"); break; } } g_string_append (new_exec, " "); g_string_append (new_exec, escaped_app); for (j = 1; j < old_argc; j++) { g_autofree char *arg = maybe_quote (old_argv[j]); if (strcasecmp (arg, "%f") == 0) g_string_append_printf (new_exec, " @@ %s @@", arg); else if (strcasecmp (arg, "%u") == 0) g_string_append_printf (new_exec, " @@u %s @@", arg); else g_string_append_printf (new_exec, " %s", arg); } } else { g_string_append (new_exec, " "); g_string_append (new_exec, escaped_app); } g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str); } new_data = g_key_file_to_data (keyfile, &new_data_len, error); if (new_data == NULL) goto out; if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error)) goto out; if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error)) goto out; if (!g_output_stream_close (out_stream, cancellable, error)) goto out; if (target) *target = g_steal_pointer (&tmpfile_name); ret = TRUE; out: if (new_exec != NULL) g_string_free (new_exec, TRUE); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94', 'CWE-74'], 'message': 'Disallow @@ and @@u usage in desktop files Fixes #4146. (cherry picked from commit 652a28ffab67cb6cd7d12dc3a93979bcd3731c7f)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _prolog_error(batch_job_launch_msg_t *req, int rc) { char *err_name_ptr, err_name[256], path_name[MAXPATHLEN]; char *fmt_char; int fd; if (req->std_err || req->std_out) { if (req->std_err) strncpy(err_name, req->std_err, sizeof(err_name)); else strncpy(err_name, req->std_out, sizeof(err_name)); if ((fmt_char = strchr(err_name, (int) '%')) && (fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) { char tmp_name[256]; fmt_char[1] = 'u'; snprintf(tmp_name, sizeof(tmp_name), err_name, req->job_id); strncpy(err_name, tmp_name, sizeof(err_name)); } } else { snprintf(err_name, sizeof(err_name), "slurm-%u.out", req->job_id); } err_name_ptr = err_name; if (err_name_ptr[0] == '/') snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr); else if (req->work_dir) snprintf(path_name, MAXPATHLEN, "%s/%s", req->work_dir, err_name_ptr); else snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr); if ((fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644)) == -1) { error("Unable to open %s: %s", path_name, slurm_strerror(errno)); return; } snprintf(err_name, sizeof(err_name), "Error running slurm prolog: %d\n", WEXITSTATUS(rc)); safe_write(fd, err_name, strlen(err_name)); if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) { snprintf(err_name, sizeof(err_name), "Couldn't change fd owner to %u:%u: %m\n", req->uid, req->gid); } rwfail: close(fd); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'Fix security issue in _prolog_error(). Fix security issue caused by insecure file path handling triggered by the failure of a Prolog script. To exploit this a user needs to anticipate or cause the Prolog to fail for their job. (This commit is slightly different from the fix to the 15.08 branch.) CVE-2016-10030.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10091 - crash in AVR analysis'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cJSON *cJSON_CreateInt( int64_t num ) { cJSON *item = cJSON_New_Item(); if ( item ) { item->type = cJSON_Number; item->valuefloat = num; item->valueint = num; } return item; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cJSON *cJSON_CreateIntArray( int64_t *numbers, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateInt( numbers[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *print_string( cJSON *item ) { return print_string_ptr( item->valuestring ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static cJSON *cJSON_New_Item( void ) { cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) ); if ( node ) memset( node, 0, sizeof(cJSON) ); return node; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: iperf_on_connect(struct iperf_test *test) { time_t now_secs; const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT"; char now_str[100]; char ipr[INET6_ADDRSTRLEN]; int port; struct sockaddr_storage sa; struct sockaddr_in *sa_inP; struct sockaddr_in6 *sa_in6P; socklen_t len; int opt; now_secs = time((time_t*) 0); (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs)); if (test->json_output) cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s timesecs: %d", now_str, (int64_t) now_secs)); else if (test->verbose) iprintf(test, report_time, now_str); if (test->role == 'c') { if (test->json_output) cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port)); else { iprintf(test, report_connecting, test->server_hostname, test->server_port); if (test->reverse) iprintf(test, report_reverse, test->server_hostname); } } else { len = sizeof(sa); getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len); if (getsockdomain(test->ctrl_sck) == AF_INET) { sa_inP = (struct sockaddr_in *) &sa; inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr)); port = ntohs(sa_inP->sin_port); } else { sa_in6P = (struct sockaddr_in6 *) &sa; inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr)); port = ntohs(sa_in6P->sin6_port); } mapped_v4_to_regular_v4(ipr); if (test->json_output) cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port)); else iprintf(test, report_accepted, ipr, port); } if (test->json_output) { cJSON_AddStringToObject(test->json_start, "cookie", test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) cJSON_AddIntToObject(test->json_start, "tcp_mss", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); cJSON_AddIntToObject(test->json_start, "tcp_mss_default", opt); } } } else if (test->verbose) { iprintf(test, report_cookie, test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) iprintf(test, " TCP MSS: %d\n", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); iprintf(test, " TCP MSS: %d (default)\n", opt); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cJSON *cJSON_CreateFloat( double num ) { cJSON *item = cJSON_New_Item(); if ( item ) { item->type = cJSON_Number; item->valuefloat = num; item->valueint = num; } return item; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void native_tss_update_io_bitmap(void) { struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw); struct thread_struct *t = &current->thread; u16 *base = &tss->x86_tss.io_bitmap_base; if (!test_thread_flag(TIF_IO_BITMAP)) { tss_invalidate_io_bitmap(tss); return; } if (IS_ENABLED(CONFIG_X86_IOPL_IOPERM) && t->iopl_emul == 3) { *base = IO_BITMAP_OFFSET_VALID_ALL; } else { struct io_bitmap *iobm = t->io_bitmap; /* * Only copy bitmap data when the sequence number differs. The * update time is accounted to the incoming task. */ if (tss->io_bitmap.prev_sequence != iobm->sequence) tss_copy_io_bitmap(tss, iobm); /* Enable the bitmap */ *base = IO_BITMAP_OFFSET_VALID_MAP; } /* * Make sure that the TSS limit is covering the IO bitmap. It might have * been cut down by a VMEXIT to 0x67 which would cause a subsequent I/O * access from user space to trigger a #GP because tbe bitmap is outside * the TSS limit. */ refresh_tss_limit(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-276'], 'message': 'x86/ioperm: Fix io bitmap invalidation on Xen PV tss_invalidate_io_bitmap() wasn't wired up properly through the pvop machinery, so the TSS and Xen's io bitmap would get out of sync whenever disabling a valid io bitmap. Add a new pvop for tss_invalidate_io_bitmap() to fix it. This is XSA-329. Fixes: 22fe5b0439dd ("x86/ioperm: Move TSS bitmap update to exit to user work") Signed-off-by: Andy Lutomirski <luto@kernel.org> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Reviewed-by: Juergen Gross <jgross@suse.com> Reviewed-by: Thomas Gleixner <tglx@linutronix.de> Cc: stable@vger.kernel.org Link: https://lkml.kernel.org/r/d53075590e1f91c19f8af705059d3ff99424c020.1595030016.git.luto@kernel.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PackLinuxElf32::PackLinuxElf32help1(InputFile *f) { e_type = get_te16(&ehdri.e_type); e_phnum = get_te16(&ehdri.e_phnum); e_shnum = get_te16(&ehdri.e_shnum); unsigned const e_phentsize = get_te16(&ehdri.e_phentsize); if (ehdri.e_ident[Elf32_Ehdr::EI_CLASS]!=Elf32_Ehdr::ELFCLASS32 || sizeof(Elf32_Phdr) != e_phentsize || (Elf32_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf32_Ehdr::EI_DATA] && &N_BELE_RTP::be_policy != bele) || (Elf32_Ehdr::ELFDATA2LSB == ehdri.e_ident[Elf32_Ehdr::EI_DATA] && &N_BELE_RTP::le_policy != bele)) { e_phoff = 0; e_shoff = 0; sz_phdrs = 0; return; } if (0==e_phnum) throwCantUnpack("0==e_phnum"); e_phoff = get_te32(&ehdri.e_phoff); unsigned const last_Phdr = e_phoff + e_phnum * sizeof(Elf32_Phdr); if (last_Phdr < e_phoff || (unsigned long)file_size < last_Phdr) { throwCantUnpack("bad e_phoff"); } e_shoff = get_te32(&ehdri.e_shoff); unsigned const last_Shdr = e_shoff + e_shnum * sizeof(Elf32_Shdr); if (last_Shdr < e_shoff || (unsigned long)file_size < last_Shdr) { if (opt->cmd == CMD_COMPRESS) { throwCantUnpack("bad e_shoff"); } } sz_phdrs = e_phnum * e_phentsize; if (f && Elf32_Ehdr::ET_DYN!=e_type) { unsigned const len = sz_phdrs + e_phoff; alloc_file_image(file_image, len); f->seek(0, SEEK_SET); f->readx(file_image, len); phdri= (Elf32_Phdr *)(e_phoff + file_image); // do not free() !! } if (f && Elf32_Ehdr::ET_DYN==e_type) { // The DT_SYMTAB has no designated length. Read the whole file. alloc_file_image(file_image, file_size); f->seek(0, SEEK_SET); f->readx(file_image, file_size); phdri= (Elf32_Phdr *)(e_phoff + file_image); // do not free() !! shdri= (Elf32_Shdr *)(e_shoff + file_image); // do not free() !! if (opt->cmd != CMD_COMPRESS) { shdri = NULL; } sec_dynsym = elf_find_section_type(Elf32_Shdr::SHT_DYNSYM); if (sec_dynsym) { unsigned t = get_te32(&sec_dynsym->sh_link); if (e_shnum <= t) throwCantPack("bad dynsym->sh_link"); sec_dynstr = &shdri[t]; } Elf32_Phdr const *phdr= phdri; for (int j = e_phnum; --j>=0; ++phdr) if (Elf32_Phdr::PT_DYNAMIC==get_te32(&phdr->p_type)) { dynseg= (Elf32_Dyn const *)(check_pt_dynamic(phdr) + file_image); invert_pt_dynamic(dynseg); } else if (PT_LOAD32==get_te32(&phdr->p_type)) { check_pt_load(phdr); } // elf_find_dynamic() returns 0 if 0==dynseg. dynstr = (char const *)elf_find_dynamic(Elf32_Dyn::DT_STRTAB); dynsym = (Elf32_Sym const *)elf_find_dynamic(Elf32_Dyn::DT_SYMTAB); gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH); hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH); if (3& ((uintptr_t)dynsym | (uintptr_t)gashtab | (uintptr_t)hashtab)) { throwCantPack("unaligned DT_SYMTAB, DT_GNU_HASH, or DT_HASH/n"); } jni_onload_sym = elf_lookup("JNI_OnLoad"); if (jni_onload_sym) { jni_onload_va = get_te32(&jni_onload_sym->st_value); jni_onload_va = 0; // FIXME not understood; need example } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Defend against bad PT_DYNAMIC https://github.com/upx/upx/issues/391 modified: p_lx_elf.cpp modified: p_lx_elf.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fm_mgr_config_mgr_connect ( fm_config_conx_hdl *hdl, fm_mgr_type_t mgr ) { char s_path[256]; char c_path[256]; char *mgr_prefix; p_hsm_com_client_hdl_t *mgr_hdl; pid_t pid; memset(s_path,0,sizeof(s_path)); memset(c_path,0,sizeof(c_path)); pid = getpid(); switch ( mgr ) { case FM_MGR_SM: mgr_prefix = HSM_FM_SCK_SM; mgr_hdl = &hdl->sm_hdl; break; case FM_MGR_PM: mgr_prefix = HSM_FM_SCK_PM; mgr_hdl = &hdl->pm_hdl; break; case FM_MGR_FE: mgr_prefix = HSM_FM_SCK_FE; mgr_hdl = &hdl->fe_hdl; break; default: return FM_CONF_INIT_ERR; } // Fill in the paths for the server and client sockets. sprintf(s_path,"%s%s%d",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance); sprintf(c_path,"%s%s%d_C_%lu",HSM_FM_SCK_PREFIX,mgr_prefix, hdl->instance, (long unsigned)pid); if ( *mgr_hdl == NULL ) { if ( hcom_client_init(mgr_hdl,s_path,c_path,32768) != HSM_COM_OK ) { return FM_CONF_INIT_ERR; } } if ( hcom_client_connect(*mgr_hdl) == HSM_COM_OK ) { hdl->conx_mask |= mgr; return FM_CONF_OK; } return FM_CONF_CONX_ERR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix scripts and code that use well-known tmp files.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void *zmalloc(size_t size) { void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix integer overflow (CVE-2021-21309). (#8522) On 32-bit systems, setting the proto-max-bulk-len config parameter to a high value may result with integer overflow and a subsequent heap overflow when parsing an input bulk (CVE-2021-21309). This fix has two parts: Set a reasonable limit to the config parameter. Add additional checks to prevent the problem in other potential but unknown code paths. (cherry picked from commit d32f2e9999ce003bad0bd2c3bca29f64dcce4433)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'vfs: Test for and handle paths that are unreachable from their mnt_root In rare cases a directory can be renamed out from under a bind mount. In those cases without special handling it becomes possible to walk up the directory tree to the root dentry of the filesystem and down from the root dentry to every other file or directory on the filesystem. Like division by zero .. from an unconnected path can not be given a useful semantic as there is no predicting at which path component the code will realize it is unconnected. We certainly can not match the current behavior as the current behavior is a security hole. Therefore when encounting .. when following an unconnected path return -ENOENT. - Add a function path_connected to verify path->dentry is reachable from path->mnt.mnt_root. AKA to validate that rename did not do something nasty to the bind mount. To avoid races path_connected must be called after following a path component to it's next path component. Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; //here we have to handle that in a clever way to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; //get the data gf_bs_read_data(bs, tmpName, to_read); //then get the break i = 0; while ( (tmpName[i] != 0) && (i < to_read) ) { i++; } //check the data is consistent if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } //no NULL char, URL is not specified if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } //OK, this has both URN and URL ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fixed 2 possible heap overflows (inc. #1088)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *child_tidptr, struct pid *pid, int trace) { int retval; struct task_struct *p; int cgroup_callbacks_done = 0; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); /* * Siblings of global init remain as zombies on exit since they are * not reaped by their parent (swapper). To solve this and to avoid * multi-rooted process trees, prevent global and container-inits * from creating siblings. */ if ((clone_flags & CLONE_PARENT) && current->signal->flags & SIGNAL_UNKILLABLE) return ERR_PTR(-EINVAL); retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; ftrace_graph_init_task(p); rt_mutex_init_task(p); #ifdef CONFIG_PROVE_LOCKING DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->real_cred->user->processes) >= p->signal->rlim[RLIMIT_NPROC].rlim_cur) { if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) && p->real_cred->user != INIT_USER) goto bad_fork_free; } retval = copy_creds(p, clone_flags); if (retval < 0) goto bad_fork_free; /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ retval = -EAGAIN; if (nr_threads >= max_threads) goto bad_fork_cleanup_count; if (!try_module_get(task_thread_info(p)->exec_domain->module)) goto bad_fork_cleanup_count; p->did_exec = 0; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ copy_flags(clone_flags, p); INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); rcu_copy_process(p); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); init_sigpending(&p->pending); p->utime = cputime_zero; p->stime = cputime_zero; p->gtime = cputime_zero; p->utimescaled = cputime_zero; p->stimescaled = cputime_zero; p->prev_utime = cputime_zero; p->prev_stime = cputime_zero; p->default_timer_slack_ns = current->timer_slack_ns; task_io_accounting_init(&p->ioac); acct_clear_integrals(p); posix_cpu_timers_init(p); p->lock_depth = -1; /* -1 = no lock */ do_posix_clock_monotonic_gettime(&p->start_time); p->real_start_time = p->start_time; monotonic_to_bootbased(&p->real_start_time); p->io_context = NULL; p->audit_context = NULL; cgroup_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_dup(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_cgroup; } mpol_fix_fork_child_flag(p); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW p->hardirqs_enabled = 1; #else p->hardirqs_enabled = 0; #endif p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif p->bts = NULL; p->stack_start = stack_start; /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork(p, clone_flags); retval = perf_event_init_task(p); if (retval) goto bad_fork_cleanup_policy; if ((retval = audit_alloc(p))) goto bad_fork_cleanup_policy; /* copy all the process information */ if ((retval = copy_semundo(clone_flags, p))) goto bad_fork_cleanup_audit; if ((retval = copy_files(clone_flags, p))) goto bad_fork_cleanup_semundo; if ((retval = copy_fs(clone_flags, p))) goto bad_fork_cleanup_files; if ((retval = copy_sighand(clone_flags, p))) goto bad_fork_cleanup_fs; if ((retval = copy_signal(clone_flags, p))) goto bad_fork_cleanup_sighand; if ((retval = copy_mm(clone_flags, p))) goto bad_fork_cleanup_signal; if ((retval = copy_namespaces(clone_flags, p))) goto bad_fork_cleanup_mm; if ((retval = copy_io(clone_flags, p))) goto bad_fork_cleanup_namespaces; retval = copy_thread(clone_flags, stack_start, stack_size, p, regs); if (retval) goto bad_fork_cleanup_io; if (pid != &init_struct_pid) { retval = -ENOMEM; pid = alloc_pid(p->nsproxy->pid_ns); if (!pid) goto bad_fork_cleanup_io; if (clone_flags & CLONE_NEWPID) { retval = pid_ns_prepare_proc(p->nsproxy->pid_ns); if (retval < 0) goto bad_fork_free_pid; } } p->pid = pid_nr(pid); p->tgid = p->pid; if (clone_flags & CLONE_THREAD) p->tgid = current->tgid; if (current->nsproxy != p->nsproxy) { retval = ns_cgroup_clone(p, pid); if (retval) goto bad_fork_free_pid; } p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL; #ifdef CONFIG_FUTEX p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; #endif /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) p->sas_ss_sp = p->sas_ss_size = 0; /* * Syscall tracing should be turned off in the child regardless * of CLONE_PTRACE. */ clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif clear_all_latency_tracing(p); /* ok, now we should be set up.. */ p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL); p->pdeath_signal = 0; p->exit_state = 0; /* * Ok, make it visible to the rest of the system. * We dont wake it up yet. */ p->group_leader = p; INIT_LIST_HEAD(&p->thread_group); /* Now that the task is set up, run cgroup callbacks if * necessary. We need to run them before the task is visible * on the tasklist. */ cgroup_fork_callbacks(p); cgroup_callbacks_done = 1; /* Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* * The task hasn't been attached yet, so its cpus_allowed mask will * not be changed, nor will its assigned CPU. * * The cpus_allowed mask of the parent may have changed after it was * copied first time - so re-copy it here, then check the child's CPU * to ensure it is on a valid CPU (and if not, just force it back to * parent's CPU). This avoids alot of nasty races. */ p->cpus_allowed = current->cpus_allowed; p->rt.nr_cpus_allowed = current->rt.nr_cpus_allowed; if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) || !cpu_online(task_cpu(p)))) set_task_cpu(p, smp_processor_id()); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) { p->real_parent = current->real_parent; p->parent_exec_id = current->parent_exec_id; } else { p->real_parent = current; p->parent_exec_id = current->self_exec_id; } spin_lock(&current->sighand->siglock); /* * Process group and session signals need to be delivered to just the * parent before the fork or both the parent and the child after the * fork. Restart if a signal comes in before we add the new process to * it's process group. * A fatal signal pending means that current will exit, so the new * thread can't slip out of an OOM kill (or normal SIGKILL). */ recalc_sigpending(); if (signal_pending(current)) { spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); retval = -ERESTARTNOINTR; goto bad_fork_free_pid; } if (clone_flags & CLONE_THREAD) { atomic_inc(&current->signal->count); atomic_inc(&current->signal->live); p->group_leader = current->group_leader; list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); } if (likely(p->pid)) { list_add_tail(&p->sibling, &p->real_parent->children); tracehook_finish_clone(p, clone_flags, trace); if (thread_group_leader(p)) { if (clone_flags & CLONE_NEWPID) p->nsproxy->pid_ns->child_reaper = p; p->signal->leader_pid = pid; tty_kref_put(p->signal->tty); p->signal->tty = tty_kref_get(current->signal->tty); attach_pid(p, PIDTYPE_PGID, task_pgrp(current)); attach_pid(p, PIDTYPE_SID, task_session(current)); list_add_tail_rcu(&p->tasks, &init_task.tasks); __get_cpu_var(process_counts)++; } attach_pid(p, PIDTYPE_PID, pid); nr_threads++; } total_forks++; spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); cgroup_post_fork(p); perf_event_fork(p); return p; bad_fork_free_pid: if (pid != &init_struct_pid) free_pid(pid); bad_fork_cleanup_io: put_io_context(p->io_context); bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: if (!(clone_flags & CLONE_THREAD)) __cleanup_signal(p->signal); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_policy: perf_event_free_task(p); #ifdef CONFIG_NUMA mpol_put(p->mempolicy); bad_fork_cleanup_cgroup: #endif cgroup_exit(p, cgroup_callbacks_done); delayacct_tsk_free(p); module_put(task_thread_info(p)->exec_domain->module); bad_fork_cleanup_count: atomic_dec(&p->cred->user->processes); exit_creds(p); bad_fork_free: free_task(p); fork_out: return ERR_PTR(retval); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-400'], 'message': 'block: Fix io_context leak after failure of clone with CLONE_IO With CLONE_IO, parent's io_context->nr_tasks is incremented, but never decremented whenever copy_process() fails afterwards, which prevents exit_io_context() from calling IO schedulers exit functions. Give a task_struct to exit_io_context(), and call exit_io_context() instead of put_io_context() in copy_process() cleanup path. Signed-off-by: Louis Rilling <louis.rilling@kerlabs.com> Signed-off-by: Jens Axboe <jens.axboe@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int h264_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; H264Context *h = avctx->priv_data; AVFrame *pict = data; int buf_index = 0; int ret; h->flags = avctx->flags; /* end of stream, output what is still in the buffers */ out: if (buf_size == 0) { Picture *out; int i, out_idx; h->cur_pic_ptr = NULL; // FIXME factorize this with the output code below out = h->delayed_pic[0]; out_idx = 0; for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++) if (h->delayed_pic[i]->poc < out->poc) { out = h->delayed_pic[i]; out_idx = i; } for (i = out_idx; h->delayed_pic[i]; i++) h->delayed_pic[i] = h->delayed_pic[i + 1]; if (out) { ret = output_frame(h, pict, &out->f); if (ret < 0) return ret; *got_frame = 1; } return buf_index; } buf_index = decode_nal_units(h, buf, buf_size, 0); if (buf_index < 0) return AVERROR_INVALIDDATA; if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) { buf_size = 0; goto out; } if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) { if (avctx->skip_frame >= AVDISCARD_NONREF) return 0; av_log(avctx, AV_LOG_ERROR, "no frame!\n"); return AVERROR_INVALIDDATA; } if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) || (h->mb_y >= h->mb_height && h->mb_height)) { if (avctx->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h, 1); field_end(h, 0); *got_frame = 0; if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) || h->next_output_pic->recovered)) { if (!h->next_output_pic->recovered) h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT; ret = output_frame(h, pict, &h->next_output_pic->f); if (ret < 0) return ret; *got_frame = 1; } } assert(pict->buf[0] || !*got_frame); return get_consumed_bytes(buf_index, buf_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'h264: reset data partitioning at the beginning of each decode call Prevents using GetBitContexts with data from previous calls. Fixes access to freed memory. Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind CC:libav-stable@libav.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ngx_gmtime(time_t t, ngx_tm_t *tp) { ngx_int_t yday; ngx_uint_t sec, min, hour, mday, mon, year, wday, days, leap; /* the calculation is valid for positive time_t only */ if (t < 0) { t = 0; } days = t / 86400; sec = t % 86400; /* January 1, 1970 was Thursday */ wday = (4 + days) % 7; hour = sec / 3600; sec %= 3600; min = sec / 60; sec %= 60; /* * the algorithm based on Gauss' formula, * see src/core/ngx_parse_time.c */ /* days since March 1, 1 BC */ days = days - (31 + 28) + 719527; /* * The "days" should be adjusted to 1 only, however, some March 1st's go * to previous year, so we adjust them to 2. This causes also shift of the * last February days to next year, but we catch the case when "yday" * becomes negative. */ year = (days + 2) * 400 / (365 * 400 + 100 - 4 + 1); yday = days - (365 * year + year / 4 - year / 100 + year / 400); if (yday < 0) { leap = (year % 4 == 0) && (year % 100 || (year % 400 == 0)); yday = 365 + leap + yday; year--; } /* * The empirical formula that maps "yday" to month. * There are at least 10 variants, some of them are: * mon = (yday + 31) * 15 / 459 * mon = (yday + 31) * 17 / 520 * mon = (yday + 31) * 20 / 612 */ mon = (yday + 31) * 10 / 306; /* the Gauss' formula that evaluates days before the month */ mday = yday - (367 * mon / 12 - 30) + 1; if (yday >= 306) { year++; mon -= 10; /* * there is no "yday" in Win32 SYSTEMTIME * * yday -= 306; */ } else { mon += 2; /* * there is no "yday" in Win32 SYSTEMTIME * * yday += 31 + 28 + leap; */ } tp->ngx_tm_sec = (ngx_tm_sec_t) sec; tp->ngx_tm_min = (ngx_tm_min_t) min; tp->ngx_tm_hour = (ngx_tm_hour_t) hour; tp->ngx_tm_mday = (ngx_tm_mday_t) mday; tp->ngx_tm_mon = (ngx_tm_mon_t) mon; tp->ngx_tm_year = (ngx_tm_year_t) year; tp->ngx_tm_wday = (ngx_tm_wday_t) wday; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Introduced time truncation to December 31, 9999 (ticket #1368). Various buffers are allocated in an assumption that there would be no more than 4 year digits. This might not be true on platforms with 64-bit time_t, as 64-bit time_t is able to represent more than that. Such dates with more than 4 year digits hardly make sense though, as various date formats in use do not allow them anyway. As such, all dates are now truncated by ngx_gmtime() to December 31, 9999. This should have no effect on valid dates, though will prevent potential buffer overflows on invalid ones.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int try_read_command(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if (c->protocol == negotiating_prot || c->transport == udp_transport) { if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; } else { c->protocol = ascii_prot; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } } if (c->protocol == binary_prot) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_string(c, "SERVER_ERROR out of memory"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } } else { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) return 0; cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Issue 102: Piping null to the server will crash it'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void cms_set_pw_data(cms_context *cms, secuPWData *pwdata) { ingress(); switch (cms->pwdata.source) { case PW_SOURCE_INVALID: case PW_PROMPT: case PW_DEVICE: case PW_SOURCE_MAX: break; case PW_FROMFD: if (cms->pwdata.intdata >= 0 && !(pwdata->source == PW_FROMFD && cms->pwdata.intdata == pwdata->intdata)) close(cms->pwdata.intdata); break; case PW_FROMFILEDB: case PW_FROMENV: case PW_FROMFILE: case PW_PLAINTEXT: memset(cms->pwdata.data, 0, strlen(cms->pwdata.data)); xfree(cms->pwdata.data); break; case PW_DATABASE: xfree(cms->pwdata.data); break; } memmove(&cms->pwdata, pwdata, sizeof(*pwdata)); dprintf("pwdata:%p", pwdata); dprintf("pwdata->source:%d", pwdata->source); dprintf("pwdata->data:%p (\"%s\")", pwdata->data, pwdata->data ? pwdata->data : "(null)"); egress(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Handle NULL pwdata in cms_set_pw_data() When 12f16710ee44ef64ddb044a3523c3c4c4d90039a rewrote this function, it didn't handle the NULL pwdata invocation from daemon.c. This leads to a explicit NULL dereference and crash on all attempts to daemonize pesign. Signed-off-by: Robbie Harwood <rharwood@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor& shape_t = ctx->input(0); const Tensor& alpha_t = ctx->input(1); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(shape_t.shape()) && (shape_t.dtype() == DataType::DT_INT32 || shape_t.dtype() == DataType::DT_INT64), errors::InvalidArgument( "shape must be a vector of {int32,int64}, got shape: ", shape_t.DebugString())); TensorShape samples_shape; if (shape_t.dtype() == DataType::DT_INT32) { auto vec = shape_t.flat<int32>(); OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(), &samples_shape)); } else if (shape_t.dtype() == DataType::DT_INT64) { auto vec = shape_t.flat<int64>(); OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(), &samples_shape)); } const int64 samples_per_alpha = samples_shape.num_elements(); samples_shape.AppendShape(alpha_t.shape()); // Allocate output samples. Tensor* samples_t = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, samples_shape, &samples_t)); if (samples_shape.num_elements() == 0) return; using random::PhiloxRandom; typedef random::NormalDistribution<PhiloxRandom, double> Normal; typedef random::UniformDistribution<PhiloxRandom, double> Uniform; #define UNIFORM(X) \ if (uniform_remaining == 0) { \ uniform_remaining = Uniform::kResultElementCount; \ uniform_result = uniform(&gen); \ } \ uniform_remaining--; \ double X = uniform_result[uniform_remaining] // Each attempt is 95+% successful, and requires 1-2 normal + 1 uniform static constexpr int kReservedSamplesPerOutput = 256; const auto alpha_flat = alpha_t.flat<T>().data(); const int64 num_alphas = alpha_t.NumElements(); OP_REQUIRES(ctx, num_alphas > 0, errors::InvalidArgument( "Input alpha should have non-zero element count, got: ", num_alphas)); auto samples_flat = samples_t->flat<T>().data(); PhiloxRandom rng = generator_.ReserveRandomOutputs( samples_per_alpha * num_alphas, kReservedSamplesPerOutput); // We partition work first across alphas then across samples-per-alpha to // avoid a couple flops which can be done on a per-alpha basis. auto DoWork = [samples_per_alpha, num_alphas, &rng, samples_flat, alpha_flat](int start_output, int limit_output) { using Eigen::numext::exp; using Eigen::numext::log; using Eigen::numext::log1p; using Eigen::numext::pow; // Capturing "rng" by-value would only make a copy for the _shared_ // lambda. Since we want to let each worker have its own copy, we pass // "rng" by reference and explicitly do a copy assignment. Normal normal; Uniform uniform; typename Normal::ResultType norm_result; typename Uniform::ResultType uniform_result; for (int64 output_idx = start_output; output_idx < limit_output; /* output_idx incremented within inner loop below */) { int64 alpha_idx = output_idx / samples_per_alpha; // Instead of +alpha_idx for each sample, we offset the pointer once. T* const samples_alpha_offset = samples_flat + alpha_idx; // Several calculations can be done on a per-alpha basis. const double alpha = static_cast<double>(alpha_flat[alpha_idx]); DISABLE_FLOAT_EQUALITY_WARNING if (alpha == static_cast<double>(1.0)) { ENABLE_FLOAT_EQUALITY_WARNING // Sample from an exponential distribution. for (int64 sample_idx = output_idx % samples_per_alpha; sample_idx < samples_per_alpha && output_idx < limit_output; sample_idx++, output_idx++) { // As we want data stable regardless of sharding // (including eventually on GPU), we skip on a per-sample basis. PhiloxRandom gen = rng; gen.Skip(kReservedSamplesPerOutput * output_idx); int16 uniform_remaining = 0; UNIFORM(u); const double res = -log1p(-u); samples_alpha_offset[sample_idx * num_alphas] = static_cast<T>(res); } // for (sample_idx) } else { // if alpha != 1.0 // Transformation-rejection from pairs of uniform and normal random // variables. http://dl.acm.org/citation.cfm?id=358414 // // The algorithm has an acceptance rate of ~95% for small alpha (~1), // and higher accept rates for higher alpha, so runtime is // O(NumAlphas * NumSamples * k) with k ~ 1 / 0.95. // // For alpha<1, we add one to d=alpha-1/3, and multiply the final // result by uniform()^(1/alpha) const bool alpha_less_than_one = alpha < 1; const double d = alpha + (alpha_less_than_one ? 2.0 / 3 : -1.0 / 3); const double c = 1.0 / 3 / sqrt(d); // Compute the rest of the samples for the current alpha value. for (int64 sample_idx = output_idx % samples_per_alpha; sample_idx < samples_per_alpha && output_idx < limit_output; sample_idx++, output_idx++) { // Since each sample may use a variable number of normal/uniform // samples, and we want data stable regardless of sharding // (including eventually on GPU), we skip on a per-sample basis. PhiloxRandom gen = rng; gen.Skip(kReservedSamplesPerOutput * output_idx); int16 norm_remaining = 0; int16 uniform_remaining = 0; // Keep trying until we don't reject a sample. In practice, we will // only reject ~5% at worst, for low alpha near 1. while (true) { if (norm_remaining == 0) { norm_remaining = Normal::kResultElementCount; norm_result = normal(&gen); } norm_remaining--; const double x = norm_result[norm_remaining]; double v = 1 + c * x; if (v <= 0) { continue; } v = v * v * v; UNIFORM(u); // The first option in the if is a "squeeze" short-circuit to // dodge the two logs. Magic constant sourced from the paper // linked above. Upward of .91 of the area covered by the log // inequality is covered by the squeeze as well (larger coverage // for smaller values of alpha). if ((u < 1 - 0.0331 * (x * x) * (x * x)) || (log(u) < 0.5 * x * x + d * (1 - v + log(v)))) { double res = d * v; if (alpha_less_than_one) { UNIFORM(b); res *= pow(b, 1 / alpha); } samples_alpha_offset[sample_idx * num_alphas] = static_cast<T>(res); break; } } // while: true } // for: sample_idx } // if (alpha == 1.0) } // for: output_idx }; // DoWork #undef UNIFORM // Two calls to log only occur for ~10% of samples reaching the log line. // 2 x 100 (64-bit cycles per log) x 0.10 = ~20. // Other ops: sqrt, +, *, /, %... something like 15 of these, at 3-6 cycles // each = ~60. // All of this /0.95 due to the rejection possibility = ~85. static const int kElementCost = 85 + 2 * Normal::kElementCost + Uniform::kElementCost + 3 * PhiloxRandom::kElementCost; auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads()); Shard(worker_threads.num_threads, worker_threads.workers, num_alphas * samples_per_alpha, kElementCost, DoWork); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-197'], 'message': 'Prevent `int64` to `int` truncation in `Shard` API usage. The function argument in `Shard` must be a function of two `int64` arguments. However, we are passing in a function with two `int` arguments. Thus, for large workloads, these arguments get truncated from positive `int64` values to negative `int` ones, resulting in a buffer out of bounds write. PiperOrigin-RevId: 332557334 Change-Id: I236c9a2e7f53580e520571da8ba941a3aa9fa0b5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefragReverseSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p3, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p1, NULL); if (reassembled == NULL) goto end; if (IPV4_GET_HLEN(reassembled) != 20) goto end; if (IPV4_GET_IPLEN(reassembled) != 39) goto end; /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefragIPv4NoDataTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int id = 12; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* This packet has an offset > 0, more frags set to 0 and no data. */ p = BuildTestPacket(id, 1, 0, 'A', 0); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; /* The fragment should have been ignored so no fragments should * have been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: auto ReferenceHandle::New(Local<Value> value, MaybeLocal<Object> options) -> unique_ptr<ReferenceHandle> { auto inherit = ReadOption<bool>(options, StringTable::Get().inheritUnsafe, false); return std::make_unique<ReferenceHandle>(value, inherit); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-913'], 'message': 'Don't invoke accessors or proxies via Reference functions'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int route4_change(struct net *net, struct sk_buff *in_skb, struct tcf_proto *tp, unsigned long base, u32 handle, struct nlattr **tca, void **arg, u32 flags, struct netlink_ext_ack *extack) { struct route4_head *head = rtnl_dereference(tp->root); struct route4_filter __rcu **fp; struct route4_filter *fold, *f1, *pfp, *f = NULL; struct route4_bucket *b; struct nlattr *opt = tca[TCA_OPTIONS]; struct nlattr *tb[TCA_ROUTE4_MAX + 1]; unsigned int h, th; int err; bool new = true; if (opt == NULL) return handle ? -EINVAL : 0; err = nla_parse_nested_deprecated(tb, TCA_ROUTE4_MAX, opt, route4_policy, NULL); if (err < 0) return err; fold = *arg; if (fold && handle && fold->handle != handle) return -EINVAL; err = -ENOBUFS; f = kzalloc(sizeof(struct route4_filter), GFP_KERNEL); if (!f) goto errout; err = tcf_exts_init(&f->exts, net, TCA_ROUTE4_ACT, TCA_ROUTE4_POLICE); if (err < 0) goto errout; if (fold) { f->id = fold->id; f->iif = fold->iif; f->res = fold->res; f->handle = fold->handle; f->tp = fold->tp; f->bkt = fold->bkt; new = false; } err = route4_set_parms(net, tp, base, f, handle, head, tb, tca[TCA_RATE], new, flags, extack); if (err < 0) goto errout; h = from_hash(f->handle >> 16); fp = &f->bkt->ht[h]; for (pfp = rtnl_dereference(*fp); (f1 = rtnl_dereference(*fp)) != NULL; fp = &f1->next) if (f->handle < f1->handle) break; tcf_block_netif_keep_dst(tp->chain->block); rcu_assign_pointer(f->next, f1); rcu_assign_pointer(*fp, f); if (fold && fold->handle && f->handle != fold->handle) { th = to_hash(fold->handle); h = from_hash(fold->handle >> 16); b = rtnl_dereference(head->table[th]); if (b) { fp = &b->ht[h]; for (pfp = rtnl_dereference(*fp); pfp; fp = &pfp->next, pfp = rtnl_dereference(*fp)) { if (pfp == fold) { rcu_assign_pointer(*fp, fold->next); break; } } } } route4_reset_fastmap(head); *arg = f; if (fold) { tcf_unbind_filter(tp, &fold->res); tcf_exts_get_net(&fold->exts); tcf_queue_work(&fold->rwork, route4_delete_filter_work); } return 0; errout: if (f) tcf_exts_destroy(&f->exts); kfree(f); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net_sched: cls_route: remove from list when handle is 0 When a route filter is replaced and the old filter has a 0 handle, the old one won't be removed from the hashtable, while it will still be freed. The test was there since before commit 1109c00547fc ("net: sched: RCU cls_route"), when a new filter was not allocated when there was an old one. The old filter was reused and the reinserting would only be necessary if an old filter was replaced. That was still wrong for the same case where the old handle was 0. Remove the old filter from the list independently from its handle value. This fixes CVE-2022-2588, also reported as ZDI-CAN-17440. Reported-by: Zhenpeng Lin <zplin@u.northwestern.edu> Signed-off-by: Thadeu Lima de Souza Cascardo <cascardo@canonical.com> Reviewed-by: Kamal Mostafa <kamal@canonical.com> Cc: <stable@vger.kernel.org> Acked-by: Jamal Hadi Salim <jhs@mojatatu.com> Link: https://lore.kernel.org/r/20220809170518.164662-1-cascardo@canonical.com Signed-off-by: Jakub Kicinski <kuba@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { auto findices = indices.flat<int>(); // Search for the key in our incomplete set auto it = incomplete_.find(key); // Check that the tuple fits within the memory limit std::size_t tuple_bytes = get_tuple_bytes(*tuple); TF_RETURN_IF_ERROR(check_memory_limit(tuple_bytes)); // Wait until we don't exceed the memory limit while (would_exceed_memory_limit(tuple_bytes)) { full_.wait(*lock); } // This key isn't present in the incomplete set // Create OptionalTuple and insert if (it == incomplete_.end()) { OptionalTuple empty(dtypes_.size()); // Initialize empty tuple with given dta for (std::size_t i = 0; i < findices.dimension(0); ++i) { std::size_t index = findices(i); TF_RETURN_IF_ERROR(check_index(key, index)); // Assign tuple at this index empty[index] = std::move((*tuple)[i]); } // Insert into incomplete map incomplete_.insert({key, std::move(empty)}); // Increment size current_bytes_ += tuple_bytes; } // Found an entry in the incomplete index // Update with given data and insert complete entries // into the main map else { // Reference existing incomplete tuple OptionalTuple& present = it->second; // Assign given data for (std::size_t i = 0; i < findices.dimension(0); ++i) { std::size_t index = findices(i); TF_RETURN_IF_ERROR(check_index(key, index)); TF_RETURN_IF_ERROR(check_index_uninitialized(key, index, present)); // Assign tuple at this index present[index] = std::move((*tuple)[i]); } // Increment size current_bytes_ += tuple_bytes; // Do we have values at all tuple elements? bool complete = std::all_of(present.begin(), present.end(), [](const OptionalTensor& v) { return v.has_value(); }); // If so, put the tuple in the actual map if (complete) { OptionalTuple insert_tuple = std::move(it->second); // Remove from incomplete incomplete_.erase(it); TF_RETURN_IF_ERROR(put_complete(key, &insert_tuple)); } } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops. PiperOrigin-RevId: 387738023 Change-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void * pvPortMalloc( size_t xWantedSize ) { void * pvReturn = NULL; static uint8_t * pucAlignedHeap = NULL; /* Ensure that blocks are always aligned to the required number of bytes. */ #if ( portBYTE_ALIGNMENT != 1 ) { if( xWantedSize & portBYTE_ALIGNMENT_MASK ) { /* Byte alignment required. */ xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); } } #endif vTaskSuspendAll(); { if( pucAlignedHeap == NULL ) { /* Ensure the heap starts on a correctly aligned boundary. */ pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); } /* Check there is enough room left for the allocation. */ if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) && ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) ) /* Check for overflow. */ { /* Return the next free byte then increment the index past this * block. */ pvReturn = pucAlignedHeap + xNextFreeByte; xNextFreeByte += xWantedSize; } traceMALLOC( pvReturn, xWantedSize ); } ( void ) xTaskResumeAll(); #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) { if( pvReturn == NULL ) { extern void vApplicationMallocFailedHook( void ); vApplicationMallocFailedHook(); } } #endif return pvReturn; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-119'], 'message': 'Improve heap2 bounds checking (#224) * Improve heap bounds checking in pvPortMalloc'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa, const std::string& emsa) : PK_Ops::Signature_with_EMSA(emsa), m_group(ecdsa.domain()), m_x(ecdsa.private_value()) { #if defined(BOTAN_HAS_RFC6979_GENERATOR) m_rfc6979_hash = hash_for_emsa(emsa); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'</s>