text
stringlengths
481
107k
<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: CreateForeignServer(CreateForeignServerStmt *stmt) { Relation rel; Datum srvoptions; Datum values[Natts_pg_foreign_server]; bool nulls[Natts_pg_foreign_server]; HeapTuple tuple; Oid srvId; Oid ownerId; AclResult aclresult; ObjectAddress myself; ObjectAddress referenced; ForeignDataWrapper *fdw; rel = heap_open(ForeignServerRelationId, RowExclusiveLock); /* For now the owner cannot be specified on create. Use effective user ID. */ ownerId = GetUserId(); /* * Check that there is no other foreign server by this name. Do nothing if * IF NOT EXISTS was enforced. */ if (GetForeignServerByName(stmt->servername, true) != NULL) { if (stmt->if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("server \"%s\" already exists, skipping", stmt->servername))); heap_close(rel, RowExclusiveLock); return InvalidObjectAddress; } else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("server \"%s\" already exists", stmt->servername))); } /* * Check that the FDW exists and that we have USAGE on it. Also get the * actual FDW for option validation etc. */ fdw = GetForeignDataWrapperByName(stmt->fdwname, false); aclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname); /* * Insert tuple into pg_foreign_server. */ memset(values, 0, sizeof(values)); memset(nulls, false, sizeof(nulls)); values[Anum_pg_foreign_server_srvname - 1] = DirectFunctionCall1(namein, CStringGetDatum(stmt->servername)); values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId); values[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid); /* Add server type if supplied */ if (stmt->servertype) values[Anum_pg_foreign_server_srvtype - 1] = CStringGetTextDatum(stmt->servertype); else nulls[Anum_pg_foreign_server_srvtype - 1] = true; /* Add server version if supplied */ if (stmt->version) values[Anum_pg_foreign_server_srvversion - 1] = CStringGetTextDatum(stmt->version); else nulls[Anum_pg_foreign_server_srvversion - 1] = true; /* Start with a blank acl */ nulls[Anum_pg_foreign_server_srvacl - 1] = true; /* Add server options */ srvoptions = transformGenericOptions(ForeignServerRelationId, PointerGetDatum(NULL), stmt->options, fdw->fdwvalidator); if (PointerIsValid(DatumGetPointer(srvoptions))) values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions; else nulls[Anum_pg_foreign_server_srvoptions - 1] = true; tuple = heap_form_tuple(rel->rd_att, values, nulls); srvId = CatalogTupleInsert(rel, tuple); heap_freetuple(tuple); /* record dependencies */ myself.classId = ForeignServerRelationId; myself.objectId = srvId; myself.objectSubId = 0; referenced.classId = ForeignDataWrapperRelationId; referenced.objectId = fdw->fdwid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); recordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId); /* dependency on extension */ recordDependencyOnCurrentExtension(&myself, false); /* Post creation hook for new foreign server */ InvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0); heap_close(rel, RowExclusiveLock); 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: GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify) { g_warning("Connection failed: SSL support not enabled in this build."); errno = ENOSYS; return NULL; } ; 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)); const auto node_id_range = node_id_range_t->vec<int32>(); 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 int32_t node_id_first = node_id_range(0); // Inclusive. const int32_t node_id_last = node_id_range(1); // Exclusive. // Get stats_summaries_list. OpInputList stats_summaries_list; OP_REQUIRES_OK(context, context->input_list("stats_summaries_list", &stats_summaries_list)); // Infer dimensions of a stats_summary. DCHECK_GT(stats_summaries_list.size(), 0); const int32_t feature_dims = stats_summaries_list[0].dim_size(1); // The last bucket is for default/missing value. const int32_t num_buckets = stats_summaries_list[0].dim_size(2) - 1; const int32_t logits_dim = logits_dim_; const int32_t hessian_dim = stats_summaries_list[0].dim_size(3) - logits_dim; DCHECK_GT(hessian_dim, 0); DCHECK_LE(hessian_dim, logits_dim * logits_dim); // Vector of stats_summaries; each element is stats for feature of shape // [max_splits, feature_dim, num_buckets, logits_dim + hessian_dim]. std::vector<TTypes<float, 4>::ConstTensor> stats_summaries; DCHECK_EQ(stats_summaries_list.size(), num_features_); stats_summaries.reserve(num_features_); for (const auto& tensor : stats_summaries_list) { stats_summaries.emplace_back(tensor.tensor<float, 4>()); } // Split types. const Tensor* split_types_t; OP_REQUIRES_OK(context, context->input("split_types", &split_types_t)); const auto split_types = split_types_t->vec<tstring>(); DCHECK_EQ(split_types.size(), num_features_); // Validate. for (int i = 0; i < num_features_; ++i) { if (!(split_types(i) == kInequalitySplit || split_types(i) == kEqualitySplit)) { OP_REQUIRES_OK( context, errors::Aborted( "Operation received an exception: Incorrect split type")); } } // Feature ids. const Tensor* candidate_feature_ids_t; OP_REQUIRES_OK(context, context->input("candidate_feature_ids", &candidate_feature_ids_t)); const auto candidate_feature_ids = candidate_feature_ids_t->vec<int32>(); DCHECK_EQ(candidate_feature_ids.size(), num_features_); // L1, L2, tree_complexity, min_node_weight. 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_ids; 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. float parent_gain; 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; int32_t best_f_id; int32_t best_f_dim; string best_split_type; Eigen::VectorXf best_contrib_for_left(logits_dim); Eigen::VectorXf best_contrib_for_right(logits_dim); // Sum of gradient and hessian. Compute parent gain using first feature. ConstMatrixMap stats_mat(&stats_summaries[0](node_id, 0, 0, 0), num_buckets + 1, // Including default bucket. 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 unused(logits_dim); CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &unused, &parent_gain); for (int f_idx = 0; f_idx < num_features_; ++f_idx) { const string split_type = split_types(f_idx); TTypes<float, 4>::ConstTensor stats_summary = stats_summaries[f_idx]; float f_best_gain = std::numeric_limits<float>::lowest(); int32_t f_best_bucket; int32_t f_best_f_dim; string f_best_split_type; Eigen::VectorXf f_best_contrib_for_left(logits_dim); Eigen::VectorXf f_best_contrib_for_right(logits_dim); if (split_type == kInequalitySplit) { CalculateBestInequalitySplit( stats_summary, node_id, feature_dims, logits_dim, hessian_dim, num_buckets, min_node_weight, l1, l2, &f_best_gain, &f_best_bucket, &f_best_f_dim, &f_best_split_type, &f_best_contrib_for_left, &f_best_contrib_for_right); } else { CalculateBestEqualitySplit( stats_summary, total_grad, total_hess, node_id, feature_dims, logits_dim, hessian_dim, num_buckets, l1, l2, &f_best_gain, &f_best_bucket, &f_best_f_dim, &f_best_split_type, &f_best_contrib_for_left, &f_best_contrib_for_right); } if (f_best_gain > best_gain) { best_gain = f_best_gain; best_f_id = candidate_feature_ids(f_idx); best_f_dim = f_best_f_dim; best_split_type = f_best_split_type; best_bucket = f_best_bucket; best_contrib_for_left = f_best_contrib_for_left; best_contrib_for_right = f_best_contrib_for_right; } } // For feature id. if (best_gain == std::numeric_limits<float>::lowest()) { // Do not add the node if no split is 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_ids.push_back(best_f_id); 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_ids Tensor* output_features_ids_t; OP_REQUIRES_OK(context, context->allocate_output("feature_ids", {num_nodes}, &output_features_ids_t)); auto output_features_vec = output_features_ids_t->vec<int32>(); // 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]; output_features_vec(i) = output_feature_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-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: bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, struct bpacket_attr_vec_arr *vecarr, struct prefix *p, afi_t afi, safi_t safi, struct peer *from, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id) { size_t cp; size_t aspath_sizep; struct aspath *aspath; int send_as4_path = 0; int send_as4_aggregator = 0; int use32bit = (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) ? 1 : 0; if (!bgp) bgp = peer->bgp; /* Remember current pointer. */ cp = stream_get_endp(s); if (p && !((afi == AFI_IP && safi == SAFI_UNICAST) && !peer_cap_enhe(peer, afi, safi))) { size_t mpattrlen_pos = 0; mpattrlen_pos = bgp_packet_mpattr_start(s, peer, afi, safi, vecarr, attr); bgp_packet_mpattr_prefix(s, afi, safi, p, prd, label, num_labels, addpath_encode, addpath_tx_id, attr); bgp_packet_mpattr_end(s, mpattrlen_pos); } /* Origin attribute. */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ORIGIN); stream_putc(s, 1); stream_putc(s, attr->origin); /* AS path attribute. */ /* If remote-peer is EBGP */ if (peer->sort == BGP_PEER_EBGP && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_AS_PATH_UNCHANGED) || attr->aspath->segments == NULL) && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_RSERVER_CLIENT))) { aspath = aspath_dup(attr->aspath); /* Even though we may not be configured for confederations we * may have * RXed an AS_PATH with AS_CONFED_SEQUENCE or AS_CONFED_SET */ aspath = aspath_delete_confed_seq(aspath); if (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) { /* Stuff our path CONFED_ID on the front */ aspath = aspath_add_seq(aspath, bgp->confed_id); } else { if (peer->change_local_as) { /* If replace-as is specified, we only use the change_local_as when advertising routes. */ if (!CHECK_FLAG( peer->flags, PEER_FLAG_LOCAL_AS_REPLACE_AS)) { aspath = aspath_add_seq(aspath, peer->local_as); } aspath = aspath_add_seq(aspath, peer->change_local_as); } else { aspath = aspath_add_seq(aspath, peer->local_as); } } } else if (peer->sort == BGP_PEER_CONFED) { /* A confed member, so we need to do the AS_CONFED_SEQUENCE * thing */ aspath = aspath_dup(attr->aspath); aspath = aspath_add_confed_seq(aspath, peer->local_as); } else aspath = attr->aspath; /* If peer is not AS4 capable, then: * - send the created AS_PATH out as AS4_PATH (optional, transitive), * but ensure that no AS_CONFED_SEQUENCE and AS_CONFED_SET path * segment * types are in it (i.e. exclude them if they are there) * AND do this only if there is at least one asnum > 65535 in the * path! * - send an AS_PATH out, but put 16Bit ASnums in it, not 32bit, and * change * all ASnums > 65535 to BGP_AS_TRANS */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, use32bit)); /* OLD session may need NEW_AS_PATH sent, if there are 4-byte ASNs * in the path */ if (!use32bit && aspath_has_as4(aspath)) send_as4_path = 1; /* we'll do this later, at the correct place */ /* Nexthop attribute. */ if (afi == AFI_IP && safi == SAFI_UNICAST && !peer_cap_enhe(peer, afi, safi)) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, attr); stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); } else if (peer_cap_enhe(from, afi, safi)) { /* * Likely this is the case when an IPv4 prefix was * received with * Extended Next-hop capability and now being advertised * to * non-ENHE peers. * Setting the mandatory (ipv4) next-hop attribute here * to enable * implicit next-hop self with correct (ipv4 address * family). */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, NULL); stream_putc(s, 4); stream_put_ipv4(s, 0); } } /* MED attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC) || bgp->maxmed_active) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MULTI_EXIT_DISC); stream_putc(s, 4); stream_putl(s, (bgp->maxmed_active ? bgp->maxmed_value : attr->med)); } /* Local preference. */ if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LOCAL_PREF); stream_putc(s, 4); stream_putl(s, attr->local_pref); } /* Atomic aggregate. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE); stream_putc(s, 0); } /* Aggregator. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) { /* Common to BGP_ATTR_AGGREGATOR, regardless of ASN size */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AGGREGATOR); if (use32bit) { /* AS4 capable peer */ stream_putc(s, 8); stream_putl(s, attr->aggregator_as); } else { /* 2-byte AS peer */ stream_putc(s, 6); /* Is ASN representable in 2-bytes? Or must AS_TRANS be * used? */ if (attr->aggregator_as > 65535) { stream_putw(s, BGP_AS_TRANS); /* we have to send AS4_AGGREGATOR, too. * we'll do that later in order to send * attributes in ascending * order. */ send_as4_aggregator = 1; } else stream_putw(s, (uint16_t)attr->aggregator_as); } stream_put_ipv4(s, attr->aggregator_addr.s_addr); } /* Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))) { if (attr->community->size * 4 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putw(s, attr->community->size * 4); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putc(s, attr->community->size * 4); } stream_put(s, attr->community->val, attr->community->size * 4); } /* * Large Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_LARGE_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))) { if (lcom_length(attr->lcommunity) > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putw(s, lcom_length(attr->lcommunity)); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putc(s, lcom_length(attr->lcommunity)); } stream_put(s, attr->lcommunity->val, lcom_length(attr->lcommunity)); } /* Route Reflector. */ if (peer->sort == BGP_PEER_IBGP && from && from->sort == BGP_PEER_IBGP) { /* Originator ID. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_ORIGINATOR_ID); stream_putc(s, 4); if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID)) stream_put_in_addr(s, &attr->originator_id); else stream_put_in_addr(s, &from->remote_id); /* Cluster list. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_CLUSTER_LIST); if (attr->cluster) { stream_putc(s, attr->cluster->length + 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); stream_put(s, attr->cluster->list, attr->cluster->length); } else { stream_putc(s, 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); } } /* Extended Communities attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_EXT_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES))) { if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { if (attr->ecommunity->size * 8 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, attr->ecommunity->size * 8); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, attr->ecommunity->size * 8); } stream_put(s, attr->ecommunity->val, attr->ecommunity->size * 8); } else { uint8_t *pnt; int tbit; int ecom_tr_size = 0; int i; for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG(tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; ecom_tr_size++; } if (ecom_tr_size) { if (ecom_tr_size * 8 > 255) { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, ecom_tr_size * 8); } else { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, ecom_tr_size * 8); } for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG( tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; stream_put(s, pnt, 8); } } } } /* Label index attribute. */ if (safi == SAFI_LABELED_UNICAST) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) { uint32_t label_index; label_index = attr->label_index; if (label_index != BGP_INVALID_LABEL_INDEX) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PREFIX_SID); stream_putc(s, 10); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX); stream_putw(s, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); stream_putc(s, 0); // reserved stream_putw(s, 0); // flags stream_putl(s, label_index); } } } if (send_as4_path) { /* If the peer is NOT As4 capable, AND */ /* there are ASnums > 65535 in path THEN * give out AS4_PATH */ /* Get rid of all AS_CONFED_SEQUENCE and AS_CONFED_SET * path segments! * Hm, I wonder... confederation things *should* only be at * the beginning of an aspath, right? Then we should use * aspath_delete_confed_seq for this, because it is already * there! (JK) * Folks, talk to me: what is reasonable here!? */ aspath = aspath_delete_confed_seq(aspath); stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS4_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, 1)); } if (aspath != attr->aspath) aspath_free(aspath); if (send_as4_aggregator) { /* send AS4_AGGREGATOR, at this place */ /* this section of code moved here in order to ensure the * correct * *ascending* order of attributes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AS4_AGGREGATOR); stream_putc(s, 8); stream_putl(s, attr->aggregator_as); stream_put_ipv4(s, attr->aggregator_addr.s_addr); } if (((afi == AFI_IP || afi == AFI_IP6) && (safi == SAFI_ENCAP || safi == SAFI_MPLS_VPN)) || (afi == AFI_L2VPN && safi == SAFI_EVPN)) { /* Tunnel Encap attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP); #if ENABLE_BGP_VNC /* VNC attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC); #endif } /* PMSI Tunnel */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PMSI_TUNNEL); stream_putc(s, 9); // Length stream_putc(s, 0); // Flags stream_putc(s, PMSI_TNLTYPE_INGR_REPL); // IR (6) stream_put(s, &(attr->label), BGP_LABEL_BYTES); // MPLS Label / VXLAN VNI stream_put_ipv4(s, attr->nexthop.s_addr); // Unicast tunnel endpoint IP address } /* Unknown transit attribute. */ if (attr->transit) stream_put(s, attr->transit->val, attr->transit->length); /* Return total size of attribute. */ return stream_get_endp(s) - cp; } ; 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: wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width) { int i; GlyphInfo *cur, *s1, *e1, *s2, *s3; int last_space; int break_type; int exit; double pen_shift_x; double pen_shift_y; int cur_line; int run_offset; TextInfo *text_info = &render_priv->text_info; last_space = -1; text_info->n_lines = 1; break_type = 0; s1 = text_info->glyphs; // current line start for (i = 0; i < text_info->length; ++i) { int break_at = -1; double s_offset, len; cur = text_info->glyphs + i; s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x); len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset; if (cur->symbol == '\n') { break_type = 2; break_at = i; ass_msg(render_priv->library, MSGL_DBG2, "forced line break at %d", break_at); } else if (cur->symbol == ' ') { last_space = i; } else if (len >= max_text_width && (render_priv->state.wrap_style != 2)) { break_type = 1; break_at = last_space; if (break_at >= 0) ass_msg(render_priv->library, MSGL_DBG2, "line break at %d", break_at); } if (break_at != -1) { // need to use one more line // marking break_at+1 as start of a new line int lead = break_at + 1; // the first symbol of the new line if (text_info->n_lines >= text_info->max_lines) { // Raise maximum number of lines text_info->max_lines *= 2; text_info->lines = realloc(text_info->lines, sizeof(LineInfo) * text_info->max_lines); } if (lead < text_info->length) { text_info->glyphs[lead].linebreak = break_type; last_space = -1; s1 = text_info->glyphs + lead; text_info->n_lines++; } } } #define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y)) exit = 0; while (!exit && render_priv->state.wrap_style != 1) { exit = 1; s3 = text_info->glyphs; s1 = s2 = 0; for (i = 0; i <= text_info->length; ++i) { cur = text_info->glyphs + i; if ((i == text_info->length) || cur->linebreak) { s1 = s2; s2 = s3; s3 = cur; if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft' double l1, l2, l1_new, l2_new; GlyphInfo *w = s2; do { --w; } while ((w > s1) && (w->symbol == ' ')); while ((w > s1) && (w->symbol != ' ')) { --w; } e1 = w; while ((e1 > s1) && (e1->symbol == ' ')) { --e1; } if (w->symbol == ' ') ++w; l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) - (s1->bbox.xMin + s1->pos.x)); l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) - (s2->bbox.xMin + s2->pos.x)); l1_new = d6_to_double( (e1->bbox.xMax + e1->pos.x) - (s1->bbox.xMin + s1->pos.x)); l2_new = d6_to_double( ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) - (w->bbox.xMin + w->pos.x)); if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) { w->linebreak = 1; s2->linebreak = 0; exit = 0; } } } if (i == text_info->length) break; } } assert(text_info->n_lines >= 1); #undef DIFF measure_text(render_priv); trim_whitespace(render_priv); cur_line = 1; run_offset = 0; i = 0; cur = text_info->glyphs + i; while (i < text_info->length && cur->skip) cur = text_info->glyphs + ++i; pen_shift_x = d6_to_double(-cur->pos.x); pen_shift_y = 0.; for (i = 0; i < text_info->length; ++i) { cur = text_info->glyphs + i; if (cur->linebreak) { while (i < text_info->length && cur->skip && cur->symbol != '\n') cur = text_info->glyphs + ++i; double height = text_info->lines[cur_line - 1].desc + text_info->lines[cur_line].asc; text_info->lines[cur_line - 1].len = i - text_info->lines[cur_line - 1].offset; text_info->lines[cur_line].offset = i; cur_line++; run_offset++; pen_shift_x = d6_to_double(-cur->pos.x); pen_shift_y += height + render_priv->settings.line_spacing; } cur->pos.x += double_to_d6(pen_shift_x); cur->pos.y += double_to_d6(pen_shift_y); } text_info->lines[cur_line - 1].len = text_info->length - text_info->lines[cur_line - 1].offset; #if 0 // print line info for (i = 0; i < text_info->n_lines; i++) { printf("line %d offset %d length %d\n", i, text_info->lines[i].offset, text_info->lines[i].len); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix line wrapping mode 0/3 bugs This fixes two separate bugs: a) Don't move a linebreak into the first symbol. This results in a empty line at the front, which does not help to equalize line lengths at all. Instead, merge line with the second one. b) When moving a linebreak into a symbol that already is a break, the number of lines must be decremented. Otherwise, uninitialized memory is possibly used for later layout operations. Found by fuzzer test case id:000085,sig:11,src:003377+003350,op:splice,rep:8. This might also affect and hopefully fix libass#229. v2: change semantics according to review'</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_ble8(const void *src) { return *(ut8 *)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: NORET_TYPE void do_exit(long code) { struct task_struct *tsk = current; int group_dead; profile_task_exit(tsk); WARN_ON(atomic_read(&tsk->fs_excl)); if (unlikely(in_interrupt())) panic("Aiee, killing interrupt handler!"); if (unlikely(!tsk->pid)) panic("Attempted to kill the idle task!"); tracehook_report_exit(&code); /* * We're taking recursive faults here in do_exit. Safest is to just * leave this task alone and wait for reboot. */ if (unlikely(tsk->flags & PF_EXITING)) { printk(KERN_ALERT "Fixing recursive fault but reboot is needed!\n"); /* * We can do this unlocked here. The futex code uses * this flag just to verify whether the pi state * cleanup has been done or not. In the worst case it * loops once more. We pretend that the cleanup was * done as there is no way to return. Either the * OWNER_DIED bit is set by now or we push the blocked * task into the wait for ever nirwana as well. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(); set_current_state(TASK_UNINTERRUPTIBLE); schedule(); } exit_signals(tsk); /* sets PF_EXITING */ /* * tsk->flags are checked in the futex code to protect against * an exiting task cleaning up the robust pi futexes. */ smp_mb(); spin_unlock_wait(&tsk->pi_lock); if (unlikely(in_atomic())) printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n", current->comm, task_pid_nr(current), preempt_count()); acct_update_integrals(tsk); if (tsk->mm) { update_hiwater_rss(tsk->mm); update_hiwater_vm(tsk->mm); } group_dead = atomic_dec_and_test(&tsk->signal->live); if (group_dead) { hrtimer_cancel(&tsk->signal->real_timer); exit_itimers(tsk->signal); } acct_collect(code, group_dead); #ifdef CONFIG_FUTEX if (unlikely(tsk->robust_list)) exit_robust_list(tsk); #ifdef CONFIG_COMPAT if (unlikely(tsk->compat_robust_list)) compat_exit_robust_list(tsk); #endif #endif if (group_dead) tty_audit_exit(); if (unlikely(tsk->audit_context)) audit_free(tsk); tsk->exit_code = code; taskstats_exit(tsk, group_dead); exit_mm(tsk); if (group_dead) acct_process(); trace_sched_process_exit(tsk); exit_sem(tsk); exit_files(tsk); exit_fs(tsk); check_stack_usage(); exit_thread(); cgroup_exit(tsk, 1); exit_keys(tsk); if (group_dead && tsk->signal->leader) disassociate_ctty(1); module_put(task_thread_info(tsk)->exec_domain->module); if (tsk->binfmt) module_put(tsk->binfmt->module); proc_exit_connector(tsk); exit_notify(tsk, group_dead); #ifdef CONFIG_NUMA mpol_put(tsk->mempolicy); tsk->mempolicy = NULL; #endif #ifdef CONFIG_FUTEX /* * This must happen late, after the PID is not * hashed anymore: */ if (unlikely(!list_empty(&tsk->pi_state_list))) exit_pi_state_list(tsk); if (unlikely(current->pi_state_cache)) kfree(current->pi_state_cache); #endif /* * Make sure we are holding no locks: */ debug_check_no_locks_held(tsk); /* * We can do this unlocked here. The futex code uses this flag * just to verify whether the pi state cleanup has been done * or not. In the worst case it loops once more. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(); if (tsk->splice_pipe) __free_pipe_info(tsk->splice_pipe); preempt_disable(); /* causes final put_task_struct in finish_task_switch(). */ tsk->state = TASK_DEAD; schedule(); BUG(); /* Avoid "noreturn function does return". */ for (;;) cpu_relax(); /* For when BUG is null */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'Move "exit_robust_list" into mm_release() We don't want to get rid of the futexes just at exit() time, we want to drop them when doing an execve() too, since that gets rid of the previous VM image too. Doing it at mm_release() time means that we automatically always do it when we disassociate a VM map from the task. Reported-by: pageexec@freemail.hu Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Nick Piggin <npiggin@suse.de> Cc: Hugh Dickins <hugh@veritas.com> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Brad Spengler <spender@grsecurity.net> Cc: Alex Efros <powerman@powerman.name> Cc: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.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: RZ_API void rz_core_analysis_esil(RzCore *core, const char *str, const char *target) { bool cfg_analysis_strings = rz_config_get_i(core->config, "analysis.strings"); bool emu_lazy = rz_config_get_i(core->config, "emu.lazy"); bool gp_fixed = rz_config_get_i(core->config, "analysis.gpfixed"); RzAnalysisEsil *ESIL = core->analysis->esil; ut64 refptr = 0LL; const char *pcname; RzAnalysisOp op = RZ_EMPTY; ut8 *buf = NULL; bool end_address_set = false; int iend; int minopsize = 4; // XXX this depends on asm->mininstrsize bool archIsArm = false; ut64 addr = core->offset; ut64 start = addr; ut64 end = 0LL; ut64 cur; if (!strcmp(str, "?")) { eprintf("Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\n"); eprintf(" aae $SS @ $S - analyze the whole section\n"); eprintf(" aae $SS str.Hello @ $S - find references for str.Hellow\n"); eprintf(" aaef - analyze functions discovered with esil\n"); return; } #define CHECKREF(x) ((refptr && (x) == refptr) || !refptr) if (target) { const char *expr = rz_str_trim_head_ro(target); if (*expr) { refptr = ntarget = rz_num_math(core->num, expr); if (!refptr) { ntarget = refptr = addr; } } else { ntarget = UT64_MAX; refptr = 0LL; } } else { ntarget = UT64_MAX; refptr = 0LL; } RzAnalysisFunction *fcn = NULL; if (!strcmp(str, "f")) { fcn = rz_analysis_get_fcn_in(core->analysis, core->offset, 0); if (fcn) { start = rz_analysis_function_min_addr(fcn); addr = fcn->addr; end = rz_analysis_function_max_addr(fcn); end_address_set = true; } } if (!end_address_set) { if (str[0] == ' ') { end = addr + rz_num_math(core->num, str + 1); } else { RzIOMap *map = rz_io_map_get(core->io, addr); if (map) { end = map->itv.addr + map->itv.size; } else { end = addr + core->blocksize; } } } iend = end - start; if (iend < 0) { return; } if (iend > MAX_SCAN_SIZE) { eprintf("Warning: Not going to analyze 0x%08" PFMT64x " bytes.\n", (ut64)iend); return; } buf = malloc((size_t)iend + 2); if (!buf) { perror("malloc"); return; } esilbreak_last_read = UT64_MAX; rz_io_read_at(core->io, start, buf, iend + 1); if (!ESIL) { rz_core_analysis_esil_reinit(core); ESIL = core->analysis->esil; if (!ESIL) { eprintf("ESIL not initialized\n"); return; } rz_core_analysis_esil_init_mem(core, NULL, UT64_MAX, UT32_MAX); } const char *spname = rz_reg_get_name(core->analysis->reg, RZ_REG_NAME_SP); EsilBreakCtx ctx = { &op, fcn, spname, rz_reg_getv(core->analysis->reg, spname) }; ESIL->cb.hook_reg_write = &esilbreak_reg_write; //this is necessary for the hook to read the id of analop ESIL->user = &ctx; ESIL->cb.hook_mem_read = &esilbreak_mem_read; ESIL->cb.hook_mem_write = &esilbreak_mem_write; if (fcn && fcn->reg_save_area) { rz_reg_setv(core->analysis->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area); } //eprintf ("Analyzing ESIL refs from 0x%"PFMT64x" - 0x%"PFMT64x"\n", addr, end); // TODO: backup/restore register state before/after analysis pcname = rz_reg_get_name(core->analysis->reg, RZ_REG_NAME_PC); if (!pcname || !*pcname) { eprintf("Cannot find program counter register in the current profile.\n"); return; } esil_analysis_stop = false; rz_cons_break_push(cccb, core); int arch = -1; if (!strcmp(core->analysis->cur->arch, "arm")) { switch (core->analysis->bits) { case 64: arch = RZ_ARCH_ARM64; break; case 32: arch = RZ_ARCH_ARM32; break; case 16: arch = RZ_ARCH_THUMB; break; } archIsArm = true; } ut64 gp = rz_config_get_i(core->config, "analysis.gp"); const char *gp_reg = NULL; if (!strcmp(core->analysis->cur->arch, "mips")) { gp_reg = "gp"; arch = RZ_ARCH_MIPS; } const char *sn = rz_reg_get_name(core->analysis->reg, RZ_REG_NAME_SN); if (!sn) { eprintf("Warning: No SN reg alias for current architecture.\n"); } rz_reg_arena_push(core->analysis->reg); IterCtx ictx = { start, end, fcn, NULL }; size_t i = addr - start; do { if (esil_analysis_stop || rz_cons_is_breaked()) { break; } size_t i_old = i; cur = start + i; if (!rz_io_is_valid_offset(core->io, cur, 0)) { break; } { RzPVector *list = rz_meta_get_all_in(core->analysis, cur, RZ_META_TYPE_ANY); void **it; rz_pvector_foreach (list, it) { RzIntervalNode *node = *it; RzAnalysisMetaItem *meta = node->data; switch (meta->type) { case RZ_META_TYPE_DATA: case RZ_META_TYPE_STRING: case RZ_META_TYPE_FORMAT: i += 4; rz_pvector_free(list); goto repeat; default: break; } } rz_pvector_free(list); } /* realign address if needed */ rz_core_seek_arch_bits(core, cur); int opalign = core->analysis->pcalign; if (opalign > 0) { cur -= (cur % opalign); } rz_analysis_op_fini(&op); rz_asm_set_pc(core->rasm, cur); if (!rz_analysis_op(core->analysis, &op, cur, buf + i, iend - i, RZ_ANALYSIS_OP_MASK_ESIL | RZ_ANALYSIS_OP_MASK_VAL | RZ_ANALYSIS_OP_MASK_HINT)) { i += minopsize - 1; // XXX dupe in op.size below } // if (op.type & 0x80000000 || op.type == 0) { if (op.type == RZ_ANALYSIS_OP_TYPE_ILL || op.type == RZ_ANALYSIS_OP_TYPE_UNK) { // i += 2 rz_analysis_op_fini(&op); goto repeat; } //we need to check again i because buf+i may goes beyond its boundaries //because of i+= minopsize - 1 if (i > iend) { goto repeat; } if (op.size < 1) { i += minopsize - 1; goto repeat; } if (emu_lazy) { if (op.type & RZ_ANALYSIS_OP_TYPE_REP) { i += op.size - 1; goto repeat; } switch (op.type & RZ_ANALYSIS_OP_TYPE_MASK) { case RZ_ANALYSIS_OP_TYPE_JMP: case RZ_ANALYSIS_OP_TYPE_CJMP: case RZ_ANALYSIS_OP_TYPE_CALL: case RZ_ANALYSIS_OP_TYPE_RET: case RZ_ANALYSIS_OP_TYPE_ILL: case RZ_ANALYSIS_OP_TYPE_NOP: case RZ_ANALYSIS_OP_TYPE_UJMP: case RZ_ANALYSIS_OP_TYPE_IO: case RZ_ANALYSIS_OP_TYPE_LEAVE: case RZ_ANALYSIS_OP_TYPE_CRYPTO: case RZ_ANALYSIS_OP_TYPE_CPL: case RZ_ANALYSIS_OP_TYPE_SYNC: case RZ_ANALYSIS_OP_TYPE_SWI: case RZ_ANALYSIS_OP_TYPE_CMP: case RZ_ANALYSIS_OP_TYPE_ACMP: case RZ_ANALYSIS_OP_TYPE_NULL: case RZ_ANALYSIS_OP_TYPE_CSWI: case RZ_ANALYSIS_OP_TYPE_TRAP: i += op.size - 1; goto repeat; // those require write support case RZ_ANALYSIS_OP_TYPE_PUSH: case RZ_ANALYSIS_OP_TYPE_POP: i += op.size - 1; goto repeat; } } if (sn && op.type == RZ_ANALYSIS_OP_TYPE_SWI) { rz_flag_space_set(core->flags, RZ_FLAGS_FS_SYSCALLS); int snv = (arch == RZ_ARCH_THUMB) ? op.val : (int)rz_reg_getv(core->analysis->reg, sn); RzSyscallItem *si = rz_syscall_get(core->analysis->syscall, snv, -1); if (si) { // eprintf ("0x%08"PFMT64x" SYSCALL %-4d %s\n", cur, snv, si->name); rz_flag_set_next(core->flags, sdb_fmt("syscall.%s", si->name), cur, 1); rz_syscall_item_free(si); } else { //todo were doing less filtering up top because we can't match against 80 on all platforms // might get too many of this path now.. // eprintf ("0x%08"PFMT64x" SYSCALL %d\n", cur, snv); rz_flag_set_next(core->flags, sdb_fmt("syscall.%d", snv), cur, 1); } rz_flag_space_set(core->flags, NULL); } const char *esilstr = RZ_STRBUF_SAFEGET(&op.esil); i += op.size - 1; if (!esilstr || !*esilstr) { goto repeat; } rz_analysis_esil_set_pc(ESIL, cur); rz_reg_setv(core->analysis->reg, pcname, cur + op.size); if (gp_fixed && gp_reg) { rz_reg_setv(core->analysis->reg, gp_reg, gp); } (void)rz_analysis_esil_parse(ESIL, esilstr); // looks like ^C is handled by esil_parse !!!! //rz_analysis_esil_dumpstack (ESIL); //rz_analysis_esil_stack_free (ESIL); switch (op.type) { case RZ_ANALYSIS_OP_TYPE_LEA: // arm64 if (core->analysis->cur && arch == RZ_ARCH_ARM64) { if (CHECKREF(ESIL->cur)) { rz_analysis_xrefs_set(core->analysis, cur, ESIL->cur, RZ_ANALYSIS_REF_TYPE_STRING); } } else if ((target && op.ptr == ntarget) || !target) { if (CHECKREF(ESIL->cur)) { if (op.ptr && rz_io_is_valid_offset(core->io, op.ptr, !core->analysis->opt.noncode)) { rz_analysis_xrefs_set(core->analysis, cur, op.ptr, RZ_ANALYSIS_REF_TYPE_STRING); } else { rz_analysis_xrefs_set(core->analysis, cur, ESIL->cur, RZ_ANALYSIS_REF_TYPE_STRING); } } } if (cfg_analysis_strings) { add_string_ref(core, op.addr, op.ptr); } break; case RZ_ANALYSIS_OP_TYPE_ADD: /* TODO: test if this is valid for other archs too */ if (core->analysis->cur && archIsArm) { /* This code is known to work on Thumb, ARM and ARM64 */ ut64 dst = ESIL->cur; if ((target && dst == ntarget) || !target) { if (CHECKREF(dst)) { rz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA); } } if (cfg_analysis_strings) { add_string_ref(core, op.addr, dst); } } else if ((core->analysis->bits == 32 && core->analysis->cur && arch == RZ_ARCH_MIPS)) { ut64 dst = ESIL->cur; if (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) { break; } if (!strcmp(op.src[0]->reg->name, "sp")) { break; } if (!strcmp(op.src[0]->reg->name, "zero")) { break; } if ((target && dst == ntarget) || !target) { if (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid(core->io, dst)) { RzFlagItem *f; char *str; if (CHECKREF(dst) || CHECKREF(cur)) { rz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA); if (cfg_analysis_strings) { add_string_ref(core, op.addr, dst); } if ((f = rz_core_flag_get_by_spaces(core->flags, dst))) { rz_meta_set_string(core->analysis, RZ_META_TYPE_COMMENT, cur, f->name); } else if ((str = is_string_at(core, dst, NULL))) { char *str2 = sdb_fmt("esilref: '%s'", str); // HACK avoid format string inside string used later as format // string crashes disasm inside agf under some conditions. // https://github.com/rizinorg/rizin/issues/6937 rz_str_replace_char(str2, '%', '&'); rz_meta_set_string(core->analysis, RZ_META_TYPE_COMMENT, cur, str2); free(str); } } } } } break; case RZ_ANALYSIS_OP_TYPE_LOAD: { ut64 dst = esilbreak_last_read; if (dst != UT64_MAX && CHECKREF(dst)) { if (myvalid(core->io, dst)) { rz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA); if (cfg_analysis_strings) { add_string_ref(core, op.addr, dst); } } } dst = esilbreak_last_data; if (dst != UT64_MAX && CHECKREF(dst)) { if (myvalid(core->io, dst)) { rz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA); if (cfg_analysis_strings) { add_string_ref(core, op.addr, dst); } } } } break; case RZ_ANALYSIS_OP_TYPE_JMP: { ut64 dst = op.jump; if (CHECKREF(dst)) { if (myvalid(core->io, dst)) { rz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_CODE); } } } break; case RZ_ANALYSIS_OP_TYPE_CALL: { ut64 dst = op.jump; if (CHECKREF(dst)) { if (myvalid(core->io, dst)) { rz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_CALL); } ESIL->old = cur + op.size; getpcfromstack(core, ESIL); } } break; case RZ_ANALYSIS_OP_TYPE_UJMP: case RZ_ANALYSIS_OP_TYPE_RJMP: case RZ_ANALYSIS_OP_TYPE_UCALL: case RZ_ANALYSIS_OP_TYPE_ICALL: case RZ_ANALYSIS_OP_TYPE_RCALL: case RZ_ANALYSIS_OP_TYPE_IRCALL: case RZ_ANALYSIS_OP_TYPE_MJMP: { ut64 dst = core->analysis->esil->jump_target; if (dst == 0 || dst == UT64_MAX) { dst = rz_reg_getv(core->analysis->reg, pcname); } if (CHECKREF(dst)) { if (myvalid(core->io, dst)) { RzAnalysisXRefType ref = (op.type & RZ_ANALYSIS_OP_TYPE_MASK) == RZ_ANALYSIS_OP_TYPE_UCALL ? RZ_ANALYSIS_REF_TYPE_CALL : RZ_ANALYSIS_REF_TYPE_CODE; rz_analysis_xrefs_set(core->analysis, cur, dst, ref); rz_core_analysis_fcn(core, dst, UT64_MAX, RZ_ANALYSIS_REF_TYPE_NULL, 1); // analyze function here #if 0 if (op.type == RZ_ANALYSIS_OP_TYPE_UCALL || op.type == RZ_ANALYSIS_OP_TYPE_RCALL) { eprintf ("0x%08"PFMT64x" RCALL TO %llx\n", cur, dst); } #endif } } } break; default: break; } rz_analysis_esil_stack_free(ESIL); repeat: if (!rz_analysis_get_block_at(core->analysis, cur)) { for (size_t bb_i = i_old + 1; bb_i <= i; bb_i++) { if (rz_analysis_get_block_at(core->analysis, start + bb_i)) { i = bb_i - 1; break; } } } if (i > iend) { break; } } while (get_next_i(&ictx, &i)); free(buf); ESIL->cb.hook_mem_read = NULL; ESIL->cb.hook_mem_write = NULL; ESIL->cb.hook_reg_write = NULL; ESIL->user = NULL; rz_analysis_op_fini(&op); rz_cons_break_pop(); // restore register rz_reg_arena_pop(core->analysis->reg); } ; 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 int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'af_key: add __GFP_ZERO flag for compose_sadb_supported in function pfkey_register Add __GFP_ZERO flag for compose_sadb_supported in function pfkey_register to initialize the buffer of supp_skb to fix a kernel-info-leak issue. 1) Function pfkey_register calls compose_sadb_supported to request a sk_buff. 2) compose_sadb_supported calls alloc_sbk to allocate a sk_buff, but it doesn't zero it. 3) If auth_len is greater 0, then compose_sadb_supported treats the memory as a struct sadb_supported and begins to initialize. But it just initializes the field sadb_supported_len and field sadb_supported_exttype without field sadb_supported_reserved. Reported-by: TCS Robot <tcs_robot@tencent.com> Signed-off-by: Haimin Zhang <tcs_kernel@tencent.com> Signed-off-by: Steffen Klassert <steffen.klassert@secunet.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: R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) { ut32 i = 0; ut64 curpos, offset = 0; RBinJavaLineNumberAttribute *lnattr; RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset); if (!attr) { return NULL; } offset += 6; attr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR; attr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.line_number_table_attr.line_number_table = r_list_newf (free); ut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length; RList *linenum_list = attr->info.line_number_table_attr.line_number_table; if (linenum_len > sz) { free (attr); return NULL; } for (i = 0; i < linenum_len; i++) { curpos = buf_offset + offset; // printf ("%llx %llx \n", curpos, sz); // XXX if (curpos + 8 >= sz) break; lnattr = R_NEW0 (RBinJavaLineNumberAttribute); if (!lnattr) { break; } lnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; lnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; lnattr->file_offset = curpos; lnattr->size = 4; r_list_append (linenum_list, lnattr); } 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 add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w) { long i; for (i = 0; i <= w - sizeof(long); i += sizeof(long)) { long a = *(long *)(src1 + i); long b = *(long *)(src2 + i); *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80); } for (; i < w; i++) dst[i] = src1[i] + src2[i]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'avcodec/pngdsp: fix (un)signed type in end comparission Fixes out of array accesses Fixes Ticket2919 Found_by: ami_stuff 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: tgs_make_reply(krb5_context context, krb5_kdc_configuration *config, KDC_REQ_BODY *b, krb5_const_principal tgt_name, const EncTicketPart *tgt, const krb5_keyblock *replykey, int rk_is_subkey, const EncryptionKey *serverkey, const krb5_keyblock *sessionkey, krb5_kvno kvno, AuthorizationData *auth_data, hdb_entry_ex *server, krb5_principal server_principal, const char *server_name, hdb_entry_ex *client, krb5_principal client_principal, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, krb5_principals spp, const krb5_data *rspac, const METHOD_DATA *enc_pa_data, const char **e_text, krb5_data *reply) { KDC_REP rep; EncKDCRepPart ek; EncTicketPart et; KDCOptions f = b->kdc_options; krb5_error_code ret; int is_weak = 0; memset(&rep, 0, sizeof(rep)); memset(&et, 0, sizeof(et)); memset(&ek, 0, sizeof(ek)); rep.pvno = 5; rep.msg_type = krb_tgs_rep; et.authtime = tgt->authtime; _kdc_fix_time(&b->till); et.endtime = min(tgt->endtime, *b->till); ALLOC(et.starttime); *et.starttime = kdc_time; ret = check_tgs_flags(context, config, b, tgt, &et); if(ret) goto out; /* We should check the transited encoding if: 1) the request doesn't ask not to be checked 2) globally enforcing a check 3) principal requires checking 4) we allow non-check per-principal, but principal isn't marked as allowing this 5) we don't globally allow this */ #define GLOBAL_FORCE_TRANSITED_CHECK \ (config->trpolicy == TRPOLICY_ALWAYS_CHECK) #define GLOBAL_ALLOW_PER_PRINCIPAL \ (config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL) #define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK \ (config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST) /* these will consult the database in future release */ #define PRINCIPAL_FORCE_TRANSITED_CHECK(P) 0 #define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P) 0 ret = fix_transited_encoding(context, config, !f.disable_transited_check || GLOBAL_FORCE_TRANSITED_CHECK || PRINCIPAL_FORCE_TRANSITED_CHECK(server) || !((GLOBAL_ALLOW_PER_PRINCIPAL && PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) || GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK), &tgt->transited, &et, krb5_principal_get_realm(context, client_principal), krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt->entry.principal)); if(ret) goto out; copy_Realm(&server_principal->realm, &rep.ticket.realm); _krb5_principal2principalname(&rep.ticket.sname, server_principal); copy_Realm(&tgt_name->realm, &rep.crealm); /* if (f.request_anonymous) _kdc_make_anonymous_principalname (&rep.cname); else */ copy_PrincipalName(&tgt_name->name, &rep.cname); rep.ticket.tkt_vno = 5; ek.caddr = et.caddr; { time_t life; life = et.endtime - *et.starttime; if(client && client->entry.max_life) life = min(life, *client->entry.max_life); if(server->entry.max_life) life = min(life, *server->entry.max_life); et.endtime = *et.starttime + life; } if(f.renewable_ok && tgt->flags.renewable && et.renew_till == NULL && et.endtime < *b->till && tgt->renew_till != NULL) { et.flags.renewable = 1; ALLOC(et.renew_till); *et.renew_till = *b->till; } if(et.renew_till){ time_t renew; renew = *et.renew_till - *et.starttime; if(client && client->entry.max_renew) renew = min(renew, *client->entry.max_renew); if(server->entry.max_renew) renew = min(renew, *server->entry.max_renew); *et.renew_till = *et.starttime + renew; } if(et.renew_till){ *et.renew_till = min(*et.renew_till, *tgt->renew_till); *et.starttime = min(*et.starttime, *et.renew_till); et.endtime = min(et.endtime, *et.renew_till); } *et.starttime = min(*et.starttime, et.endtime); if(*et.starttime == et.endtime){ ret = KRB5KDC_ERR_NEVER_VALID; goto out; } if(et.renew_till && et.endtime == *et.renew_till){ free(et.renew_till); et.renew_till = NULL; et.flags.renewable = 0; } et.flags.pre_authent = tgt->flags.pre_authent; et.flags.hw_authent = tgt->flags.hw_authent; et.flags.anonymous = tgt->flags.anonymous; et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate; if(rspac->length) { /* * No not need to filter out the any PAC from the * auth_data since it's signed by the KDC. */ ret = _kdc_tkt_add_if_relevant_ad(context, &et, KRB5_AUTHDATA_WIN2K_PAC, rspac); if (ret) goto out; } if (auth_data) { unsigned int i = 0; /* XXX check authdata */ if (et.authorization_data == NULL) { et.authorization_data = calloc(1, sizeof(*et.authorization_data)); if (et.authorization_data == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } for(i = 0; i < auth_data->len ; i++) { ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]); if (ret) { krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } /* Filter out type KRB5SignedPath */ ret = find_KRB5SignedPath(context, et.authorization_data, NULL); if (ret == 0) { if (et.authorization_data->len == 1) { free_AuthorizationData(et.authorization_data); free(et.authorization_data); et.authorization_data = NULL; } else { AuthorizationData *ad = et.authorization_data; free_AuthorizationDataElement(&ad->val[ad->len - 1]); ad->len--; } } } ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key); if (ret) goto out; et.crealm = tgt_name->realm; et.cname = tgt_name->name; ek.key = et.key; /* MIT must have at least one last_req */ ek.last_req.val = calloc(1, sizeof(*ek.last_req.val)); if (ek.last_req.val == NULL) { ret = ENOMEM; goto out; } ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */ ek.nonce = b->nonce; ek.flags = et.flags; ek.authtime = et.authtime; ek.starttime = et.starttime; ek.endtime = et.endtime; ek.renew_till = et.renew_till; ek.srealm = rep.ticket.realm; ek.sname = rep.ticket.sname; _kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.starttime, et.endtime, et.renew_till); /* Don't sign cross realm tickets, they can't be checked anyway */ { char *r = get_krbtgt_realm(&ek.sname); if (r == NULL || strcmp(r, ek.srealm) == 0) { ret = _kdc_add_KRB5SignedPath(context, config, krbtgt, krbtgt_etype, client_principal, NULL, spp, &et); if (ret) goto out; } } if (enc_pa_data->len) { rep.padata = calloc(1, sizeof(*rep.padata)); if (rep.padata == NULL) { ret = ENOMEM; goto out; } ret = copy_METHOD_DATA(enc_pa_data, rep.padata); if (ret) goto out; } if (krb5_enctype_valid(context, serverkey->keytype) != 0 && _kdc_is_weak_exception(server->entry.principal, serverkey->keytype)) { krb5_enctype_enable(context, serverkey->keytype); is_weak = 1; } /* It is somewhat unclear where the etype in the following encryption should come from. What we have is a session key in the passed tgt, and a list of preferred etypes *for the new ticket*. Should we pick the best possible etype, given the keytype in the tgt, or should we look at the etype list here as well? What if the tgt session key is DES3 and we want a ticket with a (say) CAST session key. Should the DES3 etype be added to the etype list, even if we don't want a session key with DES3? */ ret = _kdc_encode_reply(context, config, NULL, 0, &rep, &et, &ek, serverkey->keytype, kvno, serverkey, 0, replykey, rk_is_subkey, e_text, reply); if (is_weak) krb5_enctype_disable(context, serverkey->keytype); out: free_TGS_REP(&rep); free_TransitedEncoding(&et.transited); if(et.starttime) free(et.starttime); if(et.renew_till) free(et.renew_till); if(et.authorization_data) { free_AuthorizationData(et.authorization_data); free(et.authorization_data); } free_LastReq(&ek.last_req); memset(et.key.keyvalue.data, 0, et.key.keyvalue.length); free_EncryptionKey(&et.key); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'Fix transit path validation CVE-2017-6594 Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm to not be added to the transit path of issued tickets. This may, in some cases, enable bypass of capath policy in Heimdal versions 1.5 through 7.2. Note, this may break sites that rely on the bug. With the bug some incomplete [capaths] worked, that should not have. These may now break authentication in some cross-realm configurations.'</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 int object_common2(UNSERIALIZE_PARAMETER, long elements) { zval *retval_ptr = NULL; zval fname; if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) { /* We've got partially constructed object on our hands here. Wipe it. */ if(Z_TYPE_PP(rval) == IS_OBJECT) { zend_hash_clean(Z_OBJPROP_PP(rval)); } ZVAL_NULL(*rval); return 0; } if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY && zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) { INIT_PZVAL(&fname); ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0); BG(serialize_lock)++; call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC); BG(serialize_lock)--; } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction'</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: friend bool operator==(const TensorKey& t1, const TensorKey& t2) { if (t1.dtype() != t2.dtype() || t1.shape() != t2.shape()) { return false; } if (DataTypeCanUseMemcpy(t1.dtype())) { return t1.tensor_data() == t2.tensor_data(); } if (t1.dtype() == DT_STRING) { const auto s1 = t1.unaligned_flat<tstring>(); const auto s2 = t2.unaligned_flat<tstring>(); for (int64_t i = 0, n = t1.NumElements(); i < n; ++i) { if (TF_PREDICT_FALSE(s1(i) != s2(i))) { return false; } } return true; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'Fix TensorKey hash function. The original hash function only used total estimated `AllocatedBytes()`, which (a) is an estimate per tensor, and (b) is a very poor hash function for constants (e.g. `int32_t`). It also tried to access individual tensor bytes through `tensor.data()` of size `AllocatedBytes()`. This led to ASAN failures because the `AllocatedBytes()` is an estimate of total bytes allocated by a tensor, including any pointed-to constructs (e.g. strings), and does not refer to contiguous bytes in the `.data()` buffer. We couldn't use this byte vector anyways, since types like `tstring` include pointers, whereas we need to hash the string values themselves. Modified the hash function to more closely mirror the `==` operator. This correctly handles `tstring` and any numeric types that do have contiguous storage. Other types are currently left as unimplemented. PiperOrigin-RevId: 446265413'</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 hevc_frame_start(HEVCContext *s) { HEVCLocalContext *lc = &s->HEVClc; int ret; memset(s->horizontal_bs, 0, 2 * s->bs_width * (s->bs_height + 1)); memset(s->vertical_bs, 0, 2 * s->bs_width * (s->bs_height + 1)); memset(s->cbf_luma, 0, s->sps->min_tb_width * s->sps->min_tb_height); memset(s->is_pcm, 0, s->sps->min_pu_width * s->sps->min_pu_height); lc->start_of_tiles_x = 0; s->is_decoded = 0; if (s->pps->tiles_enabled_flag) lc->end_of_tiles_x = s->pps->column_width[0] << s->sps->log2_ctb_size; ret = ff_hevc_set_new_ref(s, s->sps->sao_enabled ? &s->sao_frame : &s->frame, s->poc); if (ret < 0) goto fail; ret = ff_hevc_frame_rps(s); if (ret < 0) { av_log(s->avctx, AV_LOG_ERROR, "Error constructing the frame RPS.\n"); goto fail; } ret = set_side_data(s); if (ret < 0) goto fail; av_frame_unref(s->output_frame); ret = ff_hevc_output_frame(s, s->output_frame, 0); if (ret < 0) goto fail; ff_thread_finish_setup(s->avctx); return 0; fail: if (s->ref) ff_thread_report_progress(&s->ref->tf, INT_MAX, 0); s->ref = NULL; return ret; } ; 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: static int lag_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; LagarithContext *l = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *const p = data; uint8_t frametype = 0; uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9; uint32_t offs[4]; uint8_t *srcs[4], *dst; int i, j, planes = 3; p->key_frame = 1; frametype = buf[0]; offset_gu = AV_RL32(buf + 1); offset_bv = AV_RL32(buf + 5); switch (frametype) { case FRAME_SOLID_RGBA: avctx->pix_fmt = AV_PIX_FMT_RGB32; if (ff_thread_get_buffer(avctx, &frame, 0) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } dst = p->data[0]; for (j = 0; j < avctx->height; j++) { for (i = 0; i < avctx->width; i++) AV_WN32(dst + i * 4, offset_gu); dst += p->linesize[0]; } break; case FRAME_ARITH_RGBA: avctx->pix_fmt = AV_PIX_FMT_RGB32; planes = 4; offset_ry += 4; offs[3] = AV_RL32(buf + 9); case FRAME_ARITH_RGB24: case FRAME_U_RGB24: if (frametype == FRAME_ARITH_RGB24 || frametype == FRAME_U_RGB24) avctx->pix_fmt = AV_PIX_FMT_RGB24; if (ff_thread_get_buffer(avctx, &frame, 0) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } offs[0] = offset_bv; offs[1] = offset_gu; offs[2] = offset_ry; if (!l->rgb_planes) { l->rgb_stride = FFALIGN(avctx->width, 16); l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * planes + 1); if (!l->rgb_planes) { av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n"); return AVERROR(ENOMEM); } } for (i = 0; i < planes; i++) srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride; if (offset_ry >= buf_size || offset_gu >= buf_size || offset_bv >= buf_size || (planes == 4 && offs[3] >= buf_size)) { av_log(avctx, AV_LOG_ERROR, "Invalid frame offsets\n"); return AVERROR_INVALIDDATA; } for (i = 0; i < planes; i++) lag_decode_arith_plane(l, srcs[i], avctx->width, avctx->height, -l->rgb_stride, buf + offs[i], buf_size - offs[i]); dst = p->data[0]; for (i = 0; i < planes; i++) srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height; for (j = 0; j < avctx->height; j++) { for (i = 0; i < avctx->width; i++) { uint8_t r, g, b, a; r = srcs[0][i]; g = srcs[1][i]; b = srcs[2][i]; r += g; b += g; if (frametype == FRAME_ARITH_RGBA) { a = srcs[3][i]; AV_WN32(dst + i * 4, MKBETAG(a, r, g, b)); } else { dst[i * 3 + 0] = r; dst[i * 3 + 1] = g; dst[i * 3 + 2] = b; } } dst += p->linesize[0]; for (i = 0; i < planes; i++) srcs[i] += l->rgb_stride; } break; case FRAME_ARITH_YUY2: avctx->pix_fmt = AV_PIX_FMT_YUV422P; if (ff_thread_get_buffer(avctx, &frame, 0) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } if (offset_ry >= buf_size || offset_gu >= buf_size || offset_bv >= buf_size) { av_log(avctx, AV_LOG_ERROR, "Invalid frame offsets\n"); return AVERROR_INVALIDDATA; } lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height, p->linesize[0], buf + offset_ry, buf_size - offset_ry); lag_decode_arith_plane(l, p->data[1], avctx->width / 2, avctx->height, p->linesize[1], buf + offset_gu, buf_size - offset_gu); lag_decode_arith_plane(l, p->data[2], avctx->width / 2, avctx->height, p->linesize[2], buf + offset_bv, buf_size - offset_bv); break; case FRAME_ARITH_YV12: avctx->pix_fmt = AV_PIX_FMT_YUV420P; if (ff_thread_get_buffer(avctx, &frame, 0) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } if (offset_ry >= buf_size || offset_gu >= buf_size || offset_bv >= buf_size) { av_log(avctx, AV_LOG_ERROR, "Invalid frame offsets\n"); return AVERROR_INVALIDDATA; } lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height, p->linesize[0], buf + offset_ry, buf_size - offset_ry); lag_decode_arith_plane(l, p->data[2], avctx->width / 2, avctx->height / 2, p->linesize[2], buf + offset_gu, buf_size - offset_gu); lag_decode_arith_plane(l, p->data[1], avctx->width / 2, avctx->height / 2, p->linesize[1], buf + offset_bv, buf_size - offset_bv); break; default: av_log(avctx, AV_LOG_ERROR, "Unsupported Lagarith frame type: %#x\n", frametype); return -1; } *got_frame = 1; return buf_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'lagarith: reallocate rgb_planes when needed Fixes invalid writes on pixel format changes. 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: void bpf_jit_compile(struct sk_filter *fp) { u8 temp[64]; u8 *prog; unsigned int proglen, oldproglen = 0; int ilen, i; int t_offset, f_offset; u8 t_op, f_op, seen = 0, pass; u8 *image = NULL; u8 *func; int pc_ret0 = -1; /* bpf index of first RET #0 instruction (if any) */ unsigned int cleanup_addr; /* epilogue code offset */ unsigned int *addrs; const struct sock_filter *filter = fp->insns; int flen = fp->len; if (!bpf_jit_enable) return; addrs = kmalloc(flen * sizeof(*addrs), GFP_KERNEL); if (addrs == NULL) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < flen; i++) { proglen += 64; addrs[i] = proglen; } cleanup_addr = proglen; /* epilogue address */ for (pass = 0; pass < 10; pass++) { /* no prologue/epilogue for trivial filters (RET something) */ proglen = 0; prog = temp; if (seen) { EMIT4(0x55, 0x48, 0x89, 0xe5); /* push %rbp; mov %rsp,%rbp */ EMIT4(0x48, 0x83, 0xec, 96); /* subq $96,%rsp */ /* note : must save %rbx in case bpf_error is hit */ if (seen & (SEEN_XREG | SEEN_DATAREF)) EMIT4(0x48, 0x89, 0x5d, 0xf8); /* mov %rbx, -8(%rbp) */ if (seen & SEEN_XREG) CLEAR_X(); /* make sure we dont leek kernel memory */ /* * If this filter needs to access skb data, * loads r9 and r8 with : * r9 = skb->len - skb->data_len * r8 = skb->data */ if (seen & SEEN_DATAREF) { if (offsetof(struct sk_buff, len) <= 127) /* mov off8(%rdi),%r9d */ EMIT4(0x44, 0x8b, 0x4f, offsetof(struct sk_buff, len)); else { /* mov off32(%rdi),%r9d */ EMIT3(0x44, 0x8b, 0x8f); EMIT(offsetof(struct sk_buff, len), 4); } if (is_imm8(offsetof(struct sk_buff, data_len))) /* sub off8(%rdi),%r9d */ EMIT4(0x44, 0x2b, 0x4f, offsetof(struct sk_buff, data_len)); else { EMIT3(0x44, 0x2b, 0x8f); EMIT(offsetof(struct sk_buff, data_len), 4); } if (is_imm8(offsetof(struct sk_buff, data))) /* mov off8(%rdi),%r8 */ EMIT4(0x4c, 0x8b, 0x47, offsetof(struct sk_buff, data)); else { /* mov off32(%rdi),%r8 */ EMIT3(0x4c, 0x8b, 0x87); EMIT(offsetof(struct sk_buff, data), 4); } } } switch (filter[0].code) { case BPF_S_RET_K: case BPF_S_LD_W_LEN: case BPF_S_ANC_PROTOCOL: case BPF_S_ANC_IFINDEX: case BPF_S_ANC_MARK: case BPF_S_ANC_RXHASH: case BPF_S_ANC_CPU: case BPF_S_ANC_QUEUE: case BPF_S_LD_W_ABS: case BPF_S_LD_H_ABS: case BPF_S_LD_B_ABS: /* first instruction sets A register (or is RET 'constant') */ break; default: /* make sure we dont leak kernel information to user */ CLEAR_A(); /* A = 0 */ } for (i = 0; i < flen; i++) { unsigned int K = filter[i].k; switch (filter[i].code) { case BPF_S_ALU_ADD_X: /* A += X; */ seen |= SEEN_XREG; EMIT2(0x01, 0xd8); /* add %ebx,%eax */ break; case BPF_S_ALU_ADD_K: /* A += K; */ if (!K) break; if (is_imm8(K)) EMIT3(0x83, 0xc0, K); /* add imm8,%eax */ else EMIT1_off32(0x05, K); /* add imm32,%eax */ break; case BPF_S_ALU_SUB_X: /* A -= X; */ seen |= SEEN_XREG; EMIT2(0x29, 0xd8); /* sub %ebx,%eax */ break; case BPF_S_ALU_SUB_K: /* A -= K */ if (!K) break; if (is_imm8(K)) EMIT3(0x83, 0xe8, K); /* sub imm8,%eax */ else EMIT1_off32(0x2d, K); /* sub imm32,%eax */ break; case BPF_S_ALU_MUL_X: /* A *= X; */ seen |= SEEN_XREG; EMIT3(0x0f, 0xaf, 0xc3); /* imul %ebx,%eax */ break; case BPF_S_ALU_MUL_K: /* A *= K */ if (is_imm8(K)) EMIT3(0x6b, 0xc0, K); /* imul imm8,%eax,%eax */ else { EMIT2(0x69, 0xc0); /* imul imm32,%eax */ EMIT(K, 4); } break; case BPF_S_ALU_DIV_X: /* A /= X; */ seen |= SEEN_XREG; EMIT2(0x85, 0xdb); /* test %ebx,%ebx */ if (pc_ret0 != -1) EMIT_COND_JMP(X86_JE, addrs[pc_ret0] - (addrs[i] - 4)); else { EMIT_COND_JMP(X86_JNE, 2 + 5); CLEAR_A(); EMIT1_off32(0xe9, cleanup_addr - (addrs[i] - 4)); /* jmp .+off32 */ } EMIT4(0x31, 0xd2, 0xf7, 0xf3); /* xor %edx,%edx; div %ebx */ break; case BPF_S_ALU_DIV_K: /* A = reciprocal_divide(A, K); */ EMIT3(0x48, 0x69, 0xc0); /* imul imm32,%rax,%rax */ EMIT(K, 4); EMIT4(0x48, 0xc1, 0xe8, 0x20); /* shr $0x20,%rax */ break; case BPF_S_ALU_AND_X: seen |= SEEN_XREG; EMIT2(0x21, 0xd8); /* and %ebx,%eax */ break; case BPF_S_ALU_AND_K: if (K >= 0xFFFFFF00) { EMIT2(0x24, K & 0xFF); /* and imm8,%al */ } else if (K >= 0xFFFF0000) { EMIT2(0x66, 0x25); /* and imm16,%ax */ EMIT2(K, 2); } else { EMIT1_off32(0x25, K); /* and imm32,%eax */ } break; case BPF_S_ALU_OR_X: seen |= SEEN_XREG; EMIT2(0x09, 0xd8); /* or %ebx,%eax */ break; case BPF_S_ALU_OR_K: if (is_imm8(K)) EMIT3(0x83, 0xc8, K); /* or imm8,%eax */ else EMIT1_off32(0x0d, K); /* or imm32,%eax */ break; case BPF_S_ALU_LSH_X: /* A <<= X; */ seen |= SEEN_XREG; EMIT4(0x89, 0xd9, 0xd3, 0xe0); /* mov %ebx,%ecx; shl %cl,%eax */ break; case BPF_S_ALU_LSH_K: if (K == 0) break; else if (K == 1) EMIT2(0xd1, 0xe0); /* shl %eax */ else EMIT3(0xc1, 0xe0, K); break; case BPF_S_ALU_RSH_X: /* A >>= X; */ seen |= SEEN_XREG; EMIT4(0x89, 0xd9, 0xd3, 0xe8); /* mov %ebx,%ecx; shr %cl,%eax */ break; case BPF_S_ALU_RSH_K: /* A >>= K; */ if (K == 0) break; else if (K == 1) EMIT2(0xd1, 0xe8); /* shr %eax */ else EMIT3(0xc1, 0xe8, K); break; case BPF_S_ALU_NEG: EMIT2(0xf7, 0xd8); /* neg %eax */ break; case BPF_S_RET_K: if (!K) { if (pc_ret0 == -1) pc_ret0 = i; CLEAR_A(); } else { EMIT1_off32(0xb8, K); /* mov $imm32,%eax */ } /* fallinto */ case BPF_S_RET_A: if (seen) { if (i != flen - 1) { EMIT_JMP(cleanup_addr - addrs[i]); break; } if (seen & SEEN_XREG) EMIT4(0x48, 0x8b, 0x5d, 0xf8); /* mov -8(%rbp),%rbx */ EMIT1(0xc9); /* leaveq */ } EMIT1(0xc3); /* ret */ break; case BPF_S_MISC_TAX: /* X = A */ seen |= SEEN_XREG; EMIT2(0x89, 0xc3); /* mov %eax,%ebx */ break; case BPF_S_MISC_TXA: /* A = X */ seen |= SEEN_XREG; EMIT2(0x89, 0xd8); /* mov %ebx,%eax */ break; case BPF_S_LD_IMM: /* A = K */ if (!K) CLEAR_A(); else EMIT1_off32(0xb8, K); /* mov $imm32,%eax */ break; case BPF_S_LDX_IMM: /* X = K */ seen |= SEEN_XREG; if (!K) CLEAR_X(); else EMIT1_off32(0xbb, K); /* mov $imm32,%ebx */ break; case BPF_S_LD_MEM: /* A = mem[K] : mov off8(%rbp),%eax */ seen |= SEEN_MEM; EMIT3(0x8b, 0x45, 0xf0 - K*4); break; case BPF_S_LDX_MEM: /* X = mem[K] : mov off8(%rbp),%ebx */ seen |= SEEN_XREG | SEEN_MEM; EMIT3(0x8b, 0x5d, 0xf0 - K*4); break; case BPF_S_ST: /* mem[K] = A : mov %eax,off8(%rbp) */ seen |= SEEN_MEM; EMIT3(0x89, 0x45, 0xf0 - K*4); break; case BPF_S_STX: /* mem[K] = X : mov %ebx,off8(%rbp) */ seen |= SEEN_XREG | SEEN_MEM; EMIT3(0x89, 0x5d, 0xf0 - K*4); break; case BPF_S_LD_W_LEN: /* A = skb->len; */ BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, len) != 4); if (is_imm8(offsetof(struct sk_buff, len))) /* mov off8(%rdi),%eax */ EMIT3(0x8b, 0x47, offsetof(struct sk_buff, len)); else { EMIT2(0x8b, 0x87); EMIT(offsetof(struct sk_buff, len), 4); } break; case BPF_S_LDX_W_LEN: /* X = skb->len; */ seen |= SEEN_XREG; if (is_imm8(offsetof(struct sk_buff, len))) /* mov off8(%rdi),%ebx */ EMIT3(0x8b, 0x5f, offsetof(struct sk_buff, len)); else { EMIT2(0x8b, 0x9f); EMIT(offsetof(struct sk_buff, len), 4); } break; case BPF_S_ANC_PROTOCOL: /* A = ntohs(skb->protocol); */ BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2); if (is_imm8(offsetof(struct sk_buff, protocol))) { /* movzwl off8(%rdi),%eax */ EMIT4(0x0f, 0xb7, 0x47, offsetof(struct sk_buff, protocol)); } else { EMIT3(0x0f, 0xb7, 0x87); /* movzwl off32(%rdi),%eax */ EMIT(offsetof(struct sk_buff, protocol), 4); } EMIT2(0x86, 0xc4); /* ntohs() : xchg %al,%ah */ break; case BPF_S_ANC_IFINDEX: if (is_imm8(offsetof(struct sk_buff, dev))) { /* movq off8(%rdi),%rax */ EMIT4(0x48, 0x8b, 0x47, offsetof(struct sk_buff, dev)); } else { EMIT3(0x48, 0x8b, 0x87); /* movq off32(%rdi),%rax */ EMIT(offsetof(struct sk_buff, dev), 4); } EMIT3(0x48, 0x85, 0xc0); /* test %rax,%rax */ EMIT_COND_JMP(X86_JE, cleanup_addr - (addrs[i] - 6)); BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4); EMIT2(0x8b, 0x80); /* mov off32(%rax),%eax */ EMIT(offsetof(struct net_device, ifindex), 4); break; case BPF_S_ANC_MARK: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4); if (is_imm8(offsetof(struct sk_buff, mark))) { /* mov off8(%rdi),%eax */ EMIT3(0x8b, 0x47, offsetof(struct sk_buff, mark)); } else { EMIT2(0x8b, 0x87); EMIT(offsetof(struct sk_buff, mark), 4); } break; case BPF_S_ANC_RXHASH: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, rxhash) != 4); if (is_imm8(offsetof(struct sk_buff, rxhash))) { /* mov off8(%rdi),%eax */ EMIT3(0x8b, 0x47, offsetof(struct sk_buff, rxhash)); } else { EMIT2(0x8b, 0x87); EMIT(offsetof(struct sk_buff, rxhash), 4); } break; case BPF_S_ANC_QUEUE: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2); if (is_imm8(offsetof(struct sk_buff, queue_mapping))) { /* movzwl off8(%rdi),%eax */ EMIT4(0x0f, 0xb7, 0x47, offsetof(struct sk_buff, queue_mapping)); } else { EMIT3(0x0f, 0xb7, 0x87); /* movzwl off32(%rdi),%eax */ EMIT(offsetof(struct sk_buff, queue_mapping), 4); } break; case BPF_S_ANC_CPU: #ifdef CONFIG_SMP EMIT4(0x65, 0x8b, 0x04, 0x25); /* mov %gs:off32,%eax */ EMIT((u32)(unsigned long)&cpu_number, 4); /* A = smp_processor_id(); */ #else CLEAR_A(); #endif break; case BPF_S_LD_W_ABS: func = sk_load_word; common_load: seen |= SEEN_DATAREF; if ((int)K < 0) goto out; t_offset = func - (image + addrs[i]); EMIT1_off32(0xbe, K); /* mov imm32,%esi */ EMIT1_off32(0xe8, t_offset); /* call */ break; case BPF_S_LD_H_ABS: func = sk_load_half; goto common_load; case BPF_S_LD_B_ABS: func = sk_load_byte; goto common_load; case BPF_S_LDX_B_MSH: if ((int)K < 0) { if (pc_ret0 != -1) { EMIT_JMP(addrs[pc_ret0] - addrs[i]); break; } CLEAR_A(); EMIT_JMP(cleanup_addr - addrs[i]); break; } seen |= SEEN_DATAREF | SEEN_XREG; t_offset = sk_load_byte_msh - (image + addrs[i]); EMIT1_off32(0xbe, K); /* mov imm32,%esi */ EMIT1_off32(0xe8, t_offset); /* call sk_load_byte_msh */ break; case BPF_S_LD_W_IND: func = sk_load_word_ind; common_load_ind: seen |= SEEN_DATAREF | SEEN_XREG; t_offset = func - (image + addrs[i]); EMIT1_off32(0xbe, K); /* mov imm32,%esi */ EMIT1_off32(0xe8, t_offset); /* call sk_load_xxx_ind */ break; case BPF_S_LD_H_IND: func = sk_load_half_ind; goto common_load_ind; case BPF_S_LD_B_IND: func = sk_load_byte_ind; goto common_load_ind; case BPF_S_JMP_JA: t_offset = addrs[i + K] - addrs[i]; EMIT_JMP(t_offset); break; COND_SEL(BPF_S_JMP_JGT_K, X86_JA, X86_JBE); COND_SEL(BPF_S_JMP_JGE_K, X86_JAE, X86_JB); COND_SEL(BPF_S_JMP_JEQ_K, X86_JE, X86_JNE); COND_SEL(BPF_S_JMP_JSET_K,X86_JNE, X86_JE); COND_SEL(BPF_S_JMP_JGT_X, X86_JA, X86_JBE); COND_SEL(BPF_S_JMP_JGE_X, X86_JAE, X86_JB); COND_SEL(BPF_S_JMP_JEQ_X, X86_JE, X86_JNE); COND_SEL(BPF_S_JMP_JSET_X,X86_JNE, X86_JE); cond_branch: f_offset = addrs[i + filter[i].jf] - addrs[i]; t_offset = addrs[i + filter[i].jt] - addrs[i]; /* same targets, can avoid doing the test :) */ if (filter[i].jt == filter[i].jf) { EMIT_JMP(t_offset); break; } switch (filter[i].code) { case BPF_S_JMP_JGT_X: case BPF_S_JMP_JGE_X: case BPF_S_JMP_JEQ_X: seen |= SEEN_XREG; EMIT2(0x39, 0xd8); /* cmp %ebx,%eax */ break; case BPF_S_JMP_JSET_X: seen |= SEEN_XREG; EMIT2(0x85, 0xd8); /* test %ebx,%eax */ break; case BPF_S_JMP_JEQ_K: if (K == 0) { EMIT2(0x85, 0xc0); /* test %eax,%eax */ break; } case BPF_S_JMP_JGT_K: case BPF_S_JMP_JGE_K: if (K <= 127) EMIT3(0x83, 0xf8, K); /* cmp imm8,%eax */ else EMIT1_off32(0x3d, K); /* cmp imm32,%eax */ break; case BPF_S_JMP_JSET_K: if (K <= 0xFF) EMIT2(0xa8, K); /* test imm8,%al */ else if (!(K & 0xFFFF00FF)) EMIT3(0xf6, 0xc4, K >> 8); /* test imm8,%ah */ else if (K <= 0xFFFF) { EMIT2(0x66, 0xa9); /* test imm16,%ax */ EMIT(K, 2); } else { EMIT1_off32(0xa9, K); /* test imm32,%eax */ } break; } if (filter[i].jt != 0) { if (filter[i].jf) t_offset += is_near(f_offset) ? 2 : 6; EMIT_COND_JMP(t_op, t_offset); if (filter[i].jf) EMIT_JMP(f_offset); break; } EMIT_COND_JMP(f_op, f_offset); break; default: /* hmm, too complex filter, give up with jit compiler */ goto out; } ilen = prog - temp; if (image) { if (unlikely(proglen + ilen > oldproglen)) { pr_err("bpb_jit_compile fatal error\n"); kfree(addrs); module_free(NULL, image); return; } memcpy(image + proglen, temp, ilen); } proglen += ilen; addrs[i] = proglen; prog = temp; } /* last bpf instruction is always a RET : * use it to give the cleanup instruction(s) addr */ cleanup_addr = proglen - 1; /* ret */ if (seen) cleanup_addr -= 1; /* leaveq */ if (seen & SEEN_XREG) cleanup_addr -= 4; /* mov -8(%rbp),%rbx */ if (image) { WARN_ON(proglen != oldproglen); break; } if (proglen == oldproglen) { image = module_alloc(max_t(unsigned int, proglen, sizeof(struct work_struct))); if (!image) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) pr_err("flen=%d proglen=%u pass=%d image=%p\n", flen, proglen, pass, image); if (image) { if (bpf_jit_enable > 1) print_hex_dump(KERN_ERR, "JIT code: ", DUMP_PREFIX_ADDRESS, 16, 1, image, proglen, false); bpf_flush_icache(image, image + proglen); fp->bpf_func = (void *)image; } out: kfree(addrs); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'net: bpf_jit: fix an off-one bug in x86_64 cond jump target x86 jump instruction size is 2 or 5 bytes (near/long jump), not 2 or 6 bytes. In case a conditional jump is followed by a long jump, conditional jump target is one byte past the start of target instruction. Signed-off-by: Markus Kötter <nepenthesdev@gmail.com> 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: TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { switch (params->type) { case kTfLiteFloat32: return GatherNd<float, IndicesT>(params, indices, output); case kTfLiteUInt8: return GatherNd<uint8_t, IndicesT>(params, indices, output); case kTfLiteInt8: return GatherNd<int8_t, IndicesT>(params, indices, output); case kTfLiteInt16: return GatherNd<int16_t, IndicesT>(params, indices, output); case kTfLiteInt32: return GatherNd<int32_t, IndicesT>(params, indices, output); case kTfLiteInt64: return GatherNd<int64_t, IndicesT>(params, indices, output); case kTfLiteString: return GatherNdString<IndicesT>(params, indices, output); default: context->ReportError(context, "Params type '%s' are not supported by gather_nd.", TfLiteTypeGetName(params->type)); return kTfLiteError; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent heap OOB read in TFLite's `gather_nd.cc`. Passing negative indices is illegal but there was a missing check so that resulted in OOB accesses. PiperOrigin-RevId: 387208551 Change-Id: I6b7a8a62d3e7c13a16d81619e5bc23ae2cdbc7fd'</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 mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { spinlock_t *ptl; struct vm_area_struct *vma = walk->vma; pte_t *ptep; unsigned char *vec = walk->private; int nr = (end - addr) >> PAGE_SHIFT; ptl = pmd_trans_huge_lock(pmd, vma); if (ptl) { memset(vec, 1, nr); spin_unlock(ptl); goto out; } if (pmd_trans_unstable(pmd)) { __mincore_unmapped_range(addr, end, vma, vec); goto out; } ptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); for (; addr != end; ptep++, addr += PAGE_SIZE) { pte_t pte = *ptep; if (pte_none(pte)) __mincore_unmapped_range(addr, addr + PAGE_SIZE, vma, vec); else if (pte_present(pte)) *vec = 1; else { /* pte is a swap entry */ swp_entry_t entry = pte_to_swp_entry(pte); if (non_swap_entry(entry)) { /* * migration or hwpoison entries are always * uptodate */ *vec = 1; } else { #ifdef CONFIG_SWAP *vec = mincore_page(swap_address_space(entry), swp_offset(entry)); #else WARN_ON(1); *vec = 1; #endif } } vec++; } pte_unmap_unlock(ptep - 1, ptl); out: walk->private += nr; cond_resched(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-319'], 'message': 'Change mincore() to count "mapped" pages rather than "cached" pages The semantics of what "in core" means for the mincore() system call are somewhat unclear, but Linux has always (since 2.3.52, which is when mincore() was initially done) treated it as "page is available in page cache" rather than "page is mapped in the mapping". The problem with that traditional semantic is that it exposes a lot of system cache state that it really probably shouldn't, and that users shouldn't really even care about. So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use). In many ways the old semantics were somewhat insane even aside from the information leak issue. From the very beginning (and that beginning is a long time ago: 2.3.52 was released in March 2000, I think), the code had a comment saying Later we can get more picky about what "in core" means precisely. and this is that "later". Admittedly it is much later than is really comfortable. NOTE! This is a real semantic change, and it is for example known to change the output of "fincore", since that program literally does a mmmap without populating it, and then doing "mincore()" on that mapping that doesn't actually have any pages in it. I'm hoping that nobody actually has any workflow that cares, and the info leak is real. We may have to do something different if it turns out that people have valid reasons to want the old semantics, and if we can limit the information leak sanely. Cc: Kevin Easton <kevin@guarana.org> Cc: Jiri Kosina <jikos@kernel.org> Cc: Masatake YAMATO <yamato@redhat.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Greg KH <gregkh@linuxfoundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Michal Hocko <mhocko@suse.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.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: void pjsua_init_tpselector(pjsua_transport_id tp_id, pjsip_tpselector *sel) { pjsua_transport_data *tpdata; unsigned flag; pj_bzero(sel, sizeof(*sel)); if (tp_id == PJSUA_INVALID_ID) return; pj_assert(tp_id >= 0 && tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata)); tpdata = &pjsua_var.tpdata[tp_id]; flag = pjsip_transport_get_flag_from_type(tpdata->type); if (flag & PJSIP_TRANSPORT_DATAGRAM) { sel->type = PJSIP_TPSELECTOR_TRANSPORT; sel->u.transport = tpdata->data.tp; } else { sel->type = PJSIP_TPSELECTOR_LISTENER; sel->u.listener = tpdata->data.factory; } } ; 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_sha256_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 sha256_ctx ctx; mpz_init(m); rsa_compute_root(key, m, gibberish); res = pkcs1_oaep_decrypt (key->size, m, SHA256_DIGEST_SIZE, &ctx, &nettle_sha256, (nettle_hash_init_func*)&sha256_init, (nettle_hash_update_func*)&sha256_update, (nettle_hash_digest_func*)&sha256_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: CotpConnection_readToTpktBuffer(CotpConnection* self) { uint8_t* buffer = self->readBuffer->buffer; int bufferSize = self->readBuffer->maxSize; int bufPos = self->readBuffer->size; assert (bufferSize > 4); int readBytes; if (bufPos < 4) { readBytes = readFromSocket(self, buffer + bufPos, 4 - bufPos); if (readBytes < 0) goto exit_closed; if (DEBUG_COTP) { if (readBytes > 0) printf("TPKT: read %i bytes from socket\n", readBytes); } bufPos += readBytes; if (bufPos == 4) { if ((buffer[0] == 3) && (buffer[1] == 0)) { self->packetSize = (buffer[2] * 0x100) + buffer[3]; if (DEBUG_COTP) printf("TPKT: header complete (msg size = %i)\n", self->packetSize); if (self->packetSize > bufferSize) { if (DEBUG_COTP) printf("TPKT: packet too large\n"); goto exit_error; } } else { if (DEBUG_COTP) printf("TPKT: failed to decode TPKT header.\n"); goto exit_error; } } else goto exit_waiting; } readBytes = readFromSocket(self, buffer + bufPos, self->packetSize - bufPos); if (readBytes < 0) goto exit_closed; bufPos += readBytes; if (bufPos < self->packetSize) goto exit_waiting; if (DEBUG_COTP) printf("TPKT: message complete (size = %i)\n", self->packetSize); self->readBuffer->size = bufPos; return TPKT_PACKET_COMPLETE; exit_closed: if (DEBUG_COTP) printf("TPKT: socket closed or socket error\n"); return TPKT_ERROR; exit_error: if (DEBUG_COTP) printf("TPKT: Error parsing message\n"); return TPKT_ERROR; exit_waiting: if (DEBUG_COTP) if (bufPos != 0) printf("TPKT: waiting (read %i of %i)\n", bufPos, self->packetSize); self->readBuffer->size = bufPos; return TPKT_WAITING; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122'], 'message': '- COTP: fixed possible heap buffer overflow when handling message with invalid (zero) value in length field (#250)'</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 GTextFieldSave(GTextField *gt,int utf8) { unichar_t *ret; char *cret; FILE *file; unichar_t *pt; if ( _ggadget_use_gettext ) { char *temp = GWidgetOpenFile8(_("Save"),NULL,"*.{txt,py}",NULL,NULL); ret = utf82u_copy(temp); free(temp); } else ret = GWidgetSaveAsFile(GStringGetResource(_STR_Save,NULL),NULL, txt,NULL,NULL); if ( ret==NULL ) return; cret = u2def_copy(ret); free(ret); file = fopen(cret,"w"); if ( file==NULL ) { if ( _ggadget_use_gettext ) GWidgetError8(_("Could not open file"), _("Could not open %.100s"),cret); else GWidgetError(errort,error,cret); free(cret); return; } free(cret); if ( utf8 ) { putc(0xef,file); /* Zero width something or other. Marks this as unicode, utf8 */ putc(0xbb,file); putc(0xbf,file); for ( pt = gt->text ; *pt; ++pt ) { if ( *pt<0x80 ) putc(*pt,file); else if ( *pt<0x800 ) { putc(0xc0 | (*pt>>6), file); putc(0x80 | (*pt&0x3f), file); } else if ( *pt>=0xd800 && *pt<0xdc00 && pt[1]>=0xdc00 && pt[1]<0xe000 ) { int u = ((*pt>>6)&0xf)+1, y = ((*pt&3)<<4) | ((pt[1]>>6)&0xf); putc( 0xf0 | (u>>2),file ); putc( 0x80 | ((u&3)<<4) | ((*pt>>2)&0xf),file ); putc( 0x80 | y,file ); putc( 0x80 | (pt[1]&0x3f),file ); } else { putc( 0xe0 | (*pt>>12),file ); putc( 0x80 | ((*pt>>6)&0x3f),file ); putc( 0x80 | (*pt&0x3f),file ); } } } else { putc(0xfeff>>8,file); /* Zero width something or other. Marks this as unicode */ putc(0xfeff&0xff,file); for ( pt = gt->text ; *pt; ++pt ) { putc(*pt>>8,file); putc(*pt&0xff,file); } } fclose(file); } ; 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: void operator()(OpKernelContext* ctx, bool use_cudnn, bool cudnn_use_autotune, const Tensor& input, const Tensor& filter, int row_dilation, int col_dilation, int row_stride, int col_stride, const Padding& padding, const std::vector<int64>& explicit_paddings, Tensor* output, TensorFormat data_format) { if (data_format != FORMAT_NHWC) { ctx->SetStatus( errors::Unimplemented("The Conv2D op currently only supports the " "NHWC tensor format for integer types. " "The op was given the format: ", ToString(data_format))); return; } const int64 in_depth = GetTensorDim(input, data_format, 'C'); OP_REQUIRES(ctx, in_depth == filter.dim_size(2), errors::Unimplemented( "The Conv2D op currently does not support grouped " "convolutions for integer types. A grouped convolution was " "attempted to be run because the input depth of ", in_depth, " does not match the filter input depth of ", filter.dim_size(2))); for (int64 explicit_padding : explicit_paddings) { if (!FastBoundsCheck(explicit_padding, std::numeric_limits<int>::max())) { ctx->SetStatus(errors::InvalidArgument("filter too large")); return; } } LaunchGeneric<GPUDevice, int32>()( ctx, input, filter, row_stride, col_stride, row_dilation, col_dilation, padding, explicit_paddings, output, data_format); } ; 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: static bool parseOperands(char* str, ArmOp *op) { char *t = strdup (str); int operand = 0; char *token = t; char *x; int imm_count = 0; int mem_opt = 0; if (!token) { return false; } while (token) { char *next = strchr (token, ','); if (next) { *next++ = 0; } while (token[0] == ' ') { token++; } if (operand >= MAX_OPERANDS) { eprintf ("Too many operands\n"); return false; } op->operands[operand].type = ARM_NOTYPE; op->operands[operand].reg_type = ARM_UNDEFINED; op->operands[operand].shift = ARM_NO_SHIFT; while (token[0] == ' ' || token[0] == '[' || token[0] == ']') { token ++; } if (!strncmp (token, "lsl", 3)) { op->operands[operand].shift = ARM_LSL; } else if (!strncmp (token, "lsr", 3)) { op->operands[operand].shift = ARM_LSR; } else if (!strncmp (token, "asr", 3)) { op->operands[operand].shift = ARM_ASR; } if (op->operands[operand].shift != ARM_NO_SHIFT) { op->operands_count ++; op->operands[operand].shift_amount = r_num_math (NULL, token + 4); if (op->operands[operand].shift_amount > 63) { return false; } operand ++; token = next; continue; } switch (token[0]) { case 'x': x = strchr (token, ','); if (x) { x[0] = '\0'; } op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_REG64; op->operands[operand].reg = r_num_math (NULL, token + 1); if (op->operands[operand].reg > 31) { return false; } break; case 'w': op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_REG32; op->operands[operand].reg = r_num_math (NULL, token + 1); if (op->operands[operand].reg > 31) { return false; } break; case 'v': op->operands_count ++; op->operands[operand].type = ARM_FP; op->operands[operand].reg = r_num_math (NULL, token + 1); break; case 's': case 'S': if (token[1] == 'P' || token [1] == 'p') { int i; for (i = 0; msr_const[i].name; i++) { if (!r_str_ncasecmp (token, msr_const[i].name, strlen (msr_const[i].name))) { op->operands[operand].sp_val = msr_const[i].val; break; } } op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_SP | ARM_REG64; op->operands[operand].reg = 31; break; } mem_opt = get_mem_option (token); if (mem_opt != -1) { op->operands_count ++; op->operands[operand].type = ARM_MEM_OPT; op->operands[operand].mem_option = mem_opt; } break; case 'L': case 'l': case 'I': case 'i': case 'N': case 'n': case 'O': case 'o': case 'p': case 'P': mem_opt = get_mem_option (token); if (mem_opt != -1) { op->operands_count ++; op->operands[operand].type = ARM_MEM_OPT; op->operands[operand].mem_option = mem_opt; } break; case '-': op->operands[operand].sign = -1; // falthru default: op->operands_count ++; op->operands[operand].type = ARM_CONSTANT; op->operands[operand].immediate = r_num_math (NULL, token); imm_count++; break; } token = next; operand ++; if (operand > MAX_OPERANDS) { free (t); return false; } } free (t); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix #12417/#12418 (arm assembler heap overflows)'</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 ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; comp->reslevel && reslevelno < codsty->nreslevels; reslevelno++) { Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands; bandno++) { Jpeg2000Band *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) { Jpeg2000Prec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); av_freep(&prec->cblk); } av_freep(&band->prec); } av_freep(&reslevel->band); } ff_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->i_data); av_freep(&comp->f_data); } ; 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: next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'fix #55 : check too big code point value for single byte value in next_state_val()'</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 rijndaelEncrypt(const u32 *rk, int nrounds, const u8 plaintext[16], u8 ciphertext[16]) { u32 s0, s1, s2, s3, t0, t1, t2, t3; #ifndef FULL_UNROLL int r; #endif /* ?FULL_UNROLL */ /* * map byte array block to cipher state * and add initial round key: */ s0 = GETU32(plaintext ) ^ rk[0]; s1 = GETU32(plaintext + 4) ^ rk[1]; s2 = GETU32(plaintext + 8) ^ rk[2]; s3 = GETU32(plaintext + 12) ^ rk[3]; #ifdef FULL_UNROLL /* round 1: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7]; /* round 2: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11]; /* round 3: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15]; /* round 4: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19]; /* round 5: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23]; /* round 6: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27]; /* round 7: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31]; /* round 8: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35]; /* round 9: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39]; if (nrounds > 10) { /* round 10: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43]; /* round 11: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47]; if (nrounds > 12) { /* round 12: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51]; /* round 13: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55]; } } rk += nrounds << 2; #else /* !FULL_UNROLL */ /* * nrounds - 1 full rounds: */ r = nrounds >> 1; for (;;) { t0 = Te0[(s0 >> 24) ] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[(s3 ) & 0xff] ^ rk[4]; t1 = Te0[(s1 >> 24) ] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[(s0 ) & 0xff] ^ rk[5]; t2 = Te0[(s2 >> 24) ] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[(s1 ) & 0xff] ^ rk[6]; t3 = Te0[(s3 >> 24) ] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[(s2 ) & 0xff] ^ rk[7]; rk += 8; if (--r == 0) break; s0 = Te0[(t0 >> 24) ] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[(t3 ) & 0xff] ^ rk[0]; s1 = Te0[(t1 >> 24) ] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[(t0 ) & 0xff] ^ rk[1]; s2 = Te0[(t2 >> 24) ] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[(t1 ) & 0xff] ^ rk[2]; s3 = Te0[(t3 >> 24) ] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[(t2 ) & 0xff] ^ rk[3]; } #endif /* ?FULL_UNROLL */ /* * apply last round and * map cipher state to byte array block: */ s0 = (Te4[(t0 >> 24) ] & 0xff000000) ^ (Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t3 ) & 0xff] & 0x000000ff) ^ rk[0]; PUTU32(ciphertext , s0); s1 = (Te4[(t1 >> 24) ] & 0xff000000) ^ (Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t0 ) & 0xff] & 0x000000ff) ^ rk[1]; PUTU32(ciphertext + 4, s1); s2 = (Te4[(t2 >> 24) ] & 0xff000000) ^ (Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t1 ) & 0xff] & 0x000000ff) ^ rk[2]; PUTU32(ciphertext + 8, s2); s3 = (Te4[(t3 >> 24) ] & 0xff000000) ^ (Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t2 ) & 0xff] & 0x000000ff) ^ rk[3]; PUTU32(ciphertext + 12, s3); } ; 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: JSON::encode_string(std::string const& str) { std::string result; size_t len = str.length(); for (size_t i = 0; i < len; ++i) { unsigned char ch = static_cast<unsigned char>(str.at(i)); switch (ch) { case '\\': result += "\\\\"; break; case '\"': result += "\\\""; break; case '\b': result += "\\b"; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; default: if (ch < 32) { result += "\\u" + QUtil::int_to_string_base(ch, 16, 4); } else { result.append(1, ch); } } } 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_Stream::replaceFilterData(QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms, size_t length) { this->stream_dict.replaceOrRemoveKey("/Filter", filter); this->stream_dict.replaceOrRemoveKey("/DecodeParms", decode_parms); if (length == 0) { QTC::TC("qpdf", "QPDF_Stream unknown stream length"); this->stream_dict.removeKey("/Length"); } else { this->stream_dict.replaceKey( "/Length", QPDFObjectHandle::newInteger(length)); } } ; 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 do_under_overlay_for_page( QPDF& pdf, Options& o, UnderOverlay& uo, std::map<int, std::vector<int> >& pagenos, size_t page_idx, std::map<int, QPDFObjectHandle>& fo, std::vector<QPDFPageObjectHelper>& pages, QPDFPageObjectHelper& dest_page, bool before) { int pageno = 1 + page_idx; if (! pagenos.count(pageno)) { return; } std::string content; int min_suffix = 1; QPDFObjectHandle resources = dest_page.getAttribute("/Resources", true); for (std::vector<int>::iterator iter = pagenos[pageno].begin(); iter != pagenos[pageno].end(); ++iter) { int from_pageno = *iter; if (o.verbose) { std::cout << " " << uo.which << " " << from_pageno << std::endl; } if (0 == fo.count(from_pageno)) { fo[from_pageno] = pdf.copyForeignObject( pages.at(from_pageno - 1).getFormXObjectForPage()); } // If the same page is overlaid or underlaid multiple times, // we'll generate multiple names for it, but that's harmless // and also a pretty goofy case that's not worth coding // around. std::string name = resources.getUniqueResourceName("/Fx", min_suffix); std::string new_content = dest_page.placeFormXObject( fo[from_pageno], name, dest_page.getTrimBox().getArrayAsRectangle()); if (! new_content.empty()) { resources.mergeResources( QPDFObjectHandle::parse("<< /XObject << >> >>")); resources.getKey("/XObject").replaceKey(name, fo[from_pageno]); ++min_suffix; content += new_content; } } if (! content.empty()) { if (before) { dest_page.addPageContents( QPDFObjectHandle::newStream(&pdf, content), true); } else { dest_page.addPageContents( QPDFObjectHandle::newStream(&pdf, "q\n"), true); dest_page.addPageContents( QPDFObjectHandle::newStream(&pdf, "\nQ\n" + 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: Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len) { if (this->eod) { return; } for (size_t i = 0; i < len; ++i) { char ch = toupper(buf[i]); switch (ch) { case ' ': case '\f': case '\v': case '\t': case '\r': case '\n': QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space"); // ignore whitespace break; case '>': this->eod = true; flush(); break; default: if (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'F'))) { this->inbuf[this->pos++] = ch; if (this->pos == 2) { flush(); } } else { char t[2]; t[0] = ch; t[1] = 0; throw std::runtime_error( std::string("character out of range" " during base Hex decode: ") + t); } break; } if (this->eod) { break; } } } ; 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::checkHSharedObject(std::list<std::string>& errors, std::list<std::string>& warnings, std::vector<QPDFObjectHandle> const& pages, std::map<int, int>& idx_to_obj) { // Implementation note 125 says shared object groups always // contain only one object. Implementation note 128 says that // Acrobat always nbits_nobjects to zero. Implementation note 130 // says that Acrobat does not support more than one shared object // per group. These are all consistent. // Implementation note 129 states that MD5 signatures are not // implemented in Acrobat, so signature_present must always be // zero. // Implementation note 131 states that first_shared_obj and // first_shared_offset have meaningless values for single-page // files. // Empirically, Acrobat and pdlin generate incorrect values for // these whenever there are no shared objects not referenced by // the first page (i.e., nshared_total == nshared_first_page). HSharedObject& so = this->m->shared_object_hints; if (so.nshared_total < so.nshared_first_page) { errors.push_back("shared object hint table: ntotal < nfirst_page"); } else { // The first nshared_first_page objects are consecutive // objects starting with the first page object. The rest are // consecutive starting from the first_shared_obj object. int cur_object = pages.at(0).getObjectID(); for (int i = 0; i < so.nshared_total; ++i) { if (i == so.nshared_first_page) { QTC::TC("qpdf", "QPDF lin check shared past first page"); if (this->m->part8.empty()) { errors.push_back( "part 8 is empty but nshared_total > " "nshared_first_page"); } else { int obj = this->m->part8.at(0).getObjectID(); if (obj != so.first_shared_obj) { errors.push_back( "first shared object number mismatch: " "hint table = " + QUtil::int_to_string(so.first_shared_obj) + "; computed = " + QUtil::int_to_string(obj)); } } cur_object = so.first_shared_obj; QPDFObjGen og(cur_object, 0); if (this->m->xref_table.count(og) == 0) { stopOnError("unknown object in shared object hint table"); } int offset = getLinearizationOffset(og); int h_offset = adjusted_offset(so.first_shared_offset); if (offset != h_offset) { errors.push_back( "first shared object offset mismatch: hint table = " + QUtil::int_to_string(h_offset) + "; computed = " + QUtil::int_to_string(offset)); } } idx_to_obj[i] = cur_object; HSharedObjectEntry& se = so.entries.at(i); int nobjects = se.nobjects_minus_one + 1; int length = lengthNextN(cur_object, nobjects, errors); int h_length = so.min_group_length + se.delta_group_length; if (length != h_length) { errors.push_back( "shared object " + QUtil::int_to_string(i) + " length mismatch: hint table = " + QUtil::int_to_string(h_length) + "; computed = " + QUtil::int_to_string(length)); } cur_object += nobjects; } } } ; 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: write_vector_vector(BitWriter& w, int nitems1, std::vector<T>& vec1, int T::*nitems2, int bits, std::vector<int> T::*vec2) { // nitems1 times, write nitems2 (from the ith element of vec1) items // from the vec2 vector field of the ith item of vec1. for (int i1 = 0; i1 < nitems1; ++i1) { for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) { w.writeBits((vec1.at(i1).*vec2).at(i2), bits); } } w.flush(); } ; 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_enc16le(void *dst, unsigned val) { ((unsigned char *)dst)[0] = val; ((unsigned char *)dst)[1] = val >> 8; } ; 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: QUtil::hex_decode(std::string const& input) { std::string result; size_t pos = 0; for (std::string::const_iterator p = input.begin(); p != input.end(); ++p) { char ch = *p; bool skip = false; if ((*p >= 'A') && (*p <= 'F')) { ch -= 'A'; ch += 10; } else if ((*p >= 'a') && (*p <= 'f')) { ch -= 'a'; ch += 10; } else if ((*p >= '0') && (*p <= '9')) { ch -= '0'; } else { skip = true; } if (! skip) { if (pos == 0) { result.push_back(ch << 4); pos = 1; } else { result[result.length()-1] += ch; pos = 0; } } } 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: void MD5::encodeString(char const* str) { unsigned int len = strlen(str); update(QUtil::unsigned_char_pointer(str), len); final(); } ; 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 handle_page_specs(QPDF& pdf, Options& o) { // Parse all page specifications and translate them into lists of // actual pages. // Handle "." as a shortcut for the input file for (std::vector<PageSpec>::iterator iter = o.page_specs.begin(); iter != o.page_specs.end(); ++iter) { PageSpec& page_spec = *iter; if (page_spec.filename == ".") { page_spec.filename = o.infilename; } } if (! o.keep_files_open_set) { // Count the number of distinct files to determine whether we // should keep files open or not. Rather than trying to code // some portable heuristic based on OS limits, just hard-code // this at a given number and allow users to override. std::set<std::string> filenames; for (std::vector<PageSpec>::iterator iter = o.page_specs.begin(); iter != o.page_specs.end(); ++iter) { PageSpec& page_spec = *iter; filenames.insert(page_spec.filename); } if (filenames.size() > o.keep_files_open_threshold) { QTC::TC("qpdf", "qpdf disable keep files open"); if (o.verbose) { std::cout << whoami << ": selecting --keep-open-files=n" << std::endl; } o.keep_files_open = false; } else { if (o.verbose) { std::cout << whoami << ": selecting --keep-open-files=y" << std::endl; } o.keep_files_open = true; QTC::TC("qpdf", "qpdf don't disable keep files open"); } } // Create a QPDF object for each file that we may take pages from. std::vector<PointerHolder<QPDF> > page_heap; std::map<std::string, QPDF*> page_spec_qpdfs; std::map<std::string, ClosedFileInputSource*> page_spec_cfis; page_spec_qpdfs[o.infilename] = &pdf; std::vector<QPDFPageData> parsed_specs; std::map<unsigned long long, std::set<QPDFObjGen> > copied_pages; for (std::vector<PageSpec>::iterator iter = o.page_specs.begin(); iter != o.page_specs.end(); ++iter) { PageSpec& page_spec = *iter; if (page_spec_qpdfs.count(page_spec.filename) == 0) { // Open the PDF file and store the QPDF object. Throw a // PointerHolder to the qpdf into a heap so that it // survives through copying to the output but gets cleaned up // automatically at the end. Do not canonicalize the file // name. Using two different paths to refer to the same // file is a document workaround for duplicating a page. // If you are using this an example of how to do this with // the API, you can just create two different QPDF objects // to the same underlying file with the same path to // achieve the same affect. char const* password = page_spec.password; if (o.encryption_file && (password == 0) && (page_spec.filename == o.encryption_file)) { QTC::TC("qpdf", "qpdf pages encryption password"); password = o.encryption_file_password; } if (o.verbose) { std::cout << whoami << ": processing " << page_spec.filename << std::endl; } PointerHolder<InputSource> is; ClosedFileInputSource* cis = 0; if (! o.keep_files_open) { QTC::TC("qpdf", "qpdf keep files open n"); cis = new ClosedFileInputSource(page_spec.filename.c_str()); is = cis; cis->stayOpen(true); } else { QTC::TC("qpdf", "qpdf keep files open y"); FileInputSource* fis = new FileInputSource(); is = fis; fis->setFilename(page_spec.filename.c_str()); } PointerHolder<QPDF> qpdf_ph = process_input_source(is, password, o); page_heap.push_back(qpdf_ph); page_spec_qpdfs[page_spec.filename] = qpdf_ph.getPointer(); if (cis) { cis->stayOpen(false); page_spec_cfis[page_spec.filename] = cis; } } // Read original pages from the PDF, and parse the page range // associated with this occurrence of the file. parsed_specs.push_back( QPDFPageData(page_spec.filename, page_spec_qpdfs[page_spec.filename], page_spec.range)); } if (! o.preserve_unreferenced_page_resources) { for (std::map<std::string, QPDF*>::iterator iter = page_spec_qpdfs.begin(); iter != page_spec_qpdfs.end(); ++iter) { std::string const& filename = (*iter).first; ClosedFileInputSource* cis = 0; if (page_spec_cfis.count(filename)) { cis = page_spec_cfis[filename]; cis->stayOpen(true); } QPDFPageDocumentHelper dh(*((*iter).second)); dh.removeUnreferencedResources(); if (cis) { cis->stayOpen(false); } } } // Clear all pages out of the primary QPDF's pages tree but leave // the objects in place in the file so they can be re-added // without changing their object numbers. This enables other // things in the original file, such as outlines, to continue to // work. if (o.verbose) { std::cout << whoami << ": removing unreferenced pages from primary input" << std::endl; } QPDFPageDocumentHelper dh(pdf); std::vector<QPDFPageObjectHelper> orig_pages = dh.getAllPages(); for (std::vector<QPDFPageObjectHelper>::iterator iter = orig_pages.begin(); iter != orig_pages.end(); ++iter) { dh.removePage(*iter); } if (o.collate && (parsed_specs.size() > 1)) { // Collate the pages by selecting one page from each spec in // order. When a spec runs out of pages, stop selecting from // it. std::vector<QPDFPageData> new_parsed_specs; size_t nspecs = parsed_specs.size(); size_t cur_page = 0; bool got_pages = true; while (got_pages) { got_pages = false; for (size_t i = 0; i < nspecs; ++i) { QPDFPageData& page_data = parsed_specs.at(i); if (cur_page < page_data.selected_pages.size()) { got_pages = true; new_parsed_specs.push_back( QPDFPageData( page_data, page_data.selected_pages.at(cur_page))); } } ++cur_page; } parsed_specs = new_parsed_specs; } // Add all the pages from all the files in the order specified. // Keep track of any pages from the original file that we are // selecting. std::set<int> selected_from_orig; std::vector<QPDFObjectHandle> new_labels; bool any_page_labels = false; int out_pageno = 0; for (std::vector<QPDFPageData>::iterator iter = parsed_specs.begin(); iter != parsed_specs.end(); ++iter) { QPDFPageData& page_data = *iter; ClosedFileInputSource* cis = 0; if (page_spec_cfis.count(page_data.filename)) { cis = page_spec_cfis[page_data.filename]; cis->stayOpen(true); } QPDFPageLabelDocumentHelper pldh(*page_data.qpdf); if (pldh.hasPageLabels()) { any_page_labels = true; } if (o.verbose) { std::cout << whoami << ": adding pages from " << page_data.filename << std::endl; } for (std::vector<int>::iterator pageno_iter = page_data.selected_pages.begin(); pageno_iter != page_data.selected_pages.end(); ++pageno_iter, ++out_pageno) { // Pages are specified from 1 but numbered from 0 in the // vector int pageno = *pageno_iter - 1; pldh.getLabelsForPageRange(pageno, pageno, out_pageno, new_labels); QPDFPageObjectHelper to_copy = page_data.orig_pages.at(pageno); QPDFObjGen to_copy_og = to_copy.getObjectHandle().getObjGen(); unsigned long long from_uuid = page_data.qpdf->getUniqueId(); if (copied_pages[from_uuid].count(to_copy_og)) { QTC::TC("qpdf", "qpdf copy same page more than once", (page_data.qpdf == &pdf) ? 0 : 1); to_copy = to_copy.shallowCopyPage(); } else { copied_pages[from_uuid].insert(to_copy_og); } dh.addPage(to_copy, false); if (page_data.qpdf == &pdf) { // This is a page from the original file. Keep track // of the fact that we are using it. selected_from_orig.insert(pageno); } } if (cis) { cis->stayOpen(false); } } if (any_page_labels) { QPDFObjectHandle page_labels = QPDFObjectHandle::newDictionary(); page_labels.replaceKey( "/Nums", QPDFObjectHandle::newArray(new_labels)); pdf.getRoot().replaceKey("/PageLabels", page_labels); } // Delete page objects for unused page in primary. This prevents // those objects from being preserved by being referred to from // other places, such as the outlines dictionary. for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno) { if (selected_from_orig.count(pageno) == 0) { pdf.replaceObject( orig_pages.at(pageno).getObjectHandle().getObjGen(), QPDFObjectHandle::newNull()); } } } ; 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: QPDFAcroFormDocumentHelper::traverseField( QPDFObjectHandle field, QPDFObjectHandle parent, int depth, std::set<QPDFObjGen>& visited) { if (depth > 100) { // Arbitrarily cut off recursion at a fixed depth to avoid // specially crafted files that could cause stack overflow. return; } if (! field.isIndirect()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper direct field"); field.warnIfPossible( "encountered a direct object as a field or annotation while" " traversing /AcroForm; ignoring field or annotation"); return; } if (! field.isDictionary()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper non-dictionary field"); field.warnIfPossible( "encountered a non-dictionary as a field or annotation while" " traversing /AcroForm; ignoring field or annotation"); return; } QPDFObjGen og(field.getObjGen()); if (visited.count(og) != 0) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper loop"); field.warnIfPossible("loop detected while traversing /AcroForm"); return; } visited.insert(og); // A dictionary encountered while traversing the /AcroForm field // may be a form field, an annotation, or the merger of the two. A // field that has no fields below it is a terminal. If a terminal // field looks like an annotation, it is an annotation because // annotation dictionary fields can be merged with terminal field // dictionaries. Otherwise, the annotation fields might be there // to be inherited by annotations below it. bool is_annotation = false; bool is_field = (0 == depth); QPDFObjectHandle kids = field.getKey("/Kids"); if (kids.isArray()) { is_field = true; size_t nkids = kids.getArrayNItems(); for (size_t k = 0; k < nkids; ++k) { traverseField(kids.getArrayItem(k), field, 1 + depth, visited); } } else { if (field.hasKey("/Parent")) { is_field = true; } if (field.hasKey("/Subtype") || field.hasKey("/Rect") || field.hasKey("/AP")) { is_annotation = true; } } QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field found", (depth == 0) ? 0 : 1); QTC::TC("qpdf", "QPDFAcroFormDocumentHelper annotation found", (is_field ? 0 : 1)); if (is_annotation) { QPDFObjectHandle our_field = (is_field ? field : parent); this->m->field_to_annotations[our_field.getObjGen()].push_back( QPDFAnnotationObjectHelper(field)); this->m->annotation_to_field[og] = QPDFFormFieldObjectHelper(our_field); } } ; 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::trim_user_password(std::string& user_password) { // Although unnecessary, this routine trims the padding string // from the end of a user password. Its only purpose is for // recovery of user passwords which is done in the test suite. char const* cstr = user_password.c_str(); size_t len = user_password.length(); if (len < key_bytes) { return; } char const* p1 = cstr; char const* p2 = 0; while ((p2 = strchr(p1, '\x28')) != 0) { if (memcmp(p2, padding_string, len - (p2 - cstr)) == 0) { user_password = user_password.substr(0, p2 - cstr); return; } else { QTC::TC("qpdf", "QPDF_encryption skip 0x28"); p1 = p2 + 1; } } } ; 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: MD5::checkDataChecksum(char const* const checksum, char const* buf, int len) { std::string actual_checksum = getDataChecksum(buf, len); return (checksum == actual_checksum); } ; 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: void run(char const* filename, char const* filter, bool encode, unsigned int columns, int bits_per_sample, int samples_per_pixel) { FILE* in = QUtil::safe_fopen(filename, "rb"); FILE* o1 = QUtil::safe_fopen("out", "wb"); Pipeline* out = new Pl_StdioFile("out", o1); Pipeline* pl = 0; if (strcmp(filter, "png") == 0) { pl = new Pl_PNGFilter( "png", out, encode ? Pl_PNGFilter::a_encode : Pl_PNGFilter::a_decode, columns, samples_per_pixel, bits_per_sample); } else if (strcmp(filter, "tiff") == 0) { pl = new Pl_TIFFPredictor( "png", out, encode ? Pl_TIFFPredictor::a_encode : Pl_TIFFPredictor::a_decode, columns, samples_per_pixel, bits_per_sample); } else { std::cerr << "unknown filter " << filter << std::endl; exit(2); } assert((2 * (columns + 1)) < 1024); unsigned char buf[1024]; size_t len; while (true) { len = fread(buf, 1, (2 * columns) + 1, in); if (len == 0) { break; } pl->write(buf, len); len = fread(buf, 1, 1, in); if (len == 0) { break; } pl->write(buf, len); len = fread(buf, 1, 1, in); if (len == 0) { break; } pl->write(buf, len); } pl->finish(); delete pl; delete out; fclose(o1); fclose(in); std::cout << "done" << std::endl; } ; 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::outputLengthNextN( int in_object, int n, std::map<int, qpdf_offset_t> const& lengths, std::map<int, int> const& obj_renumber) { // Figure out the length of a series of n consecutive objects in // the output file starting with whatever object in_object from // the input file mapped to. if (obj_renumber.count(in_object) == 0) { stopOnError("found object that is not renumbered while" " writing linearization data"); } int first = (*(obj_renumber.find(in_object))).second; int length = 0; for (int i = 0; i < n; ++i) { if (lengths.count(first + i) == 0) { stopOnError("found item with unknown length" " while writing linearization data"); } length += (*(lengths.find(first + i))).second; } return length; } ; 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::read_xrefTable(qpdf_offset_t xref_offset) { std::vector<QPDFObjGen> deleted_items; this->m->file->seek(xref_offset, SEEK_SET); bool done = false; while (! done) { char linebuf[51]; memset(linebuf, 0, sizeof(linebuf)); this->m->file->read(linebuf, sizeof(linebuf) - 1); std::string line = linebuf; int obj = 0; int num = 0; int bytes = 0; if (! parse_xrefFirst(line, obj, num, bytes)) { QTC::TC("qpdf", "QPDF invalid xref"); throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "xref table", this->m->file->getLastOffset(), "xref syntax invalid"); } this->m->file->seek(this->m->file->getLastOffset() + bytes, SEEK_SET); for (qpdf_offset_t i = obj; i - num < obj; ++i) { if (i == 0) { // This is needed by checkLinearization() this->m->first_xref_item_offset = this->m->file->tell(); } std::string xref_entry = this->m->file->readLine(30); // For xref_table, these will always be small enough to be ints qpdf_offset_t f1 = 0; int f2 = 0; char type = '\0'; if (! parse_xrefEntry(xref_entry, f1, f2, type)) { QTC::TC("qpdf", "QPDF invalid xref entry"); throw QPDFExc( qpdf_e_damaged_pdf, this->m->file->getName(), "xref table", this->m->file->getLastOffset(), "invalid xref entry (obj=" + QUtil::int_to_string(i) + ")"); } if (type == 'f') { // Save deleted items until after we've checked the // XRefStm, if any. deleted_items.push_back(QPDFObjGen(i, f2)); } else { insertXrefEntry(i, 1, f1, f2); } } qpdf_offset_t pos = this->m->file->tell(); QPDFTokenizer::Token t = readToken(this->m->file); if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer")) { done = true; } else { this->m->file->seek(pos, SEEK_SET); } } // Set offset to previous xref table if any QPDFObjectHandle cur_trailer = readObject(this->m->file, "trailer", 0, 0, false); if (! cur_trailer.isDictionary()) { QTC::TC("qpdf", "QPDF missing trailer"); throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", this->m->file->getLastOffset(), "expected trailer dictionary"); } if (! this->m->trailer.isInitialized()) { setTrailer(cur_trailer); if (! this->m->trailer.hasKey("/Size")) { QTC::TC("qpdf", "QPDF trailer lacks size"); throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "trailer", this->m->file->getLastOffset(), "trailer dictionary lacks /Size key"); } if (! this->m->trailer.getKey("/Size").isInteger()) { QTC::TC("qpdf", "QPDF trailer size not integer"); throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "trailer", this->m->file->getLastOffset(), "/Size key in trailer dictionary is not " "an integer"); } } if (cur_trailer.hasKey("/XRefStm")) { if (this->m->ignore_xref_streams) { QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer"); } else { if (cur_trailer.getKey("/XRefStm").isInteger()) { // Read the xref stream but disregard any return value // -- we'll use our trailer's /Prev key instead of the // xref stream's. (void) read_xrefStream( cur_trailer.getKey("/XRefStm").getIntValue()); } else { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "xref stream", xref_offset, "invalid /XRefStm"); } } } // Handle any deleted items now that we've read the /XRefStm. for (std::vector<QPDFObjGen>::iterator iter = deleted_items.begin(); iter != deleted_items.end(); ++iter) { QPDFObjGen& og = *iter; insertXrefEntry(og.getObj(), 0, 0, og.getGen()); } if (cur_trailer.hasKey("/Prev")) { if (! cur_trailer.getKey("/Prev").isInteger()) { QTC::TC("qpdf", "QPDF trailer prev not integer"); throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "trailer", this->m->file->getLastOffset(), "/Prev key in trailer dictionary is not " "an integer"); } QTC::TC("qpdf", "QPDF prev key in trailer dictionary"); xref_offset = cur_trailer.getKey("/Prev").getIntValue(); } else { xref_offset = 0; } return xref_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: MD5::checkFileChecksum(char const* const checksum, char const* filename, int up_to_size) { bool result = false; try { std::string actual_checksum = getFileChecksum(filename, up_to_size); result = (checksum == actual_checksum); } catch (std::runtime_error const&) { // Ignore -- return false } 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: ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) { PointerHolder<Pipeline> result; QPDFObjectHandle dict = image.getDict(); QPDFObjectHandle w_obj = dict.getKey("/Width"); QPDFObjectHandle h_obj = dict.getKey("/Height"); QPDFObjectHandle colorspace_obj = dict.getKey("/ColorSpace"); if (! (w_obj.isNumber() && h_obj.isNumber())) { if (o.verbose && (! description.empty())) { std::cout << whoami << ": " << description << ": not optimizing because image dictionary" << " is missing required keys" << std::endl; } return result; } QPDFObjectHandle components_obj = dict.getKey("/BitsPerComponent"); if (! (components_obj.isInteger() && (components_obj.getIntValue() == 8))) { QTC::TC("qpdf", "qpdf image optimize bits per component"); if (o.verbose && (! description.empty())) { std::cout << whoami << ": " << description << ": not optimizing because image has other than" << " 8 bits per component" << std::endl; } return result; } // Files have been seen in the wild whose width and height are // floating point, which is goofy, but we can deal with it. JDIMENSION w = static_cast<JDIMENSION>( w_obj.isInteger() ? w_obj.getIntValue() : w_obj.getNumericValue()); JDIMENSION h = static_cast<JDIMENSION>( h_obj.isInteger() ? h_obj.getIntValue() : h_obj.getNumericValue()); std::string colorspace = (colorspace_obj.isName() ? colorspace_obj.getName() : std::string()); int components = 0; J_COLOR_SPACE cs = JCS_UNKNOWN; if (colorspace == "/DeviceRGB") { components = 3; cs = JCS_RGB; } else if (colorspace == "/DeviceGray") { components = 1; cs = JCS_GRAYSCALE; } else if (colorspace == "/DeviceCMYK") { components = 4; cs = JCS_CMYK; } else { QTC::TC("qpdf", "qpdf image optimize colorspace"); if (o.verbose && (! description.empty())) { std::cout << whoami << ": " << description << ": not optimizing because qpdf can't optimize" << " images with this colorspace" << std::endl; } return result; } if (((o.oi_min_width > 0) && (w <= o.oi_min_width)) || ((o.oi_min_height > 0) && (h <= o.oi_min_height)) || ((o.oi_min_area > 0) && ((w * h) <= o.oi_min_area))) { QTC::TC("qpdf", "qpdf image optimize too small"); if (o.verbose && (! description.empty())) { std::cout << whoami << ": " << description << ": not optimizing because image" << " is smaller than requested minimum dimensions" << std::endl; } return result; } result = new Pl_DCT("jpg", next, w, h, components, cs); 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: WindowsCryptProvider() { if (!CryptAcquireContext(&crypt_prov, "Container", NULL, PROV_RSA_FULL, 0)) { #if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsign-compare" #endif if (GetLastError() == NTE_BAD_KEYSET) #if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ defined(__clang__)) # pragma GCC diagnostic pop #endif { if (! CryptAcquireContext(&crypt_prov, "Container", NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) { throw std::runtime_error( "unable to acquire crypt context with new keyset"); } } else { throw std::runtime_error("unable to acquire crypt context"); } } } ; 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: QUtil::toUTF16(unsigned long uval) { std::string result; if ((uval >= 0xd800) && (uval <= 0xdfff)) { result = "\xff\xfd"; } else if (uval <= 0xffff) { char out[2]; out[0] = (uval & 0xff00) >> 8; out[1] = (uval & 0xff); result = std::string(out, 2); } else if (uval <= 0x10ffff) { char out[4]; uval -= 0x10000; unsigned short high = ((uval & 0xffc00) >> 10) + 0xd800; unsigned short low = (uval & 0x3ff) + 0xdc00; out[0] = (high & 0xff00) >> 8; out[1] = (high & 0xff); out[2] = (low & 0xff00) >> 8; out[3] = (low & 0xff); result = std::string(out, 4); } else { result = "\xff\xfd"; } 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: QPDFWriter::doWriteSetup() { if (this->m->did_write_setup) { return; } this->m->did_write_setup = true; // Do preliminary setup if (this->m->linearized) { this->m->qdf_mode = false; } if (this->m->pclm) { this->m->stream_decode_level = qpdf_dl_none; this->m->compress_streams = false; this->m->encrypted = false; } if (this->m->qdf_mode) { if (! this->m->normalize_content_set) { this->m->normalize_content = true; } if (! this->m->compress_streams_set) { this->m->compress_streams = false; } if (! this->m->stream_decode_level_set) { this->m->stream_decode_level = qpdf_dl_generalized; } } if (this->m->encrypted) { // Encryption has been explicitly set this->m->preserve_encryption = false; } else if (this->m->normalize_content || this->m->stream_decode_level || this->m->pclm || this->m->qdf_mode) { // Encryption makes looking at contents pretty useless. If // the user explicitly encrypted though, we still obey that. this->m->preserve_encryption = false; } if (this->m->preserve_encryption) { copyEncryptionParameters(this->m->pdf); } if (! this->m->forced_pdf_version.empty()) { int major = 0; int minor = 0; parseVersion(this->m->forced_pdf_version, major, minor); disableIncompatibleEncryption(major, minor, this->m->forced_extension_level); if (compareVersions(major, minor, 1, 5) < 0) { QTC::TC("qpdf", "QPDFWriter forcing object stream disable"); this->m->object_stream_mode = qpdf_o_disable; } } if (this->m->qdf_mode || this->m->normalize_content || this->m->stream_decode_level) { initializeSpecialStreams(); } if (this->m->qdf_mode) { // Generate indirect stream lengths for qdf mode since fix-qdf // uses them for storing recomputed stream length data. // Certain streams such as object streams, xref streams, and // hint streams always get direct stream lengths. this->m->direct_stream_lengths = false; } switch (this->m->object_stream_mode) { case qpdf_o_disable: // no action required break; case qpdf_o_preserve: preserveObjectStreams(); break; case qpdf_o_generate: generateObjectStreams(); break; // no default so gcc will warn for missing case tag } if (this->m->linearized) { // Page dictionaries are not allowed to be compressed objects. std::vector<QPDFObjectHandle> pages = this->m->pdf.getAllPages(); for (std::vector<QPDFObjectHandle>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { QPDFObjectHandle& page = *iter; QPDFObjGen og = page.getObjGen(); if (this->m->object_to_object_stream.count(og)) { QTC::TC("qpdf", "QPDFWriter uncompressing page dictionary"); this->m->object_to_object_stream.erase(og); } } } if (this->m->linearized || this->m->encrypted) { // The document catalog is not allowed to be compressed in // linearized files either. It also appears that Adobe Reader // 8.0.0 has a bug that prevents it from being able to handle // encrypted files with compressed document catalogs, so we // disable them in that case as well. QPDFObjGen og = this->m->pdf.getRoot().getObjGen(); if (this->m->object_to_object_stream.count(og)) { QTC::TC("qpdf", "QPDFWriter uncompressing root"); this->m->object_to_object_stream.erase(og); } } // Generate reverse mapping from object stream to objects for (std::map<QPDFObjGen, int>::iterator iter = this->m->object_to_object_stream.begin(); iter != this->m->object_to_object_stream.end(); ++iter) { QPDFObjGen obj = (*iter).first; int stream = (*iter).second; this->m->object_stream_to_objects[stream].insert(obj); this->m->max_ostream_index = std::max(this->m->max_ostream_index, static_cast<int>( this->m->object_stream_to_objects[stream].size()) - 1); } if (! this->m->object_stream_to_objects.empty()) { setMinimumPDFVersion("1.5"); } setMinimumPDFVersion(this->m->pdf.getPDFVersion(), this->m->pdf.getExtensionLevel()); this->m->final_pdf_version = this->m->min_pdf_version; this->m->final_extension_level = this->m->min_extension_level; if (! this->m->forced_pdf_version.empty()) { QTC::TC("qpdf", "QPDFWriter using forced PDF version"); this->m->final_pdf_version = this->m->forced_pdf_version; this->m->final_extension_level = this->m->forced_extension_level; } } ; 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::getBitsSigned(int nbits) { unsigned long long bits = read_bits(this->p, this->bit_offset, this->bits_available, nbits); long long result = 0; if (static_cast<long long>(bits) > 1 << (nbits - 1)) { result = static_cast<long long>(bits - (1 << nbits)); } else { result = static_cast<long long>(bits); } 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_Stream::understandDecodeParams( std::string const& filter, QPDFObjectHandle decode_obj, int& predictor, int& columns, int& colors, int& bits_per_component, bool& early_code_change) { bool filterable = true; std::set<std::string> keys = decode_obj.getKeys(); for (std::set<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { std::string const& key = *iter; if (((filter == "/FlateDecode") || (filter == "/LZWDecode")) && (key == "/Predictor")) { QPDFObjectHandle predictor_obj = decode_obj.getKey(key); if (predictor_obj.isInteger()) { predictor = predictor_obj.getIntValue(); if (! ((predictor == 1) || (predictor == 2) || ((predictor >= 10) && (predictor <= 15)))) { filterable = false; } } else { filterable = false; } } else if ((filter == "/LZWDecode") && (key == "/EarlyChange")) { QPDFObjectHandle earlychange_obj = decode_obj.getKey(key); if (earlychange_obj.isInteger()) { int earlychange = earlychange_obj.getIntValue(); early_code_change = (earlychange == 1); if (! ((earlychange == 0) || (earlychange == 1))) { filterable = false; } } else { filterable = false; } } else if ((key == "/Columns") || (key == "/Colors") || (key == "/BitsPerComponent")) { QPDFObjectHandle param_obj = decode_obj.getKey(key); if (param_obj.isInteger()) { int val = param_obj.getIntValue(); if (key == "/Columns") { columns = val; } else if (key == "/Colors") { colors = val; } else if (key == "/BitsPerComponent") { bits_per_component = val; } } else { filterable = false; } } else if ((filter == "/Crypt") && (((key == "/Type") || (key == "/Name")) && (decode_obj.getKey("/Type").isNull() || (decode_obj.getKey("/Type").isName() && (decode_obj.getKey("/Type").getName() == "/CryptFilterDecodeParms"))))) { // we handle this in decryptStream } else { filterable = false; } } return filterable; } ; 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 const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf, RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da, size_t offset, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7); ut64 abbr_code; size_t i; if (cu->hdr.length > debug_str_len) { //avoid oob read return NULL; } while (buf && buf < buf_end && buf >= obuf) { if (cu->length && cu->capacity == cu->length) { r_bin_dwarf_expand_cu (cu); } buf = r_uleb128 (buf, buf_end - buf, &abbr_code); if (abbr_code > da->length || !buf) { return NULL; } r_bin_dwarf_init_die (&cu->dies[cu->length]); if (!abbr_code) { cu->dies[cu->length].abbrev_code = 0; cu->length++; buf++; continue; } cu->dies[cu->length].abbrev_code = abbr_code; cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag; abbr_code += offset; if (da->capacity < abbr_code) { return NULL; } for (i = 0; i < da->decls[abbr_code - 1].length; i++) { if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) { r_bin_dwarf_expand_die (&cu->dies[cu->length]); } if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) { eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n"); break; } memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i])); buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf, &da->decls[abbr_code - 1].specs[i], &cu->dies[cu->length].attr_values[i], &cu->hdr, debug_str, debug_str_len); if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) { const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string; sdb_set (s, "DW_AT_comp_dir", name, 0); } cu->dies[cu->length].length++; } cu->length++; } return buf; } ; 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: proc_lambda(mrb_state *mrb, mrb_value self) { mrb_value blk; struct RProc *p; mrb_get_args(mrb, "&", &blk); if (mrb_nil_p(blk)) { mrb_raise(mrb, E_ARGUMENT_ERROR, "tried to create Proc object without a block"); } if (!mrb_proc_p(blk)) { mrb_raise(mrb, E_ARGUMENT_ERROR, "not a proc"); } p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p)) { struct RProc *p2 = MRB_OBJ_ALLOC(mrb, MRB_TT_PROC, p->c); mrb_proc_copy(p2, p); p2->flags |= MRB_PROC_STRICT; return mrb_obj_value(p2); } return blk; } ; 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::AllocateTensors() { TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "AllocateTensors"); if (!consistent_) { ReportError("AllocateTensors() called on inconsistent model."); return kTfLiteError; } // Restore delegation state if applicable. TF_LITE_ENSURE_STATUS(RedoAllDelegates()); // Explicit (re)allocation is necessary if nodes have been changed or tensors // have been resized. For inputs marked as dynamic, we can't short-circuit the // allocation as the client may have done the resize manually. if (state_ != kStateUninvokable && !HasDynamicTensorImpl(context_, inputs())) { if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { // If the only change was the release of non-persistent memory via // ReleaseNonPersistentMemory(), just re-allocate it. For any other type // of memory-planning change (for eg, ResizeInputTensor), the state would // be kStateUninvokable. memory_planner_->AcquireNonPersistentMemory(); } return kTfLiteOk; } next_execution_plan_index_to_prepare_ = 0; next_execution_plan_index_to_plan_allocation_ = 0; next_original_execution_plan_index_to_prepare_ = 0; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocations()); } TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); state_ = kStateInvokable; // Reset the variable tensors to zero after (re)allocating the tensors. // Developers shouldn't rely on the side effect of this function to reset // variable tensors. They should call `ResetVariableTensors` directly // instead. ResetVariableTensors(); return kTfLiteOk; } ; 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: static bool extractFileTo(zip* zip, const std::string &file, std::string& to, char* buf, size_t len) { auto sep = file.rfind('/'); if (sep != std::string::npos) { auto path = to + file.substr(0, sep); if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) { return false; } if (sep == file.length() - 1) { return true; } } to.append(file); struct zip_stat zipStat; if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) { return false; } auto zipFile = zip_fopen_index(zip, zipStat.index, 0); FAIL_IF_INVALID_PTR(zipFile); auto outFile = fopen(to.c_str(), "wb"); if (outFile == nullptr) { zip_fclose(zipFile); return false; } for (auto n = zip_fread(zipFile, buf, len); n != 0; n = zip_fread(zipFile, buf, len)) { if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) { zip_fclose(zipFile); fclose(outFile); remove(to.c_str()); return false; } } zip_fclose(zipFile); if (fclose(outFile) != 0) { return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'ZipArchive::extractTo bug 70350 Summary:Don't allow upward directory traversal when extracting zip archive files. Files in zip files with `..` or starting at main root `/` should be normalized to something where the file being extracted winds up within the directory or a subdirectory where the actual extraction is taking place. http://git.php.net/?p=php-src.git;a=commit;h=f9c2bf73adb2ede0a486b0db466c264f2b27e0bb Reviewed By: FBNeal Differential Revision: D2798452 fb-gh-sync-id: 844549c93e011d1e991bb322bf85822246b04e30 shipit-source-id: 844549c93e011d1e991bb322bf85822246b04e30'</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 CModules::GetModPathInfo(CModInfo& ModInfo, const CString& sModule, const CString& sModPath, CString& sRetMsg) { ModInfo.SetName(sModule); ModInfo.SetPath(sModPath); ModHandle p = OpenModule(sModule, sModPath, ModInfo, sRetMsg); if (!p) return false; dlclose(p); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-264'], 'message': 'Fix remote code execution and privilege escalation vulnerability. To trigger this, need to have a user already. Thanks for Jeriko One <jeriko.one@gmx.us> for finding and reporting this. CVE-2019-12816'</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) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) { conn_set_state(c, conn_closing); return 1; } } 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': 'Use strncmp when checking for large ascii multigets.'</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: ZSTD_buildCTable(void* dst, size_t dstCapacity, FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type, U32* count, U32 max, const BYTE* codeTable, size_t nbSeq, const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax, const FSE_CTable* prevCTable, size_t prevCTableSize, void* workspace, size_t workspaceSize) { BYTE* op = (BYTE*)dst; const BYTE* const oend = op + dstCapacity; switch (type) { case set_rle: *op = codeTable[0]; CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max)); return 1; case set_repeat: memcpy(nextCTable, prevCTable, prevCTableSize); return 0; case set_basic: CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */ return 0; case set_compressed: { S16 norm[MaxSeq + 1]; size_t nbSeq_1 = nbSeq; const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max); if (count[codeTable[nbSeq-1]] > 1) { count[codeTable[nbSeq-1]]--; nbSeq_1--; } assert(nbSeq_1 > 1); CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max)); { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */ if (FSE_isError(NCountSize)) return NCountSize; CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize)); return NCountSize; } } default: return assert(0), ERROR(GENERIC); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'fixed T36302429'</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: QStringList JlCompress::extractDir(QuaZip &zip, const QString &dir) { if(!zip.open(QuaZip::mdUnzip)) { return QStringList(); } QDir directory(dir); QStringList extracted; if (!zip.goToFirstFile()) { return QStringList(); } do { QString name = zip.getCurrentFileName(); QString absFilePath = directory.absoluteFilePath(name); if (!extractFile(&zip, "", absFilePath)) { removeFile(extracted); return QStringList(); } extracted.append(absFilePath); } while (zip.goToNextFile()); // Chiudo il file zip zip.close(); if(zip.getZipError()!=0) { removeFile(extracted); return QStringList(); } return extracted; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed the Zip Slip vulnerability in JlCompress When extracting a file with a dangerous path like "../evil.exe" from a ZIP archive with JlCompress::extractDir(), the target file would be created outside of the target directory, potentially even overwriting an existing file there.'</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 SparseCountSparseOutputShapeFn(InferenceContext *c) { auto rank = c->Dim(c->input(0), 1); auto nvals = c->UnknownDim(); c->set_output(0, c->Matrix(nvals, rank)); // out.indices c->set_output(1, c->Vector(nvals)); // out.values c->set_output(2, c->Vector(rank)); // out.dense_shape return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix heap out of bounds error in tf.raw_ops.SparseCountSparseOutput shape inference when it is called with invalid inputs, and add a test for it. PiperOrigin-RevId: 405766415 Change-Id: I77d244ef35f351ef7b6f821efd959cac2c66db24'</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) final { // Extract inputs and validate shapes and types. const CSRSparseMatrix* input_matrix; OP_REQUIRES_OK(ctx, ExtractVariantFromInput(ctx, 0, &input_matrix)); const Tensor& input_permutation_indices = ctx->input(1); int64 num_rows; int batch_size; ValidateInputs(ctx, *input_matrix, input_permutation_indices, &batch_size, &num_rows); // Allocate batch pointers. Tensor batch_ptr(cpu_allocator(), DT_INT32, TensorShape({batch_size + 1})); auto batch_ptr_vec = batch_ptr.vec<int32>(); batch_ptr_vec(0) = 0; // Temporary vector of Eigen SparseMatrices to store the Sparse Cholesky // factors. // Note: we use column-compressed (CSC) SparseMatrix because SimplicialLLT // returns the factors in column major format. Since our input should be // symmetric, column major and row major is identical in storage. We just // have to switch to reading the upper triangular part of the input, which // corresponds to the lower triangular part in row major format. std::vector<SparseMatrix> sparse_cholesky_factors(batch_size); // TODO(anudhyan): Tune the cost per unit based on benchmarks. const double nnz_per_row = (input_matrix->total_nnz() / batch_size) / num_rows; const int64 sparse_cholesky_cost_per_batch = nnz_per_row * nnz_per_row * num_rows; // Perform sparse Cholesky factorization of each batch in parallel. auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads()); std::atomic<int64> invalid_input_index(-1); Shard(worker_threads.num_threads, worker_threads.workers, batch_size, sparse_cholesky_cost_per_batch, [&](int64 batch_begin, int64 batch_end) { for (int64 batch_index = batch_begin; batch_index < batch_end; ++batch_index) { // Define an Eigen SparseMatrix Map to operate on the // CSRSparseMatrix component without copying the data. Eigen::Map<const SparseMatrix> sparse_matrix( num_rows, num_rows, input_matrix->nnz(batch_index), input_matrix->row_pointers_vec(batch_index).data(), input_matrix->col_indices_vec(batch_index).data(), input_matrix->values_vec<T>(batch_index).data()); Eigen::SimplicialLLT<SparseMatrix, Eigen::Upper, Eigen::NaturalOrdering<int>> solver; auto permutation_indices_flat = input_permutation_indices.flat<int32>().data(); // Invert the fill-in reducing ordering and apply it to the input // sparse matrix. Eigen::Map< Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int>> permutation(permutation_indices_flat + batch_index * num_rows, num_rows); auto permutation_inverse = permutation.inverse(); SparseMatrix permuted_sparse_matrix; permuted_sparse_matrix.template selfadjointView<Eigen::Upper>() = sparse_matrix.template selfadjointView<Eigen::Upper>() .twistedBy(permutation_inverse); // Compute the Cholesky decomposition. solver.compute(permuted_sparse_matrix); if (solver.info() != Eigen::Success) { invalid_input_index = batch_index; return; } // Get the upper triangular factor, which would end up in the // lower triangular part of the output CSRSparseMatrix when // interpreted in row major format. sparse_cholesky_factors[batch_index] = std::move(solver.matrixU()); // For now, batch_ptr contains the number of nonzeros in each // batch. batch_ptr_vec(batch_index + 1) = sparse_cholesky_factors[batch_index].nonZeros(); } }); // Check for invalid input. OP_REQUIRES( ctx, invalid_input_index == -1, errors::InvalidArgument( "Sparse Cholesky factorization failed for batch index ", invalid_input_index.load(), ". The input might not be valid.")); // Compute a cumulative sum to obtain the batch pointers. std::partial_sum(batch_ptr_vec.data(), batch_ptr_vec.data() + batch_size + 1, batch_ptr_vec.data()); // Allocate output Tensors. const int64 total_nnz = batch_ptr_vec(batch_size); Tensor output_row_ptr(cpu_allocator(), DT_INT32, TensorShape({(num_rows + 1) * batch_size})); Tensor output_col_ind(cpu_allocator(), DT_INT32, TensorShape({total_nnz})); Tensor output_values(cpu_allocator(), DataTypeToEnum<T>::value, TensorShape({total_nnz})); auto output_row_ptr_ptr = output_row_ptr.flat<int32>().data(); auto output_col_ind_ptr = output_col_ind.flat<int32>().data(); auto output_values_ptr = output_values.flat<T>().data(); // Copy the output matrices from each batch into the CSRSparseMatrix // Tensors. // TODO(b/129906419): Factor out the copy from Eigen SparseMatrix to // CSRSparseMatrix into common utils. This is also used in // SparseMatrixSparseMatMul. Shard(worker_threads.num_threads, worker_threads.workers, batch_size, (3 * total_nnz) / batch_size /* cost per unit */, [&](int64 batch_begin, int64 batch_end) { for (int64 batch_index = batch_begin; batch_index < batch_end; ++batch_index) { const SparseMatrix& cholesky_factor = sparse_cholesky_factors[batch_index]; const int64 nnz = cholesky_factor.nonZeros(); std::copy(cholesky_factor.outerIndexPtr(), cholesky_factor.outerIndexPtr() + num_rows + 1, output_row_ptr_ptr + batch_index * (num_rows + 1)); std::copy(cholesky_factor.innerIndexPtr(), cholesky_factor.innerIndexPtr() + nnz, output_col_ind_ptr + batch_ptr_vec(batch_index)); std::copy(cholesky_factor.valuePtr(), cholesky_factor.valuePtr() + nnz, output_values_ptr + batch_ptr_vec(batch_index)); } }); // Create the CSRSparseMatrix instance from its component Tensors and // prepare the Variant output Tensor. CSRSparseMatrix output_csr_matrix; OP_REQUIRES_OK( ctx, CSRSparseMatrix::CreateCSRSparseMatrix( DataTypeToEnum<T>::value, input_matrix->dense_shape(), batch_ptr, output_row_ptr, output_col_ind, output_values, &output_csr_matrix)); Tensor* output_csr_matrix_tensor; AllocatorAttributes cpu_alloc; cpu_alloc.set_on_host(true); OP_REQUIRES_OK( ctx, ctx->allocate_output(0, TensorShape({}), &output_csr_matrix_tensor, cpu_alloc)); output_csr_matrix_tensor->scalar<Variant>()() = std::move(output_csr_matrix); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Remove `OP_REQUIRES` call from helper function. Since `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway. PiperOrigin-RevId: 369524386 Change-Id: I54f6cf9328445675ccc392e661b04336b229c9da'</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 __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (!mp) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); } ; 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: static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return -ENOMEM; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; } ; 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 int stellaris_enet_load(QEMUFile *f, void *opaque, int version_id) { stellaris_enet_state *s = (stellaris_enet_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->ris = qemu_get_be32(f); s->im = qemu_get_be32(f); s->rctl = qemu_get_be32(f); s->tctl = qemu_get_be32(f); s->thr = qemu_get_be32(f); s->mctl = qemu_get_be32(f); s->mdv = qemu_get_be32(f); s->mtxd = qemu_get_be32(f); s->mrxd = qemu_get_be32(f); s->np = qemu_get_be32(f); s->tx_fifo_len = qemu_get_be32(f); qemu_get_buffer(f, s->tx_fifo, sizeof(s->tx_fifo)); for (i = 0; i < 31; i++) { s->rx[i].len = qemu_get_be32(f); qemu_get_buffer(f, s->rx[i].data, sizeof(s->rx[i].data)); } s->next_packet = qemu_get_be32(f); s->rx_fifo_offset = qemu_get_be32(f); return 0; } ; 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: CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString, int stmt_location, int stmt_len) { const char *schemaName = stmt->schemaname; Oid namespaceId; OverrideSearchPath *overridePath; List *parsetree_list; ListCell *parsetree_item; Oid owner_uid; Oid saved_uid; int save_sec_context; AclResult aclresult; ObjectAddress address; GetUserIdAndSecContext(&saved_uid, &save_sec_context); /* * Who is supposed to own the new schema? */ if (stmt->authrole) owner_uid = get_rolespec_oid(stmt->authrole, false); else owner_uid = saved_uid; /* fill schema name with the user name if not specified */ if (!schemaName) { HeapTuple tuple; tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(owner_uid)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for role %u", owner_uid); schemaName = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname)); ReleaseSysCache(tuple); } /* * To create a schema, must have schema-create privilege on the current * database and must be able to become the target role (this does not * imply that the target role itself must have create-schema privilege). * The latter provision guards against "giveaway" attacks. Note that a * superuser will always have both of these privileges a fortiori. */ aclresult = pg_database_aclcheck(MyDatabaseId, saved_uid, ACL_CREATE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_DATABASE, get_database_name(MyDatabaseId)); check_is_member_of_role(saved_uid, owner_uid); /* Additional check to protect reserved schema names */ if (!allowSystemTableMods && IsReservedName(schemaName)) ereport(ERROR, (errcode(ERRCODE_RESERVED_NAME), errmsg("unacceptable schema name \"%s\"", schemaName), errdetail("The prefix \"pg_\" is reserved for system schemas."))); /* * If if_not_exists was given and the schema already exists, bail out. * (Note: we needn't check this when not if_not_exists, because * NamespaceCreate will complain anyway.) We could do this before making * the permissions checks, but since CREATE TABLE IF NOT EXISTS makes its * creation-permission check first, we do likewise. */ if (stmt->if_not_exists && SearchSysCacheExists1(NAMESPACENAME, PointerGetDatum(schemaName))) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_SCHEMA), errmsg("schema \"%s\" already exists, skipping", schemaName))); return InvalidOid; } /* * If the requested authorization is different from the current user, * temporarily set the current user so that the object(s) will be created * with the correct ownership. * * (The setting will be restored at the end of this routine, or in case of * error, transaction abort will clean things up.) */ if (saved_uid != owner_uid) SetUserIdAndSecContext(owner_uid, save_sec_context | SECURITY_LOCAL_USERID_CHANGE); /* Create the schema's namespace */ namespaceId = NamespaceCreate(schemaName, owner_uid, false); /* Advance cmd counter to make the namespace visible */ CommandCounterIncrement(); /* * Temporarily make the new namespace be the front of the search path, as * well as the default creation target namespace. This will be undone at * the end of this routine, or upon error. */ overridePath = GetOverrideSearchPath(CurrentMemoryContext); overridePath->schemas = lcons_oid(namespaceId, overridePath->schemas); /* XXX should we clear overridePath->useTemp? */ PushOverrideSearchPath(overridePath); /* * Report the new schema to possibly interested event triggers. Note we * must do this here and not in ProcessUtilitySlow because otherwise the * objects created below are reported before the schema, which would be * wrong. */ ObjectAddressSet(address, NamespaceRelationId, namespaceId); EventTriggerCollectSimpleCommand(address, InvalidObjectAddress, (Node *) stmt); /* * Examine the list of commands embedded in the CREATE SCHEMA command, and * reorganize them into a sequentially executable order with no forward * references. Note that the result is still a list of raw parsetrees --- * we cannot, in general, run parse analysis on one statement until we * have actually executed the prior ones. */ parsetree_list = transformCreateSchemaStmt(stmt); /* * Execute each command contained in the CREATE SCHEMA. Since the grammar * allows only utility commands in CREATE SCHEMA, there is no need to pass * them through parse_analyze() or the rewriter; we can just hand them * straight to ProcessUtility. */ foreach(parsetree_item, parsetree_list) { Node *stmt = (Node *) lfirst(parsetree_item); PlannedStmt *wrapper; /* need to make a wrapper PlannedStmt */ wrapper = makeNode(PlannedStmt); wrapper->commandType = CMD_UTILITY; wrapper->canSetTag = false; wrapper->utilityStmt = stmt; wrapper->stmt_location = stmt_location; wrapper->stmt_len = stmt_len; /* do this step */ ProcessUtility(wrapper, queryString, PROCESS_UTILITY_SUBCOMMAND, NULL, NULL, None_Receiver, NULL); /* make sure later steps can see the object created here */ CommandCounterIncrement(); } /* Reset search path to normal state */ PopOverrideSearchPath(); /* Reset current user and security context */ SetUserIdAndSecContext(saved_uid, save_sec_context); return namespaceId; } ; 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 int dxtory_decode_v1_410(AVCodecContext *avctx, AVFrame *pic, const uint8_t *src, int src_size) { int h, w; uint8_t *Y1, *Y2, *Y3, *Y4, *U, *V; int ret; if (src_size < avctx->width * avctx->height * 18 / 16) { av_log(avctx, AV_LOG_ERROR, "packet too small\n"); return AVERROR_INVALIDDATA; } avctx->pix_fmt = AV_PIX_FMT_YUV410P; if ((ret = ff_get_buffer(avctx, pic, 0)) < 0) return ret; Y1 = pic->data[0]; Y2 = pic->data[0] + pic->linesize[0]; Y3 = pic->data[0] + pic->linesize[0] * 2; Y4 = pic->data[0] + pic->linesize[0] * 3; U = pic->data[1]; V = pic->data[2]; for (h = 0; h < avctx->height; h += 4) { for (w = 0; w < avctx->width; w += 4) { AV_COPY32(Y1 + w, src); AV_COPY32(Y2 + w, src + 4); AV_COPY32(Y3 + w, src + 8); AV_COPY32(Y4 + w, src + 12); U[w >> 2] = src[16] + 0x80; V[w >> 2] = src[17] + 0x80; src += 18; } Y1 += pic->linesize[0] << 2; Y2 += pic->linesize[0] << 2; Y3 += pic->linesize[0] << 2; Y4 += pic->linesize[0] << 2; U += pic->linesize[1]; V += pic->linesize[2]; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'avcodec/dxtory: fix src size checks Fixes integer overflow Fixes out of array read Fixes: d104661bb59b202df7671fb19a00ca6c-asan_heap-oob_d6429d_5066_cov_1729501105_dxtory_mic.avi Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind 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: static int descriptor_modify(struct ldb_module *module, struct ldb_request *req) { struct ldb_context *ldb = ldb_module_get_ctx(module); struct ldb_request *mod_req; struct ldb_message *msg; struct ldb_result *current_res, *parent_res; const struct ldb_val *old_sd = NULL; const struct ldb_val *parent_sd = NULL; const struct ldb_val *user_sd; struct ldb_dn *dn = req->op.mod.message->dn; struct ldb_dn *parent_dn; struct ldb_message_element *objectclass_element, *sd_element; int ret; uint32_t instanceType; bool explicit_sd_flags = false; uint32_t sd_flags = dsdb_request_sd_flags(req, &explicit_sd_flags); const struct dsdb_schema *schema; DATA_BLOB *sd; const struct dsdb_class *objectclass; static const char * const parent_attrs[] = { "nTSecurityDescriptor", NULL }; static const char * const current_attrs[] = { "nTSecurityDescriptor", "instanceType", "objectClass", NULL }; struct GUID parent_guid = { .time_low = 0 }; struct ldb_control *sd_propagation_control; int cmp_ret = -1; /* do not manipulate our control entries */ if (ldb_dn_is_special(dn)) { return ldb_next_request(module, req); } sd_propagation_control = ldb_request_get_control(req, DSDB_CONTROL_SEC_DESC_PROPAGATION_OID); if (sd_propagation_control != NULL) { if (sd_propagation_control->data != module) { return ldb_operr(ldb); } if (req->op.mod.message->num_elements != 0) { return ldb_operr(ldb); } if (explicit_sd_flags) { return ldb_operr(ldb); } if (sd_flags != 0xF) { return ldb_operr(ldb); } if (sd_propagation_control->critical == 0) { return ldb_operr(ldb); } sd_propagation_control->critical = 0; } sd_element = ldb_msg_find_element(req->op.mod.message, "nTSecurityDescriptor"); if (sd_propagation_control == NULL && sd_element == NULL) { return ldb_next_request(module, req); } /* * nTSecurityDescriptor with DELETE is not supported yet. * TODO: handle this correctly. */ if (sd_propagation_control == NULL && LDB_FLAG_MOD_TYPE(sd_element->flags) == LDB_FLAG_MOD_DELETE) { return ldb_module_error(module, LDB_ERR_UNWILLING_TO_PERFORM, "MOD_DELETE for nTSecurityDescriptor " "not supported yet"); } user_sd = ldb_msg_find_ldb_val(req->op.mod.message, "nTSecurityDescriptor"); /* nTSecurityDescriptor without a value is an error, letting through so it is handled */ if (sd_propagation_control == NULL && user_sd == NULL) { return ldb_next_request(module, req); } ldb_debug(ldb, LDB_DEBUG_TRACE,"descriptor_modify: %s\n", ldb_dn_get_linearized(dn)); ret = dsdb_module_search_dn(module, req, &current_res, dn, current_attrs, DSDB_FLAG_NEXT_MODULE | DSDB_FLAG_AS_SYSTEM | DSDB_SEARCH_SHOW_RECYCLED | DSDB_SEARCH_SHOW_EXTENDED_DN, req); if (ret != LDB_SUCCESS) { ldb_debug(ldb, LDB_DEBUG_ERROR,"descriptor_modify: Could not find %s\n", ldb_dn_get_linearized(dn)); return ret; } instanceType = ldb_msg_find_attr_as_uint(current_res->msgs[0], "instanceType", 0); /* if the object has a parent, retrieve its SD to * use for calculation */ if (!ldb_dn_is_null(current_res->msgs[0]->dn) && !(instanceType & INSTANCE_TYPE_IS_NC_HEAD)) { NTSTATUS status; parent_dn = ldb_dn_get_parent(req, dn); if (parent_dn == NULL) { return ldb_oom(ldb); } ret = dsdb_module_search_dn(module, req, &parent_res, parent_dn, parent_attrs, DSDB_FLAG_NEXT_MODULE | DSDB_FLAG_AS_SYSTEM | DSDB_SEARCH_SHOW_RECYCLED | DSDB_SEARCH_SHOW_EXTENDED_DN, req); if (ret != LDB_SUCCESS) { ldb_debug(ldb, LDB_DEBUG_ERROR, "descriptor_modify: Could not find SD for %s\n", ldb_dn_get_linearized(parent_dn)); return ret; } if (parent_res->count != 1) { return ldb_operr(ldb); } parent_sd = ldb_msg_find_ldb_val(parent_res->msgs[0], "nTSecurityDescriptor"); status = dsdb_get_extended_dn_guid(parent_res->msgs[0]->dn, &parent_guid, "GUID"); if (!NT_STATUS_IS_OK(status)) { return ldb_operr(ldb); } } schema = dsdb_get_schema(ldb, req); objectclass_element = ldb_msg_find_element(current_res->msgs[0], "objectClass"); if (objectclass_element == NULL) { return ldb_operr(ldb); } objectclass = dsdb_get_last_structural_class(schema, objectclass_element); if (objectclass == NULL) { return ldb_operr(ldb); } old_sd = ldb_msg_find_ldb_val(current_res->msgs[0], "nTSecurityDescriptor"); if (old_sd == NULL) { return ldb_operr(ldb); } if (sd_propagation_control != NULL) { /* * This just triggers a recalculation of the * inherited aces. */ user_sd = old_sd; } sd = get_new_descriptor(module, current_res->msgs[0]->dn, req, objectclass, parent_sd, user_sd, old_sd, sd_flags); if (sd == NULL) { return ldb_operr(ldb); } msg = ldb_msg_copy_shallow(req, req->op.mod.message); if (msg == NULL) { return ldb_oom(ldb); } cmp_ret = data_blob_cmp(old_sd, sd); if (sd_propagation_control != NULL) { if (cmp_ret == 0) { /* * The nTSecurityDescriptor is unchanged, * which means we can stop the processing. * * We mark the control as critical again, * as we have not processed it, so the caller * can tell that the descriptor was unchanged. */ sd_propagation_control->critical = 1; return ldb_module_done(req, NULL, NULL, LDB_SUCCESS); } ret = ldb_msg_add_empty(msg, "nTSecurityDescriptor", LDB_FLAG_MOD_REPLACE, &sd_element); if (ret != LDB_SUCCESS) { return ldb_oom(ldb); } ret = ldb_msg_add_value(msg, "nTSecurityDescriptor", sd, NULL); if (ret != LDB_SUCCESS) { return ldb_oom(ldb); } } else if (cmp_ret != 0) { struct GUID guid; struct ldb_dn *nc_root; NTSTATUS status; ret = dsdb_find_nc_root(ldb, msg, current_res->msgs[0]->dn, &nc_root); if (ret != LDB_SUCCESS) { return ldb_oom(ldb); } status = dsdb_get_extended_dn_guid(current_res->msgs[0]->dn, &guid, "GUID"); if (!NT_STATUS_IS_OK(status)) { return ldb_operr(ldb); } /* * Force SD propagation on children of this record */ ret = dsdb_module_schedule_sd_propagation(module, nc_root, guid, parent_guid, false); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } sd_element->values[0] = *sd; } else { sd_element->values[0] = *sd; } ret = ldb_build_mod_req(&mod_req, ldb, req, msg, req->controls, req, dsdb_next_callback, req); LDB_REQ_SET_LOCATION(mod_req); if (ret != LDB_SUCCESS) { return ret; } return ldb_next_request(module, mod_req); } ; 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 samldb_user_account_control_change(struct samldb_ctx *ac) { struct ldb_context *ldb = ldb_module_get_ctx(ac->module); uint32_t old_uac; uint32_t new_uac; uint32_t raw_uac; uint32_t old_ufa; uint32_t new_ufa; uint32_t old_uac_computed; uint32_t clear_uac; uint32_t old_atype; uint32_t new_atype; uint32_t old_pgrid; uint32_t new_pgrid; NTTIME old_lockoutTime; struct ldb_message_element *el; struct ldb_val *val; struct ldb_val computer_val; struct ldb_message *tmp_msg; struct dom_sid *sid; int ret; struct ldb_result *res; const char * const attrs[] = { "objectClass", "isCriticalSystemObject", "userAccountControl", "msDS-User-Account-Control-Computed", "lockoutTime", "objectSid", NULL }; bool is_computer_objectclass = false; bool old_is_critical = false; bool new_is_critical = false; ret = dsdb_get_expected_new_values(ac, ac->msg, "userAccountControl", &el, ac->req->operation); if (ret != LDB_SUCCESS) { return ret; } if (el == NULL || el->num_values == 0) { ldb_asprintf_errstring(ldb, "%08X: samldb: 'userAccountControl' can't be deleted!", W_ERROR_V(WERR_DS_ILLEGAL_MOD_OPERATION)); return LDB_ERR_UNWILLING_TO_PERFORM; } /* Create a temporary message for fetching the "userAccountControl" */ tmp_msg = ldb_msg_new(ac->msg); if (tmp_msg == NULL) { return ldb_module_oom(ac->module); } ret = ldb_msg_add(tmp_msg, el, 0); if (ret != LDB_SUCCESS) { return ret; } raw_uac = ldb_msg_find_attr_as_uint(tmp_msg, "userAccountControl", 0); talloc_free(tmp_msg); /* * UF_LOCKOUT, UF_PASSWD_CANT_CHANGE and UF_PASSWORD_EXPIRED * are only generated and not stored. We ignore them almost * completely, along with unknown bits and UF_SCRIPT. * * The only exception is ACB_AUTOLOCK, which features in * clear_acb when the bit is cleared in this modify operation. * * MS-SAMR 2.2.1.13 UF_FLAG Codes states that some bits are * ignored by clients and servers */ new_uac = raw_uac & UF_SETTABLE_BITS; /* Fetch the old "userAccountControl" and "objectClass" */ ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs, DSDB_FLAG_NEXT_MODULE, ac->req); if (ret != LDB_SUCCESS) { return ret; } old_uac = ldb_msg_find_attr_as_uint(res->msgs[0], "userAccountControl", 0); if (old_uac == 0) { return ldb_operr(ldb); } old_uac_computed = ldb_msg_find_attr_as_uint(res->msgs[0], "msDS-User-Account-Control-Computed", 0); old_lockoutTime = ldb_msg_find_attr_as_int64(res->msgs[0], "lockoutTime", 0); old_is_critical = ldb_msg_find_attr_as_bool(res->msgs[0], "isCriticalSystemObject", 0); /* * When we do not have objectclass "computer" we cannot * switch to a workstation or (RO)DC */ el = ldb_msg_find_element(res->msgs[0], "objectClass"); if (el == NULL) { return ldb_operr(ldb); } computer_val = data_blob_string_const("computer"); val = ldb_msg_find_val(el, &computer_val); if (val != NULL) { is_computer_objectclass = true; } old_ufa = old_uac & UF_ACCOUNT_TYPE_MASK; old_atype = ds_uf2atype(old_ufa); old_pgrid = ds_uf2prim_group_rid(old_uac); new_ufa = new_uac & UF_ACCOUNT_TYPE_MASK; if (new_ufa == 0) { /* * "userAccountControl" = 0 or missing one of the * types means "UF_NORMAL_ACCOUNT". See MS-SAMR * 3.1.1.8.10 point 8 */ new_ufa = UF_NORMAL_ACCOUNT; new_uac |= new_ufa; } sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid"); if (sid == NULL) { return ldb_module_operr(ac->module); } ret = samldb_check_user_account_control_rules(ac, sid, raw_uac, new_uac, old_uac, is_computer_objectclass); if (ret != LDB_SUCCESS) { return ret; } new_atype = ds_uf2atype(new_ufa); new_pgrid = ds_uf2prim_group_rid(new_uac); clear_uac = (old_uac | old_uac_computed) & ~raw_uac; switch (new_ufa) { case UF_NORMAL_ACCOUNT: new_is_critical = old_is_critical; break; case UF_INTERDOMAIN_TRUST_ACCOUNT: new_is_critical = true; break; case UF_WORKSTATION_TRUST_ACCOUNT: new_is_critical = false; if (new_uac & UF_PARTIAL_SECRETS_ACCOUNT) { new_is_critical = true; } break; case UF_SERVER_TRUST_ACCOUNT: new_is_critical = true; break; default: ldb_asprintf_errstring(ldb, "%08X: samldb: invalid userAccountControl[0x%08X]", W_ERROR_V(WERR_INVALID_PARAMETER), raw_uac); return LDB_ERR_OTHER; } if (old_atype != new_atype) { ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType", new_atype); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(ac->msg, "sAMAccountType"); el->flags = LDB_FLAG_MOD_REPLACE; } /* As per MS-SAMR 3.1.1.8.10 these flags have not to be set */ if ((clear_uac & UF_LOCKOUT) && (old_lockoutTime != 0)) { /* "lockoutTime" reset as per MS-SAMR 3.1.1.8.10 */ ldb_msg_remove_attr(ac->msg, "lockoutTime"); ret = samdb_msg_add_uint64(ldb, ac->msg, ac->msg, "lockoutTime", (NTTIME)0); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(ac->msg, "lockoutTime"); el->flags = LDB_FLAG_MOD_REPLACE; } /* * "isCriticalSystemObject" might be set/changed * * Even a change from UF_NORMAL_ACCOUNT (implicitly FALSE) to * UF_WORKSTATION_TRUST_ACCOUNT (actually FALSE) triggers * creating the attribute. */ if (old_is_critical != new_is_critical || old_atype != new_atype) { ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject", new_is_critical ? "TRUE": "FALSE"); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(ac->msg, "isCriticalSystemObject"); el->flags = LDB_FLAG_MOD_REPLACE; } if (!ldb_msg_find_element(ac->msg, "primaryGroupID") && (old_pgrid != new_pgrid)) { /* Older AD deployments don't know about the RODC group */ if (new_pgrid == DOMAIN_RID_READONLY_DCS) { ret = samldb_prim_group_tester(ac, new_pgrid); if (ret != LDB_SUCCESS) { return ret; } } ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "primaryGroupID", new_pgrid); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(ac->msg, "primaryGroupID"); el->flags = LDB_FLAG_MOD_REPLACE; } /* Propagate eventual "userAccountControl" attribute changes */ if (old_uac != new_uac) { char *tempstr = talloc_asprintf(ac->msg, "%d", new_uac); if (tempstr == NULL) { return ldb_module_oom(ac->module); } ret = ldb_msg_add_empty(ac->msg, "userAccountControl", LDB_FLAG_MOD_REPLACE, &el); el->values = talloc(ac->msg, struct ldb_val); el->num_values = 1; el->values[0].data = (uint8_t *) tempstr; el->values[0].length = strlen(tempstr); } else { ldb_msg_remove_attr(ac->msg, "userAccountControl"); } return LDB_SUCCESS; } ; 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 samldb_rodc_add(struct samldb_ctx *ac) { struct ldb_context *ldb = ldb_module_get_ctx(ac->module); uint32_t krbtgt_number, i_start, i; int ret; struct ldb_val newpass_utf16; /* find a unused msDS-SecondaryKrbTgtNumber */ i_start = generate_random() & 0xFFFF; if (i_start == 0) { i_start = 1; } for (i=i_start; i<=0xFFFF; i++) { if (samldb_krbtgtnumber_available(ac, i)) { krbtgt_number = i; goto found; } } for (i=1; i<i_start; i++) { if (samldb_krbtgtnumber_available(ac, i)) { krbtgt_number = i; goto found; } } ldb_asprintf_errstring(ldb, "%08X: Unable to find available msDS-SecondaryKrbTgtNumber", W_ERROR_V(WERR_NO_SYSTEM_RESOURCES)); return LDB_ERR_OTHER; found: ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber", LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "msDS-SecondaryKrbTgtNumber", krbtgt_number); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u", krbtgt_number); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } newpass_utf16 = data_blob_talloc_zero(ac->module, 256); if (newpass_utf16.data == NULL) { return ldb_oom(ldb); } /* * Note that the password_hash module will ignore * this value and use it's own generate_secret_buffer() * that's why we can just use generate_random_buffer() * here. */ generate_random_buffer(newpass_utf16.data, newpass_utf16.length); ret = ldb_msg_add_steal_value(ac->msg, "clearTextPassword", &newpass_utf16); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } return samldb_next_step(ac); } ; 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 protocol_client_msg(VncState *vs, uint8_t *data, size_t len) { int i; uint16_t limit; VncDisplay *vd = vs->vd; if (data[0] > 3) { update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE); } switch (data[0]) { case VNC_MSG_CLIENT_SET_PIXEL_FORMAT: if (len == 1) return 20; set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5), read_u8(data, 6), read_u8(data, 7), read_u16(data, 8), read_u16(data, 10), read_u16(data, 12), read_u8(data, 14), read_u8(data, 15), read_u8(data, 16)); break; case VNC_MSG_CLIENT_SET_ENCODINGS: if (len == 1) return 4; if (len == 4) { limit = read_u16(data, 2); if (limit > 0) return 4 + (limit * 4); } else limit = read_u16(data, 2); for (i = 0; i < limit; i++) { int32_t val = read_s32(data, 4 + (i * 4)); memcpy(data + 4 + (i * 4), &val, sizeof(val)); } set_encodings(vs, (int32_t *)(data + 4), limit); break; case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST: if (len == 1) return 10; framebuffer_update_request(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4), read_u16(data, 6), read_u16(data, 8)); break; case VNC_MSG_CLIENT_KEY_EVENT: if (len == 1) return 8; key_event(vs, read_u8(data, 1), read_u32(data, 4)); break; case VNC_MSG_CLIENT_POINTER_EVENT: if (len == 1) return 6; pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4)); break; case VNC_MSG_CLIENT_CUT_TEXT: if (len == 1) return 8; if (len == 8) { uint32_t dlen = read_u32(data, 4); if (dlen > 0) return 8 + dlen; } client_cut_text(vs, read_u32(data, 4), data + 8); break; case VNC_MSG_CLIENT_QEMU: if (len == 1) return 2; switch (read_u8(data, 1)) { case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT: if (len == 2) return 12; ext_key_event(vs, read_u16(data, 2), read_u32(data, 4), read_u32(data, 8)); break; case VNC_MSG_CLIENT_QEMU_AUDIO: if (len == 2) return 4; switch (read_u16 (data, 2)) { case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE: audio_add(vs); break; case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE: audio_del(vs); break; case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT: if (len == 4) return 10; switch (read_u8(data, 4)) { case 0: vs->as.fmt = AUD_FMT_U8; break; case 1: vs->as.fmt = AUD_FMT_S8; break; case 2: vs->as.fmt = AUD_FMT_U16; break; case 3: vs->as.fmt = AUD_FMT_S16; break; case 4: vs->as.fmt = AUD_FMT_U32; break; case 5: vs->as.fmt = AUD_FMT_S32; break; default: printf("Invalid audio format %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } vs->as.nchannels = read_u8(data, 5); if (vs->as.nchannels != 1 && vs->as.nchannels != 2) { printf("Invalid audio channel coount %d\n", read_u8(data, 5)); vnc_client_error(vs); break; } vs->as.freq = read_u32(data, 6); break; default: printf ("Invalid audio message %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", read_u16(data, 0)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", data[0]); vnc_client_error(vs); break; } vnc_read_when(vs, protocol_client_msg, 1); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'ui/vnc: limit client_cut_text msg payload size currently a malicious client could define a payload size of 2^32 - 1 bytes and send up to that size of data to the vnc server. The server would allocated that amount of memory which could easily create an out of memory condition. This patch limits the payload size to 1MB max. Please note that client_cut_text messages are currently silently ignored. Signed-off-by: Peter Lieven <pl@kamp.de> Signed-off-by: Gerd Hoffmann <kraxel@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 zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; char *key; uint len; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(error_zval_ptr);; } switch (Z_TYPE_P(offset)) { case IS_STRING: key = Z_STRVAL_P(offset); len = Z_STRLEN_P(offset) + 1; string_offest: if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined index: %s", key); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined index: %s", key); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; case IS_NULL: key = ""; len = 1; goto string_offest; case IS_RESOURCE: zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset)); case IS_DOUBLE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; default: zend_error(E_WARNING, "Illegal offset type"); return (type == BP_VAR_W || type == BP_VAR_RW) ? &EG(error_zval_ptr) : &EG(uninitialized_zval_ptr); } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #73029 - Missing type check when unserializing SplArray'</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_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth) { u32 i, sceneT, odT, descIndex, size, size64; GF_InitialObjectDescriptor *iod; GF_SLConfig slc; GF_ISOSample *samp; Bool remove_ocr; u8 *buffer; char buf64[5000], sdpLine[5100]; gf_isom_sdp_clean(file); if (bandwidth) { sprintf(buf64, "b=AS:%d", bandwidth); gf_isom_sdp_add_line(file, buf64); } //xtended attribute for copyright if (gf_sys_is_test_mode()) { sprintf(buf64, "a=x-copyright: %s", "MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)"); } else { sprintf(buf64, "a=x-copyright: MP4/3GP File hinted with GPAC %s - %s", gf_gpac_version(), gf_gpac_copyright() ); } gf_isom_sdp_add_line(file, buf64); if (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK; odT = sceneT = 0; for (i=0; i<gf_isom_get_track_count(file); i++) { if (!gf_isom_is_track_in_root_od(file, i+1)) continue; switch (gf_isom_get_media_type(file,i+1)) { case GF_ISOM_MEDIA_OD: odT = i+1; break; case GF_ISOM_MEDIA_SCENE: sceneT = i+1; break; } } remove_ocr = 0; if (IOD_Profile == GF_SDP_IOD_ISMA_STRICT) { IOD_Profile = GF_SDP_IOD_ISMA; remove_ocr = 1; } /*if we want ISMA like iods, we need at least BIFS */ if ( (IOD_Profile == GF_SDP_IOD_ISMA) && !sceneT ) return GF_BAD_PARAM; /*do NOT change PLs, we assume they are correct*/ iod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file); if (!iod) return GF_NOT_SUPPORTED; /*rewrite an IOD with good SL config - embbed data if possible*/ if (IOD_Profile == GF_SDP_IOD_ISMA) { GF_ESD *esd; Bool is_ok = 1; while (gf_list_count(iod->ESDescriptors)) { esd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0); gf_odf_desc_del((GF_Descriptor *) esd); gf_list_rem(iod->ESDescriptors, 0); } /*get OD esd, and embbed stream data if possible*/ if (odT) { esd = gf_isom_get_esd(file, odT, 1); if (gf_isom_get_sample_count(file, odT)==1) { samp = gf_isom_get_sample(file, odT, 1, &descIndex); if (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) { InitSL_NULL(&slc); slc.predefined = 0; slc.hasRandomAccessUnitsOnlyFlag = 1; slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT); slc.OCRResolution = 1000; slc.startCTS = samp->DTS+samp->CTS_Offset; slc.startDTS = samp->DTS; //set the SL for future extraction gf_isom_set_extraction_slc(file, odT, 1, &slc); size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000); buf64[size64] = 0; sprintf(sdpLine, "data:application/mpeg4-od-au;base64,%s", buf64); esd->decoderConfig->avgBitrate = 0; esd->decoderConfig->bufferSizeDB = samp->dataLength; esd->decoderConfig->maxBitrate = 0; size64 = (u32) strlen(sdpLine)+1; esd->URLString = (char*)gf_malloc(sizeof(char) * size64); strcpy(esd->URLString, sdpLine); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_RTP, ("[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\n")); is_ok = 0; } gf_isom_sample_del(&samp); } if (remove_ocr) esd->OCRESID = 0; else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0; //OK, add this to our IOD gf_list_add(iod->ESDescriptors, esd); } esd = gf_isom_get_esd(file, sceneT, 1); if (gf_isom_get_sample_count(file, sceneT)==1) { samp = gf_isom_get_sample(file, sceneT, 1, &descIndex); if (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) { slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT); slc.OCRResolution = 1000; slc.startCTS = samp->DTS+samp->CTS_Offset; slc.startDTS = samp->DTS; //set the SL for future extraction gf_isom_set_extraction_slc(file, sceneT, 1, &slc); //encode in Base64 the sample size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000); buf64[size64] = 0; sprintf(sdpLine, "data:application/mpeg4-bifs-au;base64,%s", buf64); esd->decoderConfig->avgBitrate = 0; esd->decoderConfig->bufferSizeDB = samp->dataLength; esd->decoderConfig->maxBitrate = 0; esd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1)); strcpy(esd->URLString, sdpLine); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_RTP, ("[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\n")); is_ok = 0; } gf_isom_sample_del(&samp); } if (remove_ocr) esd->OCRESID = 0; else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0; gf_list_add(iod->ESDescriptors, esd); if (is_ok) { u32 has_a, has_v, has_i_a, has_i_v; has_a = has_v = has_i_a = has_i_v = 0; for (i=0; i<gf_isom_get_track_count(file); i++) { esd = gf_isom_get_esd(file, i+1, 1); if (!esd) continue; if (esd->decoderConfig->streamType==GF_STREAM_VISUAL) { if (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++; else has_v++; } else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) { if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++; else has_a++; } gf_odf_desc_del((GF_Descriptor *)esd); } /*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/ if (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) { sprintf(sdpLine, "a=isma-compliance:1,1.0,1"); gf_isom_sdp_add_line(file, sdpLine); } } } //encode the IOD buffer = NULL; size = 0; gf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size); gf_odf_desc_del((GF_Descriptor *)iod); //encode in Base64 the iod size64 = gf_base64_encode(buffer, size, buf64, 2000); buf64[size64] = 0; gf_free(buffer); sprintf(sdpLine, "a=mpeg4-iod:\"data:application/mpeg4-iod;base64,%s\"", buf64); gf_isom_sdp_add_line(file, sdpLine); return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1770 (fuzz)'</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 CClient::OnTextMessage(CTextMessage& Message) { CString sTargets = Message.GetTarget(); VCString vTargets; sTargets.Split(",", vTargets, false); for (CString& sTarget : vTargets) { Message.SetTarget(sTarget); if (m_pNetwork) { // May be nullptr. Message.SetChan(m_pNetwork->FindChan(sTarget)); } if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) { if (sTarget.Equals("status")) { CString sMsg = Message.GetText(); UserCommand(sMsg); } else { CALLMOD(sTarget, this, m_pUser, m_pNetwork, OnModCommand(Message.GetText())); } continue; } bool bContinue = false; NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this, &bContinue); if (bContinue) continue; if (!GetIRCSock()) { // Some lagmeters do a PRIVMSG to their own nick, ignore those. if (!sTarget.Equals(m_sNick)) PutStatus( t_f("Your message to {1} got lost, you are not connected " "to IRC!")(Message.GetTarget())); continue; } if (m_pNetwork) { AddBuffer(Message); EchoMessage(Message); PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); } } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix echo-message for *status Close #1705'</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: AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return "TRACE cannot be controlled by <Limit>, see TraceEnable"; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) <Limit>, else <LimitExcept> */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive excludes all methods", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive specifies methods already excluded", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'core: Disallow Methods' registration at run time (.htaccess), they may be used only if registered at init time (httpd.conf). Calling ap_method_register() in children processes is not the right scope since it won't be shared for all requests. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68'</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_GetObjectItem( cJSON *object, const char *string ) { cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) c = c->next; return c; } ; 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 const char *parse_number( cJSON *item, const char *num ) { int64_t i = 0; double f = 0; int isint = 1; int sign = 1, scale = 0, subscale = 0, signsubscale = 1; /* Could use sscanf for this? */ if ( *num == '-' ) { /* Has sign. */ sign = -1; ++num; } if ( *num == '0' ) /* Is zero. */ ++num; if ( *num >= '1' && *num<='9' ) { /* Number. */ do { i = ( i * 10 ) + ( *num - '0' ); f = ( f * 10.0 ) + ( *num - '0' ); ++num; } while ( *num >= '0' && *num <= '9' ); } if ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) { /* Fractional part. */ isint = 0; ++num; do { f = ( f * 10.0 ) + ( *num++ - '0' ); scale--; } while ( *num >= '0' && *num <= '9' ); } if ( *num == 'e' || *num == 'E' ) { /* Exponent. */ isint = 0; ++num; if ( *num == '+' ) ++num; else if ( *num == '-' ) { /* With sign. */ signsubscale = -1; ++num; } while ( *num >= '0' && *num <= '9' ) subscale = ( subscale * 10 ) + ( *num++ - '0' ); } /* Put it together. */ if ( isint ) { /* Int: number = +/- number */ i = sign * i; item->valueint = i; item->valuefloat = i; } else { /* Float: number = +/- number.fraction * 10^+/- exponent */ f = sign * f * ipow( 10.0, scale + subscale * signsubscale ); item->valueint = f; item->valuefloat = f; } item->type = cJSON_Number; return num; } ; 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* cJSON_strdup( const char* str ) { size_t len; char* copy; len = strlen( str ) + 1; if ( ! ( copy = (char*) cJSON_malloc( len ) ) ) return 0; memcpy( copy, str, len ); return copy; } ; 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 cJSON_InitHooks(cJSON_Hooks* hooks) { if ( ! hooks ) { /* Reset hooks. */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; } ; 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_CreateNull( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_NULL; 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: static inline void switch_to_bitmap(unsigned long tifp) { /* * Invalidate I/O bitmap if the previous task used it. This prevents * any possible leakage of an active I/O bitmap. * * If the next task has an I/O bitmap it will handle it on exit to * user mode. */ if (tifp & _TIF_IO_BITMAP) tss_invalidate_io_bitmap(this_cpu_ptr(&cpu_tss_rw)); } ; 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: PackLinuxElf64::PackLinuxElf64help1(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[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64 || sizeof(Elf64_Phdr) != e_phentsize || (Elf64_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA] && &N_BELE_RTP::be_policy != bele) || (Elf64_Ehdr::ELFDATA2LSB == ehdri.e_ident[Elf64_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_te64(&ehdri.e_phoff); upx_uint64_t const last_Phdr = e_phoff + e_phnum * sizeof(Elf64_Phdr); if (last_Phdr < e_phoff || (unsigned long)file_size < last_Phdr) { throwCantUnpack("bad e_phoff"); } e_shoff = get_te64(&ehdri.e_shoff); upx_uint64_t const last_Shdr = e_shoff + e_shnum * sizeof(Elf64_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 && Elf64_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= (Elf64_Phdr *)(e_phoff + file_image); // do not free() !! } if (f && Elf64_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= (Elf64_Phdr *)(e_phoff + file_image); // do not free() !! shdri= (Elf64_Shdr *)(e_shoff + file_image); // do not free() !! if (opt->cmd != CMD_COMPRESS) { shdri = NULL; } sec_dynsym = elf_find_section_type(Elf64_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]; } Elf64_Phdr const *phdr= phdri; for (int j = e_phnum; --j>=0; ++phdr) if (Elf64_Phdr::PT_DYNAMIC==get_te64(&phdr->p_type)) { dynseg= (Elf64_Dyn const *)(check_pt_dynamic(phdr) + file_image); invert_pt_dynamic(dynseg); } else if (PT_LOAD64==get_te32(&phdr->p_type)) { 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); gashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_GNU_HASH); hashtab = (unsigned const *)elf_find_dynamic(Elf64_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_te64(&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: hcom_client_init ( OUT p_hsm_com_client_hdl_t *p_hdl, IN char *server_path, IN char *client_path, IN int max_data_len ) { hsm_com_client_hdl_t *hdl = NULL; hsm_com_errno_t res = HSM_COM_OK; if((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(server_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(client_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->scr.scratch = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->recv_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->send_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } hdl->scr.scratch_fill = 0; hdl->scr.scratch_len = max_data_len; hdl->buf_len = max_data_len; hdl->trans_id = 1; strcpy(hdl->s_path,server_path); strcpy(hdl->c_path,client_path); hdl->client_state = HSM_COM_C_STATE_IN; *p_hdl = hdl; return res; cleanup: if(hdl) { if (hdl->scr.scratch) { free(hdl->scr.scratch); } if (hdl->recv_buf) { free(hdl->recv_buf); } free(hdl); } return res; } ; 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: int parse_sequence_header(davs2_mgr_t *mgr, davs2_seq_t *seq, davs2_bs_t *bs) { static const float FRAME_RATE[8] = { 24000.0f / 1001.0f, 24.0f, 25.0f, 30000.0f / 1001.0f, 30.0f, 50.0f, 60000.0f / 1001.0f, 60.0f }; rps_t *p_rps = NULL; int i, j; int num_of_rps; bs->i_bit_pos += 32; /* skip start code */ memset(seq, 0, sizeof(davs2_seq_t)); // reset all value seq->head.profile_id = u_v(bs, 8, "profile_id"); seq->head.level_id = u_v(bs, 8, "level_id"); seq->head.progressive = u_v(bs, 1, "progressive_sequence"); seq->b_field_coding = u_flag(bs, "field_coded_sequence"); seq->head.width = u_v(bs, 14, "horizontal_size"); seq->head.height = u_v(bs, 14, "vertical_size"); if (seq->head.width < 16 || seq->head.height < 16) { return -1; } seq->head.chroma_format = u_v(bs, 2, "chroma_format"); if (seq->head.chroma_format != CHROMA_420 && seq->head.chroma_format != CHROMA_400) { return -1; } if (seq->head.chroma_format == CHROMA_400) { davs2_log(mgr, DAVS2_LOG_WARNING, "Un-supported Chroma Format YUV400 as 0 for GB/T.\n"); } /* sample bit depth */ if (seq->head.profile_id == MAIN10_PROFILE) { seq->sample_precision = u_v(bs, 3, "sample_precision"); seq->encoding_precision = u_v(bs, 3, "encoding_precision"); } else { seq->sample_precision = u_v(bs, 3, "sample_precision"); seq->encoding_precision = 1; } if (seq->sample_precision < 1 || seq->sample_precision > 3 || seq->encoding_precision < 1 || seq->encoding_precision > 3) { return -1; } seq->head.internal_bit_depth = 6 + (seq->encoding_precision << 1); seq->head.output_bit_depth = 6 + (seq->encoding_precision << 1); seq->head.bytes_per_sample = seq->head.output_bit_depth > 8 ? 2 : 1; /* */ seq->head.aspect_ratio = u_v(bs, 4, "aspect_ratio_information"); seq->head.frame_rate_id = u_v(bs, 4, "frame_rate_id"); seq->bit_rate_lower = u_v(bs, 18, "bit_rate_lower"); u_v(bs, 1, "marker bit"); seq->bit_rate_upper = u_v(bs, 12, "bit_rate_upper"); seq->head.low_delay = u_v(bs, 1, "low_delay"); u_v(bs, 1, "marker bit"); seq->b_temporal_id_exist = u_flag(bs, "temporal_id exist flag"); // get Extension Flag u_v(bs, 18, "bbv buffer size"); seq->log2_lcu_size = u_v(bs, 3, "Largest Coding Block Size"); if (seq->log2_lcu_size < 4 || seq->log2_lcu_size > 6) { davs2_log(mgr, DAVS2_LOG_ERROR, "Invalid LCU size: %d\n", seq->log2_lcu_size); return -1; } seq->enable_weighted_quant = u_flag(bs, "enable_weighted_quant"); if (seq->enable_weighted_quant) { int load_seq_wquant_data_flag; int x, y, sizeId, uiWqMSize; const int *Seq_WQM; load_seq_wquant_data_flag = u_flag(bs, "load_seq_weight_quant_data_flag"); for (sizeId = 0; sizeId < 2; sizeId++) { uiWqMSize = DAVS2_MIN(1 << (sizeId + 2), 8); if (load_seq_wquant_data_flag == 1) { for (y = 0; y < uiWqMSize; y++) { for (x = 0; x < uiWqMSize; x++) { seq->seq_wq_matrix[sizeId][y * uiWqMSize + x] = (int16_t)ue_v(bs, "weight_quant_coeff"); } } } else if (load_seq_wquant_data_flag == 0) { Seq_WQM = wq_get_default_matrix(sizeId); for (i = 0; i < (uiWqMSize * uiWqMSize); i++) { seq->seq_wq_matrix[sizeId][i] = (int16_t)Seq_WQM[i]; } } } } seq->enable_background_picture = u_flag(bs, "background_picture_disable") ^ 0x01; seq->enable_mhp_skip = u_flag(bs, "mhpskip enabled"); seq->enable_dhp = u_flag(bs, "dhp enabled"); seq->enable_wsm = u_flag(bs, "wsm enabled"); seq->enable_amp = u_flag(bs, "Asymmetric Motion Partitions"); seq->enable_nsqt = u_flag(bs, "use NSQT"); seq->enable_sdip = u_flag(bs, "use NSIP"); seq->enable_2nd_transform = u_flag(bs, "secT enabled"); seq->enable_sao = u_flag(bs, "SAO Enable Flag"); seq->enable_alf = u_flag(bs, "ALF Enable Flag"); seq->enable_pmvr = u_flag(bs, "pmvr enabled"); if (1 != u_v(bs, 1, "marker bit")) { davs2_log(mgr, DAVS2_LOG_ERROR, "expected marker_bit 1 while received 0, FILE %s, Row %d\n", __FILE__, __LINE__); } num_of_rps = u_v(bs, 6, "num_of_RPS"); if (num_of_rps > AVS2_GOP_NUM) { return -1; } seq->num_of_rps = num_of_rps; for (i = 0; i < num_of_rps; i++) { p_rps = &seq->seq_rps[i]; p_rps->refered_by_others = u_v(bs, 1, "refered by others"); p_rps->num_of_ref = u_v(bs, 3, "num of reference picture"); for (j = 0; j < p_rps->num_of_ref; j++) { p_rps->ref_pic[j] = u_v(bs, 6, "delta COI of ref pic"); } p_rps->num_to_remove = u_v(bs, 3, "num of removed picture"); for (j = 0; j < p_rps->num_to_remove; j++) { p_rps->remove_pic[j] = u_v(bs, 6, "delta COI of removed pic"); } if (1 != u_v(bs, 1, "marker bit")) { davs2_log(mgr, DAVS2_LOG_ERROR, "expected marker_bit 1 while received 0, FILE %s, Row %d\n", __FILE__, __LINE__); } } if (seq->head.low_delay == 0) { seq->picture_reorder_delay = u_v(bs, 5, "picture_reorder_delay"); } seq->cross_loop_filter_flag = u_flag(bs, "Cross Loop Filter Flag"); u_v(bs, 2, "reserved bits"); bs_align(bs); /* align position */ seq->head.bitrate = ((seq->bit_rate_upper << 18) + seq->bit_rate_lower) * 400; seq->head.frame_rate = FRAME_RATE[seq->head.frame_rate_id - 1]; seq->i_enc_width = ((seq->head.width + MIN_CU_SIZE - 1) >> MIN_CU_SIZE_IN_BIT) << MIN_CU_SIZE_IN_BIT; seq->i_enc_height = ((seq->head.height + MIN_CU_SIZE - 1) >> MIN_CU_SIZE_IN_BIT) << MIN_CU_SIZE_IN_BIT; seq->valid_flag = 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Add checking for `frame_rate_code`. Signed-off-by: luofl <falei.luo@gmail.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 follow_dotdot(struct nameidata *nd) { if (!nd->root.mnt) set_root(nd); while(1) { struct dentry *old = nd->path.dentry; if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { /* rare case of legitimate dget_parent()... */ nd->path.dentry = dget_parent(nd->path.dentry); dput(old); break; } if (!follow_up(&nd->path)) break; } follow_mount(&nd->path); nd->inode = nd->path.dentry->d_inode; } ; 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 hdlr_dump(GF_Box *a, FILE * trace) { GF_HandlerBox *p = (GF_HandlerBox *)a; gf_isom_box_dump_start(a, "HandlerBox", trace); if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) { fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1); } else { fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8); } fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1); dump_data(trace, (char *) p->reserved2, 12); fprintf(trace, "\""); fprintf(trace, ">\n"); gf_isom_box_dump_done("HandlerBox", a, trace); 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 int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error Fixes: Null pointer dereference Fixes: CVE-2017-9608 Found-by: Yihan Lian Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> (cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd) 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: static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size, int parse_extradata) { AVCodecContext *const avctx = h->avctx; H264Context *hx; ///< thread context int buf_index; int context_count; int next_avc; int pass = !(avctx->active_thread_type & FF_THREAD_FRAME); int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts int nal_index; int ret = 0; h->max_contexts = h->slice_context_count; if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) { h->current_slice = 0; if (!h->first_field) h->cur_pic_ptr = NULL; ff_h264_reset_sei(h); } for (; pass <= 1; pass++) { buf_index = 0; context_count = 0; next_avc = h->is_avc ? 0 : buf_size; nal_index = 0; for (;;) { int consumed; int dst_length; int bit_length; const uint8_t *ptr; int i, nalsize = 0; int err; if (buf_index >= next_avc) { if (buf_index >= buf_size - h->nal_length_size) break; nalsize = 0; for (i = 0; i < h->nal_length_size; i++) nalsize = (nalsize << 8) | buf[buf_index++]; if (nalsize <= 0 || nalsize > buf_size - buf_index) { av_log(h->avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize); break; } next_avc = buf_index + nalsize; } else { // start code prefix search for (; buf_index + 3 < next_avc; buf_index++) // This should always succeed in the first iteration. if (buf[buf_index] == 0 && buf[buf_index + 1] == 0 && buf[buf_index + 2] == 1) break; if (buf_index + 3 >= buf_size) { buf_index = buf_size; break; } buf_index += 3; if (buf_index >= next_avc) continue; } hx = h->thread_context[context_count]; ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index); if (ptr == NULL || dst_length < 0) { ret = -1; goto end; } i = buf_index + consumed; if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc && buf[i] == 0x00 && buf[i + 1] == 0x00 && buf[i + 2] == 0x01 && buf[i + 3] == 0xE0) h->workaround_bugs |= FF_BUG_TRUNCATED; if (!(h->workaround_bugs & FF_BUG_TRUNCATED)) while (dst_length > 0 && ptr[dst_length - 1] == 0) dst_length--; bit_length = !dst_length ? 0 : (8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1)); if (h->avctx->debug & FF_DEBUG_STARTCODE) av_log(h->avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", hx->nal_unit_type, buf_index, buf_size, dst_length); if (h->is_avc && (nalsize != consumed) && nalsize) av_log(h->avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize); buf_index += consumed; nal_index++; if (pass == 0) { /* packets can sometimes contain multiple PPS/SPS, * e.g. two PAFF field pictures in one packet, or a demuxer * which splits NALs strangely if so, when frame threading we * can't start the next thread until we've read all of them */ switch (hx->nal_unit_type) { case NAL_SPS: case NAL_PPS: nals_needed = nal_index; break; case NAL_DPA: case NAL_IDR_SLICE: case NAL_SLICE: init_get_bits(&hx->gb, ptr, bit_length); if (!get_ue_golomb(&hx->gb)) nals_needed = nal_index; } continue; } if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0 && h->nal_unit_type != NAL_SEI) continue; again: /* Ignore every NAL unit type except PPS and SPS during extradata * parsing. Decoding slices is not possible in codec init * with frame-mt */ if (parse_extradata && HAVE_THREADS && (h->avctx->active_thread_type & FF_THREAD_FRAME) && (hx->nal_unit_type != NAL_PPS && hx->nal_unit_type != NAL_SPS)) { if (hx->nal_unit_type < NAL_AUD || hx->nal_unit_type > NAL_AUXILIARY_SLICE) av_log(avctx, AV_LOG_INFO, "Ignoring NAL unit %d during extradata parsing\n", hx->nal_unit_type); hx->nal_unit_type = NAL_FF_IGNORE; } err = 0; switch (hx->nal_unit_type) { case NAL_IDR_SLICE: if (h->nal_unit_type != NAL_IDR_SLICE) { av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices\n"); ret = -1; goto end; } idr(h); // FIXME ensure we don't lose some frames if there is reordering case NAL_SLICE: init_get_bits(&hx->gb, ptr, bit_length); hx->intra_gb_ptr = hx->inter_gb_ptr = &hx->gb; hx->data_partitioning = 0; if ((err = decode_slice_header(hx, h))) break; if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) { h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) & ((1 << h->sps.log2_max_frame_num) - 1); } h->cur_pic_ptr->f.key_frame |= (hx->nal_unit_type == NAL_IDR_SLICE) || (h->sei_recovery_frame_cnt >= 0); if (hx->nal_unit_type == NAL_IDR_SLICE || h->recovery_frame == h->frame_num) { h->recovery_frame = -1; h->cur_pic_ptr->recovered = 1; } // If we have an IDR, all frames after it in decoded order are // "recovered". if (hx->nal_unit_type == NAL_IDR_SLICE) h->frame_recovered |= FRAME_RECOVERED_IDR; h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR); if (h->current_slice == 1) { if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) decode_postinit(h, nal_index >= nals_needed); if (h->avctx->hwaccel && (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0) return ret; } if (hx->redundant_pic_count == 0 && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos != AV_PICTURE_TYPE_B) && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos == AV_PICTURE_TYPE_I) && avctx->skip_frame < AVDISCARD_ALL) { if (avctx->hwaccel) { ret = avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed); if (ret < 0) return ret; } else context_count++; } break; case NAL_DPA: init_get_bits(&hx->gb, ptr, bit_length); hx->intra_gb_ptr = hx->inter_gb_ptr = NULL; if ((err = decode_slice_header(hx, h)) < 0) { /* make sure data_partitioning is cleared if it was set * before, so we don't try decoding a slice without a valid * slice header later */ h->data_partitioning = 0; break; } hx->data_partitioning = 1; break; case NAL_DPB: init_get_bits(&hx->intra_gb, ptr, bit_length); hx->intra_gb_ptr = &hx->intra_gb; break; case NAL_DPC: init_get_bits(&hx->inter_gb, ptr, bit_length); hx->inter_gb_ptr = &hx->inter_gb; if (hx->redundant_pic_count == 0 && hx->intra_gb_ptr && hx->data_partitioning && h->cur_pic_ptr && h->context_initialized && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos != AV_PICTURE_TYPE_B) && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos == AV_PICTURE_TYPE_I) && avctx->skip_frame < AVDISCARD_ALL) context_count++; break; case NAL_SEI: init_get_bits(&h->gb, ptr, bit_length); ff_h264_decode_sei(h); break; case NAL_SPS: init_get_bits(&h->gb, ptr, bit_length); ret = ff_h264_decode_seq_parameter_set(h); if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) { av_log(h->avctx, AV_LOG_DEBUG, "SPS decoding failure, trying again with the complete NAL\n"); init_get_bits(&h->gb, buf + buf_index + 1 - consumed, 8 * (nalsize - 1)); ff_h264_decode_seq_parameter_set(h); } ret = h264_set_parameter_from_sps(h); if (ret < 0) goto end; break; case NAL_PPS: init_get_bits(&h->gb, ptr, bit_length); ff_h264_decode_picture_parameter_set(h, bit_length); break; case NAL_AUD: case NAL_END_SEQUENCE: case NAL_END_STREAM: case NAL_FILLER_DATA: case NAL_SPS_EXT: case NAL_AUXILIARY_SLICE: break; case NAL_FF_IGNORE: break; default: av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length); } if (context_count == h->max_contexts) { execute_decode_slices(h, context_count); context_count = 0; } if (err < 0) { av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n"); h->ref_count[0] = h->ref_count[1] = h->list_count = 0; } else if (err == 1) { /* Slice could not be decoded in parallel mode, copy down * NAL unit stuff to context 0 and restart. Note that * rbsp_buffer is not transferred, but since we no longer * run in parallel mode this should not be an issue. */ h->nal_unit_type = hx->nal_unit_type; h->nal_ref_idc = hx->nal_ref_idc; hx = h; goto again; } } } if (context_count) execute_decode_slices(h, context_count); end: /* clean up */ if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } return (ret < 0) ? ret : buf_index; } ; 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: void Compute(OpKernelContext* context) override { const Tensor& logits_in = context->input(0); const Tensor& labels_in = context->input(1); TensorShape shape_in = logits_in.shape(); BCast bcast(BCast::FromShape(logits_in.shape()), BCast::FromShape(labels_in.shape())); if (!logits_in.IsSameSize(labels_in)) { OP_REQUIRES(context, bcast.IsValid(), errors::InvalidArgument( "logits and labels must be broadcastable: logits_size=", logits_in.shape().DebugString(), " labels_size=", labels_in.shape().DebugString())); shape_in = BCast::ToShape(bcast.output_shape()); } OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in), errors::InvalidArgument("logits and labels must be either " "2-dimensional, or broadcasted to be " "2-dimensional")); if (std::is_same<Device, GPUDevice>::value) { OP_REQUIRES(context, !OpDeterminismRequired(), errors::Unimplemented( "The GPU implementation of SoftmaxCrossEntropyWithLogits" " that would have been executed is not deterministic." " Note that the Python API uses an alternative," " deterministic, GPU-accelerated path when determinism is" " enabled.")); } // loss is 1-D (one per example), and size is batch_size. Tensor scratch; OP_REQUIRES_OK( context, context->allocate_temp(DataTypeToEnum<T>::value, TensorShape({shape_in.dim_size(0), 1}), &scratch)); Tensor* loss_out = nullptr; OP_REQUIRES_OK(context, context->allocate_output( 0, TensorShape({shape_in.dim_size(0)}), &loss_out)); Tensor* back_out = nullptr; // Try to reuse the logits_in buffer for the backprop output. OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 1, shape_in, &back_out)); if (shape_in.dim_size(0) > 0) { functor::XentFunctor<Device, T> functor; if (logits_in.IsSameSize(labels_in)) { functor(context->eigen_device<Device>(), shape_in.AsEigenDSizes<2>(), Eigen::array<Eigen::DenseIndex, 2>{1, 1}, Eigen::array<Eigen::DenseIndex, 2>{1, 1}, logits_in.matrix<T>(), labels_in.matrix<T>(), scratch.matrix<T>(), loss_out->vec<T>(), back_out->matrix<T>()); } else { functor(context->eigen_device<Device>(), shape_in.AsEigenDSizes<2>(), BCast::ToIndexArray<2>(bcast.x_bcast()), BCast::ToIndexArray<2>(bcast.y_bcast()), logits_in.template shaped<T, 2>(bcast.x_reshape()), labels_in.template shaped<T, 2>(bcast.y_reshape()), scratch.matrix<T>(), loss_out->vec<T>(), back_out->matrix<T>()); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-354'], 'message': 'Fix crash in softmax-xent when some input dimensions are 1. Before, tf.nn.softmax_cross_entropy_with_logits would fail a CHECK if one input tensor had shape (1, 1) and the other did not. In particular, the call to ToIndexArray<2> here https://github.com/tensorflow/tensorflow/blob/1f3da84a89702d3b4f234ee83762d738caffe098/tensorflow/core/kernels/xent_op.cc#L99 would fail, since the call assumed the array had two dimensions. If both dimensions were 1, BCast would merge the two dimensions into a single dimension. Passing fewer_dims_optimization=false stops this optimization PiperOrigin-RevId: 384844496 Change-Id: Ifb02dc74964132c3ed3f3bc98b0858dbe4e258b7'</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 sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avformat/rtpdec_h264: Fix heap-buffer-overflow Fixes: rtp_sdp/poc.sdp Found-by: Bingchang <l.bing.chang.bc@gmail.com> 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: TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input, const TfLiteTensor* axis, TfLiteTensor* output) { int axis_value; // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss. if (axis->type == kTfLiteInt64) { axis_value = static_cast<int>(*GetTensorData<int64_t>(axis)); } else { axis_value = *GetTensorData<int>(axis); } if (axis_value < 0) { axis_value += NumDimensions(input); } // Copy the input dimensions to output except the axis dimension. TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1); int j = 0; for (int i = 0; i < NumDimensions(input); ++i) { if (i != axis_value) { output_dims->data[j] = SizeOfDimension(input, i); ++j; } } return context->ResizeTensor(context, output, output_dims); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Prevent array write out-of-bounds. If user passes an invalid axis, then we copy one too many dimensions to the output in the loop below these checks. Even if we didn't do that, there will be further issues with an invalid axis, so we check for that right now. PiperOrigin-RevId: 371023299 Change-Id: I9eca37ffc2b29e8e48710f500701270ef0790224'</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: folly::Optional<TLSMessage> PlaintextReadRecordLayer::read( folly::IOBufQueue& buf) { while (true) { folly::io::Cursor cursor(buf.front()); if (buf.empty() || !cursor.canAdvance(kPlaintextHeaderSize)) { return folly::none; } TLSMessage msg; msg.type = static_cast<ContentType>(cursor.readBE<ContentTypeType>()); if (skipEncryptedRecords_) { if (msg.type == ContentType::application_data) { cursor.skip(sizeof(ProtocolVersion)); auto length = cursor.readBE<uint16_t>(); if (buf.chainLength() < (cursor - buf.front()) + length) { return folly::none; } length += sizeof(ContentType) + sizeof(ProtocolVersion) + sizeof(uint16_t); buf.trimStart(length); continue; } else if (msg.type != ContentType::change_cipher_spec) { skipEncryptedRecords_ = false; } } switch (msg.type) { case ContentType::handshake: case ContentType::alert: break; case ContentType::change_cipher_spec: break; default: throw std::runtime_error(folly::to<std::string>( "received plaintext content type ", static_cast<ContentTypeType>(msg.type), ", header: ", folly::hexlify(buf.splitAtMost(10)->coalesce()))); } receivedRecordVersion_ = static_cast<ProtocolVersion>(cursor.readBE<ProtocolVersionType>()); auto length = cursor.readBE<uint16_t>(); if (length > kMaxPlaintextRecordSize) { throw std::runtime_error("received too long plaintext record"); } if (length == 0) { throw std::runtime_error("received empty plaintext record"); } if (buf.chainLength() < (cursor - buf.front()) + length) { return folly::none; } cursor.clone(msg.fragment, length); buf.trimStart(cursor - buf.front()); if (msg.type == ContentType::change_cipher_spec) { msg.fragment->coalesce(); if (msg.fragment->length() == 1 && *msg.fragment->data() == 0x01) { continue; } else { throw FizzException( "received ccs", AlertDescription::illegal_parameter); } } return std::move(msg); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-835', 'CWE-787'], 'message': 'Avoid arithmetic operation on uint16 read from the wire. Summary: This could overflow previously. CVE-2019-3560 Reviewed By: yfeldblum Differential Revision: D14152362 fbshipit-source-id: c0ebb3fc59b49c7c23e6bcb90458c19cd891be65'</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 DefragTrackerReuseTest(void) { int ret = 0; int id = 1; Packet *p1 = NULL; DefragTracker *tracker1 = NULL, *tracker2 = NULL; DefragInit(); /* Build a packet, its not a fragment but shouldn't matter for * this test. */ p1 = BuildTestPacket(id, 0, 0, 'A', 8); if (p1 == NULL) { goto end; } /* Get a tracker. It shouldn't look like its already in use. */ tracker1 = DefragGetTracker(NULL, NULL, p1); if (tracker1 == NULL) { goto end; } if (tracker1->seen_last) { goto end; } if (tracker1->remove) { goto end; } DefragTrackerRelease(tracker1); /* Get a tracker again, it should be the same one. */ tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 != tracker1) { goto end; } DefragTrackerRelease(tracker1); /* Now mark the tracker for removal. It should not be returned * when we get a tracker for a packet that may have the same * attributes. */ tracker1->remove = 1; tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 == tracker1) { goto end; } if (tracker2->remove) { goto end; } ret = 1; end: if (p1 != NULL) { SCFree(p1); } 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: static int DefragMfIpv6Test(void) { int retval = 0; int ip_id = 9; Packet *p = NULL; DefragInit(); Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8); Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8); Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8); if (p1 == NULL || p2 == NULL || p3 == NULL) { goto end; } p = Defrag(NULL, NULL, p1, NULL); if (p != NULL) { goto end; } p = Defrag(NULL, NULL, p2, NULL); if (p != NULL) { goto end; } /* This should return a packet as MF=0. */ p = Defrag(NULL, NULL, p3, NULL); if (p == NULL) { goto end; } /* For IPv6 the expected length is just the length of the payload * of 2 fragments, so 16. */ if (IPV6_GET_PLEN(p) != 16) { goto end; } retval = 1; end: if (p1 != NULL) { SCFree(p1); } if (p2 != NULL) { SCFree(p2); } if (p3 != NULL) { SCFree(p3); } if (p != NULL) { SCFree(p); } DefragDestroy(); return retval; } ; 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::Get(Local<Value> key_handle, MaybeLocal<Object> maybe_options) -> Local<Value> { return ThreePhaseTask::Run<async, GetRunner>(*isolate, *this, key_handle, maybe_options, 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 truemotion1_decode_header(TrueMotion1Context *s) { int i, ret; int width_shift = 0; int new_pix_fmt; struct frame_header header; uint8_t header_buffer[128] = { 0 }; /* logical maximum size of the header */ const uint8_t *sel_vector_table; header.header_size = ((s->buf[0] >> 5) | (s->buf[0] << 3)) & 0x7f; if (s->buf[0] < 0x10) { av_log(s->avctx, AV_LOG_ERROR, "invalid header size (%d)\n", s->buf[0]); return AVERROR_INVALIDDATA; } /* unscramble the header bytes with a XOR operation */ for (i = 1; i < header.header_size; i++) header_buffer[i - 1] = s->buf[i] ^ s->buf[i + 1]; header.compression = header_buffer[0]; header.deltaset = header_buffer[1]; header.vectable = header_buffer[2]; header.ysize = AV_RL16(&header_buffer[3]); header.xsize = AV_RL16(&header_buffer[5]); header.checksum = AV_RL16(&header_buffer[7]); header.version = header_buffer[9]; header.header_type = header_buffer[10]; header.flags = header_buffer[11]; header.control = header_buffer[12]; /* Version 2 */ if (header.version >= 2) { if (header.header_type > 3) { av_log(s->avctx, AV_LOG_ERROR, "invalid header type (%d)\n", header.header_type); return AVERROR_INVALIDDATA; } else if ((header.header_type == 2) || (header.header_type == 3)) { s->flags = header.flags; if (!(s->flags & FLAG_INTERFRAME)) s->flags |= FLAG_KEYFRAME; } else s->flags = FLAG_KEYFRAME; } else /* Version 1 */ s->flags = FLAG_KEYFRAME; if (s->flags & FLAG_SPRITE) { avpriv_request_sample(s->avctx, "Frame with sprite"); /* FIXME header.width, height, xoffset and yoffset aren't initialized */ return AVERROR_PATCHWELCOME; } else { s->w = header.xsize; s->h = header.ysize; if (header.header_type < 2) { if ((s->w < 213) && (s->h >= 176)) { s->flags |= FLAG_INTERPOLATED; avpriv_request_sample(s->avctx, "Interpolated frame"); } } } if (header.compression >= 17) { av_log(s->avctx, AV_LOG_ERROR, "invalid compression type (%d)\n", header.compression); return AVERROR_INVALIDDATA; } if ((header.deltaset != s->last_deltaset) || (header.vectable != s->last_vectable)) select_delta_tables(s, header.deltaset); if ((header.compression & 1) && header.header_type) sel_vector_table = pc_tbl2; else { if (header.vectable > 0 && header.vectable < 4) sel_vector_table = tables[header.vectable - 1]; else { av_log(s->avctx, AV_LOG_ERROR, "invalid vector table id (%d)\n", header.vectable); return AVERROR_INVALIDDATA; } } if (compression_types[header.compression].algorithm == ALGO_RGB24H) { new_pix_fmt = AV_PIX_FMT_RGB32; width_shift = 1; } else new_pix_fmt = AV_PIX_FMT_RGB555; // RGB565 is supported as well s->w >>= width_shift; if (s->w != s->avctx->width || s->h != s->avctx->height || new_pix_fmt != s->avctx->pix_fmt) { av_frame_unref(s->frame); s->avctx->sample_aspect_ratio = (AVRational){ 1 << width_shift, 1 }; s->avctx->pix_fmt = new_pix_fmt; if ((ret = ff_set_dimensions(s->avctx, s->w, s->h)) < 0) return ret; av_fast_malloc(&s->vert_pred, &s->vert_pred_size, s->avctx->width * sizeof(unsigned int)); } /* There is 1 change bit per 4 pixels, so each change byte represents * 32 pixels; divide width by 4 to obtain the number of change bits and * then round up to the nearest byte. */ s->mb_change_bits_row_size = ((s->avctx->width >> (2 - width_shift)) + 7) >> 3; if ((header.deltaset != s->last_deltaset) || (header.vectable != s->last_vectable)) { if (compression_types[header.compression].algorithm == ALGO_RGB24H) gen_vector_table24(s, sel_vector_table); else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB555) gen_vector_table15(s, sel_vector_table); else gen_vector_table16(s, sel_vector_table); } /* set up pointers to the other key data chunks */ s->mb_change_bits = s->buf + header.header_size; if (s->flags & FLAG_KEYFRAME) { /* no change bits specified for a keyframe; only index bytes */ s->index_stream = s->mb_change_bits; } else { /* one change bit per 4x4 block */ s->index_stream = s->mb_change_bits + (s->mb_change_bits_row_size * (s->avctx->height >> 2)); } s->index_stream_size = s->size - (s->index_stream - s->buf); s->last_deltaset = header.deltaset; s->last_vectable = header.vectable; s->compression = header.compression; s->block_width = compression_types[header.compression].block_width; s->block_height = compression_types[header.compression].block_height; s->block_type = compression_types[header.compression].block_type; if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_INFO, "tables: %d / %d c:%d %dx%d t:%d %s%s%s%s\n", s->last_deltaset, s->last_vectable, s->compression, s->block_width, s->block_height, s->block_type, s->flags & FLAG_KEYFRAME ? " KEY" : "", s->flags & FLAG_INTERFRAME ? " INTER" : "", s->flags & FLAG_SPRITE ? " SPRITE" : "", s->flags & FLAG_INTERPOLATED ? " INTERPOL" : ""); return header.header_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'truemotion1: check the header size Fixes invalid reads. 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: Status check_index_ordering(const Tensor& indices) { auto findices = indices.flat<int>(); for (std::size_t i = 0; i < findices.dimension(0) - 1; ++i) { if (findices(i) < findices(i + 1)) { continue; } return Status( errors::InvalidArgument("Indices are not strictly ordered")); } 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: bool has_capacity() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { return capacity_ > 0; } ; 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: DSA_Verification_Operation(const DSA_PublicKey& dsa, const std::string& emsa) : PK_Ops::Verification_with_EMSA(emsa), m_group(dsa.get_group()), m_y(dsa.get_y()), m_mod_q(dsa.group_q()) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'</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 filter_frame(AVFilterLink *inlink, AVFrame *in) { PadContext *s = inlink->dst->priv; AVFrame *out; int needs_copy = frame_needs_copy(s, in); if (needs_copy) { av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n"); out = ff_get_video_buffer(inlink->dst->outputs[0], FFMAX(inlink->w, s->w), FFMAX(inlink->h, s->h)); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } else { int i; out = in; for (i = 0; i < 4 && out->data[i]; i++) { int hsub = s->draw.hsub[i]; int vsub = s->draw.vsub[i]; out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] + (s->y >> vsub) * out->linesize[i]; } } /* top bar */ if (s->y) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, 0, s->w, s->y); } /* bottom bar */ if (s->h > s->y + s->in_h) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y + s->in_h, s->w, s->h - s->y - s->in_h); } /* left border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y, s->x, in->height); if (needs_copy) { ff_copy_rectangle2(&s->draw, out->data, out->linesize, in->data, in->linesize, s->x, s->y, 0, 0, in->width, in->height); } /* right border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, s->x + s->in_w, s->y, s->w - s->x - s->in_w, in->height); out->width = s->w; out->height = s->h; if (in != out) av_frame_free(&in); return ff_filter_frame(inlink->dst->outputs[0], out); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avfilter: fix plane validity checks Fixes out of array accesses 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: static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { // handle a table switch condition if (pos + 8 > len) { return op->size; } int min_val = (ut32)(UINT (data, pos + 4)), max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { //caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset); for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { //ut32 value = (ut32)(UINT (data, pos)); if (pos + 4 >= len) { // switch is too big cant read further break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr); } } op->size = pos; return op->size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10296 - Heap out of bounds read in java_switch_op()'</s>