text
stringlengths
478
483k
<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: target_count_create(struct iter_qstate* iq) { if(!iq->target_count) { iq->target_count = (int*)calloc(2, sizeof(int)); /* if calloc fails we simply do not track this number */ if(iq->target_count) iq->target_count[0] = 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: delegpt_add_rrset_A(struct delegpt* dp, struct regional* region, struct ub_packed_rrset_key* ak, uint8_t lame) { struct packed_rrset_data* d=(struct packed_rrset_data*)ak->entry.data; size_t i; struct sockaddr_in sa; socklen_t len = (socklen_t)sizeof(sa); log_assert(!dp->dp_type_mlc); memset(&sa, 0, len); sa.sin_family = AF_INET; sa.sin_port = (in_port_t)htons(UNBOUND_DNS_PORT); for(i=0; i<d->count; i++) { if(d->rr_len[i] != 2 + INET_SIZE) continue; memmove(&sa.sin_addr, d->rr_data[i]+2, INET_SIZE); if(!delegpt_add_target(dp, region, ak->rk.dname, ak->rk.dname_len, (struct sockaddr_storage*)&sa, len, (d->security==sec_status_bogus), lame)) return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id) { struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id]; struct module_qstate* subq; log_assert(iq->dp); if(iq->depth == ie->max_dependency_depth) return; if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, NULL)) return; /* is this query the same as the nscheck? */ if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS && query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 && (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){ /* spawn off A, AAAA queries for in-zone glue to check */ generate_a_aaaa_check(qstate, iq, id); return; } /* no need to get the NS record for DS, it is above the zonecut */ if(qstate->qinfo.qtype == LDNS_RR_TYPE_DS) return; log_nametypeclass(VERB_ALGO, "schedule ns fetch", iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass); if(!generate_sub_request(iq->dp->name, iq->dp->namelen, LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) { verbose(VERB_ALGO, "could not generate ns check"); return; } if(subq) { struct iter_qstate* subiq = (struct iter_qstate*)subq->minfo[id]; /* make copy to avoid use of stub dp by different qs/threads */ /* refetch glue to start higher up the tree */ subiq->refetch_glue = 1; subiq->dp = delegpt_copy(iq->dp, subq->region); if(!subiq->dp) { log_err("out of memory generating ns check, copydp"); fptr_ok(fptr_whitelist_modenv_kill_sub( qstate->env->kill_sub)); (*qstate->env->kill_sub)(subq); return; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq, struct iter_env* ie, int id, int maxtargets, int* num) { int query_count = 0; struct delegpt_ns* ns; int missing; int toget = 0; if(iq->depth == ie->max_dependency_depth) return 0; if(iq->depth > 0 && iq->target_count && iq->target_count[1] > MAX_TARGET_COUNT) { char s[LDNS_MAX_DOMAINLEN+1]; dname_str(qstate->qinfo.qname, s); verbose(VERB_QUERY, "request %s has exceeded the maximum " "number of glue fetches %d", s, iq->target_count[1]); return 0; } iter_mark_cycle_targets(qstate, iq->dp); missing = (int)delegpt_count_missing_targets(iq->dp); log_assert(maxtargets != 0); /* that would not be useful */ /* Generate target requests. Basically, any missing targets * are queried for here, regardless if it is necessary to do * so to continue processing. */ if(maxtargets < 0 || maxtargets > missing) toget = missing; else toget = maxtargets; if(toget == 0) { *num = 0; return 1; } /* select 'toget' items from the total of 'missing' items */ log_assert(toget <= missing); /* loop over missing targets */ for(ns = iq->dp->nslist; ns; ns = ns->next) { if(ns->resolved) continue; /* randomly select this item with probability toget/missing */ if(!iter_ns_probability(qstate->env->rnd, toget, missing)) { /* do not select this one, next; select toget number * of items from a list one less in size */ missing --; continue; } if(ie->supports_ipv6 && !ns->got6) { /* Send the AAAA request. */ if(!generate_target_query(qstate, iq, id, ns->name, ns->namelen, LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) { *num = query_count; if(query_count > 0) qstate->ext_state[id] = module_wait_subquery; return 0; } query_count++; } /* Send the A request. */ if(ie->supports_ipv4 && !ns->got4) { if(!generate_target_query(qstate, iq, id, ns->name, ns->namelen, LDNS_RR_TYPE_A, iq->qchase.qclass)) { *num = query_count; if(query_count > 0) qstate->ext_state[id] = module_wait_subquery; return 0; } query_count++; } /* mark this target as in progress. */ ns->resolved = 1; missing--; toget--; if(toget == 0) break; } *num = query_count; if(query_count > 0) qstate->ext_state[id] = module_wait_subquery; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id) { struct module_qstate* subq = NULL; verbose(VERB_ALGO, "processDSNSFind"); if(!iq->dsns_point) { /* initialize */ iq->dsns_point = iq->qchase.qname; iq->dsns_point_len = iq->qchase.qname_len; } /* robustcheck for internal error: we are not underneath the dp */ if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) { errinf_dname(qstate, "for DS query parent-child nameserver search the query is not under the zone", iq->dp->name); return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); } /* go up one (more) step, until we hit the dp, if so, end */ dname_remove_label(&iq->dsns_point, &iq->dsns_point_len); if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) { /* there was no inbetween nameserver, use the old delegation * point again. And this time, because dsns_point is nonNULL * we are going to accept the (bad) result */ iq->state = QUERYTARGETS_STATE; return 1; } iq->state = DSNS_FIND_STATE; /* spawn NS lookup (validation not needed, this is for DS lookup) */ log_nametypeclass(VERB_ALGO, "fetch nameservers", iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass); if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len, LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) { errinf_dname(qstate, "for DS query parent-child nameserver search, could not generate NS lookup for", iq->dsns_point); return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct delegpt* delegpt_copy(struct delegpt* dp, struct regional* region) { struct delegpt* copy = delegpt_create(region); struct delegpt_ns* ns; struct delegpt_addr* a; if(!copy) return NULL; if(!delegpt_set_name(copy, region, dp->name)) return NULL; copy->bogus = dp->bogus; copy->has_parent_side_NS = dp->has_parent_side_NS; copy->ssl_upstream = dp->ssl_upstream; for(ns = dp->nslist; ns; ns = ns->next) { if(!delegpt_add_ns(copy, region, ns->name, ns->lame)) return NULL; copy->nslist->resolved = ns->resolved; copy->nslist->got4 = ns->got4; copy->nslist->got6 = ns->got6; copy->nslist->done_pside4 = ns->done_pside4; copy->nslist->done_pside6 = ns->done_pside6; } for(a = dp->target_list; a; a = a->next_target) { if(!delegpt_add_addr(copy, region, &a->addr, a->addrlen, a->bogus, a->lame, a->tls_auth_name)) return NULL; } return copy; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: delegpt_add_rrset_AAAA(struct delegpt* dp, struct regional* region, struct ub_packed_rrset_key* ak, uint8_t lame) { struct packed_rrset_data* d=(struct packed_rrset_data*)ak->entry.data; size_t i; struct sockaddr_in6 sa; socklen_t len = (socklen_t)sizeof(sa); log_assert(!dp->dp_type_mlc); memset(&sa, 0, len); sa.sin6_family = AF_INET6; sa.sin6_port = (in_port_t)htons(UNBOUND_DNS_PORT); for(i=0; i<d->count; i++) { if(d->rr_len[i] != 2 + INET6_SIZE) /* rdatalen + len of IP6 */ continue; memmove(&sa.sin6_addr, d->rr_data[i]+2, INET6_SIZE); if(!delegpt_add_target(dp, region, ak->rk.dname, ak->rk.dname_len, (struct sockaddr_storage*)&sa, len, (d->security==sec_status_bogus), lame)) return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: generate_dnskey_prefetch(struct module_qstate* qstate, struct iter_qstate* iq, int id) { struct module_qstate* subq; log_assert(iq->dp); /* is this query the same as the prefetch? */ if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY && query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 && (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){ return; } /* if the DNSKEY is in the cache this lookup will stop quickly */ log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch", iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass); if(!generate_sub_request(iq->dp->name, iq->dp->namelen, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) { /* we'll be slower, but it'll work */ verbose(VERB_ALGO, "could not generate dnskey prefetch"); return; } if(subq) { struct iter_qstate* subiq = (struct iter_qstate*)subq->minfo[id]; /* this qstate has the right delegation for the dnskey lookup*/ /* make copy to avoid use of stub dp by different qs/threads */ subiq->dp = delegpt_copy(iq->dp, subq->region); /* if !subiq->dp, it'll start from the cache, no problem */ } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq, struct iter_env* ie, int id) { uint8_t* delname; size_t delnamelen; struct dns_msg* msg = NULL; log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo); /* check effort */ /* We enforce a maximum number of query restarts. This is primarily a * cheap way to prevent CNAME loops. */ if(iq->query_restart_count > MAX_RESTART_COUNT) { verbose(VERB_QUERY, "request has exceeded the maximum number" " of query restarts with %d", iq->query_restart_count); errinf(qstate, "request has exceeded the maximum number " "restarts (eg. indirections)"); if(iq->qchase.qname) errinf_dname(qstate, "stop at", iq->qchase.qname); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } /* We enforce a maximum recursion/dependency depth -- in general, * this is unnecessary for dependency loops (although it will * catch those), but it provides a sensible limit to the amount * of work required to answer a given query. */ verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth); if(iq->depth > ie->max_dependency_depth) { verbose(VERB_QUERY, "request has exceeded the maximum " "dependency depth with depth of %d", iq->depth); errinf(qstate, "request has exceeded the maximum dependency " "depth (eg. nameserver lookup recursion)"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } /* If the request is qclass=ANY, setup to generate each class */ if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) { iq->qchase.qclass = 0; return next_state(iq, COLLECT_CLASS_STATE); } /* * If we are restricted by a forward-zone or a stub-zone, we * can't re-fetch glue for this delegation point. * we won’t try to re-fetch glue if the iq->dp is null. */ if (iq->refetch_glue && iq->dp && !can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, NULL)) { iq->refetch_glue = 0; } /* Resolver Algorithm Step 1 -- Look for the answer in local data. */ /* This either results in a query restart (CNAME cache response), a * terminating response (ANSWER), or a cache miss (null). */ if (iter_stub_fwd_no_cache(qstate, &iq->qchase)) { /* Asked to not query cache. */ verbose(VERB_ALGO, "no-cache set, going to the network"); qstate->no_cache_lookup = 1; qstate->no_cache_store = 1; msg = NULL; } else if(qstate->blacklist) { /* if cache, or anything else, was blacklisted then * getting older results from cache is a bad idea, no cache */ verbose(VERB_ALGO, "cache blacklisted, going to the network"); msg = NULL; } else if(!qstate->no_cache_lookup) { msg = dns_cache_lookup(qstate->env, iq->qchase.qname, iq->qchase.qname_len, iq->qchase.qtype, iq->qchase.qclass, qstate->query_flags, qstate->region, qstate->env->scratch, 0); if(!msg && qstate->env->neg_cache && iter_qname_indicates_dnssec(qstate->env, &iq->qchase)) { /* lookup in negative cache; may result in * NOERROR/NODATA or NXDOMAIN answers that need validation */ msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase, qstate->region, qstate->env->rrset_cache, qstate->env->scratch_buffer, *qstate->env->now, 1/*add SOA*/, NULL, qstate->env->cfg); } /* item taken from cache does not match our query name, thus * security needs to be re-examined later */ if(msg && query_dname_compare(qstate->qinfo.qname, iq->qchase.qname) != 0) msg->rep->security = sec_status_unchecked; } if(msg) { /* handle positive cache response */ enum response_type type = response_type_from_cache(msg, &iq->qchase); if(verbosity >= VERB_ALGO) { log_dns_msg("msg from cache lookup", &msg->qinfo, msg->rep); verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d", (int)msg->rep->ttl, (int)msg->rep->prefetch_ttl); } if(type == RESPONSE_TYPE_CNAME) { uint8_t* sname = 0; size_t slen = 0; verbose(VERB_ALGO, "returning CNAME response from " "cache"); if(!handle_cname_response(qstate, iq, msg, &sname, &slen)) { errinf(qstate, "failed to prepend CNAME " "components, malloc failure"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } iq->qchase.qname = sname; iq->qchase.qname_len = slen; /* This *is* a query restart, even if it is a cheap * one. */ iq->dp = NULL; iq->refetch_glue = 0; iq->query_restart_count++; iq->sent_count = 0; sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region); if(qstate->env->cfg->qname_minimisation) iq->minimisation_state = INIT_MINIMISE_STATE; return next_state(iq, INIT_REQUEST_STATE); } /* if from cache, NULL, else insert 'cache IP' len=0 */ if(qstate->reply_origin) sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region); if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_SERVFAIL) errinf(qstate, "SERVFAIL in cache"); /* it is an answer, response, to final state */ verbose(VERB_ALGO, "returning answer from cache."); iq->response = msg; return final_state(iq); } /* attempt to forward the request */ if(forward_request(qstate, iq)) { if(!iq->dp) { log_err("alloc failure for forward dp"); errinf(qstate, "malloc failure for forward zone"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } iq->refetch_glue = 0; iq->minimisation_state = DONOT_MINIMISE_STATE; /* the request has been forwarded. * forwarded requests need to be immediately sent to the * next state, QUERYTARGETS. */ return next_state(iq, QUERYTARGETS_STATE); } /* Resolver Algorithm Step 2 -- find the "best" servers. */ /* first, adjust for DS queries. To avoid the grandparent problem, * we just look for the closest set of server to the parent of qname. * When re-fetching glue we also need to ask the parent. */ if(iq->refetch_glue) { if(!iq->dp) { log_err("internal or malloc fail: no dp for refetch"); errinf(qstate, "malloc failure, for delegation info"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } delname = iq->dp->name; delnamelen = iq->dp->namelen; } else { delname = iq->qchase.qname; delnamelen = iq->qchase.qname_len; } if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue || (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway && can_have_last_resort(qstate->env, delname, delnamelen, iq->qchase.qclass, NULL))) { /* remove first label from delname, root goes to hints, * but only to fetch glue, not for qtype=DS. */ /* also when prefetching an NS record, fetch it again from * its parent, just as if it expired, so that you do not * get stuck on an older nameserver that gives old NSrecords */ if(dname_is_root(delname) && (iq->refetch_glue || (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway))) delname = NULL; /* go to root priming */ else dname_remove_label(&delname, &delnamelen); } /* delname is the name to lookup a delegation for. If NULL rootprime */ while(1) { /* Lookup the delegation in the cache. If null, then the * cache needs to be primed for the qclass. */ if(delname) iq->dp = dns_cache_find_delegation(qstate->env, delname, delnamelen, iq->qchase.qtype, iq->qchase.qclass, qstate->region, &iq->deleg_msg, *qstate->env->now+qstate->prefetch_leeway); else iq->dp = NULL; /* If the cache has returned nothing, then we have a * root priming situation. */ if(iq->dp == NULL) { int r; /* if under auth zone, no prime needed */ if(!auth_zone_delegpt(qstate, iq, delname, delnamelen)) return error_response(qstate, id, LDNS_RCODE_SERVFAIL); if(iq->dp) /* use auth zone dp */ return next_state(iq, INIT_REQUEST_2_STATE); /* if there is a stub, then no root prime needed */ r = prime_stub(qstate, iq, id, delname, iq->qchase.qclass); if(r == 2) break; /* got noprime-stub-zone, continue */ else if(r) return 0; /* stub prime request made */ if(forwards_lookup_root(qstate->env->fwds, iq->qchase.qclass)) { /* forward zone root, no root prime needed */ /* fill in some dp - safety belt */ iq->dp = hints_lookup_root(qstate->env->hints, iq->qchase.qclass); if(!iq->dp) { log_err("internal error: no hints dp"); errinf(qstate, "no hints for this class"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } iq->dp = delegpt_copy(iq->dp, qstate->region); if(!iq->dp) { log_err("out of memory in safety belt"); errinf(qstate, "malloc failure, in safety belt"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } return next_state(iq, INIT_REQUEST_2_STATE); } /* Note that the result of this will set a new * DelegationPoint based on the result of priming. */ if(!prime_root(qstate, iq, id, iq->qchase.qclass)) return error_response(qstate, id, LDNS_RCODE_REFUSED); /* priming creates and sends a subordinate query, with * this query as the parent. So further processing for * this event will stop until reactivated by the * results of priming. */ return 0; } if(!iq->ratelimit_ok && qstate->prefetch_leeway) iq->ratelimit_ok = 1; /* allow prefetches, this keeps otherwise valid data in the cache */ if(!iq->ratelimit_ok && infra_ratelimit_exceeded( qstate->env->infra_cache, iq->dp->name, iq->dp->namelen, *qstate->env->now)) { /* and increment the rate, so that the rate for time * now will also exceed the rate, keeping cache fresh */ (void)infra_ratelimit_inc(qstate->env->infra_cache, iq->dp->name, iq->dp->namelen, *qstate->env->now, &qstate->qinfo, qstate->reply); /* see if we are passed through with slip factor */ if(qstate->env->cfg->ratelimit_factor != 0 && ub_random_max(qstate->env->rnd, qstate->env->cfg->ratelimit_factor) == 1) { iq->ratelimit_ok = 1; log_nametypeclass(VERB_ALGO, "ratelimit allowed through for " "delegation point", iq->dp->name, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN); } else { lock_basic_lock(&ie->queries_ratelimit_lock); ie->num_queries_ratelimited++; lock_basic_unlock(&ie->queries_ratelimit_lock); log_nametypeclass(VERB_ALGO, "ratelimit exceeded with " "delegation point", iq->dp->name, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN); qstate->was_ratelimited = 1; errinf(qstate, "query was ratelimited"); errinf_dname(qstate, "for zone", iq->dp->name); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } } /* see if this dp not useless. * It is useless if: * o all NS items are required glue. * or the query is for NS item that is required glue. * o no addresses are provided. * o RD qflag is on. * Instead, go up one level, and try to get even further * If the root was useless, use safety belt information. * Only check cache returns, because replies for servers * could be useless but lead to loops (bumping into the * same server reply) if useless-checked. */ if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags, iq->dp)) { struct delegpt* retdp = NULL; if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, &retdp)) { if(retdp) { verbose(VERB_QUERY, "cache has stub " "or fwd but no addresses, " "fallback to config"); iq->dp = delegpt_copy(retdp, qstate->region); if(!iq->dp) { log_err("out of memory in " "stub/fwd fallback"); errinf(qstate, "malloc failure, for fallback to config"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } break; } verbose(VERB_ALGO, "useless dp " "but cannot go up, servfail"); delegpt_log(VERB_ALGO, iq->dp); errinf(qstate, "no useful nameservers, " "and cannot go up"); errinf_dname(qstate, "for zone", iq->dp->name); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } if(dname_is_root(iq->dp->name)) { /* use safety belt */ verbose(VERB_QUERY, "Cache has root NS but " "no addresses. Fallback to the safety belt."); iq->dp = hints_lookup_root(qstate->env->hints, iq->qchase.qclass); /* note deleg_msg is from previous lookup, * but RD is on, so it is not used */ if(!iq->dp) { log_err("internal error: no hints dp"); return error_response(qstate, id, LDNS_RCODE_REFUSED); } iq->dp = delegpt_copy(iq->dp, qstate->region); if(!iq->dp) { log_err("out of memory in safety belt"); errinf(qstate, "malloc failure, in safety belt, for root"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } break; } else { verbose(VERB_ALGO, "cache delegation was useless:"); delegpt_log(VERB_ALGO, iq->dp); /* go up */ delname = iq->dp->name; delnamelen = iq->dp->namelen; dname_remove_label(&delname, &delnamelen); } } else break; } verbose(VERB_ALGO, "cache delegation returns delegpt"); delegpt_log(VERB_ALGO, iq->dp); /* Otherwise, set the current delegation point and move on to the * next state. */ return next_state(iq, INIT_REQUEST_2_STATE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: iter_new(struct module_qstate* qstate, int id) { struct iter_qstate* iq = (struct iter_qstate*)regional_alloc( qstate->region, sizeof(struct iter_qstate)); qstate->minfo[id] = iq; if(!iq) return 0; memset(iq, 0, sizeof(*iq)); iq->state = INIT_REQUEST_STATE; iq->final_state = FINISHED_STATE; iq->an_prepend_list = NULL; iq->an_prepend_last = NULL; iq->ns_prepend_list = NULL; iq->ns_prepend_last = NULL; iq->dp = NULL; iq->depth = 0; iq->num_target_queries = 0; iq->num_current_queries = 0; iq->query_restart_count = 0; iq->referral_count = 0; iq->sent_count = 0; iq->ratelimit_ok = 0; iq->target_count = NULL; iq->wait_priming_stub = 0; iq->refetch_glue = 0; iq->dnssec_expected = 0; iq->dnssec_lame_query = 0; iq->chase_flags = qstate->query_flags; /* Start with the (current) qname. */ iq->qchase = qstate->qinfo; outbound_list_init(&iq->outlist); iq->minimise_count = 0; iq->timeout_count = 0; if (qstate->env->cfg->qname_minimisation) iq->minimisation_state = INIT_MINIMISE_STATE; else iq->minimisation_state = DONOT_MINIMISE_STATE; memset(&iq->qinfo_out, 0, sizeof(struct query_info)); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: delegpt_add_target(struct delegpt* dp, struct regional* region, uint8_t* name, size_t namelen, struct sockaddr_storage* addr, socklen_t addrlen, uint8_t bogus, uint8_t lame) { struct delegpt_ns* ns = delegpt_find_ns(dp, name, namelen); log_assert(!dp->dp_type_mlc); if(!ns) { /* ignore it */ return 1; } if(!lame) { if(addr_is_ip6(addr, addrlen)) ns->got6 = 1; else ns->got4 = 1; if(ns->got4 && ns->got6) ns->resolved = 1; } return delegpt_add_addr(dp, region, addr, addrlen, bogus, lame, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: processPrimeResponse(struct module_qstate* qstate, int id) { struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; enum response_type type; iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */ type = response_type_from_server( (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd), iq->response, &iq->qchase, iq->dp); if(type == RESPONSE_TYPE_ANSWER) { qstate->return_rcode = LDNS_RCODE_NOERROR; qstate->return_msg = iq->response; } else { errinf(qstate, "prime response did not get an answer"); errinf_dname(qstate, "for", qstate->qinfo.qname); qstate->return_rcode = LDNS_RCODE_SERVFAIL; qstate->return_msg = NULL; } /* validate the root or stub after priming (if enabled). * This is the same query as the prime query, but with validation. * Now that we are primed, the additional queries that validation * may need can be resolved, such as DLV. */ if(qstate->env->cfg->harden_referral_path) { struct module_qstate* subq = NULL; log_nametypeclass(VERB_ALGO, "schedule prime validation", qstate->qinfo.qname, qstate->qinfo.qtype, qstate->qinfo.qclass); if(!generate_sub_request(qstate->qinfo.qname, qstate->qinfo.qname_len, qstate->qinfo.qtype, qstate->qinfo.qclass, qstate, id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) { verbose(VERB_ALGO, "could not generate prime check"); } generate_a_aaaa_check(qstate, iq, id); } /* This event is finished. */ qstate->ext_state[id] = module_finished; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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: prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id, uint16_t qclass) { struct delegpt* dp; struct module_qstate* subq; verbose(VERB_DETAIL, "priming . %s NS", sldns_lookup_by_id(sldns_rr_classes, (int)qclass)? sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??"); dp = hints_lookup_root(qstate->env->hints, qclass); if(!dp) { verbose(VERB_ALGO, "Cannot prime due to lack of hints"); return 0; } /* Priming requests start at the QUERYTARGETS state, skipping * the normal INIT state logic (which would cause an infloop). */ if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS, qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) { verbose(VERB_ALGO, "could not prime root"); return 0; } if(subq) { struct iter_qstate* subiq = (struct iter_qstate*)subq->minfo[id]; /* Set the initial delegation point to the hint. * copy dp, it is now part of the root prime query. * dp was part of in the fixed hints structure. */ subiq->dp = delegpt_copy(dp, subq->region); if(!subiq->dp) { log_err("out of memory priming root, copydp"); fptr_ok(fptr_whitelist_modenv_kill_sub( qstate->env->kill_sub)); (*qstate->env->kill_sub)(subq); return 0; } /* there should not be any target queries. */ subiq->num_target_queries = 0; subiq->dnssec_expected = iter_indicates_dnssec( qstate->env, subiq->dp, NULL, subq->qinfo.qclass); } /* this module stops, our submodule starts, and does the query. */ qstate->ext_state[id] = module_wait_subquery; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</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 ssize_t psi_write(struct file *file, const char __user *user_buf, size_t nbytes, enum psi_res res) { char buf[32]; size_t buf_size; struct seq_file *seq; struct psi_trigger *new; if (static_branch_likely(&psi_disabled)) return -EOPNOTSUPP; buf_size = min(nbytes, sizeof(buf)); if (copy_from_user(buf, user_buf, buf_size)) return -EFAULT; buf[buf_size - 1] = '\0'; new = psi_trigger_create(&psi_system, buf, nbytes, res); if (IS_ERR(new)) return PTR_ERR(new); seq = file->private_data; /* Take seq->lock to protect seq->private from concurrent writes */ mutex_lock(&seq->lock); psi_trigger_replace(&seq->private, new); mutex_unlock(&seq->lock); return nbytes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'sched/psi: Fix OOB write when writing 0 bytes to PSI files Issuing write() with count parameter set to 0 on any file under /proc/pressure/ will cause an OOB write because of the access to buf[buf_size-1] when NUL-termination is performed. Fix this by checking for buf_size to be non-zero. Signed-off-by: Suren Baghdasaryan <surenb@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Signed-off-by: Ingo Molnar <mingo@kernel.org> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Link: https://lkml.kernel.org/r/20200203212216.7076-1-surenb@google.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 char *multipart_buffer_read_body(multipart_buffer *self, size_t *len) { char buf[FILLUNIT], *out=NULL; int total_bytes=0, read_bytes=0; while((read_bytes = multipart_buffer_read(self, buf, sizeof(buf), NULL))) { out = erealloc(out, total_bytes + read_bytes + 1); memcpy(out + total_bytes, buf, read_bytes); total_bytes += read_bytes; } if (out) { out[total_bytes] = '\0'; } *len = total_bytes; return out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Merge branch 'PHP-7.3' into PHP-7.4 * PHP-7.3: Fix #78876: Long variables cause OOM and temp files are not cleaned Fix #78875: Long filenames cause OOM and temp files are not cleaned Update NEWS for 7.2.31 Update CREDITS for PHP 7.2.30 Update NEWS for PHP 7.2.30'</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 SSize_t S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, SSize_t *minlenp, SSize_t *deltap, regnode *last, scan_data_t *data, I32 stopparen, U32 recursed_depth, regnode_ssc *and_withp, U32 flags, U32 depth) /* scanp: Start here (read-write). */ /* deltap: Write maxlen-minlen here. */ /* last: Stop before this one. */ /* data: string data about the pattern */ /* stopparen: treat close N as END */ /* recursed: which subroutines have we recursed into */ /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */ { dVAR; /* There must be at least this number of characters to match */ SSize_t min = 0; I32 pars = 0, code; regnode *scan = *scanp, *next; SSize_t delta = 0; int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF); int is_inf_internal = 0; /* The studied chunk is infinite */ I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0; scan_data_t data_fake; SV *re_trie_maxbuff = NULL; regnode *first_non_open = scan; SSize_t stopmin = SSize_t_MAX; scan_frame *frame = NULL; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_STUDY_CHUNK; RExC_study_started= 1; Zero(&data_fake, 1, scan_data_t); if ( depth == 0 ) { while (first_non_open && OP(first_non_open) == OPEN) first_non_open=regnext(first_non_open); } fake_study_recurse: DEBUG_r( RExC_study_chunk_recursed_count++; ); DEBUG_OPTIMISE_MORE_r( { Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p", depth, (long)stopparen, (unsigned long)RExC_study_chunk_recursed_count, (unsigned long)depth, (unsigned long)recursed_depth, scan, last); if (recursed_depth) { U32 i; U32 j; for ( j = 0 ; j < recursed_depth ; j++ ) { for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) { if ( PAREN_TEST(RExC_study_chunk_recursed + ( j * RExC_study_chunk_recursed_bytes), i ) && ( !j || !PAREN_TEST(RExC_study_chunk_recursed + (( j - 1 ) * RExC_study_chunk_recursed_bytes), i) ) ) { Perl_re_printf( aTHX_ " %d",(int)i); break; } } if ( j + 1 < recursed_depth ) { Perl_re_printf( aTHX_ ","); } } } Perl_re_printf( aTHX_ "\n"); } ); while ( scan && OP(scan) != END && scan < last ){ UV min_subtract = 0; /* How mmany chars to subtract from the minimum node length to get a real minimum (because the folded version may be shorter) */ bool unfolded_multi_char = FALSE; /* Peephole optimizer: */ DEBUG_STUDYDATA("Peep", data, depth, is_inf); DEBUG_PEEP("Peep", scan, depth, flags); /* The reason we do this here is that we need to deal with things like * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT * parsing code, as each (?:..) is handled by a different invocation of * reg() -- Yves */ JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0); /* Follow the next-chain of the current node and optimize away all the NOTHINGs from it. */ if (OP(scan) != CURLYX) { const int max = (reg_off_by_arg[OP(scan)] ? I32_MAX /* I32 may be smaller than U16 on CRAYs! */ : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX)); int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan)); int noff; regnode *n = scan; /* Skip NOTHING and LONGJMP. */ while ((n = regnext(n)) && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n))) || ((OP(n) == LONGJMP) && (noff = ARG(n)))) && off + noff < max) off += noff; if (reg_off_by_arg[OP(scan)]) ARG(scan) = off; else NEXT_OFF(scan) = off; } /* The principal pseudo-switch. Cannot be a switch, since we look into several different things. */ if ( OP(scan) == DEFINEP ) { SSize_t minlen = 0; SSize_t deltanext = 0; SSize_t fake_last_close = 0; I32 f = SCF_IN_DEFINE; StructCopy(&zero_scan_data, &data_fake, scan_data_t); scan = regnext(scan); assert( OP(scan) == IFTHEN ); DEBUG_PEEP("expect IFTHEN", scan, depth, flags); data_fake.last_closep= &fake_last_close; minlen = *minlenp; next = regnext(scan); scan = NEXTOPER(NEXTOPER(scan)); DEBUG_PEEP("scan", scan, depth, flags); DEBUG_PEEP("next", next, depth, flags); /* we suppose the run is continuous, last=next... * NOTE we dont use the return here! */ /* DEFINEP study_chunk() recursion */ (void)study_chunk(pRExC_state, &scan, &minlen, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); scan = next; } else if ( OP(scan) == BRANCH || OP(scan) == BRANCHJ || OP(scan) == IFTHEN ) { next = regnext(scan); code = OP(scan); /* The op(next)==code check below is to see if we * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN" * IFTHEN is special as it might not appear in pairs. * Not sure whether BRANCH-BRANCHJ is possible, regardless * we dont handle it cleanly. */ if (OP(next) == code || code == IFTHEN) { /* NOTE - There is similar code to this block below for * handling TRIE nodes on a re-study. If you change stuff here * check there too. */ SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0; regnode_ssc accum; regnode * const startbranch=scan; if (flags & SCF_DO_SUBSTR) { /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); while (OP(scan) == code) { SSize_t deltanext, minnext, fake; I32 f = 0; regnode_ssc this_class; DEBUG_PEEP("Branch", scan, depth, flags); num++; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; next = regnext(scan); scan = NEXTOPER(scan); /* everything */ if (code != BRANCH) /* everything but BRANCH */ scan = NEXTOPER(scan); if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; /* we suppose the run is continuous, last=next...*/ /* recurse study_chunk() for each BRANCH in an alternation */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (min1 > minnext) min1 = minnext; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < minnext + deltanext) max1 = minnext + deltanext; scan = next; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > minnext) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class); } if (code == IFTHEN && num < 2) /* Empty ELSE branch */ min1 = 0; if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; if (data->pos_delta >= SSize_t_MAX - (max1 - min1)) data->pos_delta = SSize_t_MAX; else data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; } min += min1; if (delta == SSize_t_MAX || SSize_t_MAX - delta - (max1 - min1) < 0) delta = SSize_t_MAX; else delta += max1 - min1; if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) { /* demq. Assuming this was/is a branch we are dealing with: 'scan' now points at the item that follows the branch sequence, whatever it is. We now start at the beginning of the sequence and look for subsequences of BRANCH->EXACT=>x1 BRANCH->EXACT=>x2 tail which would be constructed from a pattern like /A|LIST|OF|WORDS/ If we can find such a subsequence we need to turn the first element into a trie and then add the subsequent branch exact strings to the trie. We have two cases 1. patterns where the whole set of branches can be converted. 2. patterns where only a subset can be converted. In case 1 we can replace the whole set with a single regop for the trie. In case 2 we need to keep the start and end branches so 'BRANCH EXACT; BRANCH EXACT; BRANCH X' becomes BRANCH TRIE; BRANCH X; There is an additional case, that being where there is a common prefix, which gets split out into an EXACT like node preceding the TRIE node. If x(1..n)==tail then we can do a simple trie, if not we make a "jump" trie, such that when we match the appropriate word we "jump" to the appropriate tail node. Essentially we turn a nested if into a case structure of sorts. */ int made=0; if (!re_trie_maxbuff) { re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1); if (!SvIOK(re_trie_maxbuff)) sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); } if ( SvIV(re_trie_maxbuff)>=0 ) { regnode *cur; regnode *first = (regnode *)NULL; regnode *last = (regnode *)NULL; regnode *tail = scan; U8 trietype = 0; U32 count=0; /* var tail is used because there may be a TAIL regop in the way. Ie, the exacts will point to the thing following the TAIL, but the last branch will point at the TAIL. So we advance tail. If we have nested (?:) we may have to move through several tails. */ while ( OP( tail ) == TAIL ) { /* this is the TAIL generated by (?:) */ tail = regnext( tail ); } DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state); Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n", depth+1, "Looking for TRIE'able sequences. Tail node is ", (UV) REGNODE_OFFSET(tail), SvPV_nolen_const( RExC_mysv ) ); }); /* Step through the branches cur represents each branch, noper is the first thing to be matched as part of that branch noper_next is the regnext() of that node. We normally handle a case like this /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also support building with NOJUMPTRIE, which restricts the trie logic to structures like /FOO|BAR/. If noper is a trieable nodetype then the branch is a possible optimization target. If we are building under NOJUMPTRIE then we require that noper_next is the same as scan (our current position in the regex program). Once we have two or more consecutive such branches we can create a trie of the EXACT's contents and stitch it in place into the program. If the sequence represents all of the branches in the alternation we replace the entire thing with a single TRIE node. Otherwise when it is a subsequence we need to stitch it in place and replace only the relevant branches. This means the first branch has to remain as it is used by the alternation logic, and its next pointer, and needs to be repointed at the item on the branch chain following the last branch we have optimized away. This could be either a BRANCH, in which case the subsequence is internal, or it could be the item following the branch sequence in which case the subsequence is at the end (which does not necessarily mean the first node is the start of the alternation). TRIE_TYPE(X) is a define which maps the optype to a trietype. optype | trietype ----------------+----------- NOTHING | NOTHING EXACT | EXACT EXACT_ONLY8 | EXACT EXACTFU | EXACTFU EXACTFU_ONLY8 | EXACTFU EXACTFUP | EXACTFU EXACTFAA | EXACTFAA EXACTL | EXACTL EXACTFLU8 | EXACTFLU8 */ #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \ ? NOTHING \ : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \ ? EXACT \ : ( EXACTFU == (X) \ || EXACTFU_ONLY8 == (X) \ || EXACTFUP == (X) ) \ ? EXACTFU \ : ( EXACTFAA == (X) ) \ ? EXACTFAA \ : ( EXACTL == (X) ) \ ? EXACTL \ : ( EXACTFLU8 == (X) ) \ ? EXACTFLU8 \ : 0 ) /* dont use tail as the end marker for this traverse */ for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) { regnode * const noper = NEXTOPER( cur ); U8 noper_type = OP( noper ); U8 noper_trietype = TRIE_TYPE( noper_type ); #if defined(DEBUGGING) || defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0; #endif DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %d:%s (%d)", depth+1, REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) ); regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state); Perl_re_printf( aTHX_ " -> %d:%s", REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv)); if ( noper_next ) { regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state); Perl_re_printf( aTHX_ "\t=> %d:%s\t", REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv)); } Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] ); }); /* Is noper a trieable nodetype that can be merged * with the current trie (if there is one)? */ if ( noper_trietype && ( ( noper_trietype == NOTHING ) || ( trietype == NOTHING ) || ( trietype == noper_trietype ) ) #ifdef NOJUMPTRIE && noper_next >= tail #endif && count < U16_MAX) { /* Handle mergable triable node Either we are * the first node in a new trieable sequence, * in which case we do some bookkeeping, * otherwise we update the end pointer. */ if ( !first ) { first = cur; if ( noper_trietype == NOTHING ) { #if !defined(DEBUGGING) && !defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0; #endif if ( noper_next_trietype ) { trietype = noper_next_trietype; } else if (noper_next_type) { /* a NOTHING regop is 1 regop wide. * We need at least two for a trie * so we can't merge this in */ first = NULL; } } else { trietype = noper_trietype; } } else { if ( trietype == NOTHING ) trietype = noper_trietype; last = cur; } if (first) count++; } /* end handle mergable triable node */ else { /* handle unmergable node - * noper may either be a triable node which can * not be tried together with the current trie, * or a non triable node */ if ( last ) { /* If last is set and trietype is not * NOTHING then we have found at least two * triable branch sequences in a row of a * similar trietype so we can turn them * into a trie. If/when we allow NOTHING to * start a trie sequence this condition * will be required, and it isn't expensive * so we leave it in for now. */ if ( trietype && trietype != NOTHING ) make_trie( pRExC_state, startbranch, first, cur, tail, count, trietype, depth+1 ); last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */ } if ( noper_trietype #ifdef NOJUMPTRIE && noper_next >= tail #endif ){ /* noper is triable, so we can start a new * trie sequence */ count = 1; first = cur; trietype = noper_trietype; } else if (first) { /* if we already saw a first but the * current node is not triable then we have * to reset the first information. */ count = 0; first = NULL; trietype = 0; } } /* end handle unmergable node */ } /* loop over branches */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype] ); }); if ( last && trietype ) { if ( trietype != NOTHING ) { /* the last branch of the sequence was part of * a trie, so we have to construct it here * outside of the loop */ made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 ); #ifdef TRIE_STUDY_OPT if ( ((made == MADE_EXACT_TRIE && startbranch == first) || ( first_non_open == first )) && depth==0 ) { flags |= SCF_TRIE_RESTUDY; if ( startbranch == first && scan >= tail ) { RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN; } } #endif } else { /* at this point we know whatever we have is a * NOTHING sequence/branch AND if 'startbranch' * is 'first' then we can turn the whole thing * into a NOTHING */ if ( startbranch == first ) { regnode *opt; /* the entire thing is a NOTHING sequence, * something like this: (?:|) So we can * turn it into a plain NOTHING op. */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); }); OP(startbranch)= NOTHING; NEXT_OFF(startbranch)= tail - startbranch; for ( opt= startbranch + 1; opt < tail ; opt++ ) OP(opt)= OPTIMIZED; } } } /* end if ( last) */ } /* TRIE_MAXBUF is non zero */ } /* do trie */ } else if ( code == BRANCHJ ) { /* single branch is optimized. */ scan = NEXTOPER(NEXTOPER(scan)); } else /* single branch is optimized. */ scan = NEXTOPER(scan); continue; } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) { I32 paren = 0; regnode *start = NULL; regnode *end = NULL; U32 my_recursed_depth= recursed_depth; if (OP(scan) != SUSPEND) { /* GOSUB */ /* Do setup, note this code has side effects beyond * the rest of this block. Specifically setting * RExC_recurse[] must happen at least once during * study_chunk(). */ paren = ARG(scan); RExC_recurse[ARG2L(scan)] = scan; start = REGNODE_p(RExC_open_parens[paren]); end = REGNODE_p(RExC_close_parens[paren]); /* NOTE we MUST always execute the above code, even * if we do nothing with a GOSUB */ if ( ( flags & SCF_IN_DEFINE ) || ( (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF)) && ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 ) ) ) { /* no need to do anything here if we are in a define. */ /* or we are after some kind of infinite construct * so we can skip recursing into this item. * Since it is infinite we will not change the maxlen * or delta, and if we miss something that might raise * the minlen it will merely pessimise a little. * * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/ * might result in a minlen of 1 and not of 4, * but this doesn't make us mismatch, just try a bit * harder than we should. * */ scan= regnext(scan); continue; } if ( !recursed_depth || !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren) ) { /* it is quite possible that there are more efficient ways * to do this. We maintain a bitmap per level of recursion * of which patterns we have entered so we can detect if a * pattern creates a possible infinite loop. When we * recurse down a level we copy the previous levels bitmap * down. When we are at recursion level 0 we zero the top * level bitmap. It would be nice to implement a different * more efficient way of doing this. In particular the top * level bitmap may be unnecessary. */ if (!recursed_depth) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8); } else { Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed_bytes, U8); } /* we havent recursed into this paren yet, so recurse into it */ DEBUG_STUDYDATA("gosub-set", data, depth, is_inf); PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren); my_recursed_depth= recursed_depth + 1; } else { DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf); /* some form of infinite recursion, assume infinite length * */ if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; start= NULL; /* reset start so we dont recurse later on. */ } } else { paren = stopparen; start = scan + 2; end = regnext(scan); } if (start) { scan_frame *newframe; assert(end); if (!RExC_frame_last) { Newxz(newframe, 1, scan_frame); SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe); RExC_frame_head= newframe; RExC_frame_count++; } else if (!RExC_frame_last->next_frame) { Newxz(newframe, 1, scan_frame); RExC_frame_last->next_frame= newframe; newframe->prev_frame= RExC_frame_last; RExC_frame_count++; } else { newframe= RExC_frame_last->next_frame; } RExC_frame_last= newframe; newframe->next_regnode = regnext(scan); newframe->last_regnode = last; newframe->stopparen = stopparen; newframe->prev_recursed_depth = recursed_depth; newframe->this_prev_frame= frame; DEBUG_STUDYDATA("frame-new", data, depth, is_inf); DEBUG_PEEP("fnew", scan, depth, flags); frame = newframe; scan = start; stopparen = paren; last = end; depth = depth + 1; recursed_depth= my_recursed_depth; continue; } } else if ( OP(scan) == EXACT || OP(scan) == EXACT_ONLY8 || OP(scan) == EXACTL) { SSize_t l = STR_LEN(scan); UV uc; assert(l); if (UTF) { const U8 * const s = (U8*)STRING(scan); uc = utf8_to_uvchr_buf(s, s + l, NULL); l = utf8_length(s, s + l); } else { uc = *((U8*)STRING(scan)); } min += l; if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */ /* The code below prefers earlier match for fixed offset, later match for variable offset. */ if (data->last_end == -1) { /* Update the start info. */ data->last_start_min = data->pos_min; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta; } sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan)); if (UTF) SvUTF8_on(data->last_found); { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += utf8_length((U8*)STRING(scan), (U8*)STRING(scan)+STR_LEN(scan)); } data->last_end = data->pos_min + l; data->pos_min += l; /* As in the first entry. */ data->flags &= ~SF_BEFORE_EOL; } /* ANDing the code point leaves at most it, and not in locale, and * can't match null string */ if (flags & SCF_DO_STCLASS_AND) { ssc_cp_and(data->start_class, uc); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ssc_clear_locale(data->start_class); } else if (flags & SCF_DO_STCLASS_OR) { ssc_add_cp(data->start_class, uc); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT!, so is EXACTFish */ SSize_t l = STR_LEN(scan); const U8 * s = (U8*)STRING(scan); /* Search for fixed substrings supports EXACT only. */ if (flags & SCF_DO_SUBSTR) { assert(data); scan_commit(pRExC_state, data, minlenp, is_inf); } if (UTF) { l = utf8_length(s, s + l); } if (unfolded_multi_char) { RExC_seen |= REG_UNFOLDED_MULTI_SEEN; } min += l - min_subtract; assert (min >= 0); delta += min_subtract; if (flags & SCF_DO_SUBSTR) { data->pos_min += l - min_subtract; if (data->pos_min < 0) { data->pos_min = 0; } data->pos_delta += min_subtract; if (min_subtract) { data->cur_is_floating = 1; /* float */ } } if (flags & SCF_DO_STCLASS) { SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan); assert(EXACTF_invlist); if (flags & SCF_DO_STCLASS_AND) { if (OP(scan) != EXACTFL) ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ANYOF_POSIXL_ZERO(data->start_class); ssc_intersection(data->start_class, EXACTF_invlist, FALSE); } else { /* SCF_DO_STCLASS_OR */ ssc_union(data->start_class, EXACTF_invlist, FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; SvREFCNT_dec(EXACTF_invlist); } } else if (REGNODE_VARIES(OP(scan))) { SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0; I32 fl = 0, f = flags; regnode * const oscan = scan; regnode_ssc this_class; regnode_ssc *oclass = NULL; I32 next_is_eval = 0; switch (PL_regkind[OP(scan)]) { case WHILEM: /* End of (?:...)* . */ scan = NEXTOPER(scan); goto finish; case PLUS: if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) { next = NEXTOPER(scan); if ( OP(next) == EXACT || OP(next) == EXACT_ONLY8 || OP(next) == EXACTL || (flags & SCF_DO_STCLASS)) { mincount = 1; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } } if (flags & SCF_DO_SUBSTR) data->pos_min++; min++; /* FALLTHROUGH */ case STAR: next = NEXTOPER(scan); /* This temporary node can now be turned into EXACTFU, and * must, as regexec.c doesn't handle it */ if (OP(next) == EXACTFU_S_EDGE) { OP(next) = EXACTFU; } if ( STR_LEN(next) == 1 && isALPHA_A(* STRING(next)) && ( OP(next) == EXACTFAA || ( OP(next) == EXACTFU && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))) { /* These differ in just one bit */ U8 mask = ~ ('A' ^ 'a'); assert(isALPHA_A(* STRING(next))); /* Then replace it by an ANYOFM node, with * the mask set to the complement of the * bit that differs between upper and lower * case, and the lowest code point of the * pair (which the '&' forces) */ OP(next) = ANYOFM; ARG_SET(next, *STRING(next) & mask); FLAGS(next) = mask; } if (flags & SCF_DO_STCLASS) { mincount = 0; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; scan = regnext(scan); goto optimize_curly_tail; case CURLY: if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM) && (scan->flags == stopparen)) { mincount = 1; maxcount = 1; } else { mincount = ARG1(scan); maxcount = ARG2(scan); } next = regnext(scan); if (OP(scan) == CURLYX) { I32 lp = (data ? *(data->last_closep) : 0); scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX); } scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS; next_is_eval = (OP(scan) == EVAL); do_curly: if (flags & SCF_DO_SUBSTR) { if (mincount == 0) scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ pos_before = data->pos_min; } if (data) { fl = data->flags; data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL); if (is_inf) data->flags |= SF_IS_INF; } if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); oclass = data->start_class; data->start_class = &this_class; f |= SCF_DO_STCLASS_AND; f &= ~SCF_DO_STCLASS_OR; } /* Exclude from super-linear cache processing any {n,m} regops for which the combination of input pos and regex pos is not enough information to determine if a match will be possible. For example, in the regex /foo(bar\s*){4,8}baz/ with the regex pos at the \s*, the prospects for a match depend not only on the input position but also on how many (bar\s*) repeats into the {4,8} we are. */ if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY)) f &= ~SCF_WHILEM_VISITED_POS; /* This will finish on WHILEM, setting scan, or on NULL: */ /* recurse study_chunk() on loop bodies */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data, stopparen, recursed_depth, NULL, (mincount == 0 ? (f & ~SCF_DO_SUBSTR) : f) ,depth+1); if (flags & SCF_DO_STCLASS) data->start_class = oclass; if (mincount == 0 || minnext == 0) { if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); } else if (flags & SCF_DO_STCLASS_AND) { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&this_class, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } else { /* Non-zero len */ if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); } else if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class); flags &= ~SCF_DO_STCLASS; } if (!scan) /* It was not CURLYX, but CURLY. */ scan = next; if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR) /* ? quantifier ok, except for (?{ ... }) */ && (next_is_eval || !(mincount == 0 && maxcount == 1)) && (minnext == 0) && (deltanext == 0) && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR)) && maxcount <= REG_INFTY/3) /* Complement check for big count */ { _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP), Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Quantifier unexpected on zero-length expression " "in regex m/%" UTF8f "/", UTF8fARG(UTF, RExC_precomp_end - RExC_precomp, RExC_precomp))); } min += minnext * mincount; is_inf_internal |= deltanext == SSize_t_MAX || (maxcount == REG_INFTY && minnext + deltanext > 0); is_inf |= is_inf_internal; if (is_inf) { delta = SSize_t_MAX; } else { delta += (minnext + deltanext) * maxcount - minnext * mincount; } /* Try powerful optimization CURLYX => CURLYN. */ if ( OP(oscan) == CURLYX && data && data->flags & SF_IN_PAR && !(data->flags & SF_HAS_EVAL) && !deltanext && minnext == 1 ) { /* Try to optimize to CURLYN. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; regnode * const nxt1 = nxt; #ifdef DEBUGGING regnode *nxt2; #endif /* Skip open. */ nxt = regnext(nxt); if (!REGNODE_SIMPLE(OP(nxt)) && !(PL_regkind[OP(nxt)] == EXACT && STR_LEN(nxt) == 1)) goto nogo; #ifdef DEBUGGING nxt2 = nxt; #endif nxt = regnext(nxt); if (OP(nxt) != CLOSE) goto nogo; if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->while*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2; } /* Now we know that nxt2 is the only contents: */ oscan->flags = (U8)ARG(nxt); OP(oscan) = CURLYN; OP(nxt1) = NOTHING; /* was OPEN. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */ NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */ #endif } nogo: /* Try optimization CURLYX => CURLYM. */ if ( OP(oscan) == CURLYX && data && !(data->flags & SF_HAS_PAR) && !(data->flags & SF_HAS_EVAL) && !deltanext /* atom is fixed width */ && minnext != 0 /* CURLYM can't handle zero width */ /* Nor characters whose fold at run-time may be * multi-character */ && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN) ) { /* XXXX How to optimize if data == 0? */ /* Optimize to a simpler form. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */ regnode *nxt2; OP(oscan) = CURLYM; while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/ && (OP(nxt2) != WHILEM)) nxt = nxt2; OP(nxt2) = SUCCEED; /* Whas WHILEM */ /* Need to optimize away parenths. */ if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) { /* Set the parenth number. */ regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/ oscan->flags = (U8)ARG(nxt); if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->NOTHING*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2) + 1; } OP(nxt1) = OPTIMIZED; /* was OPEN. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */ NEXT_OFF(nxt + 1) = 0; /* just for consistency. */ #endif #if 0 while ( nxt1 && (OP(nxt1) != WHILEM)) { regnode *nnxt = regnext(nxt1); if (nnxt == nxt) { if (reg_off_by_arg[OP(nxt1)]) ARG_SET(nxt1, nxt2 - nxt1); else if (nxt2 - nxt1 < U16_MAX) NEXT_OFF(nxt1) = nxt2 - nxt1; else OP(nxt) = NOTHING; /* Cannot beautify */ } nxt1 = nnxt; } #endif /* Optimize again: */ /* recurse study_chunk() on optimised CURLYX => CURLYM */ study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt, NULL, stopparen, recursed_depth, NULL, 0, depth+1); } else oscan->flags = 0; } else if ((OP(oscan) == CURLYX) && (flags & SCF_WHILEM_VISITED_POS) /* See the comment on a similar expression above. However, this time it's not a subexpression we care about, but the expression itself. */ && (maxcount == REG_INFTY) && data) { /* This stays as CURLYX, we can put the count/of pair. */ /* Find WHILEM (as in regexec.c) */ regnode *nxt = oscan + NEXT_OFF(oscan); if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */ nxt += ARG(nxt); nxt = PREVOPER(nxt); if (nxt->flags & 0xf) { /* we've already set whilem count on this node */ } else if (++data->whilem_c < 16) { assert(data->whilem_c <= RExC_whilem_seen); nxt->flags = (U8)(data->whilem_c | (RExC_whilem_seen << 4)); /* On WHILEM */ } } if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (flags & SCF_DO_SUBSTR) { SV *last_str = NULL; STRLEN last_chrs = 0; int counted = mincount != 0; if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */ SSize_t b = pos_before >= data->last_start_min ? pos_before : data->last_start_min; STRLEN l; const char * const s = SvPV_const(data->last_found, l); SSize_t old = b - data->last_start_min; assert(old >= 0); if (UTF) old = utf8_hop_forward((U8*)s, old, (U8 *) SvEND(data->last_found)) - (U8*)s; l -= old; /* Get the added string: */ last_str = newSVpvn_utf8(s + old, l, UTF); last_chrs = UTF ? utf8_length((U8*)(s + old), (U8*)(s + old + l)) : l; if (deltanext == 0 && pos_before == b) { /* What was added is a constant string */ if (mincount > 1) { SvGROW(last_str, (mincount * l) + 1); repeatcpy(SvPVX(last_str) + l, SvPVX_const(last_str), l, mincount - 1); SvCUR_set(last_str, SvCUR(last_str) * mincount); /* Add additional parts. */ SvCUR_set(data->last_found, SvCUR(data->last_found) - l); sv_catsv(data->last_found, last_str); { SV * sv = data->last_found; MAGIC *mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += last_chrs * (mincount-1); } last_chrs *= mincount; data->last_end += l * (mincount - 1); } } else { /* start offset must point into the last copy */ data->last_start_min += minnext * (mincount - 1); data->last_start_max = is_inf ? SSize_t_MAX : data->last_start_max + (maxcount - 1) * (minnext + data->pos_delta); } } /* It is counted once already... */ data->pos_min += minnext * (mincount - counted); #if 0 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf " SSize_t_MAX=%" UVuf " minnext=%" UVuf " maxcount=%" UVuf " mincount=%" UVuf "\n", (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount, (UV)mincount); if (deltanext != SSize_t_MAX) Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n", (UV)(-counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta)); #endif if (deltanext == SSize_t_MAX || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta) data->pos_delta = SSize_t_MAX; else data->pos_delta += - counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount; if (mincount != maxcount) { /* Cannot extend fixed substrings found inside the group. */ scan_commit(pRExC_state, data, minlenp, is_inf); if (mincount && last_str) { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg) mg->mg_len = -1; sv_setsv(sv, last_str); data->last_end = data->pos_min; data->last_start_min = data->pos_min - last_chrs; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta - last_chrs; } data->cur_is_floating = 1; /* float */ } SvREFCNT_dec(last_str); } if (data && (fl & SF_HAS_EVAL)) data->flags |= SF_HAS_EVAL; optimize_curly_tail: if (OP(oscan) != CURLYX) { while (PL_regkind[OP(next = regnext(oscan))] == NOTHING && NEXT_OFF(next)) NEXT_OFF(oscan) += NEXT_OFF(next); } continue; default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d", OP(scan)); #endif case REF: case CLUMP: if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) { if (OP(scan) == CLUMP) { /* Actually is any start char, but very few code points * aren't start characters */ ssc_match_all_cp(data->start_class); } else { ssc_anything(data->start_class); } } flags &= ~SCF_DO_STCLASS; break; } } else if (OP(scan) == LNBREAK) { if (flags & SCF_DO_STCLASS) { if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } else if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg for * 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } min++; if (delta != SSize_t_MAX) delta++; /* Because of the 2 char string cr-lf */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += 1; if (data->pos_delta != SSize_t_MAX) { data->pos_delta += 1; } data->cur_is_floating = 1; /* float */ } } else if (REGNODE_SIMPLE(OP(scan))) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min++; } min++; if (flags & SCF_DO_STCLASS) { bool invert = 0; SV* my_invlist = NULL; U8 namedclass; /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; /* Some of the logic below assumes that switching locale on will only add false positives. */ switch (OP(scan)) { default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); #endif case SANY: if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_match_all_cp(data->start_class); break; case REG_ANY: { SV* REG_ANY_invlist = _new_invlist(2); REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist, '\n'); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert, hence all but \n */ ); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert */ ); ssc_clear_locale(data->start_class); } SvREFCNT_dec_NN(REG_ANY_invlist); } break; case ANYOFD: case ANYOFL: case ANYOFPOSIXL: case ANYOFH: case ANYOF: if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) scan); else ssc_or(pRExC_state, data->start_class, (regnode_charclass *) scan); break; case NANYOFM: case ANYOFM: { SV* cp_list = get_ANYOFM_contents(scan); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, cp_list, invert); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, cp_list, invert); } SvREFCNT_dec_NN(cp_list); break; } case NPOSIXL: invert = 1; /* FALLTHROUGH */ case POSIXL: namedclass = classnum_to_namedclass(FLAGS(scan)) + invert; if (flags & SCF_DO_STCLASS_AND) { bool was_there = cBOOL( ANYOF_POSIXL_TEST(data->start_class, namedclass)); ANYOF_POSIXL_ZERO(data->start_class); if (was_there) { /* Do an AND */ ANYOF_POSIXL_SET(data->start_class, namedclass); } /* No individual code points can now match */ data->start_class->invlist = sv_2mortal(_new_invlist(0)); } else { int complement = namedclass + ((invert) ? -1 : 1); assert(flags & SCF_DO_STCLASS_OR); /* If the complement of this class was already there, * the result is that they match all code points, * (\d + \D == everything). Remove the classes from * future consideration. Locale is not relevant in * this case */ if (ANYOF_POSIXL_TEST(data->start_class, complement)) { ssc_match_all_cp(data->start_class); ANYOF_POSIXL_CLEAR(data->start_class, namedclass); ANYOF_POSIXL_CLEAR(data->start_class, complement); } else { /* The usual case; just add this class to the existing set */ ANYOF_POSIXL_SET(data->start_class, namedclass); } } break; case NPOSIXA: /* For these, we always know the exact set of what's matched */ invert = 1; /* FALLTHROUGH */ case POSIXA: my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL); goto join_posix_and_ascii; case NPOSIXD: case NPOSIXU: invert = 1; /* FALLTHROUGH */ case POSIXD: case POSIXU: my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL); /* NPOSIXD matches all upper Latin1 code points unless the * target string being matched is UTF-8, which is * unknowable until match time. Since we are going to * invert, we want to get rid of all of them so that the * inversion will match all */ if (OP(scan) == NPOSIXD) { _invlist_subtract(my_invlist, PL_UpperLatin1, &my_invlist); } join_posix_and_ascii: if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, my_invlist, invert); ssc_clear_locale(data->start_class); } else { assert(flags & SCF_DO_STCLASS_OR); ssc_union(data->start_class, my_invlist, invert); } SvREFCNT_dec(my_invlist); } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) { data->flags |= (OP(scan) == MEOL ? SF_BEFORE_MEOL : SF_BEFORE_SEOL); scan_commit(pRExC_state, data, minlenp, is_inf); } else if ( PL_regkind[OP(scan)] == BRANCHJ /* Lookbehind, or need to calculate parens/evals/stclass: */ && (scan->flags || data || (flags & SCF_DO_STCLASS)) && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) { if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY || OP(scan) == UNLESSM ) { /* Negative Lookahead/lookbehind In this case we can't do fixed string optimisation. */ SSize_t deltanext, minnext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* recurse study_chunk() for lookahead body */ minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { if ( deltanext < 0 || deltanext > (I32) U8_MAX || minnext > (I32)U8_MAX || minnext + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } /* The 'next_off' field has been repurposed to count the * additional starting positions to try beyond the initial * one. (This leaves it at 0 for non-variable length * matches to avoid breakage for those not using this * extension) */ if (deltanext) { scan->next_off = deltanext; ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__VLB, "Variable length lookbehind is experimental"); } scan->flags = (U8)minnext + deltanext; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (f & SCF_DO_STCLASS_AND) { if (flags & SCF_DO_STCLASS_OR) { /* OR before, AND after: ideally we would recurse with * data_fake to get the AND applied by study of the * remainder of the pattern, and then derecurse; * *** HACK *** for now just treat as "no information". * See [perl #56690]. */ ssc_init(pRExC_state, data->start_class); } else { /* AND before and after: combine and continue. These * assertions are zero-length, so can match an EMPTY * string */ ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } } #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY else { /* Positive Lookahead/lookbehind In this case we can do fixed string optimisation, but we must be careful about it. Note in the case of lookbehind the positions will be offset by the minimum length of the pattern, something we won't know about until after the recurse. */ SSize_t deltanext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; /* We use SAVEFREEPV so that when the full compile is finished perl will clean up the allocated minlens when it's all done. This way we don't have to worry about freeing them when we know they wont be used, which would be a pain. */ SSize_t *minnextp; Newx( minnextp, 1, SSize_t ); SAVEFREEPV(minnextp); if (data) { StructCopy(data, &data_fake, scan_data_t); if ((flags & SCF_DO_SUBSTR) && data->last_found) { f |= SCF_DO_SUBSTR; if (scan->flags) scan_commit(pRExC_state, &data_fake, minlenp, is_inf); data_fake.last_found=newSVsv(data->last_found); } } else data_fake.last_closep = &fake; data_fake.flags = 0; data_fake.substrs[0].flags = 0; data_fake.substrs[1].flags = 0; data_fake.pos_delta = delta; if (is_inf) data_fake.flags |= SF_IS_INF; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* positive lookahead study_chunk() recursion */ *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { assert(0); /* This code has never been tested since this is normally not compiled */ if ( deltanext < 0 || deltanext > (I32) U8_MAX || *minnextp > (I32)U8_MAX || *minnextp + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } if (deltanext) { scan->next_off = deltanext; } scan->flags = (U8)*minnextp + deltanext; } *minnextp += min; if (f & SCF_DO_STCLASS_AND) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) { int i; if (RExC_rx->minlen<*minnextp) RExC_rx->minlen=*minnextp; scan_commit(pRExC_state, &data_fake, minnextp, is_inf); SvREFCNT_dec_NN(data_fake.last_found); for (i = 0; i < 2; i++) { if (data_fake.substrs[i].minlenp != minlenp) { data->substrs[i].min_offset = data_fake.substrs[i].min_offset; data->substrs[i].max_offset = data_fake.substrs[i].max_offset; data->substrs[i].minlenp = data_fake.substrs[i].minlenp; data->substrs[i].lookbehind += scan->flags; } } } } } #endif } else if (OP(scan) == OPEN) { if (stopparen != (I32)ARG(scan)) pars++; } else if (OP(scan) == CLOSE) { if (stopparen == (I32)ARG(scan)) { break; } if ((I32)ARG(scan) == is_par) { next = regnext(scan); if ( next && (OP(next) != WHILEM) && next < last) is_par = 0; /* Disable optimization */ } if (data) *(data->last_closep) = ARG(scan); } else if (OP(scan) == EVAL) { if (data) data->flags |= SF_HAS_EVAL; } else if ( PL_regkind[OP(scan)] == ENDLIKE ) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); flags &= ~SCF_DO_SUBSTR; } if (data && OP(scan)==ACCEPT) { data->flags |= SCF_SEEN_ACCEPT; if (stopmin > min) stopmin = min; } } else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */ { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; } else if (OP(scan) == GPOS) { if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) && !(delta || is_inf || (data && data->pos_delta))) { if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR)) RExC_rx->intflags |= PREGf_ANCH_GPOS; if (RExC_rx->gofs < (STRLEN)min) RExC_rx->gofs = min; } else { RExC_rx->intflags |= PREGf_GPOS_FLOAT; RExC_rx->gofs = 0; } } #ifdef TRIE_STUDY_OPT #ifdef FULL_TRIE_STUDY else if (PL_regkind[OP(scan)] == TRIE) { /* NOTE - There is similar code to this block above for handling BRANCH nodes on the initial study. If you change stuff here check there too. */ regnode *trie_node= scan; regnode *tail= regnext(scan); reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; SSize_t max1 = 0, min1 = SSize_t_MAX; regnode_ssc accum; if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */ /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); if (!trie->jump) { min1= trie->minlen; max1= trie->maxlen; } else { const regnode *nextbranch= NULL; U32 word; for ( word=1 ; word <= trie->wordcount ; word++) { SSize_t deltanext=0, minnext=0, f = 0, fake; regnode_ssc this_class; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; if (trie->jump[word]) { if (!nextbranch) nextbranch = trie_node + trie->jump[0]; scan= trie_node + trie->jump[word]; /* We go from the jump point to the branch that follows it. Note this means we need the vestigal unused branches even though they arent otherwise used. */ /* optimise study_chunk() for TRIE */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, (regnode *)nextbranch, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); } if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) nextbranch= regnext((regnode*)nextbranch); if (min1 > (SSize_t)(minnext + trie->minlen)) min1 = minnext + trie->minlen; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen)) max1 = minnext + deltanext + trie->maxlen; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > min + min1) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class); } } if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; /* float */ } min += min1; if (delta != SSize_t_MAX) { if (SSize_t_MAX - (max1 - min1) >= delta) delta += max1 - min1; else delta = SSize_t_MAX; } if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } scan= tail; continue; } #else else if (PL_regkind[OP(scan)] == TRIE) { reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; U8*bang=NULL; min += trie->minlen; delta += (trie->maxlen - trie->minlen); flags &= ~SCF_DO_STCLASS; /* xxx */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += trie->minlen; data->pos_delta += (trie->maxlen - trie->minlen); if (trie->maxlen != trie->minlen) data->cur_is_floating = 1; /* float */ } if (trie->jump) /* no more substrings -- for now /grr*/ flags &= ~SCF_DO_SUBSTR; } #endif /* old or new */ #endif /* TRIE_STUDY_OPT */ /* Else: zero-length, ignore. */ scan = regnext(scan); } finish: if (frame) { /* we need to unwind recursion. */ depth = depth - 1; DEBUG_STUDYDATA("frame-end", data, depth, is_inf); DEBUG_PEEP("fend", scan, depth, flags); /* restore previous context */ last = frame->last_regnode; scan = frame->next_regnode; stopparen = frame->stopparen; recursed_depth = frame->prev_recursed_depth; RExC_frame_last = frame->prev_frame; frame = frame->this_prev_frame; goto fake_study_recurse; } assert(!frame); DEBUG_STUDYDATA("pre-fin", data, depth, is_inf); *scanp = scan; *deltap = is_inf_internal ? SSize_t_MAX : delta; if (flags & SCF_DO_SUBSTR && is_inf) data->pos_delta = SSize_t_MAX - data->pos_min; if (is_par > (I32)U8_MAX) is_par = 0; if (is_par && pars==1 && data) { data->flags |= SF_IN_PAR; data->flags &= ~SF_HAS_PAR; } else if (pars && data) { data->flags |= SF_HAS_PAR; data->flags &= ~SF_IN_PAR; } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); if (flags & SCF_TRIE_RESTUDY) data->flags |= SCF_TRIE_RESTUDY; DEBUG_STUDYDATA("post-fin", data, depth, is_inf); { SSize_t final_minlen= min < stopmin ? min : stopmin; if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) { if (final_minlen > SSize_t_MAX - delta) RExC_maxlen = SSize_t_MAX; else if (RExC_maxlen < final_minlen + delta) RExC_maxlen = final_minlen + delta; } return final_minlen; } NOT_REACHED; /* NOTREACHED */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'regcomp.c: Prevent integer overflow from nested regex quantifiers. (CVE-2020-10543) On 32bit systems the size calculations for nested regular expression quantifiers could overflow causing heap memory corruption. Fixes: Perl/perl5-security#125 (cherry picked from commit bfd31397db5dc1a5c5d3e0a1f753a4f89a736e71)'</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: REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN"); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Assembling pattern from %d elements%s\n", pat_count, orig_rx_flags & RXf_SPLIT ? " for split" : "")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Precompiled pattern%s\n", orig_rx_flags & RXf_SPLIT ? " for split" : "")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL("Regexp out of space"); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ "Eval-group in insecure regular expression"); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Starting parse and generation\n"); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL("Regexp out of space"); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, "foo"); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Required size %" IVdf " nodes\n", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ "%s %" UVuf " bytes for offset annotations.\n", RExC_offsets ? "Got" : "Couldn't get", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ "\n"); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ "Starting post parse optimization\n"); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is "must appear" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP("first:", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""); data.substrs[1].str = newSVpvs(""); data.last_found = newSVpvs(""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name("study_chunk"); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name("study_chunk"); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the "real" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify "special" patterns that might result * in Perl NOT calling the regex engine and instead doing the match "itself", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ "Final program:\n"); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'regcomp: use long jumps if there is any possibility of overflow (CVE-2020-10878) Be conservative for backporting, we'll aim to do something more aggressive for bleadperl. (cherry picked from commit 9d7759db46f3b31b1d3f79c44266b6ba42a47fc6)'</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 SSize_t S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, SSize_t *minlenp, SSize_t *deltap, regnode *last, scan_data_t *data, I32 stopparen, U32 recursed_depth, regnode_ssc *and_withp, U32 flags, U32 depth) /* scanp: Start here (read-write). */ /* deltap: Write maxlen-minlen here. */ /* last: Stop before this one. */ /* data: string data about the pattern */ /* stopparen: treat close N as END */ /* recursed: which subroutines have we recursed into */ /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */ { dVAR; /* There must be at least this number of characters to match */ SSize_t min = 0; I32 pars = 0, code; regnode *scan = *scanp, *next; SSize_t delta = 0; int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF); int is_inf_internal = 0; /* The studied chunk is infinite */ I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0; scan_data_t data_fake; SV *re_trie_maxbuff = NULL; regnode *first_non_open = scan; SSize_t stopmin = SSize_t_MAX; scan_frame *frame = NULL; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_STUDY_CHUNK; RExC_study_started= 1; Zero(&data_fake, 1, scan_data_t); if ( depth == 0 ) { while (first_non_open && OP(first_non_open) == OPEN) first_non_open=regnext(first_non_open); } fake_study_recurse: DEBUG_r( RExC_study_chunk_recursed_count++; ); DEBUG_OPTIMISE_MORE_r( { Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p", depth, (long)stopparen, (unsigned long)RExC_study_chunk_recursed_count, (unsigned long)depth, (unsigned long)recursed_depth, scan, last); if (recursed_depth) { U32 i; U32 j; for ( j = 0 ; j < recursed_depth ; j++ ) { for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) { if ( PAREN_TEST(RExC_study_chunk_recursed + ( j * RExC_study_chunk_recursed_bytes), i ) && ( !j || !PAREN_TEST(RExC_study_chunk_recursed + (( j - 1 ) * RExC_study_chunk_recursed_bytes), i) ) ) { Perl_re_printf( aTHX_ " %d",(int)i); break; } } if ( j + 1 < recursed_depth ) { Perl_re_printf( aTHX_ ","); } } } Perl_re_printf( aTHX_ "\n"); } ); while ( scan && OP(scan) != END && scan < last ){ UV min_subtract = 0; /* How mmany chars to subtract from the minimum node length to get a real minimum (because the folded version may be shorter) */ bool unfolded_multi_char = FALSE; /* Peephole optimizer: */ DEBUG_STUDYDATA("Peep", data, depth, is_inf); DEBUG_PEEP("Peep", scan, depth, flags); /* The reason we do this here is that we need to deal with things like * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT * parsing code, as each (?:..) is handled by a different invocation of * reg() -- Yves */ JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0); /* Follow the next-chain of the current node and optimize away all the NOTHINGs from it. */ rck_elide_nothing(scan); /* The principal pseudo-switch. Cannot be a switch, since we look into several different things. */ if ( OP(scan) == DEFINEP ) { SSize_t minlen = 0; SSize_t deltanext = 0; SSize_t fake_last_close = 0; I32 f = SCF_IN_DEFINE; StructCopy(&zero_scan_data, &data_fake, scan_data_t); scan = regnext(scan); assert( OP(scan) == IFTHEN ); DEBUG_PEEP("expect IFTHEN", scan, depth, flags); data_fake.last_closep= &fake_last_close; minlen = *minlenp; next = regnext(scan); scan = NEXTOPER(NEXTOPER(scan)); DEBUG_PEEP("scan", scan, depth, flags); DEBUG_PEEP("next", next, depth, flags); /* we suppose the run is continuous, last=next... * NOTE we dont use the return here! */ /* DEFINEP study_chunk() recursion */ (void)study_chunk(pRExC_state, &scan, &minlen, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); scan = next; } else if ( OP(scan) == BRANCH || OP(scan) == BRANCHJ || OP(scan) == IFTHEN ) { next = regnext(scan); code = OP(scan); /* The op(next)==code check below is to see if we * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN" * IFTHEN is special as it might not appear in pairs. * Not sure whether BRANCH-BRANCHJ is possible, regardless * we dont handle it cleanly. */ if (OP(next) == code || code == IFTHEN) { /* NOTE - There is similar code to this block below for * handling TRIE nodes on a re-study. If you change stuff here * check there too. */ SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0; regnode_ssc accum; regnode * const startbranch=scan; if (flags & SCF_DO_SUBSTR) { /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); while (OP(scan) == code) { SSize_t deltanext, minnext, fake; I32 f = 0; regnode_ssc this_class; DEBUG_PEEP("Branch", scan, depth, flags); num++; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; next = regnext(scan); scan = NEXTOPER(scan); /* everything */ if (code != BRANCH) /* everything but BRANCH */ scan = NEXTOPER(scan); if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; /* we suppose the run is continuous, last=next...*/ /* recurse study_chunk() for each BRANCH in an alternation */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (min1 > minnext) min1 = minnext; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < minnext + deltanext) max1 = minnext + deltanext; scan = next; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > minnext) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class); } if (code == IFTHEN && num < 2) /* Empty ELSE branch */ min1 = 0; if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; if (data->pos_delta >= SSize_t_MAX - (max1 - min1)) data->pos_delta = SSize_t_MAX; else data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; } min += min1; if (delta == SSize_t_MAX || SSize_t_MAX - delta - (max1 - min1) < 0) delta = SSize_t_MAX; else delta += max1 - min1; if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) { /* demq. Assuming this was/is a branch we are dealing with: 'scan' now points at the item that follows the branch sequence, whatever it is. We now start at the beginning of the sequence and look for subsequences of BRANCH->EXACT=>x1 BRANCH->EXACT=>x2 tail which would be constructed from a pattern like /A|LIST|OF|WORDS/ If we can find such a subsequence we need to turn the first element into a trie and then add the subsequent branch exact strings to the trie. We have two cases 1. patterns where the whole set of branches can be converted. 2. patterns where only a subset can be converted. In case 1 we can replace the whole set with a single regop for the trie. In case 2 we need to keep the start and end branches so 'BRANCH EXACT; BRANCH EXACT; BRANCH X' becomes BRANCH TRIE; BRANCH X; There is an additional case, that being where there is a common prefix, which gets split out into an EXACT like node preceding the TRIE node. If x(1..n)==tail then we can do a simple trie, if not we make a "jump" trie, such that when we match the appropriate word we "jump" to the appropriate tail node. Essentially we turn a nested if into a case structure of sorts. */ int made=0; if (!re_trie_maxbuff) { re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1); if (!SvIOK(re_trie_maxbuff)) sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); } if ( SvIV(re_trie_maxbuff)>=0 ) { regnode *cur; regnode *first = (regnode *)NULL; regnode *last = (regnode *)NULL; regnode *tail = scan; U8 trietype = 0; U32 count=0; /* var tail is used because there may be a TAIL regop in the way. Ie, the exacts will point to the thing following the TAIL, but the last branch will point at the TAIL. So we advance tail. If we have nested (?:) we may have to move through several tails. */ while ( OP( tail ) == TAIL ) { /* this is the TAIL generated by (?:) */ tail = regnext( tail ); } DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state); Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n", depth+1, "Looking for TRIE'able sequences. Tail node is ", (UV) REGNODE_OFFSET(tail), SvPV_nolen_const( RExC_mysv ) ); }); /* Step through the branches cur represents each branch, noper is the first thing to be matched as part of that branch noper_next is the regnext() of that node. We normally handle a case like this /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also support building with NOJUMPTRIE, which restricts the trie logic to structures like /FOO|BAR/. If noper is a trieable nodetype then the branch is a possible optimization target. If we are building under NOJUMPTRIE then we require that noper_next is the same as scan (our current position in the regex program). Once we have two or more consecutive such branches we can create a trie of the EXACT's contents and stitch it in place into the program. If the sequence represents all of the branches in the alternation we replace the entire thing with a single TRIE node. Otherwise when it is a subsequence we need to stitch it in place and replace only the relevant branches. This means the first branch has to remain as it is used by the alternation logic, and its next pointer, and needs to be repointed at the item on the branch chain following the last branch we have optimized away. This could be either a BRANCH, in which case the subsequence is internal, or it could be the item following the branch sequence in which case the subsequence is at the end (which does not necessarily mean the first node is the start of the alternation). TRIE_TYPE(X) is a define which maps the optype to a trietype. optype | trietype ----------------+----------- NOTHING | NOTHING EXACT | EXACT EXACT_ONLY8 | EXACT EXACTFU | EXACTFU EXACTFU_ONLY8 | EXACTFU EXACTFUP | EXACTFU EXACTFAA | EXACTFAA EXACTL | EXACTL EXACTFLU8 | EXACTFLU8 */ #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \ ? NOTHING \ : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \ ? EXACT \ : ( EXACTFU == (X) \ || EXACTFU_ONLY8 == (X) \ || EXACTFUP == (X) ) \ ? EXACTFU \ : ( EXACTFAA == (X) ) \ ? EXACTFAA \ : ( EXACTL == (X) ) \ ? EXACTL \ : ( EXACTFLU8 == (X) ) \ ? EXACTFLU8 \ : 0 ) /* dont use tail as the end marker for this traverse */ for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) { regnode * const noper = NEXTOPER( cur ); U8 noper_type = OP( noper ); U8 noper_trietype = TRIE_TYPE( noper_type ); #if defined(DEBUGGING) || defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0; #endif DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %d:%s (%d)", depth+1, REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) ); regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state); Perl_re_printf( aTHX_ " -> %d:%s", REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv)); if ( noper_next ) { regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state); Perl_re_printf( aTHX_ "\t=> %d:%s\t", REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv)); } Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] ); }); /* Is noper a trieable nodetype that can be merged * with the current trie (if there is one)? */ if ( noper_trietype && ( ( noper_trietype == NOTHING ) || ( trietype == NOTHING ) || ( trietype == noper_trietype ) ) #ifdef NOJUMPTRIE && noper_next >= tail #endif && count < U16_MAX) { /* Handle mergable triable node Either we are * the first node in a new trieable sequence, * in which case we do some bookkeeping, * otherwise we update the end pointer. */ if ( !first ) { first = cur; if ( noper_trietype == NOTHING ) { #if !defined(DEBUGGING) && !defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0; #endif if ( noper_next_trietype ) { trietype = noper_next_trietype; } else if (noper_next_type) { /* a NOTHING regop is 1 regop wide. * We need at least two for a trie * so we can't merge this in */ first = NULL; } } else { trietype = noper_trietype; } } else { if ( trietype == NOTHING ) trietype = noper_trietype; last = cur; } if (first) count++; } /* end handle mergable triable node */ else { /* handle unmergable node - * noper may either be a triable node which can * not be tried together with the current trie, * or a non triable node */ if ( last ) { /* If last is set and trietype is not * NOTHING then we have found at least two * triable branch sequences in a row of a * similar trietype so we can turn them * into a trie. If/when we allow NOTHING to * start a trie sequence this condition * will be required, and it isn't expensive * so we leave it in for now. */ if ( trietype && trietype != NOTHING ) make_trie( pRExC_state, startbranch, first, cur, tail, count, trietype, depth+1 ); last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */ } if ( noper_trietype #ifdef NOJUMPTRIE && noper_next >= tail #endif ){ /* noper is triable, so we can start a new * trie sequence */ count = 1; first = cur; trietype = noper_trietype; } else if (first) { /* if we already saw a first but the * current node is not triable then we have * to reset the first information. */ count = 0; first = NULL; trietype = 0; } } /* end handle unmergable node */ } /* loop over branches */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype] ); }); if ( last && trietype ) { if ( trietype != NOTHING ) { /* the last branch of the sequence was part of * a trie, so we have to construct it here * outside of the loop */ made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 ); #ifdef TRIE_STUDY_OPT if ( ((made == MADE_EXACT_TRIE && startbranch == first) || ( first_non_open == first )) && depth==0 ) { flags |= SCF_TRIE_RESTUDY; if ( startbranch == first && scan >= tail ) { RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN; } } #endif } else { /* at this point we know whatever we have is a * NOTHING sequence/branch AND if 'startbranch' * is 'first' then we can turn the whole thing * into a NOTHING */ if ( startbranch == first ) { regnode *opt; /* the entire thing is a NOTHING sequence, * something like this: (?:|) So we can * turn it into a plain NOTHING op. */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); }); OP(startbranch)= NOTHING; NEXT_OFF(startbranch)= tail - startbranch; for ( opt= startbranch + 1; opt < tail ; opt++ ) OP(opt)= OPTIMIZED; } } } /* end if ( last) */ } /* TRIE_MAXBUF is non zero */ } /* do trie */ } else if ( code == BRANCHJ ) { /* single branch is optimized. */ scan = NEXTOPER(NEXTOPER(scan)); } else /* single branch is optimized. */ scan = NEXTOPER(scan); continue; } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) { I32 paren = 0; regnode *start = NULL; regnode *end = NULL; U32 my_recursed_depth= recursed_depth; if (OP(scan) != SUSPEND) { /* GOSUB */ /* Do setup, note this code has side effects beyond * the rest of this block. Specifically setting * RExC_recurse[] must happen at least once during * study_chunk(). */ paren = ARG(scan); RExC_recurse[ARG2L(scan)] = scan; start = REGNODE_p(RExC_open_parens[paren]); end = REGNODE_p(RExC_close_parens[paren]); /* NOTE we MUST always execute the above code, even * if we do nothing with a GOSUB */ if ( ( flags & SCF_IN_DEFINE ) || ( (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF)) && ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 ) ) ) { /* no need to do anything here if we are in a define. */ /* or we are after some kind of infinite construct * so we can skip recursing into this item. * Since it is infinite we will not change the maxlen * or delta, and if we miss something that might raise * the minlen it will merely pessimise a little. * * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/ * might result in a minlen of 1 and not of 4, * but this doesn't make us mismatch, just try a bit * harder than we should. * */ scan= regnext(scan); continue; } if ( !recursed_depth || !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren) ) { /* it is quite possible that there are more efficient ways * to do this. We maintain a bitmap per level of recursion * of which patterns we have entered so we can detect if a * pattern creates a possible infinite loop. When we * recurse down a level we copy the previous levels bitmap * down. When we are at recursion level 0 we zero the top * level bitmap. It would be nice to implement a different * more efficient way of doing this. In particular the top * level bitmap may be unnecessary. */ if (!recursed_depth) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8); } else { Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed_bytes, U8); } /* we havent recursed into this paren yet, so recurse into it */ DEBUG_STUDYDATA("gosub-set", data, depth, is_inf); PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren); my_recursed_depth= recursed_depth + 1; } else { DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf); /* some form of infinite recursion, assume infinite length * */ if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; start= NULL; /* reset start so we dont recurse later on. */ } } else { paren = stopparen; start = scan + 2; end = regnext(scan); } if (start) { scan_frame *newframe; assert(end); if (!RExC_frame_last) { Newxz(newframe, 1, scan_frame); SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe); RExC_frame_head= newframe; RExC_frame_count++; } else if (!RExC_frame_last->next_frame) { Newxz(newframe, 1, scan_frame); RExC_frame_last->next_frame= newframe; newframe->prev_frame= RExC_frame_last; RExC_frame_count++; } else { newframe= RExC_frame_last->next_frame; } RExC_frame_last= newframe; newframe->next_regnode = regnext(scan); newframe->last_regnode = last; newframe->stopparen = stopparen; newframe->prev_recursed_depth = recursed_depth; newframe->this_prev_frame= frame; DEBUG_STUDYDATA("frame-new", data, depth, is_inf); DEBUG_PEEP("fnew", scan, depth, flags); frame = newframe; scan = start; stopparen = paren; last = end; depth = depth + 1; recursed_depth= my_recursed_depth; continue; } } else if ( OP(scan) == EXACT || OP(scan) == EXACT_ONLY8 || OP(scan) == EXACTL) { SSize_t l = STR_LEN(scan); UV uc; assert(l); if (UTF) { const U8 * const s = (U8*)STRING(scan); uc = utf8_to_uvchr_buf(s, s + l, NULL); l = utf8_length(s, s + l); } else { uc = *((U8*)STRING(scan)); } min += l; if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */ /* The code below prefers earlier match for fixed offset, later match for variable offset. */ if (data->last_end == -1) { /* Update the start info. */ data->last_start_min = data->pos_min; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta; } sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan)); if (UTF) SvUTF8_on(data->last_found); { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += utf8_length((U8*)STRING(scan), (U8*)STRING(scan)+STR_LEN(scan)); } data->last_end = data->pos_min + l; data->pos_min += l; /* As in the first entry. */ data->flags &= ~SF_BEFORE_EOL; } /* ANDing the code point leaves at most it, and not in locale, and * can't match null string */ if (flags & SCF_DO_STCLASS_AND) { ssc_cp_and(data->start_class, uc); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ssc_clear_locale(data->start_class); } else if (flags & SCF_DO_STCLASS_OR) { ssc_add_cp(data->start_class, uc); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT!, so is EXACTFish */ SSize_t l = STR_LEN(scan); const U8 * s = (U8*)STRING(scan); /* Search for fixed substrings supports EXACT only. */ if (flags & SCF_DO_SUBSTR) { assert(data); scan_commit(pRExC_state, data, minlenp, is_inf); } if (UTF) { l = utf8_length(s, s + l); } if (unfolded_multi_char) { RExC_seen |= REG_UNFOLDED_MULTI_SEEN; } min += l - min_subtract; assert (min >= 0); delta += min_subtract; if (flags & SCF_DO_SUBSTR) { data->pos_min += l - min_subtract; if (data->pos_min < 0) { data->pos_min = 0; } data->pos_delta += min_subtract; if (min_subtract) { data->cur_is_floating = 1; /* float */ } } if (flags & SCF_DO_STCLASS) { SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan); assert(EXACTF_invlist); if (flags & SCF_DO_STCLASS_AND) { if (OP(scan) != EXACTFL) ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ANYOF_POSIXL_ZERO(data->start_class); ssc_intersection(data->start_class, EXACTF_invlist, FALSE); } else { /* SCF_DO_STCLASS_OR */ ssc_union(data->start_class, EXACTF_invlist, FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; SvREFCNT_dec(EXACTF_invlist); } } else if (REGNODE_VARIES(OP(scan))) { SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0; I32 fl = 0, f = flags; regnode * const oscan = scan; regnode_ssc this_class; regnode_ssc *oclass = NULL; I32 next_is_eval = 0; switch (PL_regkind[OP(scan)]) { case WHILEM: /* End of (?:...)* . */ scan = NEXTOPER(scan); goto finish; case PLUS: if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) { next = NEXTOPER(scan); if ( OP(next) == EXACT || OP(next) == EXACT_ONLY8 || OP(next) == EXACTL || (flags & SCF_DO_STCLASS)) { mincount = 1; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } } if (flags & SCF_DO_SUBSTR) data->pos_min++; min++; /* FALLTHROUGH */ case STAR: next = NEXTOPER(scan); /* This temporary node can now be turned into EXACTFU, and * must, as regexec.c doesn't handle it */ if (OP(next) == EXACTFU_S_EDGE) { OP(next) = EXACTFU; } if ( STR_LEN(next) == 1 && isALPHA_A(* STRING(next)) && ( OP(next) == EXACTFAA || ( OP(next) == EXACTFU && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))) { /* These differ in just one bit */ U8 mask = ~ ('A' ^ 'a'); assert(isALPHA_A(* STRING(next))); /* Then replace it by an ANYOFM node, with * the mask set to the complement of the * bit that differs between upper and lower * case, and the lowest code point of the * pair (which the '&' forces) */ OP(next) = ANYOFM; ARG_SET(next, *STRING(next) & mask); FLAGS(next) = mask; } if (flags & SCF_DO_STCLASS) { mincount = 0; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; scan = regnext(scan); goto optimize_curly_tail; case CURLY: if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM) && (scan->flags == stopparen)) { mincount = 1; maxcount = 1; } else { mincount = ARG1(scan); maxcount = ARG2(scan); } next = regnext(scan); if (OP(scan) == CURLYX) { I32 lp = (data ? *(data->last_closep) : 0); scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX); } scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS; next_is_eval = (OP(scan) == EVAL); do_curly: if (flags & SCF_DO_SUBSTR) { if (mincount == 0) scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ pos_before = data->pos_min; } if (data) { fl = data->flags; data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL); if (is_inf) data->flags |= SF_IS_INF; } if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); oclass = data->start_class; data->start_class = &this_class; f |= SCF_DO_STCLASS_AND; f &= ~SCF_DO_STCLASS_OR; } /* Exclude from super-linear cache processing any {n,m} regops for which the combination of input pos and regex pos is not enough information to determine if a match will be possible. For example, in the regex /foo(bar\s*){4,8}baz/ with the regex pos at the \s*, the prospects for a match depend not only on the input position but also on how many (bar\s*) repeats into the {4,8} we are. */ if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY)) f &= ~SCF_WHILEM_VISITED_POS; /* This will finish on WHILEM, setting scan, or on NULL: */ /* recurse study_chunk() on loop bodies */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data, stopparen, recursed_depth, NULL, (mincount == 0 ? (f & ~SCF_DO_SUBSTR) : f) ,depth+1); if (flags & SCF_DO_STCLASS) data->start_class = oclass; if (mincount == 0 || minnext == 0) { if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); } else if (flags & SCF_DO_STCLASS_AND) { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&this_class, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } else { /* Non-zero len */ if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); } else if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class); flags &= ~SCF_DO_STCLASS; } if (!scan) /* It was not CURLYX, but CURLY. */ scan = next; if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR) /* ? quantifier ok, except for (?{ ... }) */ && (next_is_eval || !(mincount == 0 && maxcount == 1)) && (minnext == 0) && (deltanext == 0) && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR)) && maxcount <= REG_INFTY/3) /* Complement check for big count */ { _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP), Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Quantifier unexpected on zero-length expression " "in regex m/%" UTF8f "/", UTF8fARG(UTF, RExC_precomp_end - RExC_precomp, RExC_precomp))); } if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext ) || min >= SSize_t_MAX - minnext * mincount ) { FAIL("Regexp out of space"); } min += minnext * mincount; is_inf_internal |= deltanext == SSize_t_MAX || (maxcount == REG_INFTY && minnext + deltanext > 0); is_inf |= is_inf_internal; if (is_inf) { delta = SSize_t_MAX; } else { delta += (minnext + deltanext) * maxcount - minnext * mincount; } /* Try powerful optimization CURLYX => CURLYN. */ if ( OP(oscan) == CURLYX && data && data->flags & SF_IN_PAR && !(data->flags & SF_HAS_EVAL) && !deltanext && minnext == 1 ) { /* Try to optimize to CURLYN. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; regnode * const nxt1 = nxt; #ifdef DEBUGGING regnode *nxt2; #endif /* Skip open. */ nxt = regnext(nxt); if (!REGNODE_SIMPLE(OP(nxt)) && !(PL_regkind[OP(nxt)] == EXACT && STR_LEN(nxt) == 1)) goto nogo; #ifdef DEBUGGING nxt2 = nxt; #endif nxt = regnext(nxt); if (OP(nxt) != CLOSE) goto nogo; if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->while*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2; } /* Now we know that nxt2 is the only contents: */ oscan->flags = (U8)ARG(nxt); OP(oscan) = CURLYN; OP(nxt1) = NOTHING; /* was OPEN. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */ NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */ #endif } nogo: /* Try optimization CURLYX => CURLYM. */ if ( OP(oscan) == CURLYX && data && !(data->flags & SF_HAS_PAR) && !(data->flags & SF_HAS_EVAL) && !deltanext /* atom is fixed width */ && minnext != 0 /* CURLYM can't handle zero width */ /* Nor characters whose fold at run-time may be * multi-character */ && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN) ) { /* XXXX How to optimize if data == 0? */ /* Optimize to a simpler form. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */ regnode *nxt2; OP(oscan) = CURLYM; while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/ && (OP(nxt2) != WHILEM)) nxt = nxt2; OP(nxt2) = SUCCEED; /* Whas WHILEM */ /* Need to optimize away parenths. */ if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) { /* Set the parenth number. */ regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/ oscan->flags = (U8)ARG(nxt); if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->NOTHING*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2) + 1; } OP(nxt1) = OPTIMIZED; /* was OPEN. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */ NEXT_OFF(nxt + 1) = 0; /* just for consistency. */ #endif #if 0 while ( nxt1 && (OP(nxt1) != WHILEM)) { regnode *nnxt = regnext(nxt1); if (nnxt == nxt) { if (reg_off_by_arg[OP(nxt1)]) ARG_SET(nxt1, nxt2 - nxt1); else if (nxt2 - nxt1 < U16_MAX) NEXT_OFF(nxt1) = nxt2 - nxt1; else OP(nxt) = NOTHING; /* Cannot beautify */ } nxt1 = nnxt; } #endif /* Optimize again: */ /* recurse study_chunk() on optimised CURLYX => CURLYM */ study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt, NULL, stopparen, recursed_depth, NULL, 0, depth+1); } else oscan->flags = 0; } else if ((OP(oscan) == CURLYX) && (flags & SCF_WHILEM_VISITED_POS) /* See the comment on a similar expression above. However, this time it's not a subexpression we care about, but the expression itself. */ && (maxcount == REG_INFTY) && data) { /* This stays as CURLYX, we can put the count/of pair. */ /* Find WHILEM (as in regexec.c) */ regnode *nxt = oscan + NEXT_OFF(oscan); if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */ nxt += ARG(nxt); nxt = PREVOPER(nxt); if (nxt->flags & 0xf) { /* we've already set whilem count on this node */ } else if (++data->whilem_c < 16) { assert(data->whilem_c <= RExC_whilem_seen); nxt->flags = (U8)(data->whilem_c | (RExC_whilem_seen << 4)); /* On WHILEM */ } } if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (flags & SCF_DO_SUBSTR) { SV *last_str = NULL; STRLEN last_chrs = 0; int counted = mincount != 0; if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */ SSize_t b = pos_before >= data->last_start_min ? pos_before : data->last_start_min; STRLEN l; const char * const s = SvPV_const(data->last_found, l); SSize_t old = b - data->last_start_min; assert(old >= 0); if (UTF) old = utf8_hop_forward((U8*)s, old, (U8 *) SvEND(data->last_found)) - (U8*)s; l -= old; /* Get the added string: */ last_str = newSVpvn_utf8(s + old, l, UTF); last_chrs = UTF ? utf8_length((U8*)(s + old), (U8*)(s + old + l)) : l; if (deltanext == 0 && pos_before == b) { /* What was added is a constant string */ if (mincount > 1) { SvGROW(last_str, (mincount * l) + 1); repeatcpy(SvPVX(last_str) + l, SvPVX_const(last_str), l, mincount - 1); SvCUR_set(last_str, SvCUR(last_str) * mincount); /* Add additional parts. */ SvCUR_set(data->last_found, SvCUR(data->last_found) - l); sv_catsv(data->last_found, last_str); { SV * sv = data->last_found; MAGIC *mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += last_chrs * (mincount-1); } last_chrs *= mincount; data->last_end += l * (mincount - 1); } } else { /* start offset must point into the last copy */ data->last_start_min += minnext * (mincount - 1); data->last_start_max = is_inf ? SSize_t_MAX : data->last_start_max + (maxcount - 1) * (minnext + data->pos_delta); } } /* It is counted once already... */ data->pos_min += minnext * (mincount - counted); #if 0 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf " SSize_t_MAX=%" UVuf " minnext=%" UVuf " maxcount=%" UVuf " mincount=%" UVuf "\n", (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount, (UV)mincount); if (deltanext != SSize_t_MAX) Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n", (UV)(-counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta)); #endif if (deltanext == SSize_t_MAX || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta) data->pos_delta = SSize_t_MAX; else data->pos_delta += - counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount; if (mincount != maxcount) { /* Cannot extend fixed substrings found inside the group. */ scan_commit(pRExC_state, data, minlenp, is_inf); if (mincount && last_str) { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg) mg->mg_len = -1; sv_setsv(sv, last_str); data->last_end = data->pos_min; data->last_start_min = data->pos_min - last_chrs; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta - last_chrs; } data->cur_is_floating = 1; /* float */ } SvREFCNT_dec(last_str); } if (data && (fl & SF_HAS_EVAL)) data->flags |= SF_HAS_EVAL; optimize_curly_tail: rck_elide_nothing(oscan); continue; default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d", OP(scan)); #endif case REF: case CLUMP: if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) { if (OP(scan) == CLUMP) { /* Actually is any start char, but very few code points * aren't start characters */ ssc_match_all_cp(data->start_class); } else { ssc_anything(data->start_class); } } flags &= ~SCF_DO_STCLASS; break; } } else if (OP(scan) == LNBREAK) { if (flags & SCF_DO_STCLASS) { if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } else if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg for * 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } min++; if (delta != SSize_t_MAX) delta++; /* Because of the 2 char string cr-lf */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += 1; if (data->pos_delta != SSize_t_MAX) { data->pos_delta += 1; } data->cur_is_floating = 1; /* float */ } } else if (REGNODE_SIMPLE(OP(scan))) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min++; } min++; if (flags & SCF_DO_STCLASS) { bool invert = 0; SV* my_invlist = NULL; U8 namedclass; /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; /* Some of the logic below assumes that switching locale on will only add false positives. */ switch (OP(scan)) { default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); #endif case SANY: if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_match_all_cp(data->start_class); break; case REG_ANY: { SV* REG_ANY_invlist = _new_invlist(2); REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist, '\n'); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert, hence all but \n */ ); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert */ ); ssc_clear_locale(data->start_class); } SvREFCNT_dec_NN(REG_ANY_invlist); } break; case ANYOFD: case ANYOFL: case ANYOFPOSIXL: case ANYOFH: case ANYOF: if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) scan); else ssc_or(pRExC_state, data->start_class, (regnode_charclass *) scan); break; case NANYOFM: case ANYOFM: { SV* cp_list = get_ANYOFM_contents(scan); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, cp_list, invert); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, cp_list, invert); } SvREFCNT_dec_NN(cp_list); break; } case NPOSIXL: invert = 1; /* FALLTHROUGH */ case POSIXL: namedclass = classnum_to_namedclass(FLAGS(scan)) + invert; if (flags & SCF_DO_STCLASS_AND) { bool was_there = cBOOL( ANYOF_POSIXL_TEST(data->start_class, namedclass)); ANYOF_POSIXL_ZERO(data->start_class); if (was_there) { /* Do an AND */ ANYOF_POSIXL_SET(data->start_class, namedclass); } /* No individual code points can now match */ data->start_class->invlist = sv_2mortal(_new_invlist(0)); } else { int complement = namedclass + ((invert) ? -1 : 1); assert(flags & SCF_DO_STCLASS_OR); /* If the complement of this class was already there, * the result is that they match all code points, * (\d + \D == everything). Remove the classes from * future consideration. Locale is not relevant in * this case */ if (ANYOF_POSIXL_TEST(data->start_class, complement)) { ssc_match_all_cp(data->start_class); ANYOF_POSIXL_CLEAR(data->start_class, namedclass); ANYOF_POSIXL_CLEAR(data->start_class, complement); } else { /* The usual case; just add this class to the existing set */ ANYOF_POSIXL_SET(data->start_class, namedclass); } } break; case NPOSIXA: /* For these, we always know the exact set of what's matched */ invert = 1; /* FALLTHROUGH */ case POSIXA: my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL); goto join_posix_and_ascii; case NPOSIXD: case NPOSIXU: invert = 1; /* FALLTHROUGH */ case POSIXD: case POSIXU: my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL); /* NPOSIXD matches all upper Latin1 code points unless the * target string being matched is UTF-8, which is * unknowable until match time. Since we are going to * invert, we want to get rid of all of them so that the * inversion will match all */ if (OP(scan) == NPOSIXD) { _invlist_subtract(my_invlist, PL_UpperLatin1, &my_invlist); } join_posix_and_ascii: if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, my_invlist, invert); ssc_clear_locale(data->start_class); } else { assert(flags & SCF_DO_STCLASS_OR); ssc_union(data->start_class, my_invlist, invert); } SvREFCNT_dec(my_invlist); } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) { data->flags |= (OP(scan) == MEOL ? SF_BEFORE_MEOL : SF_BEFORE_SEOL); scan_commit(pRExC_state, data, minlenp, is_inf); } else if ( PL_regkind[OP(scan)] == BRANCHJ /* Lookbehind, or need to calculate parens/evals/stclass: */ && (scan->flags || data || (flags & SCF_DO_STCLASS)) && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) { if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY || OP(scan) == UNLESSM ) { /* Negative Lookahead/lookbehind In this case we can't do fixed string optimisation. */ SSize_t deltanext, minnext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* recurse study_chunk() for lookahead body */ minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { if ( deltanext < 0 || deltanext > (I32) U8_MAX || minnext > (I32)U8_MAX || minnext + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } /* The 'next_off' field has been repurposed to count the * additional starting positions to try beyond the initial * one. (This leaves it at 0 for non-variable length * matches to avoid breakage for those not using this * extension) */ if (deltanext) { scan->next_off = deltanext; ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__VLB, "Variable length lookbehind is experimental"); } scan->flags = (U8)minnext + deltanext; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (f & SCF_DO_STCLASS_AND) { if (flags & SCF_DO_STCLASS_OR) { /* OR before, AND after: ideally we would recurse with * data_fake to get the AND applied by study of the * remainder of the pattern, and then derecurse; * *** HACK *** for now just treat as "no information". * See [perl #56690]. */ ssc_init(pRExC_state, data->start_class); } else { /* AND before and after: combine and continue. These * assertions are zero-length, so can match an EMPTY * string */ ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } } #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY else { /* Positive Lookahead/lookbehind In this case we can do fixed string optimisation, but we must be careful about it. Note in the case of lookbehind the positions will be offset by the minimum length of the pattern, something we won't know about until after the recurse. */ SSize_t deltanext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; /* We use SAVEFREEPV so that when the full compile is finished perl will clean up the allocated minlens when it's all done. This way we don't have to worry about freeing them when we know they wont be used, which would be a pain. */ SSize_t *minnextp; Newx( minnextp, 1, SSize_t ); SAVEFREEPV(minnextp); if (data) { StructCopy(data, &data_fake, scan_data_t); if ((flags & SCF_DO_SUBSTR) && data->last_found) { f |= SCF_DO_SUBSTR; if (scan->flags) scan_commit(pRExC_state, &data_fake, minlenp, is_inf); data_fake.last_found=newSVsv(data->last_found); } } else data_fake.last_closep = &fake; data_fake.flags = 0; data_fake.substrs[0].flags = 0; data_fake.substrs[1].flags = 0; data_fake.pos_delta = delta; if (is_inf) data_fake.flags |= SF_IS_INF; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* positive lookahead study_chunk() recursion */ *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { assert(0); /* This code has never been tested since this is normally not compiled */ if ( deltanext < 0 || deltanext > (I32) U8_MAX || *minnextp > (I32)U8_MAX || *minnextp + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } if (deltanext) { scan->next_off = deltanext; } scan->flags = (U8)*minnextp + deltanext; } *minnextp += min; if (f & SCF_DO_STCLASS_AND) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) { int i; if (RExC_rx->minlen<*minnextp) RExC_rx->minlen=*minnextp; scan_commit(pRExC_state, &data_fake, minnextp, is_inf); SvREFCNT_dec_NN(data_fake.last_found); for (i = 0; i < 2; i++) { if (data_fake.substrs[i].minlenp != minlenp) { data->substrs[i].min_offset = data_fake.substrs[i].min_offset; data->substrs[i].max_offset = data_fake.substrs[i].max_offset; data->substrs[i].minlenp = data_fake.substrs[i].minlenp; data->substrs[i].lookbehind += scan->flags; } } } } } #endif } else if (OP(scan) == OPEN) { if (stopparen != (I32)ARG(scan)) pars++; } else if (OP(scan) == CLOSE) { if (stopparen == (I32)ARG(scan)) { break; } if ((I32)ARG(scan) == is_par) { next = regnext(scan); if ( next && (OP(next) != WHILEM) && next < last) is_par = 0; /* Disable optimization */ } if (data) *(data->last_closep) = ARG(scan); } else if (OP(scan) == EVAL) { if (data) data->flags |= SF_HAS_EVAL; } else if ( PL_regkind[OP(scan)] == ENDLIKE ) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); flags &= ~SCF_DO_SUBSTR; } if (data && OP(scan)==ACCEPT) { data->flags |= SCF_SEEN_ACCEPT; if (stopmin > min) stopmin = min; } } else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */ { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; } else if (OP(scan) == GPOS) { if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) && !(delta || is_inf || (data && data->pos_delta))) { if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR)) RExC_rx->intflags |= PREGf_ANCH_GPOS; if (RExC_rx->gofs < (STRLEN)min) RExC_rx->gofs = min; } else { RExC_rx->intflags |= PREGf_GPOS_FLOAT; RExC_rx->gofs = 0; } } #ifdef TRIE_STUDY_OPT #ifdef FULL_TRIE_STUDY else if (PL_regkind[OP(scan)] == TRIE) { /* NOTE - There is similar code to this block above for handling BRANCH nodes on the initial study. If you change stuff here check there too. */ regnode *trie_node= scan; regnode *tail= regnext(scan); reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; SSize_t max1 = 0, min1 = SSize_t_MAX; regnode_ssc accum; if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */ /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); if (!trie->jump) { min1= trie->minlen; max1= trie->maxlen; } else { const regnode *nextbranch= NULL; U32 word; for ( word=1 ; word <= trie->wordcount ; word++) { SSize_t deltanext=0, minnext=0, f = 0, fake; regnode_ssc this_class; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; if (trie->jump[word]) { if (!nextbranch) nextbranch = trie_node + trie->jump[0]; scan= trie_node + trie->jump[word]; /* We go from the jump point to the branch that follows it. Note this means we need the vestigal unused branches even though they arent otherwise used. */ /* optimise study_chunk() for TRIE */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, (regnode *)nextbranch, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); } if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) nextbranch= regnext((regnode*)nextbranch); if (min1 > (SSize_t)(minnext + trie->minlen)) min1 = minnext + trie->minlen; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen)) max1 = minnext + deltanext + trie->maxlen; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > min + min1) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class); } } if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; /* float */ } min += min1; if (delta != SSize_t_MAX) { if (SSize_t_MAX - (max1 - min1) >= delta) delta += max1 - min1; else delta = SSize_t_MAX; } if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } scan= tail; continue; } #else else if (PL_regkind[OP(scan)] == TRIE) { reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; U8*bang=NULL; min += trie->minlen; delta += (trie->maxlen - trie->minlen); flags &= ~SCF_DO_STCLASS; /* xxx */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += trie->minlen; data->pos_delta += (trie->maxlen - trie->minlen); if (trie->maxlen != trie->minlen) data->cur_is_floating = 1; /* float */ } if (trie->jump) /* no more substrings -- for now /grr*/ flags &= ~SCF_DO_SUBSTR; } #endif /* old or new */ #endif /* TRIE_STUDY_OPT */ /* Else: zero-length, ignore. */ scan = regnext(scan); } finish: if (frame) { /* we need to unwind recursion. */ depth = depth - 1; DEBUG_STUDYDATA("frame-end", data, depth, is_inf); DEBUG_PEEP("fend", scan, depth, flags); /* restore previous context */ last = frame->last_regnode; scan = frame->next_regnode; stopparen = frame->stopparen; recursed_depth = frame->prev_recursed_depth; RExC_frame_last = frame->prev_frame; frame = frame->this_prev_frame; goto fake_study_recurse; } assert(!frame); DEBUG_STUDYDATA("pre-fin", data, depth, is_inf); *scanp = scan; *deltap = is_inf_internal ? SSize_t_MAX : delta; if (flags & SCF_DO_SUBSTR && is_inf) data->pos_delta = SSize_t_MAX - data->pos_min; if (is_par > (I32)U8_MAX) is_par = 0; if (is_par && pars==1 && data) { data->flags |= SF_IN_PAR; data->flags &= ~SF_HAS_PAR; } else if (pars && data) { data->flags |= SF_HAS_PAR; data->flags &= ~SF_IN_PAR; } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); if (flags & SCF_TRIE_RESTUDY) data->flags |= SCF_TRIE_RESTUDY; DEBUG_STUDYDATA("post-fin", data, depth, is_inf); { SSize_t final_minlen= min < stopmin ? min : stopmin; if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) { if (final_minlen > SSize_t_MAX - delta) RExC_maxlen = SSize_t_MAX; else if (RExC_maxlen < final_minlen + delta) RExC_maxlen = final_minlen + delta; } return final_minlen; } NOT_REACHED; /* NOTREACHED */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'study_chunk: avoid mutating regexp program within GOSUB gh16947 and gh17743: studying GOSUB may restudy in an inner call (via a mix of recursion and enframing) something that an outer call is in the middle of looking at. Let the outer frame deal with it. (CVE-2020-12723) (cherry picked from commit c4033e740bd18d9fbe3456a9db2ec2053cdc5271)'</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 ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length) { size_t item_len; mysql->affected_rows= net_field_length_ll(&pos); mysql->insert_id= net_field_length_ll(&pos); mysql->server_status=uint2korr(pos); pos+=2; mysql->warning_count=uint2korr(pos); pos+=2; if (pos < mysql->net.read_pos+length) { if ((item_len= net_field_length(&pos))) mysql->info=(char*) pos; /* check if server supports session tracking */ if (mysql->server_capabilities & CLIENT_SESSION_TRACKING) { ma_clear_session_state(mysql); pos+= item_len; if (mysql->server_status & SERVER_SESSION_STATE_CHANGED) { int i; if (pos < mysql->net.read_pos + length) { LIST *session_item; MYSQL_LEX_STRING *str= NULL; enum enum_session_state_type si_type; uchar *old_pos= pos; size_t item_len= net_field_length(&pos); /* length for all items */ /* length was already set, so make sure that info will be zero terminated */ if (mysql->info) *old_pos= 0; while (item_len > 0) { size_t plen; char *data; old_pos= pos; si_type= (enum enum_session_state_type)net_field_length(&pos); switch(si_type) { case SESSION_TRACK_SCHEMA: case SESSION_TRACK_STATE_CHANGE: case SESSION_TRACK_TRANSACTION_CHARACTERISTICS: case SESSION_TRACK_SYSTEM_VARIABLES: if (si_type != SESSION_TRACK_STATE_CHANGE) net_field_length(&pos); /* ignore total length, item length will follow next */ plen= net_field_length(&pos); if (!(session_item= ma_multi_malloc(0, &session_item, sizeof(LIST), &str, sizeof(MYSQL_LEX_STRING), &data, plen, NULL))) { ma_clear_session_state(mysql); SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0); return -1; } str->length= plen; str->str= data; memcpy(str->str, (char *)pos, plen); pos+= plen; session_item->data= str; mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item); /* in case schema has changed, we have to update mysql->db */ if (si_type == SESSION_TRACK_SCHEMA) { free(mysql->db); mysql->db= malloc(plen + 1); memcpy(mysql->db, str->str, plen); mysql->db[plen]= 0; } else if (si_type == SESSION_TRACK_SYSTEM_VARIABLES) { my_bool set_charset= 0; /* make sure that we update charset in case it has changed */ if (!strncmp(str->str, "character_set_client", str->length)) set_charset= 1; plen= net_field_length(&pos); if (!(session_item= ma_multi_malloc(0, &session_item, sizeof(LIST), &str, sizeof(MYSQL_LEX_STRING), &data, plen, NULL))) { ma_clear_session_state(mysql); SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0); return -1; } str->length= plen; str->str= data; memcpy(str->str, (char *)pos, plen); pos+= plen; session_item->data= str; mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item); if (set_charset && strncmp(mysql->charset->csname, str->str, str->length) != 0) { char cs_name[64]; MARIADB_CHARSET_INFO *cs_info; memcpy(cs_name, str->str, str->length); cs_name[str->length]= 0; if ((cs_info = (MARIADB_CHARSET_INFO *)mysql_find_charset_name(cs_name))) mysql->charset= cs_info; } } break; default: /* not supported yet */ plen= net_field_length(&pos); pos+= plen; break; } item_len-= (pos - old_pos); } } for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++) { mysql->extension->session_state[i].list= list_reverse(mysql->extension->session_state[i].list); mysql->extension->session_state[i].current= mysql->extension->session_state[i].list; } } } } /* CONC-351: clear session state information */ else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING) ma_clear_session_state(mysql); return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'sanity checks for client-supplied OK packet content reported by Matthias Kaiser, Apple Information Security'</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: exif_mnote_data_olympus_load (ExifMnoteData *en, const unsigned char *buf, unsigned int buf_size) { ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) en; ExifShort c; size_t i, tcount, o, o2, datao = 6, base = 0; if (!n || !buf || !buf_size) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataOlympus", "Short MakerNote"); return; } o2 = 6 + n->offset; /* Start of interesting data */ if ((o2 + 10 < o2) || (o2 + 10 < 10) || (o2 + 10 > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataOlympus", "Short MakerNote"); return; } /* * Olympus headers start with "OLYMP" and need to have at least * a size of 22 bytes (6 for 'OLYMP', 2 other bytes, 2 for the * number of entries, and 12 for one entry. * * Sanyo format is identical and uses identical tags except that * header starts with "SANYO". * * Epson format is identical and uses identical tags except that * header starts with "EPSON". * * Nikon headers start with "Nikon" (6 bytes including '\0'), * version number (1 or 2). * * Version 1 continues with 0, 1, 0, number_of_tags, * or just with number_of_tags (models D1H, D1X...). * * Version 2 continues with an unknown byte (0 or 10), * two unknown bytes (0), "MM" or "II", another byte 0 and * lastly 0x2A. */ n->version = exif_mnote_data_olympus_identify_variant(buf+o2, buf_size-o2); switch (n->version) { case olympusV1: case sanyoV1: case epsonV1: exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Parsing Olympus/Sanyo/Epson maker note v1..."); /* The number of entries is at position 8. */ if (buf[o2 + 6] == 1) n->order = EXIF_BYTE_ORDER_INTEL; else if (buf[o2 + 6 + 1] == 1) n->order = EXIF_BYTE_ORDER_MOTOROLA; o2 += 8; c = exif_get_short (buf + o2, n->order); if ((!(c & 0xFF)) && (c > 0x500)) { if (n->order == EXIF_BYTE_ORDER_INTEL) { n->order = EXIF_BYTE_ORDER_MOTOROLA; } else { n->order = EXIF_BYTE_ORDER_INTEL; } } break; case olympusV2: /* Olympus S760, S770 */ datao = o2; o2 += 8; if ((o2 + 4 < o2) || (o2 + 4 < 4) || (o2 + 4 > buf_size)) return; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Parsing Olympus maker note v2 (0x%02x, %02x, %02x, %02x)...", buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3]); if ((buf[o2] == 'I') && (buf[o2 + 1] == 'I')) n->order = EXIF_BYTE_ORDER_INTEL; else if ((buf[o2] == 'M') && (buf[o2 + 1] == 'M')) n->order = EXIF_BYTE_ORDER_MOTOROLA; /* The number of entries is at position 8+4. */ o2 += 4; break; case nikonV1: o2 += 6; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Parsing Nikon maker note v1 (0x%02x, %02x, %02x, " "%02x)...", buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3]); /* Skip version number */ o2 += 1; /* Skip an unknown byte (00 or 0A). */ o2 += 1; base = MNOTE_NIKON1_TAG_BASE; /* Fix endianness, if needed */ c = exif_get_short (buf + o2, n->order); if ((!(c & 0xFF)) && (c > 0x500)) { if (n->order == EXIF_BYTE_ORDER_INTEL) { n->order = EXIF_BYTE_ORDER_MOTOROLA; } else { n->order = EXIF_BYTE_ORDER_INTEL; } } break; case nikonV2: o2 += 6; if ((o2 + 12 < o2) || (o2 + 12 < 12) || (o2 + 12 > buf_size)) return; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Parsing Nikon maker note v2 (0x%02x, %02x, %02x, " "%02x, %02x, %02x, %02x, %02x)...", buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3], buf[o2 + 4], buf[o2 + 5], buf[o2 + 6], buf[o2 + 7]); /* Skip version number */ o2 += 1; /* Skip an unknown byte (00 or 0A). */ o2 += 1; /* Skip 2 unknown bytes (00 00). */ o2 += 2; /* * Byte order. From here the data offset * gets calculated. */ datao = o2; if (!strncmp ((char *)&buf[o2], "II", 2)) n->order = EXIF_BYTE_ORDER_INTEL; else if (!strncmp ((char *)&buf[o2], "MM", 2)) n->order = EXIF_BYTE_ORDER_MOTOROLA; else { exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Unknown " "byte order '%c%c'", buf[o2], buf[o2 + 1]); return; } o2 += 2; /* Skip 2 unknown bytes (00 2A). */ o2 += 2; /* Go to where the number of entries is. */ o2 = datao + exif_get_long (buf + o2, n->order); break; case nikonV0: exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Parsing Nikon maker note v0 (0x%02x, %02x, %02x, " "%02x, %02x, %02x, %02x, %02x)...", buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3], buf[o2 + 4], buf[o2 + 5], buf[o2 + 6], buf[o2 + 7]); /* 00 1b is # of entries in Motorola order - the rest should also be in MM order */ n->order = EXIF_BYTE_ORDER_MOTOROLA; break; default: exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus", "Unknown Olympus variant %i.", n->version); return; } /* Sanity check the offset */ if ((o2 + 2 < o2) || (o2 + 2 < 2) || (o2 + 2 > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteOlympus", "Short MakerNote"); return; } /* Read the number of tags */ c = exif_get_short (buf + o2, n->order); o2 += 2; /* Remove any old entries */ exif_mnote_data_olympus_clear (n); /* Reserve enough space for all the possible MakerNote tags */ n->entries = exif_mem_alloc (en->mem, sizeof (MnoteOlympusEntry) * c); if (!n->entries) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteOlympus", sizeof (MnoteOlympusEntry) * c); return; } /* Parse all c entries, storing ones that are successfully parsed */ tcount = 0; for (i = c, o = o2; i; --i, o += 12) { size_t s; if ((o + 12 < o) || (o + 12 < 12) || (o + 12 > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteOlympus", "Short MakerNote"); break; } n->entries[tcount].tag = exif_get_short (buf + o, n->order) + base; n->entries[tcount].format = exif_get_short (buf + o + 2, n->order); n->entries[tcount].components = exif_get_long (buf + o + 4, n->order); n->entries[tcount].order = n->order; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteOlympus", "Loading entry 0x%x ('%s')...", n->entries[tcount].tag, mnote_olympus_tag_get_name (n->entries[tcount].tag)); /* exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteOlympus", "0x%x %d %ld*(%d)", n->entries[tcount].tag, n->entries[tcount].format, n->entries[tcount].components, (int)exif_format_get_size(n->entries[tcount].format)); */ /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components; n->entries[tcount].size = s; if (s) { size_t dataofs = o + 8; if (s > 4) { /* The data in this case is merely a pointer */ dataofs = exif_get_long (buf + dataofs, n->order) + datao; #ifdef EXIF_OVERCOME_SANYO_OFFSET_BUG /* Some Sanyo models (e.g. VPC-C5, C40) suffer from a bug when * writing the offset for the MNOTE_OLYMPUS_TAG_THUMBNAILIMAGE * tag in its MakerNote. The offset is actually the absolute * position in the file instead of the position within the IFD. */ if (dataofs + s > buf_size && n->version == sanyoV1) { /* fix pointer */ dataofs -= datao + 6; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteOlympus", "Inconsistent thumbnail tag offset; attempting to recover"); } #endif } if ((dataofs + s < dataofs) || (dataofs + s < s) || (dataofs + s > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteOlympus", "Tag data past end of buffer (%u > %u)", (unsigned)(dataofs + s), buf_size); continue; } n->entries[tcount].data = exif_mem_alloc (en->mem, s); if (!n->entries[tcount].data) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteOlympus", s); continue; } memcpy (n->entries[tcount].data, buf + dataofs, s); } /* Tag was successfully parsed */ ++tcount; } /* Store the count of successfully parsed tags */ n->count = tcount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix MakerNote tag size overflow issues at read time. Check for a size overflow while reading tags, which ensures that the size is always consistent for the given components and type of the entry, making checking further down superfluous. This provides an alternate fix for https://sourceforge.net/p/libexif/bugs/125/ CVE-2016-6328 and for all the MakerNote types. Likely, this makes both commits 41bd0423 and 89e5b1c1 redundant as it ensures that MakerNote entries are well-formed when they're populated. Some improvements on top by Marcus Meissner <marcus@jet.franken.de> CVE-2020-13112'</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: exif_mnote_data_canon_load (ExifMnoteData *ne, const unsigned char *buf, unsigned int buf_size) { ExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne; ExifShort c; size_t i, tcount, o, datao; if (!n || !buf || !buf_size) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Short MakerNote"); return; } datao = 6 + n->offset; if ((datao + 2 < datao) || (datao + 2 < 2) || (datao + 2 > buf_size)) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Short MakerNote"); return; } /* Read the number of tags */ c = exif_get_short (buf + datao, n->order); datao += 2; /* Remove any old entries */ exif_mnote_data_canon_clear (n); /* Reserve enough space for all the possible MakerNote tags */ n->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c); if (!n->entries) { EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", sizeof (MnoteCanonEntry) * c); return; } /* Parse the entries */ tcount = 0; for (i = c, o = datao; i; --i, o += 12) { size_t s; if ((o + 12 < o) || (o + 12 < 12) || (o + 12 > buf_size)) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Short MakerNote"); break; } n->entries[tcount].tag = exif_get_short (buf + o, n->order); n->entries[tcount].format = exif_get_short (buf + o + 2, n->order); n->entries[tcount].components = exif_get_long (buf + o + 4, n->order); n->entries[tcount].order = n->order; exif_log (ne->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteCanon", "Loading entry 0x%x ('%s')...", n->entries[tcount].tag, mnote_canon_tag_get_name (n->entries[tcount].tag)); /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components; n->entries[tcount].size = s; if (!s) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Invalid zero-length tag size"); continue; } else { size_t dataofs = o + 8; if (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6; if ((dataofs + s < s) || (dataofs + s < dataofs) || (dataofs + s > buf_size)) { exif_log (ne->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteCanon", "Tag data past end of buffer (%u > %u)", (unsigned)(dataofs + s), buf_size); continue; } n->entries[tcount].data = exif_mem_alloc (ne->mem, s); if (!n->entries[tcount].data) { EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", s); continue; } memcpy (n->entries[tcount].data, buf + dataofs, s); } /* Tag was successfully parsed */ ++tcount; } /* Store the count of successfully parsed tags */ n->count = tcount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix MakerNote tag size overflow issues at read time. Check for a size overflow while reading tags, which ensures that the size is always consistent for the given components and type of the entry, making checking further down superfluous. This provides an alternate fix for https://sourceforge.net/p/libexif/bugs/125/ CVE-2016-6328 and for all the MakerNote types. Likely, this makes both commits 41bd0423 and 89e5b1c1 redundant as it ensures that MakerNote entries are well-formed when they're populated. Some improvements on top by Marcus Meissner <marcus@jet.franken.de> CVE-2020-13112'</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: exif_mnote_data_pentax_load (ExifMnoteData *en, const unsigned char *buf, unsigned int buf_size) { ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) en; size_t i, tcount, o, datao, base = 0; ExifShort c; if (!n || !buf || !buf_size) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataPentax", "Short MakerNote"); return; } datao = 6 + n->offset; if (CHECKOVERFLOW(datao, buf_size, 8)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataPentax", "Short MakerNote"); return; } /* Detect variant of Pentax/Casio MakerNote found */ if (!memcmp(buf + datao, "AOC", 4)) { if ((buf[datao + 4] == 'I') && (buf[datao + 5] == 'I')) { n->version = pentaxV3; n->order = EXIF_BYTE_ORDER_INTEL; } else if ((buf[datao + 4] == 'M') && (buf[datao + 5] == 'M')) { n->version = pentaxV3; n->order = EXIF_BYTE_ORDER_MOTOROLA; } else { /* Uses Casio v2 tags */ n->version = pentaxV2; } exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax", "Parsing Pentax maker note v%d...", (int)n->version); datao += 4 + 2; base = MNOTE_PENTAX2_TAG_BASE; } else if (!memcmp(buf + datao, "QVC", 4)) { exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax", "Parsing Casio maker note v2..."); n->version = casioV2; base = MNOTE_CASIO2_TAG_BASE; datao += 4 + 2; } else { /* probably assert(!memcmp(buf + datao, "\x00\x1b", 2)) */ exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax", "Parsing Pentax maker note v1..."); n->version = pentaxV1; } /* Read the number of tags */ c = exif_get_short (buf + datao, n->order); datao += 2; /* Remove any old entries */ exif_mnote_data_pentax_clear (n); /* Reserve enough space for all the possible MakerNote tags */ n->entries = exif_mem_alloc (en->mem, sizeof (MnotePentaxEntry) * c); if (!n->entries) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataPentax", sizeof (MnotePentaxEntry) * c); return; } /* Parse all c entries, storing ones that are successfully parsed */ tcount = 0; for (i = c, o = datao; i; --i, o += 12) { size_t s; if (CHECKOVERFLOW(o,buf_size,12)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataPentax", "Short MakerNote"); break; } n->entries[tcount].tag = exif_get_short (buf + o + 0, n->order) + base; n->entries[tcount].format = exif_get_short (buf + o + 2, n->order); n->entries[tcount].components = exif_get_long (buf + o + 4, n->order); n->entries[tcount].order = n->order; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnotePentax", "Loading entry 0x%x ('%s')...", n->entries[tcount].tag, mnote_pentax_tag_get_name (n->entries[tcount].tag)); /* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection, * we will check the buffer sizes closer later. */ if ( exif_format_get_size (n->entries[tcount].format) && buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components ) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataPentax", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components); break; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components; n->entries[tcount].size = s; if (s) { size_t dataofs = o + 8; if (s > 4) /* The data in this case is merely a pointer */ dataofs = exif_get_long (buf + dataofs, n->order) + 6; if (CHECKOVERFLOW(dataofs, buf_size, s)) { exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax", "Tag data past end " "of buffer (%u > %u)", (unsigned)(dataofs + s), buf_size); continue; } n->entries[tcount].data = exif_mem_alloc (en->mem, s); if (!n->entries[tcount].data) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataPentax", s); continue; } memcpy (n->entries[tcount].data, buf + dataofs, s); } /* Tag was successfully parsed */ ++tcount; } /* Store the count of successfully parsed tags */ n->count = tcount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-908'], 'message': 'Ensure the MakerNote data pointers are initialized with NULL. This ensures that an uninitialized pointer isn't dereferenced later in the case where the number of components (and therefore size) is 0. This fixes the second issue reported at https://sourceforge.net/p/libexif/bugs/125/ CVE-2020-13113'</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: exif_mnote_data_canon_load (ExifMnoteData *ne, const unsigned char *buf, unsigned int buf_size) { ExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne; ExifShort c; size_t i, tcount, o, datao; if (!n || !buf || !buf_size) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Short MakerNote"); return; } datao = 6 + n->offset; if (CHECKOVERFLOW(datao, buf_size, 2)) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Short MakerNote"); return; } /* Read the number of tags */ c = exif_get_short (buf + datao, n->order); datao += 2; /* Remove any old entries */ exif_mnote_data_canon_clear (n); /* Reserve enough space for all the possible MakerNote tags */ n->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c); if (!n->entries) { EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", sizeof (MnoteCanonEntry) * c); return; } /* Parse the entries */ tcount = 0; for (i = c, o = datao; i; --i, o += 12) { size_t s; if (CHECKOVERFLOW(o,buf_size,12)) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Short MakerNote"); break; } n->entries[tcount].tag = exif_get_short (buf + o, n->order); n->entries[tcount].format = exif_get_short (buf + o + 2, n->order); n->entries[tcount].components = exif_get_long (buf + o + 4, n->order); n->entries[tcount].order = n->order; exif_log (ne->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteCanon", "Loading entry 0x%x ('%s')...", n->entries[tcount].tag, mnote_canon_tag_get_name (n->entries[tcount].tag)); /* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection, * we will check the buffer sizes closer later. */ if ( exif_format_get_size (n->entries[tcount].format) && buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components ) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components); continue; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components; n->entries[tcount].size = s; if (!s) { exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteCanon", "Invalid zero-length tag size"); continue; } else { size_t dataofs = o + 8; if (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6; if (CHECKOVERFLOW(dataofs, buf_size, s)) { exif_log (ne->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteCanon", "Tag data past end of buffer (%u > %u)", (unsigned)(dataofs + s), buf_size); continue; } n->entries[tcount].data = exif_mem_alloc (ne->mem, s); if (!n->entries[tcount].data) { EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", s); continue; } memcpy (n->entries[tcount].data, buf + dataofs, s); } /* Tag was successfully parsed */ ++tcount; } /* Store the count of successfully parsed tags */ n->count = tcount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-908'], 'message': 'Ensure the MakerNote data pointers are initialized with NULL. This ensures that an uninitialized pointer isn't dereferenced later in the case where the number of components (and therefore size) is 0. This fixes the second issue reported at https://sourceforge.net/p/libexif/bugs/125/ CVE-2020-13113'</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 RGWCORSRule::format_exp_headers(string& s) { s = ""; for(list<string>::iterator it = exposable_hdrs.begin(); it != exposable_hdrs.end(); ++it) { if (s.length() > 0) s.append(","); s.append((*it)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-113'], 'message': 'rgw: sanitize newlines in s3 CORSConfiguration's ExposeHeader the values in the <ExposeHeader> element are sent back to clients in a Access-Control-Expose-Headers response header. if the values are allowed to have newlines in them, they can be used to inject arbitrary response headers this issue only affects s3, which gets these values from an xml document in swift, they're given in the request header X-Container-Meta-Access-Control-Expose-Headers, so the value itself cannot contain newlines Signed-off-by: Casey Bodley <cbodley@redhat.com> Reported-by: Adam Mohammed <amohammed@linode.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 ati_cursor_draw_line(VGACommonState *vga, uint8_t *d, int scr_y) { ATIVGAState *s = container_of(vga, ATIVGAState, vga); uint8_t *src; uint32_t *dp = (uint32_t *)d; int i, j, h; if (!(s->regs.crtc_gen_cntl & CRTC2_CUR_EN) || scr_y < vga->hw_cursor_y || scr_y >= vga->hw_cursor_y + 64 || scr_y > s->regs.crtc_v_total_disp >> 16) { return; } /* FIXME handle cur_hv_offs correctly */ src = s->vga.vram_ptr + s->cursor_offset + (scr_y - vga->hw_cursor_y) * 16; dp = &dp[vga->hw_cursor_x]; h = ((s->regs.crtc_h_total_disp >> 16) + 1) * 8; for (i = 0; i < 8; i++) { uint32_t color; uint8_t abits = src[i]; uint8_t xbits = src[i + 8]; for (j = 0; j < 8; j++, abits <<= 1, xbits <<= 1) { if (abits & BIT(7)) { if (xbits & BIT(7)) { color = dp[i * 8 + j] ^ 0xffffffff; /* complement */ } else { continue; /* transparent, no change */ } } else { color = (xbits & BIT(7) ? s->regs.cur_color1 : s->regs.cur_color0) | 0xff000000; } if (vga->hw_cursor_x + i * 8 + j >= h) { return; /* end of screen, don't span to next line */ } dp[i * 8 + j] = color; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ati: use vga_read_byte in ati_cursor_define This makes sure reads are confined to vga video memory. v3: use uint32_t, fix cut+paste bug. v2: fix ati_cursor_draw_line too. Reported-by: xu hang <flier_m@outlook.com> Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Reviewed-by: BALATON Zoltan <balaton@eik.bme.hu> Reviewed-by: Philippe Mathieu-Daudé <philmd@redhat.com> Message-id: 20190917111441.27405-3-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: BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp) { size_t olen; if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen)) return FALSE; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fixed GHSL-2020-101 missing NULL check (cherry picked from commit b207dbba35c505bbc3ad5aadc10b34980c6b7e8e)'</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: unsigned long move_page_tables(struct vm_area_struct *vma, unsigned long old_addr, struct vm_area_struct *new_vma, unsigned long new_addr, unsigned long len, bool need_rmap_locks) { unsigned long extent, next, old_end; struct mmu_notifier_range range; pmd_t *old_pmd, *new_pmd; old_end = old_addr + len; flush_cache_range(vma, old_addr, old_end); mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm, old_addr, old_end); mmu_notifier_invalidate_range_start(&range); for (; old_addr < old_end; old_addr += extent, new_addr += extent) { cond_resched(); next = (old_addr + PMD_SIZE) & PMD_MASK; /* even if next overflowed, extent below will be ok */ extent = next - old_addr; if (extent > old_end - old_addr) extent = old_end - old_addr; old_pmd = get_old_pmd(vma->vm_mm, old_addr); if (!old_pmd) continue; new_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr); if (!new_pmd) break; if (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) { if (extent == HPAGE_PMD_SIZE) { bool moved; /* See comment in move_ptes() */ if (need_rmap_locks) take_rmap_locks(vma); moved = move_huge_pmd(vma, old_addr, new_addr, old_end, old_pmd, new_pmd); if (need_rmap_locks) drop_rmap_locks(vma); if (moved) continue; } split_huge_pmd(vma, old_pmd, old_addr); if (pmd_trans_unstable(old_pmd)) continue; } else if (extent == PMD_SIZE) { #ifdef CONFIG_HAVE_MOVE_PMD /* * If the extent is PMD-sized, try to speed the move by * moving at the PMD level if possible. */ bool moved; if (need_rmap_locks) take_rmap_locks(vma); moved = move_normal_pmd(vma, old_addr, new_addr, old_end, old_pmd, new_pmd); if (need_rmap_locks) drop_rmap_locks(vma); if (moved) continue; #endif } if (pte_alloc(new_vma->vm_mm, new_pmd)) break; next = (new_addr + PMD_SIZE) & PMD_MASK; if (extent > next - new_addr) extent = next - new_addr; move_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma, new_pmd, new_addr, need_rmap_locks); } mmu_notifier_invalidate_range_end(&range); return len + old_addr - old_end; /* how much done */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'mm: Fix mremap not considering huge pmd devmap The original code in mm/mremap.c checks huge pmd by: if (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) { However, a DAX mapped nvdimm is mapped as huge page (by default) but it is not transparent huge page (_PAGE_PSE | PAGE_DEVMAP). This commit changes the condition to include the case. This addresses CVE-2020-10757. Fixes: 5c7fb56e5e3f ("mm, dax: dax-pmd vs thp-pmd vs hugetlbfs-pmd") Cc: <stable@vger.kernel.org> Reported-by: Fan Yang <Fan_Yang@sjtu.edu.cn> Signed-off-by: Fan Yang <Fan_Yang@sjtu.edu.cn> Tested-by: Fan Yang <Fan_Yang@sjtu.edu.cn> Tested-by: Dan Williams <dan.j.williams@intel.com> Reviewed-by: Dan Williams <dan.j.williams@intel.com> Acked-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.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: verify_peer_certificate (GTlsConnectionBase *tls, GTlsCertificate *peer_certificate) { GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls); GSocketConnectable *peer_identity; GTlsDatabase *database; GTlsCertificateFlags errors; gboolean is_client; is_client = G_IS_TLS_CLIENT_CONNECTION (tls); if (!is_client) peer_identity = NULL; else if (!g_tls_connection_base_is_dtls (tls)) peer_identity = g_tls_client_connection_get_server_identity (G_TLS_CLIENT_CONNECTION (tls)); else peer_identity = g_dtls_client_connection_get_server_identity (G_DTLS_CLIENT_CONNECTION (tls)); errors = 0; database = g_tls_connection_get_database (G_TLS_CONNECTION (tls)); if (!database) { errors |= G_TLS_CERTIFICATE_UNKNOWN_CA; errors |= g_tls_certificate_verify (peer_certificate, peer_identity, NULL); } else { GError *error = NULL; errors |= g_tls_database_verify_chain (database, peer_certificate, is_client ? G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER : G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT, peer_identity, g_tls_connection_get_interaction (G_TLS_CONNECTION (tls)), G_TLS_DATABASE_VERIFY_NONE, NULL, &error); if (error) { g_warning ("failure verifying certificate chain: %s", error->message); g_assert (errors != 0); g_clear_error (&error); } } if (tls_class->verify_peer_certificate) errors |= tls_class->verify_peer_certificate (tls, peer_certificate, errors); return errors; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'Return bad identity error if identity is unset When the server-identity property of GTlsClientConnection is unset, the documentation sasy we need to fail the certificate verification with G_TLS_CERTIFICATE_BAD_IDENTITY. This is important because otherwise, it's easy for applications to fail to specify server identity. Unfortunately, we did not correctly implement the intended, documented behavior. When server identity is missing, we check the validity of the TLS certificate, but do not check if it corresponds to the expected server (since we have no expected server). Then we assume the identity is good, instead of returning bad identity, as documented. This means, for example, that evil.com can present a valid certificate issued to evil.com, and we would happily accept it for paypal.com. Fixes #135'</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: f_histadd(typval_T *argvars UNUSED, typval_T *rettv) { #ifdef FEAT_CMDHIST int histype; char_u *str; char_u buf[NUMBUFLEN]; #endif rettv->vval.v_number = FALSE; if (check_restricted() || check_secure()) return; #ifdef FEAT_CMDHIST str = tv_get_string_chk(&argvars[0]); /* NULL on type error */ histype = str != NULL ? get_histtype(str) : -1; if (histype >= 0) { str = tv_get_string_buf(&argvars[1], buf); if (*str != NUL) { init_history(); add_to_history(histype, str, FALSE, NUL); rettv->vval.v_number = TRUE; return; } } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</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: f_luaeval(typval_T *argvars, typval_T *rettv) { char_u *str; char_u buf[NUMBUFLEN]; str = tv_get_string_buf(&argvars[0], buf); do_luaeval(str, argvars + 1, rettv); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</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: f_settabvar(typval_T *argvars, typval_T *rettv) { tabpage_T *save_curtab; tabpage_T *tp; char_u *varname, *tabvarname; typval_T *varp; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) return; tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); varname = tv_get_string_chk(&argvars[1]); varp = &argvars[2]; if (varname != NULL && varp != NULL && tp != NULL) { save_curtab = curtab; goto_tabpage_tp(tp, FALSE, FALSE); tabvarname = alloc((unsigned)STRLEN(varname) + 3); if (tabvarname != NULL) { STRCPY(tabvarname, "t:"); STRCPY(tabvarname + 2, varname); set_var(tabvarname, varp, TRUE); vim_free(tabvarname); } /* Restore current tabpage */ if (valid_tabpage(save_curtab)) goto_tabpage_tp(save_curtab, FALSE, FALSE); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</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: f_writefile(typval_T *argvars, typval_T *rettv) { int binary = FALSE; int append = FALSE; #ifdef HAVE_FSYNC int do_fsync = p_fs; #endif char_u *fname; FILE *fd; int ret = 0; listitem_T *li; list_T *list = NULL; blob_T *blob = NULL; rettv->vval.v_number = -1; if (check_restricted() || check_secure()) return; if (argvars[0].v_type == VAR_LIST) { list = argvars[0].vval.v_list; if (list == NULL) return; for (li = list->lv_first; li != NULL; li = li->li_next) if (tv_get_string_chk(&li->li_tv) == NULL) return; } else if (argvars[0].v_type == VAR_BLOB) { blob = argvars[0].vval.v_blob; if (blob == NULL) return; } else { semsg(_(e_invarg2), "writefile()"); return; } if (argvars[2].v_type != VAR_UNKNOWN) { char_u *arg2 = tv_get_string_chk(&argvars[2]); if (arg2 == NULL) return; if (vim_strchr(arg2, 'b') != NULL) binary = TRUE; if (vim_strchr(arg2, 'a') != NULL) append = TRUE; #ifdef HAVE_FSYNC if (vim_strchr(arg2, 's') != NULL) do_fsync = TRUE; else if (vim_strchr(arg2, 'S') != NULL) do_fsync = FALSE; #endif } fname = tv_get_string_chk(&argvars[1]); if (fname == NULL) return; /* Always open the file in binary mode, library functions have a mind of * their own about CR-LF conversion. */ if (*fname == NUL || (fd = mch_fopen((char *)fname, append ? APPENDBIN : WRITEBIN)) == NULL) { semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname); ret = -1; } else if (blob) { if (write_blob(fd, blob) == FAIL) ret = -1; #ifdef HAVE_FSYNC else if (do_fsync) // Ignore the error, the user wouldn't know what to do about it. // May happen for a device. vim_ignored = fsync(fileno(fd)); #endif fclose(fd); } else { if (write_list(fd, list, binary) == FAIL) ret = -1; #ifdef HAVE_FSYNC else if (do_fsync) /* Ignore the error, the user wouldn't know what to do about it. * May happen for a device. */ vim_ignored = fsync(fileno(fd)); #endif fclose(fd); } rettv->vval.v_number = ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</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: check_restricted(void) { if (restricted) { emsg(_("E145: Shell commands not allowed in rvim")); return TRUE; } return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</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: do_one_cmd( char_u **cmdlinep, int sourcing, #ifdef FEAT_EVAL struct condstack *cstack, #endif char_u *(*fgetline)(int, void *, int), void *cookie) /* argument for fgetline() */ { char_u *p; linenr_T lnum; long n; char *errormsg = NULL; /* error message */ char_u *after_modifier = NULL; exarg_T ea; /* Ex command arguments */ int save_msg_scroll = msg_scroll; cmdmod_T save_cmdmod; int ni; /* set when Not Implemented */ char_u *cmd; vim_memset(&ea, 0, sizeof(ea)); ea.line1 = 1; ea.line2 = 1; #ifdef FEAT_EVAL ++ex_nesting_level; #endif /* When the last file has not been edited :q has to be typed twice. */ if (quitmore #ifdef FEAT_EVAL /* avoid that a function call in 'statusline' does this */ && !getline_equal(fgetline, cookie, get_func_line) #endif /* avoid that an autocommand, e.g. QuitPre, does this */ && !getline_equal(fgetline, cookie, getnextac)) --quitmore; /* * Reset browse, confirm, etc.. They are restored when returning, for * recursive calls. */ save_cmdmod = cmdmod; /* "#!anything" is handled like a comment. */ if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!') goto doend; /* * 1. Skip comment lines and leading white space and colons. * 2. Handle command modifiers. */ // The "ea" structure holds the arguments that can be used. ea.cmd = *cmdlinep; ea.cmdlinep = cmdlinep; ea.getline = fgetline; ea.cookie = cookie; #ifdef FEAT_EVAL ea.cstack = cstack; #endif if (parse_command_modifiers(&ea, &errormsg, FALSE) == FAIL) goto doend; after_modifier = ea.cmd; #ifdef FEAT_EVAL ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE)); #else ea.skip = (if_level > 0); #endif /* * 3. Skip over the range to find the command. Let "p" point to after it. * * We need the command to know what kind of range it uses. */ cmd = ea.cmd; ea.cmd = skip_range(ea.cmd, NULL); if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL) ea.cmd = skipwhite(ea.cmd + 1); p = find_command(&ea, NULL); #ifdef FEAT_EVAL # ifdef FEAT_PROFILE // Count this line for profiling if skip is TRUE. if (do_profiling == PROF_YES && (!ea.skip || cstack->cs_idx == 0 || (cstack->cs_idx > 0 && (cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)))) { int skip = did_emsg || got_int || did_throw; if (ea.cmdidx == CMD_catch) skip = !skip && !(cstack->cs_idx >= 0 && (cstack->cs_flags[cstack->cs_idx] & CSF_THROWN) && !(cstack->cs_flags[cstack->cs_idx] & CSF_CAUGHT)); else if (ea.cmdidx == CMD_else || ea.cmdidx == CMD_elseif) skip = skip || !(cstack->cs_idx >= 0 && !(cstack->cs_flags[cstack->cs_idx] & (CSF_ACTIVE | CSF_TRUE))); else if (ea.cmdidx == CMD_finally) skip = FALSE; else if (ea.cmdidx != CMD_endif && ea.cmdidx != CMD_endfor && ea.cmdidx != CMD_endtry && ea.cmdidx != CMD_endwhile) skip = ea.skip; if (!skip) { if (getline_equal(fgetline, cookie, get_func_line)) func_line_exec(getline_cookie(fgetline, cookie)); else if (getline_equal(fgetline, cookie, getsourceline)) script_line_exec(); } } # endif /* May go to debug mode. If this happens and the ">quit" debug command is * used, throw an interrupt exception and skip the next command. */ dbg_check_breakpoint(&ea); if (!ea.skip && got_int) { ea.skip = TRUE; (void)do_intthrow(cstack); } #endif /* * 4. parse a range specifier of the form: addr [,addr] [;addr] .. * * where 'addr' is: * * % (entire file) * $ [+-NUM] * 'x [+-NUM] (where x denotes a currently defined mark) * . [+-NUM] * [+-NUM].. * NUM * * The ea.cmd pointer is updated to point to the first character following the * range spec. If an initial address is found, but no second, the upper bound * is equal to the lower. */ /* ea.addr_type for user commands is set by find_ucmd */ if (!IS_USER_CMDIDX(ea.cmdidx)) { if (ea.cmdidx != CMD_SIZE) ea.addr_type = cmdnames[(int)ea.cmdidx].cmd_addr_type; else ea.addr_type = ADDR_LINES; /* :wincmd range depends on the argument. */ if (ea.cmdidx == CMD_wincmd && p != NULL) get_wincmd_addr_type(skipwhite(p), &ea); } ea.cmd = cmd; if (parse_cmd_address(&ea, &errormsg, FALSE) == FAIL) goto doend; /* * 5. Parse the command. */ /* * Skip ':' and any white space */ ea.cmd = skipwhite(ea.cmd); while (*ea.cmd == ':') ea.cmd = skipwhite(ea.cmd + 1); /* * If we got a line, but no command, then go to the line. * If we find a '|' or '\n' we set ea.nextcmd. */ if (*ea.cmd == NUL || *ea.cmd == '"' || (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL) { /* * strange vi behaviour: * ":3" jumps to line 3 * ":3|..." prints line 3 * ":|" prints current line */ if (ea.skip) /* skip this if inside :if */ goto doend; if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2)) { ea.cmdidx = CMD_print; ea.argt = RANGE+COUNT+TRLBAR; if ((errormsg = invalid_range(&ea)) == NULL) { correct_range(&ea); ex_print(&ea); } } else if (ea.addr_count != 0) { if (ea.line2 > curbuf->b_ml.ml_line_count) { /* With '-' in 'cpoptions' a line number past the file is an * error, otherwise put it at the end of the file. */ if (vim_strchr(p_cpo, CPO_MINUS) != NULL) ea.line2 = -1; else ea.line2 = curbuf->b_ml.ml_line_count; } if (ea.line2 < 0) errormsg = _(e_invrange); else { if (ea.line2 == 0) curwin->w_cursor.lnum = 1; else curwin->w_cursor.lnum = ea.line2; beginline(BL_SOL | BL_FIX); } } goto doend; } /* If this looks like an undefined user command and there are CmdUndefined * autocommands defined, trigger the matching autocommands. */ if (p != NULL && ea.cmdidx == CMD_SIZE && !ea.skip && ASCII_ISUPPER(*ea.cmd) && has_cmdundefined()) { int ret; p = ea.cmd; while (ASCII_ISALNUM(*p)) ++p; p = vim_strnsave(ea.cmd, (int)(p - ea.cmd)); ret = apply_autocmds(EVENT_CMDUNDEFINED, p, p, TRUE, NULL); vim_free(p); /* If the autocommands did something and didn't cause an error, try * finding the command again. */ p = (ret #ifdef FEAT_EVAL && !aborting() #endif ) ? find_command(&ea, NULL) : ea.cmd; } #ifdef FEAT_USR_CMDS if (p == NULL) { if (!ea.skip) errormsg = _("E464: Ambiguous use of user-defined command"); goto doend; } /* Check for wrong commands. */ if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78 && !IS_USER_CMDIDX(ea.cmdidx)) { errormsg = uc_fun_cmd(); goto doend; } #endif if (ea.cmdidx == CMD_SIZE) { if (!ea.skip) { STRCPY(IObuff, _("E492: Not an editor command")); if (!sourcing) { /* If the modifier was parsed OK the error must be in the * following command */ if (after_modifier != NULL) append_command(after_modifier); else append_command(*cmdlinep); } errormsg = (char *)IObuff; did_emsg_syntax = TRUE; } goto doend; } ni = (!IS_USER_CMDIDX(ea.cmdidx) && (cmdnames[ea.cmdidx].cmd_func == ex_ni #ifdef HAVE_EX_SCRIPT_NI || cmdnames[ea.cmdidx].cmd_func == ex_script_ni #endif )); #ifndef FEAT_EVAL /* * When the expression evaluation is disabled, recognize the ":if" and * ":endif" commands and ignore everything in between it. */ if (ea.cmdidx == CMD_if) ++if_level; if (if_level) { if (ea.cmdidx == CMD_endif) --if_level; goto doend; } #endif /* forced commands */ if (*p == '!' && ea.cmdidx != CMD_substitute && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic) { ++p; ea.forceit = TRUE; } else ea.forceit = FALSE; /* * 6. Parse arguments. */ if (!IS_USER_CMDIDX(ea.cmdidx)) ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt; if (!ea.skip) { #ifdef HAVE_SANDBOX if (sandbox != 0 && !(ea.argt & SBOXOK)) { /* Command not allowed in sandbox. */ errormsg = _(e_sandbox); goto doend; } #endif if (!curbuf->b_p_ma && (ea.argt & MODIFY)) { /* Command not allowed in non-'modifiable' buffer */ errormsg = _(e_modifiable); goto doend; } if (text_locked() && !(ea.argt & CMDWIN) && !IS_USER_CMDIDX(ea.cmdidx)) { /* Command not allowed when editing the command line. */ errormsg = _(get_text_locked_msg()); goto doend; } /* Disallow editing another buffer when "curbuf_lock" is set. * Do allow ":checktime" (it is postponed). * Do allow ":edit" (check for an argument later). * Do allow ":file" with no arguments (check for an argument later). */ if (!(ea.argt & CMDWIN) && ea.cmdidx != CMD_checktime && ea.cmdidx != CMD_edit && ea.cmdidx != CMD_file && !IS_USER_CMDIDX(ea.cmdidx) && curbuf_locked()) goto doend; if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0) { /* no range allowed */ errormsg = _(e_norange); goto doend; } } if (!ni && !(ea.argt & BANG) && ea.forceit) /* no <!> allowed */ { errormsg = _(e_nobang); goto doend; } /* * Don't complain about the range if it is not used * (could happen if line_count is accidentally set to 0). */ if (!ea.skip && !ni) { /* * If the range is backwards, ask for confirmation and, if given, swap * ea.line1 & ea.line2 so it's forwards again. * When global command is busy, don't ask, will fail below. */ if (!global_busy && ea.line1 > ea.line2) { if (msg_silent == 0) { if (sourcing || exmode_active) { errormsg = _("E493: Backwards range given"); goto doend; } if (ask_yesno((char_u *) _("Backwards range given, OK to swap"), FALSE) != 'y') goto doend; } lnum = ea.line1; ea.line1 = ea.line2; ea.line2 = lnum; } if ((errormsg = invalid_range(&ea)) != NULL) goto doend; } if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */ ea.line2 = 1; correct_range(&ea); #ifdef FEAT_FOLDING if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy && ea.addr_type == ADDR_LINES) { /* Put the first line at the start of a closed fold, put the last line * at the end of a closed fold. */ (void)hasFolding(ea.line1, &ea.line1, NULL); (void)hasFolding(ea.line2, NULL, &ea.line2); } #endif #ifdef FEAT_QUICKFIX /* * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg' * option here, so things like % get expanded. */ p = replace_makeprg(&ea, p, cmdlinep); if (p == NULL) goto doend; #endif /* * Skip to start of argument. * Don't do this for the ":!" command, because ":!! -l" needs the space. */ if (ea.cmdidx == CMD_bang) ea.arg = p; else ea.arg = skipwhite(p); // ":file" cannot be run with an argument when "curbuf_lock" is set if (ea.cmdidx == CMD_file && *ea.arg != NUL && curbuf_locked()) goto doend; /* * Check for "++opt=val" argument. * Must be first, allow ":w ++enc=utf8 !cmd" */ if (ea.argt & ARGOPT) while (ea.arg[0] == '+' && ea.arg[1] == '+') if (getargopt(&ea) == FAIL && !ni) { errormsg = _(e_invarg); goto doend; } if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { if (*ea.arg == '>') /* append */ { if (*++ea.arg != '>') /* typed wrong */ { errormsg = _("E494: Use w or w>>"); goto doend; } ea.arg = skipwhite(ea.arg + 1); ea.append = TRUE; } else if (*ea.arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */ { ++ea.arg; ea.usefilter = TRUE; } } if (ea.cmdidx == CMD_read) { if (ea.forceit) { ea.usefilter = TRUE; /* :r! filter if ea.forceit */ ea.forceit = FALSE; } else if (*ea.arg == '!') /* :r !filter */ { ++ea.arg; ea.usefilter = TRUE; } } if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { ea.amount = 1; while (*ea.arg == *ea.cmd) /* count number of '>' or '<' */ { ++ea.arg; ++ea.amount; } ea.arg = skipwhite(ea.arg); } /* * Check for "+command" argument, before checking for next command. * Don't do this for ":read !cmd" and ":write !cmd". */ if ((ea.argt & EDITCMD) && !ea.usefilter) ea.do_ecmd_cmd = getargcmd(&ea.arg); /* * Check for '|' to separate commands and '"' to start comments. * Don't do this for ":read !cmd" and ":write !cmd". */ if ((ea.argt & TRLBAR) && !ea.usefilter) separate_nextcmd(&ea); /* * Check for <newline> to end a shell command. * Also do this for ":read !cmd", ":write !cmd" and ":global". * Any others? */ else if (ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal || ea.cmdidx == CMD_global || ea.cmdidx == CMD_vglobal || ea.usefilter) { for (p = ea.arg; *p; ++p) { /* Remove one backslash before a newline, so that it's possible to * pass a newline to the shell and also a newline that is preceded * with a backslash. This makes it impossible to end a shell * command in a backslash, but that doesn't appear useful. * Halving the number of backslashes is incompatible with previous * versions. */ if (*p == '\\' && p[1] == '\n') STRMOVE(p, p + 1); else if (*p == '\n') { ea.nextcmd = p + 1; *p = NUL; break; } } } if ((ea.argt & DFLALL) && ea.addr_count == 0) { buf_T *buf; ea.line1 = 1; switch (ea.addr_type) { case ADDR_LINES: ea.line2 = curbuf->b_ml.ml_line_count; break; case ADDR_LOADED_BUFFERS: buf = firstbuf; while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) buf = buf->b_next; ea.line1 = buf->b_fnum; buf = lastbuf; while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) buf = buf->b_prev; ea.line2 = buf->b_fnum; break; case ADDR_BUFFERS: ea.line1 = firstbuf->b_fnum; ea.line2 = lastbuf->b_fnum; break; case ADDR_WINDOWS: ea.line2 = LAST_WIN_NR; break; case ADDR_TABS: ea.line2 = LAST_TAB_NR; break; case ADDR_TABS_RELATIVE: ea.line2 = 1; break; case ADDR_ARGUMENTS: if (ARGCOUNT == 0) ea.line1 = ea.line2 = 0; else ea.line2 = ARGCOUNT; break; #ifdef FEAT_QUICKFIX case ADDR_QUICKFIX: ea.line2 = qf_get_size(&ea); if (ea.line2 == 0) ea.line2 = 1; break; #endif } } /* accept numbered register only when no count allowed (:put) */ if ( (ea.argt & REGSTR) && *ea.arg != NUL /* Do not allow register = for user commands */ && (!IS_USER_CMDIDX(ea.cmdidx) || *ea.arg != '=') && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg))) { #ifndef FEAT_CLIPBOARD /* check these explicitly for a more specific error message */ if (*ea.arg == '*' || *ea.arg == '+') { errormsg = _(e_invalidreg); goto doend; } #endif if (valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put && !IS_USER_CMDIDX(ea.cmdidx)))) { ea.regname = *ea.arg++; #ifdef FEAT_EVAL /* for '=' register: accept the rest of the line as an expression */ if (ea.arg[-1] == '=' && ea.arg[0] != NUL) { set_expr_line(vim_strsave(ea.arg)); ea.arg += STRLEN(ea.arg); } #endif ea.arg = skipwhite(ea.arg); } } /* * Check for a count. When accepting a BUFNAME, don't use "123foo" as a * count, it's a buffer name. */ if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg) && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL || VIM_ISWHITE(*p))) { n = getdigits(&ea.arg); ea.arg = skipwhite(ea.arg); if (n <= 0 && !ni && (ea.argt & ZEROR) == 0) { errormsg = _(e_zerocount); goto doend; } if (ea.argt & NOTADR) /* e.g. :buffer 2, :sleep 3 */ { ea.line2 = n; if (ea.addr_count == 0) ea.addr_count = 1; } else { ea.line1 = ea.line2; ea.line2 += n - 1; ++ea.addr_count; /* * Be vi compatible: no error message for out of range. */ if (ea.addr_type == ADDR_LINES && ea.line2 > curbuf->b_ml.ml_line_count) ea.line2 = curbuf->b_ml.ml_line_count; } } /* * Check for flags: 'l', 'p' and '#'. */ if (ea.argt & EXFLAGS) get_flags(&ea); /* no arguments allowed */ if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0)) { errormsg = _(e_trailing); goto doend; } if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL) { errormsg = _(e_argreq); goto doend; } #ifdef FEAT_EVAL /* * Skip the command when it's not going to be executed. * The commands like :if, :endif, etc. always need to be executed. * Also make an exception for commands that handle a trailing command * themselves. */ if (ea.skip) { switch (ea.cmdidx) { /* commands that need evaluation */ case CMD_while: case CMD_endwhile: case CMD_for: case CMD_endfor: case CMD_if: case CMD_elseif: case CMD_else: case CMD_endif: case CMD_try: case CMD_catch: case CMD_finally: case CMD_endtry: case CMD_function: break; /* Commands that handle '|' themselves. Check: A command should * either have the TRLBAR flag, appear in this list or appear in * the list at ":help :bar". */ case CMD_aboveleft: case CMD_and: case CMD_belowright: case CMD_botright: case CMD_browse: case CMD_call: case CMD_confirm: case CMD_delfunction: case CMD_djump: case CMD_dlist: case CMD_dsearch: case CMD_dsplit: case CMD_echo: case CMD_echoerr: case CMD_echomsg: case CMD_echon: case CMD_execute: case CMD_filter: case CMD_help: case CMD_hide: case CMD_ijump: case CMD_ilist: case CMD_isearch: case CMD_isplit: case CMD_keepalt: case CMD_keepjumps: case CMD_keepmarks: case CMD_keeppatterns: case CMD_leftabove: case CMD_let: case CMD_lockmarks: case CMD_lua: case CMD_match: case CMD_mzscheme: case CMD_noautocmd: case CMD_noswapfile: case CMD_perl: case CMD_psearch: case CMD_python: case CMD_py3: case CMD_python3: case CMD_return: case CMD_rightbelow: case CMD_ruby: case CMD_silent: case CMD_smagic: case CMD_snomagic: case CMD_substitute: case CMD_syntax: case CMD_tab: case CMD_tcl: case CMD_throw: case CMD_tilde: case CMD_topleft: case CMD_unlet: case CMD_verbose: case CMD_vertical: case CMD_wincmd: break; default: goto doend; } } #endif if (ea.argt & XFILE) { if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL) goto doend; } /* * Accept buffer name. Cannot be used at the same time with a buffer * number. Don't do this for a user command. */ if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0 && !IS_USER_CMDIDX(ea.cmdidx)) { /* * :bdelete, :bwipeout and :bunload take several arguments, separated * by spaces: find next space (skipping over escaped characters). * The others take one argument: ignore trailing spaces. */ if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout || ea.cmdidx == CMD_bunload) p = skiptowhite_esc(ea.arg); else { p = ea.arg + STRLEN(ea.arg); while (p > ea.arg && VIM_ISWHITE(p[-1])) --p; } ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE, FALSE); if (ea.line2 < 0) /* failed */ goto doend; ea.addr_count = 1; ea.arg = skipwhite(p); } /* The :try command saves the emsg_silent flag, reset it here when * ":silent! try" was used, it should only apply to :try itself. */ if (ea.cmdidx == CMD_try && ea.did_esilent > 0) { emsg_silent -= ea.did_esilent; if (emsg_silent < 0) emsg_silent = 0; ea.did_esilent = 0; } /* * 7. Execute the command. */ #ifdef FEAT_USR_CMDS if (IS_USER_CMDIDX(ea.cmdidx)) { /* * Execute a user-defined command. */ do_ucmd(&ea); } else #endif { /* * Call the function to execute the command. */ ea.errmsg = NULL; (cmdnames[ea.cmdidx].cmd_func)(&ea); if (ea.errmsg != NULL) errormsg = _(ea.errmsg); } #ifdef FEAT_EVAL /* * If the command just executed called do_cmdline(), any throw or ":return" * or ":finish" encountered there must also check the cstack of the still * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught * exception, or reanimate a returned function or finished script file and * return or finish it again. */ if (need_rethrow) do_throw(cstack); else if (check_cstack) { if (source_finished(fgetline, cookie)) do_finish(&ea, TRUE); else if (getline_equal(fgetline, cookie, get_func_line) && current_func_returned()) do_return(&ea, TRUE, FALSE, NULL); } need_rethrow = check_cstack = FALSE; #endif doend: if (curwin->w_cursor.lnum == 0) /* can happen with zero line number */ { curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; } if (errormsg != NULL && *errormsg != NUL && !did_emsg) { if (sourcing) { if (errormsg != (char *)IObuff) { STRCPY(IObuff, errormsg); errormsg = (char *)IObuff; } append_command(*cmdlinep); } emsg(errormsg); } #ifdef FEAT_EVAL do_errthrow(cstack, (ea.cmdidx != CMD_SIZE && !IS_USER_CMDIDX(ea.cmdidx)) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL); #endif if (ea.verbose_save >= 0) p_verbose = ea.verbose_save; free_cmdmod(); cmdmod = save_cmdmod; if (ea.save_msg_silent != -1) { /* messages could be enabled for a serious error, need to check if the * counters don't become negative */ if (!did_emsg || msg_silent > ea.save_msg_silent) msg_silent = ea.save_msg_silent; emsg_silent -= ea.did_esilent; if (emsg_silent < 0) emsg_silent = 0; /* Restore msg_scroll, it's set by file I/O commands, even when no * message is actually displayed. */ msg_scroll = save_msg_scroll; /* "silent reg" or "silent echo x" inside "redir" leaves msg_col * somewhere in the line. Put it back in the first column. */ if (redirecting()) msg_col = 0; } #ifdef HAVE_SANDBOX if (ea.did_sandbox) --sandbox; #endif if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */ ea.nextcmd = NULL; #ifdef FEAT_EVAL --ex_nesting_level; #endif return ea.nextcmd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</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: UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames) { UINT32 index; size_t position; BOOL asciiNames; int formatNameLength; char* szFormatName; WCHAR* wszFormatName; UINT32 dataLen = formatList->dataLen; CLIPRDR_FORMAT* formats = NULL; UINT error = CHANNEL_RC_OK; asciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE; index = 0; formatList->numFormats = 0; position = Stream_GetPosition(s); if (!formatList->dataLen) { /* empty format list */ formatList->formats = NULL; formatList->numFormats = 0; } else if (!useLongFormatNames) { formatList->numFormats = (dataLen / 36); if ((formatList->numFormats * 36) != dataLen) { WLog_ERR(TAG, "Invalid short format list length: %" PRIu32 "", dataLen); return ERROR_INTERNAL_ERROR; } if (formatList->numFormats) formats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT)); if (!formats) { WLog_ERR(TAG, "calloc failed!"); return CHANNEL_RC_NO_MEMORY; } formatList->formats = formats; while (dataLen) { Stream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */ dataLen -= 4; formats[index].formatName = NULL; /* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is "a 32-byte block containing * the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters * or 16 Unicode characters)" * However, both Windows RDSH and mstsc violate this specs as seen in the following * example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.] * These are 16 unicode charaters - *without* terminating null ! */ if (asciiNames) { szFormatName = (char*)Stream_Pointer(s); if (szFormatName[0]) { /* ensure null termination */ formats[index].formatName = (char*)malloc(32 + 1); if (!formats[index].formatName) { WLog_ERR(TAG, "malloc failed!"); error = CHANNEL_RC_NO_MEMORY; goto error_out; } CopyMemory(formats[index].formatName, szFormatName, 32); formats[index].formatName[32] = '\0'; } } else { wszFormatName = (WCHAR*)Stream_Pointer(s); if (wszFormatName[0]) { /* ConvertFromUnicode always returns a null-terminated * string on success, even if the source string isn't. */ if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16, &(formats[index].formatName), 0, NULL, NULL) < 1) { WLog_ERR(TAG, "failed to convert short clipboard format name"); error = ERROR_INTERNAL_ERROR; goto error_out; } } } Stream_Seek(s, 32); dataLen -= 32; index++; } } else { while (dataLen) { Stream_Seek(s, 4); /* formatId (4 bytes) */ dataLen -= 4; wszFormatName = (WCHAR*)Stream_Pointer(s); if (!wszFormatName[0]) formatNameLength = 0; else formatNameLength = _wcslen(wszFormatName); Stream_Seek(s, (formatNameLength + 1) * 2); dataLen -= ((formatNameLength + 1) * 2); formatList->numFormats++; } dataLen = formatList->dataLen; Stream_SetPosition(s, position); if (formatList->numFormats) formats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT)); if (!formats) { WLog_ERR(TAG, "calloc failed!"); return CHANNEL_RC_NO_MEMORY; } formatList->formats = formats; while (dataLen) { Stream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */ dataLen -= 4; formats[index].formatName = NULL; wszFormatName = (WCHAR*)Stream_Pointer(s); if (!wszFormatName[0]) formatNameLength = 0; else formatNameLength = _wcslen(wszFormatName); if (formatNameLength) { if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, -1, &(formats[index].formatName), 0, NULL, NULL) < 1) { WLog_ERR(TAG, "failed to convert long clipboard format name"); error = ERROR_INTERNAL_ERROR; goto error_out; } } Stream_Seek(s, (formatNameLength + 1) * 2); dataLen -= ((formatNameLength + 1) * 2); index++; } } return error; error_out: cliprdr_free_format_list(formatList); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in cliprdr_read_format_list'</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 ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge) { size_t size; Stream_Read_UINT8(s, challenge->RespType); Stream_Read_UINT8(s, challenge->HiRespType); Stream_Read_UINT16(s, challenge->Reserved1); Stream_Read_UINT32(s, challenge->Reserved2); Stream_Read(s, challenge->Timestamp, 8); Stream_Read(s, challenge->ClientChallenge, 8); Stream_Read_UINT32(s, challenge->Reserved3); size = Stream_Length(s) - Stream_GetPosition(s); if (size > UINT32_MAX) return -1; challenge->cbAvPairs = size; challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs); if (!challenge->AvPairs) return -1; Stream_Read(s, challenge->AvPairs, size); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in ntlm_read_ntlm_v2_response'</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: SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 flags; NTLM_AV_PAIR* AvFlags; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; flags = 0; AvFlags = NULL; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKeyFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateKeyExchange = (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE; if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) || (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len)) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } PayloadBufferOffset = Stream_GetPosition(s); if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->NtChallengeResponse.Len > 0) { size_t cbAvFlags; wStream* snt = Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len); if (!snt) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0) { Stream_Free(s, FALSE); Stream_Free(snt, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Free(snt, FALSE); context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer; context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len; sspi_SecBufferFree(&(context->ChallengeTargetInfo)); context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs; context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16); CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8); AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); } if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKey */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->EncryptedRandomSessionKey.Len > 0) { if (message->EncryptedRandomSessionKey.Len != 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer, 16); } length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; Stream_SetPosition(s, PayloadBufferOffset); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s); if (Stream_GetRemainingLength(s) < 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->MessageIntegrityCheck, 16); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")", context->AuthenticateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer, context->AuthenticateMessage.cbBuffer); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs, context->NTLMv2Response.Challenge.cbAvPairs); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { WLog_DBG(TAG, "MessageIntegrityCheck:"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif if (message->UserName.Len > 0) { credentials->identity.User = (UINT16*)malloc(message->UserName.Len); if (!credentials->identity.User) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len); credentials->identity.UserLength = message->UserName.Len / 2; } if (message->DomainName.Len > 0) { credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len); if (!credentials->identity.Domain) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.Domain, message->DomainName.Buffer, message->DomainName.Len); credentials->identity.DomainLength = message->DomainName.Len / 2; } Stream_Free(s, FALSE); /* Computations beyond this point require the NTLM hash of the password */ context->state = NTLM_STATE_COMPLETION; return SEC_I_COMPLETE_NEEDED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in ntlm_read_AuthenticateMessage'</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 nego_read_request(rdpNego* nego, wStream* s) { BYTE li; BYTE type; UINT16 length; if (!tpkt_read_header(s, &length)) return FALSE; if (!tpdu_read_connection_request(s, &li, length)) return FALSE; if (li != Stream_GetRemainingLength(s) + 6) { WLog_ERR(TAG, "Incorrect TPDU length indicator."); return FALSE; } if (!nego_read_request_token_or_cookie(nego, s)) { WLog_ERR(TAG, "Failed to parse routing token or cookie."); return FALSE; } if (Stream_GetRemainingLength(s) >= 8) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ if (type != TYPE_RDP_NEG_REQ) { WLog_ERR(TAG, "Incorrect negotiation request type %" PRIu8 "", type); return FALSE; } nego_process_negotiation_request(nego, s); } return tpkt_ensure_stream_consumed(s, length); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</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 UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp) { UINT32 Length; UINT64 Offset; rdpPrintJob* printjob = NULL; UINT error = CHANNEL_RC_OK; Stream_Read_UINT32(irp->input, Length); Stream_Read_UINT64(irp->input, Offset); Stream_Seek(irp->input, 20); /* Padding */ if (printer_dev->printer) printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId); if (!printjob) { irp->IoStatus = STATUS_UNSUCCESSFUL; Length = 0; } else { error = printjob->Write(printjob, Stream_Pointer(irp->input), Length); } if (error) { WLog_ERR(TAG, "printjob->Write failed with error %" PRIu32 "!", error); return error; } Stream_Write_UINT32(irp->output, Length); Stream_Write_UINT8(irp->output, 0); /* Padding */ return irp->Complete(irp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</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 wStream* rdg_receive_packet(rdpRdg* rdg) { wStream* s; const size_t header = sizeof(RdgPacketHeader); size_t packetLength; assert(header <= INT_MAX); s = Stream_New(NULL, 1024); if (!s) return NULL; if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header)) { Stream_Free(s, TRUE); return NULL; } Stream_Seek(s, 4); Stream_Read_UINT32(s, packetLength); if ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength)) { Stream_Free(s, TRUE); return NULL; } if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s) + header, (int)packetLength - (int)header)) { Stream_Free(s, TRUE); return NULL; } Stream_SetLength(s, packetLength); return s; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</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 UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp) { DWORD DesiredAccess; DWORD SharedAccess; DWORD CreateDisposition; UINT32 PathLength; if (Stream_GetRemainingLength(irp->input) < 32) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, DesiredAccess); /* DesiredAccess (4 bytes) */ Stream_Seek_UINT64(irp->input); /* AllocationSize (8 bytes) */ Stream_Seek_UINT32(irp->input); /* FileAttributes (4 bytes) */ Stream_Read_UINT32(irp->input, SharedAccess); /* SharedAccess (4 bytes) */ Stream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */ Stream_Seek_UINT32(irp->input); /* CreateOptions (4 bytes) */ Stream_Read_UINT32(irp->input, PathLength); /* PathLength (4 bytes) */ if (Stream_GetRemainingLength(irp->input) < PathLength) return ERROR_INVALID_DATA; Stream_Seek(irp->input, PathLength); /* Path (variable) */ assert(PathLength == 0); /* MS-RDPESP 2.2.2.2 */ #ifndef _WIN32 /* Windows 2012 server sends on a first call : * DesiredAccess = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES * SharedAccess = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ * CreateDisposition = 0x00000001: CREATE_NEW * * then Windows 2012 sends : * DesiredAccess = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES | * FILE_READ_EA | FILE_READ_DATA SharedAccess = 0x00000007: FILE_SHARE_DELETE | * FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW * * assert(DesiredAccess == (GENERIC_READ | GENERIC_WRITE)); * assert(SharedAccess == 0); * assert(CreateDisposition == OPEN_EXISTING); * */ WLog_Print(serial->log, WLOG_DEBUG, "DesiredAccess: 0x%" PRIX32 ", SharedAccess: 0x%" PRIX32 ", CreateDisposition: 0x%" PRIX32 "", DesiredAccess, SharedAccess, CreateDisposition); /* FIXME: As of today only the flags below are supported by CommCreateFileA: */ DesiredAccess = GENERIC_READ | GENERIC_WRITE; SharedAccess = 0; CreateDisposition = OPEN_EXISTING; #endif serial->hComm = CreateFile(serial->device.name, DesiredAccess, SharedAccess, NULL, /* SecurityAttributes */ CreateDisposition, 0, /* FlagsAndAttributes */ NULL); /* TemplateFile */ if (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE)) { WLog_Print(serial->log, WLOG_WARN, "CreateFile failure: %s last-error: 0x%08" PRIX32 "", serial->device.name, GetLastError()); irp->IoStatus = STATUS_UNSUCCESSFUL; goto error_handle; } _comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId); _comm_set_permissive(serial->hComm, serial->permissive); /* NOTE: binary mode/raw mode required for the redirection. On * Linux, CommCreateFileA forces this setting. */ /* ZeroMemory(&dcb, sizeof(DCB)); */ /* dcb.DCBlength = sizeof(DCB); */ /* GetCommState(serial->hComm, &dcb); */ /* dcb.fBinary = TRUE; */ /* SetCommState(serial->hComm, &dcb); */ assert(irp->FileId == 0); irp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */ irp->IoStatus = STATUS_SUCCESS; WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") created.", serial->device.name, irp->device->id, irp->FileId); error_handle: Stream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */ Stream_Write_UINT8(irp->output, 0); /* Information (1 byte) */ return CHANNEL_RC_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</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 nego_process_negotiation_request(rdpNego* nego, wStream* s) { BYTE flags; UINT16 length; Stream_Read_UINT8(s, flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, nego->RequestedProtocols); WLog_DBG(TAG, "RDP_NEG_REQ: RequestedProtocol: 0x%08" PRIX32 "", nego->RequestedProtocols); nego->state = NEGO_STATE_FINAL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</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 UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp) { UINT32 Length; UINT64 Offset; DWORD nbWritten = 0; if (Stream_GetRemainingLength(irp->input) < 32) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */ Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */ Stream_Seek(irp->input, 20); /* Padding (20 bytes) */ /* MS-RDPESP 3.2.5.1.5: The Offset field is ignored * assert(Offset == 0); * * Using a serial printer, noticed though this field could be * set. */ WLog_Print(serial->log, WLOG_DEBUG, "writing %" PRIu32 " bytes to %s", Length, serial->device.name); /* FIXME: CommWriteFile to be replaced by WriteFile */ if (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL)) { irp->IoStatus = STATUS_SUCCESS; } else { WLog_Print(serial->log, WLOG_DEBUG, "write failure to %s, nbWritten=%" PRIu32 ", last-error: 0x%08" PRIX32 "", serial->device.name, nbWritten, GetLastError()); irp->IoStatus = _GetLastErrorToIoStatus(serial); } WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes written to %s", nbWritten, serial->device.name); Stream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */ Stream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */ return CHANNEL_RC_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</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: TEST_P(Http2CodecImplTest, Invalid103) { initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, true)); request_encoder_->encodeHeaders(request_headers, true); TestResponseHeaderMapImpl continue_headers{{":status", "100"}}; EXPECT_CALL(response_decoder_, decode100ContinueHeaders_(_)); response_encoder_->encode100ContinueHeaders(continue_headers); TestResponseHeaderMapImpl early_hint_headers{{":status", "103"}}; EXPECT_CALL(response_decoder_, decodeHeaders_(_, false)); response_encoder_->encodeHeaders(early_hint_headers, false); EXPECT_THROW_WITH_MESSAGE(response_encoder_->encodeHeaders(early_hint_headers, false), ClientCodecError, "Unexpected 'trailers' with no end stream."); EXPECT_EQ(1, stats_store_.counter("http2.too_many_header_frames").value()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, InvalidContinueWithFin) { initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, true)); request_encoder_->encodeHeaders(request_headers, true); TestResponseHeaderMapImpl continue_headers{{":status", "100"}}; EXPECT_THROW(response_encoder_->encodeHeaders(continue_headers, true), ClientCodecError); EXPECT_EQ(1, stats_store_.counter("http2.rx_messaging_error").value()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(AltsIntegrationTestClientWrongHandshaker, ConnectToWrongHandshakerAddress) { initialize(); codec_client_ = makeRawHttpConnection(makeAltsConnection()); EXPECT_FALSE(codec_client_->connected()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: IntegrationCodecClientPtr makeRawHttpConnection(Network::ClientConnectionPtr&& conn) override { IntegrationCodecClientPtr codec = HttpIntegrationTest::makeRawHttpConnection(std::move(conn)); if (codec->disconnected()) { // Connection may get closed during version negotiation or handshake. ENVOY_LOG(error, "Fail to connect to server with error: {}", codec->connection()->transportFailureReason()); } else { codec->setCodecClientCallbacks(client_codec_callback_); } return codec; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(QuicHttpIntegrationTest, StopAcceptingConnectionsWhenOverloaded) { initialize(); fake_upstreams_[0]->set_allow_unexpected_disconnects(true); // Put envoy in overloaded state and check that it doesn't accept the new client connection. updateResource(0.9); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_connections.active", 1); codec_client_ = makeRawHttpConnection(makeClientConnection((lookupPort("http")))); EXPECT_TRUE(codec_client_->disconnected()); // Reduce load a little to allow the connection to be accepted connection. updateResource(0.8); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_connections.active", 0); codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); waitForNextUpstreamRequest(0); // Send response headers, but hold response body for now. upstream_request_->encodeHeaders(default_response_headers_, /*end_stream=*/false); updateResource(0.95); test_server_->waitForGaugeEq("overload.envoy.overload_actions.stop_accepting_requests.active", 1); // Existing request should be able to finish. upstream_request_->encodeData(10, true); response->waitForEndStream(); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); // New request should be rejected. auto response2 = codec_client_->makeHeaderOnlyRequest(default_request_headers_); response2->waitForEndStream(); EXPECT_EQ("503", response2->headers().getStatusValue()); EXPECT_EQ("envoy overloaded", response2->body()); codec_client_->close(); EXPECT_TRUE(makeRawHttpConnection(makeClientConnection((lookupPort("http"))))->disconnected()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void initialize() override { allow_metadata_ = true; http2OptionsFromTuple(client_http2_options_, client_settings_); http2OptionsFromTuple(server_http2_options_, server_settings_); client_ = std::make_unique<MetadataTestClientConnectionImpl>( client_connection_, client_callbacks_, stats_store_, client_http2_options_, max_request_headers_kb_, max_response_headers_count_, http2_session_factory_); server_ = std::make_unique<TestServerConnectionImpl>( server_connection_, server_callbacks_, stats_store_, server_http2_options_, max_request_headers_kb_, max_request_headers_count_, headers_with_underscores_action_); ON_CALL(client_connection_, write(_, _)) .WillByDefault(Invoke([&](Buffer::Instance& data, bool) -> void { ASSERT_TRUE(server_wrapper_.dispatch(data, *server_).ok()); })); ON_CALL(server_connection_, write(_, _)) .WillByDefault(Invoke([&](Buffer::Instance& data, bool) -> void { ASSERT_TRUE(client_wrapper_.dispatch(data, *client_).ok()); })); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void setUpBufferLimits() { ON_CALL(response_encoder_, getStream()).WillByDefault(ReturnRef(stream_)); EXPECT_CALL(stream_, addCallbacks(_)) .WillOnce(Invoke( [&](Http::StreamCallbacks& callbacks) -> void { stream_callbacks_ = &callbacks; })); EXPECT_CALL(stream_, bufferLimit()).WillOnce(Return(initial_buffer_limit_)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(SslCertficateIntegrationTest, ServerRsaClientEcdsaOnly) { server_rsa_cert_ = true; server_ecdsa_cert_ = false; client_ecdsa_cert_ = true; initialize(); EXPECT_FALSE( makeRawHttpConnection(makeSslClientConnection(ecdsaOnlyClientOptions()))->connected()); const std::string counter_name = listenerStatPrefix("ssl.connection_error"); Stats::CounterSharedPtr counter = test_server_->counter(counter_name); test_server_->waitForCounterGe(counter_name, 1); EXPECT_EQ(1U, counter->value()); counter->reset(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: HttpIntegrationTest::makeRawHttpConnection(Network::ClientConnectionPtr&& conn) { std::shared_ptr<Upstream::MockClusterInfo> cluster{new NiceMock<Upstream::MockClusterInfo>()}; cluster->max_response_headers_count_ = 200; cluster->http2_options_.set_allow_connect(true); cluster->http2_options_.set_allow_metadata(true); cluster->http1_settings_.enable_trailers_ = true; Upstream::HostDescriptionConstSharedPtr host_description{Upstream::makeTestHostDescription( cluster, fmt::format("tcp://{}:80", Network::Test::getLoopbackAddressUrlString(version_)))}; return std::make_unique<IntegrationCodecClient>(*dispatcher_, std::move(conn), host_description, downstream_protocol_); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, ResponseDataFlood) { initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, false)); request_encoder_->encodeHeaders(request_headers, false); int frame_count = 0; Buffer::OwnedImpl buffer; ON_CALL(server_connection_, write(_, _)) .WillByDefault(Invoke([&buffer, &frame_count](Buffer::Instance& frame, bool) { ++frame_count; buffer.move(frame); })); TestResponseHeaderMapImpl response_headers{{":status", "200"}}; response_encoder_->encodeHeaders(response_headers, false); // Account for the single HEADERS frame above for (uint32_t i = 0; i < CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_FRAMES; ++i) { Buffer::OwnedImpl data("0"); EXPECT_NO_THROW(response_encoder_->encodeData(data, false)); } // Presently flood mitigation is done only when processing downstream data // So we need to send stream from downstream client to trigger mitigation EXPECT_EQ(0, nghttp2_submit_ping(client_->session(), NGHTTP2_FLAG_NONE, nullptr)); EXPECT_THROW(client_->sendPendingFrames(), ServerCodecError); EXPECT_EQ(frame_count, CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_FRAMES + 1); EXPECT_EQ(1, stats_store_.counter("http2.outbound_flood").value()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, HeaderNameWithUnderscoreAllowed) { headers_with_underscores_action_ = envoy::config::core::v3::HttpProtocolOptions::ALLOW; initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); request_headers.addCopy("bad_header", "something"); TestRequestHeaderMapImpl expected_headers(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(HeaderMapEqual(&expected_headers), _)); EXPECT_CALL(server_stream_callbacks_, onResetStream(_, _)).Times(0); request_encoder_->encodeHeaders(request_headers, false); EXPECT_EQ(0, stats_store_.counter("http2.dropped_headers_with_underscores").value()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, TrailingHeadersLargeBody) { initialize(); // Buffer server data so we can make sure we don't get any window updates. ON_CALL(client_connection_, write(_, _)) .WillByDefault( Invoke([&](Buffer::Instance& data, bool) -> void { server_wrapper_.buffer_.add(data); })); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, false)); request_encoder_->encodeHeaders(request_headers, false); EXPECT_CALL(request_decoder_, decodeData(_, false)).Times(AtLeast(1)); Buffer::OwnedImpl body(std::string(1024 * 1024, 'a')); request_encoder_->encodeData(body, false); EXPECT_CALL(request_decoder_, decodeTrailers_(_)); request_encoder_->encodeTrailers(TestRequestTrailerMapImpl{{"trailing", "header"}}); // Flush pending data. setupDefaultConnectionMocks(); auto status = server_wrapper_.dispatch(Buffer::OwnedImpl(), *server_); EXPECT_TRUE(status.ok()); TestResponseHeaderMapImpl response_headers{{":status", "200"}}; EXPECT_CALL(response_decoder_, decodeHeaders_(_, false)); response_encoder_->encodeHeaders(response_headers, false); EXPECT_CALL(response_decoder_, decodeData(_, false)); Buffer::OwnedImpl world("world"); response_encoder_->encodeData(world, false); EXPECT_CALL(response_decoder_, decodeTrailers_(_)); response_encoder_->encodeTrailers(TestResponseTrailerMapImpl{{"trailing", "header"}}); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionManagerImpl::ActiveStream::decodeHeaders(RequestHeaderMapPtr&& headers, bool end_stream) { ScopeTrackerScopeState scope(this, connection_manager_.read_callbacks_->connection().dispatcher()); request_headers_ = std::move(headers); // Both saw_connection_close_ and is_head_request_ affect local replies: set // them as early as possible. const Protocol protocol = connection_manager_.codec_->protocol(); const bool fixed_connection_close = Runtime::runtimeFeatureEnabled("envoy.reloadable_features.fixed_connection_close"); if (fixed_connection_close) { state_.saw_connection_close_ = HeaderUtility::shouldCloseConnection(protocol, *request_headers_); } if (Http::Headers::get().MethodValues.Head == request_headers_->getMethodValue()) { state_.is_head_request_ = true; } if (HeaderUtility::isConnect(*request_headers_) && !request_headers_->Path() && !Runtime::runtimeFeatureEnabled("envoy.reloadable_features.stop_faking_paths")) { request_headers_->setPath("/"); } // We need to snap snapped_route_config_ here as it's used in mutateRequestHeaders later. if (connection_manager_.config_.isRoutable()) { if (connection_manager_.config_.routeConfigProvider() != nullptr) { snapped_route_config_ = connection_manager_.config_.routeConfigProvider()->config(); } else if (connection_manager_.config_.scopedRouteConfigProvider() != nullptr) { snapped_scoped_routes_config_ = connection_manager_.config_.scopedRouteConfigProvider()->config<Router::ScopedConfig>(); snapScopedRouteConfig(); } } else { snapped_route_config_ = connection_manager_.config_.routeConfigProvider()->config(); } ENVOY_STREAM_LOG(debug, "request headers complete (end_stream={}):\n{}", *this, end_stream, *request_headers_); // We end the decode here only if the request is header only. If we convert the request to a // header only, the stream will be marked as done once a subsequent decodeData/decodeTrailers is // called with end_stream=true. maybeEndDecode(end_stream); // Drop new requests when overloaded as soon as we have decoded the headers. if (connection_manager_.overload_stop_accepting_requests_ref_ == Server::OverloadActionState::Active) { // In this one special case, do not create the filter chain. If there is a risk of memory // overload it is more important to avoid unnecessary allocation than to create the filters. state_.created_filter_chain_ = true; connection_manager_.stats_.named_.downstream_rq_overload_close_.inc(); sendLocalReply(Grpc::Common::isGrpcRequestHeaders(*request_headers_), Http::Code::ServiceUnavailable, "envoy overloaded", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().Overload); return; } if (!connection_manager_.config_.proxy100Continue() && request_headers_->Expect() && request_headers_->Expect()->value() == Headers::get().ExpectValues._100Continue.c_str()) { // Note in the case Envoy is handling 100-Continue complexity, it skips the filter chain // and sends the 100-Continue directly to the encoder. chargeStats(continueHeader()); response_encoder_->encode100ContinueHeaders(continueHeader()); // Remove the Expect header so it won't be handled again upstream. request_headers_->removeExpect(); } connection_manager_.user_agent_.initializeFromHeaders(*request_headers_, connection_manager_.stats_.prefixStatName(), connection_manager_.stats_.scope_); // Make sure we are getting a codec version we support. if (protocol == Protocol::Http10) { // Assume this is HTTP/1.0. This is fine for HTTP/0.9 but this code will also affect any // requests with non-standard version numbers (0.9, 1.3), basically anything which is not // HTTP/1.1. // // The protocol may have shifted in the HTTP/1.0 case so reset it. stream_info_.protocol(protocol); if (!connection_manager_.config_.http1Settings().accept_http_10_) { // Send "Upgrade Required" if HTTP/1.0 support is not explicitly configured on. sendLocalReply(false, Code::UpgradeRequired, "", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().LowVersion); return; } else if (!fixed_connection_close) { // HTTP/1.0 defaults to single-use connections. Make sure the connection // will be closed unless Keep-Alive is present. state_.saw_connection_close_ = true; if (absl::EqualsIgnoreCase(request_headers_->getConnectionValue(), Http::Headers::get().ConnectionValues.KeepAlive)) { state_.saw_connection_close_ = false; } } if (!request_headers_->Host() && !connection_manager_.config_.http1Settings().default_host_for_http_10_.empty()) { // Add a default host if configured to do so. request_headers_->setHost( connection_manager_.config_.http1Settings().default_host_for_http_10_); } } if (!request_headers_->Host()) { // Require host header. For HTTP/1.1 Host has already been translated to :authority. sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, "", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().MissingHost); return; } // Verify header sanity checks which should have been performed by the codec. ASSERT(HeaderUtility::requestHeadersValid(*request_headers_).has_value() == false); // Check for the existence of the :path header for non-CONNECT requests, or present-but-empty // :path header for CONNECT requests. We expect the codec to have broken the path into pieces if // applicable. NOTE: Currently the HTTP/1.1 codec only does this when the allow_absolute_url flag // is enabled on the HCM. if ((!HeaderUtility::isConnect(*request_headers_) || request_headers_->Path()) && request_headers_->getPathValue().empty()) { sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, "", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().MissingPath); return; } // Currently we only support relative paths at the application layer. if (!request_headers_->getPathValue().empty() && request_headers_->getPathValue()[0] != '/') { connection_manager_.stats_.named_.downstream_rq_non_relative_path_.inc(); sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, "", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().AbsolutePath); return; } // Path sanitization should happen before any path access other than the above sanity check. if (!ConnectionManagerUtility::maybeNormalizePath(*request_headers_, connection_manager_.config_)) { sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, "", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().PathNormalizationFailed); return; } ConnectionManagerUtility::maybeNormalizeHost(*request_headers_, connection_manager_.config_, localPort()); if (!fixed_connection_close && protocol == Protocol::Http11 && absl::EqualsIgnoreCase(request_headers_->getConnectionValue(), Http::Headers::get().ConnectionValues.Close)) { state_.saw_connection_close_ = true; } // Note: Proxy-Connection is not a standard header, but is supported here // since it is supported by http-parser the underlying parser for http // requests. if (!fixed_connection_close && protocol < Protocol::Http2 && !state_.saw_connection_close_ && absl::EqualsIgnoreCase(request_headers_->getProxyConnectionValue(), Http::Headers::get().ConnectionValues.Close)) { state_.saw_connection_close_ = true; } if (!state_.is_internally_created_) { // Only sanitize headers on first pass. // Modify the downstream remote address depending on configuration and headers. stream_info_.setDownstreamRemoteAddress(ConnectionManagerUtility::mutateRequestHeaders( *request_headers_, connection_manager_.read_callbacks_->connection(), connection_manager_.config_, *snapped_route_config_, connection_manager_.local_info_)); } ASSERT(stream_info_.downstreamRemoteAddress() != nullptr); ASSERT(!cached_route_); refreshCachedRoute(); if (!state_.is_internally_created_) { // Only mutate tracing headers on first pass. ConnectionManagerUtility::mutateTracingRequestHeader( *request_headers_, connection_manager_.runtime_, connection_manager_.config_, cached_route_.value().get()); } stream_info_.setRequestHeaders(*request_headers_); const bool upgrade_rejected = createFilterChain() == false; // TODO if there are no filters when starting a filter iteration, the connection manager // should return 404. The current returns no response if there is no router filter. if (hasCachedRoute()) { // Do not allow upgrades if the route does not support it. if (upgrade_rejected) { // While downstream servers should not send upgrade payload without the upgrade being // accepted, err on the side of caution and refuse to process any further requests on this // connection, to avoid a class of HTTP/1.1 smuggling bugs where Upgrade or CONNECT payload // contains a smuggled HTTP request. state_.saw_connection_close_ = true; connection_manager_.stats_.named_.downstream_rq_ws_on_non_ws_route_.inc(); sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::Forbidden, "", nullptr, state_.is_head_request_, absl::nullopt, StreamInfo::ResponseCodeDetails::get().UpgradeFailed); return; } // Allow non websocket requests to go through websocket enabled routes. } if (hasCachedRoute()) { const Router::RouteEntry* route_entry = cached_route_.value()->routeEntry(); if (route_entry != nullptr && route_entry->idleTimeout()) { idle_timeout_ms_ = route_entry->idleTimeout().value(); if (idle_timeout_ms_.count()) { // If we have a route-level idle timeout but no global stream idle timeout, create a timer. if (stream_idle_timer_ == nullptr) { stream_idle_timer_ = connection_manager_.read_callbacks_->connection().dispatcher().createTimer( [this]() -> void { onIdleTimeout(); }); } } else if (stream_idle_timer_ != nullptr) { // If we had a global stream idle timeout but the route-level idle timeout is set to zero // (to override), we disable the idle timer. stream_idle_timer_->disableTimer(); stream_idle_timer_ = nullptr; } } } // Check if tracing is enabled at all. if (connection_manager_.config_.tracingConfig()) { traceRequest(); } decodeHeaders(nullptr, *request_headers_, end_stream); // Reset it here for both global and overridden cases. resetIdleTimer(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionImpl::StreamImpl::encodeTrailersBase(const HeaderMap& trailers) { ASSERT(!local_end_stream_); local_end_stream_ = true; if (pending_send_data_.length() > 0) { // In this case we want trailers to come after we release all pending body data that is // waiting on window updates. We need to save the trailers so that we can emit them later. ASSERT(!pending_trailers_to_encode_); pending_trailers_to_encode_ = cloneTrailers(trailers); } else { submitTrailers(trailers); parent_.sendPendingFrames(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: ConnectionImpl::~ConnectionImpl() { nghttp2_session_del(session_); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(SdsDynamicDownstreamIntegrationTest, WrongSecretFirst) { on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getWrongSecret(server_cert_)); }; initialize(); codec_client_ = makeRawHttpConnection(makeSslClientConnection()); // the connection state is not connected. EXPECT_FALSE(codec_client_->connected()); codec_client_->connection()->close(Network::ConnectionCloseType::NoFlush); sendSdsResponse(getServerSecret()); // Wait for ssl_context_updated_by_sds counter. test_server_->waitForCounterGe( listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 1); ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr { return makeSslClientConnection(); }; testRouterHeaderOnlyRequestAndResponse(&creator); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplFlowControlTest, TestFlowControlInPendingSendData) { initialize(); MockStreamCallbacks callbacks; request_encoder_->getStream().addCallbacks(callbacks); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); TestRequestHeaderMapImpl expected_headers; HttpTestUtility::addDefaultHeaders(expected_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(HeaderMapEqual(&expected_headers), false)); request_encoder_->encodeHeaders(request_headers, false); // Force the server stream to be read disabled. This will cause it to stop sending window // updates to the client. server_->getStream(1)->readDisable(true); uint32_t initial_stream_window = nghttp2_session_get_stream_effective_local_window_size(client_->session(), 1); // If this limit is changed, this test will fail due to the initial large writes being divided // into more than 4 frames. Fast fail here with this explanatory comment. ASSERT_EQ(65535, initial_stream_window); // Make sure the limits were configured properly in test set up. EXPECT_EQ(initial_stream_window, server_->getStream(1)->bufferLimit()); EXPECT_EQ(initial_stream_window, client_->getStream(1)->bufferLimit()); // One large write gets broken into smaller frames. EXPECT_CALL(request_decoder_, decodeData(_, false)).Times(AnyNumber()); Buffer::OwnedImpl long_data(std::string(initial_stream_window, 'a')); request_encoder_->encodeData(long_data, false); // Verify that the window is full. The client will not send more data to the server for this // stream. EXPECT_EQ(0, nghttp2_session_get_stream_local_window_size(server_->session(), 1)); EXPECT_EQ(0, nghttp2_session_get_stream_remote_window_size(client_->session(), 1)); EXPECT_EQ(initial_stream_window, server_->getStream(1)->unconsumed_bytes_); // Now that the flow control window is full, further data causes the send buffer to back up. Buffer::OwnedImpl more_long_data(std::string(initial_stream_window, 'a')); request_encoder_->encodeData(more_long_data, false); EXPECT_EQ(initial_stream_window, client_->getStream(1)->pending_send_data_.length()); EXPECT_EQ(initial_stream_window, server_->getStream(1)->unconsumed_bytes_); // If we go over the limit, the stream callbacks should fire. EXPECT_CALL(callbacks, onAboveWriteBufferHighWatermark()); Buffer::OwnedImpl last_byte("!"); request_encoder_->encodeData(last_byte, false); EXPECT_EQ(initial_stream_window + 1, client_->getStream(1)->pending_send_data_.length()); // Now create a second stream on the connection. MockResponseDecoder response_decoder2; RequestEncoder* request_encoder2 = &client_->newStream(response_decoder_); StreamEncoder* response_encoder2; MockStreamCallbacks server_stream_callbacks2; MockRequestDecoder request_decoder2; // When the server stream is created it should check the status of the // underlying connection. Pretend it is overrun. EXPECT_CALL(server_connection_, aboveHighWatermark()).WillOnce(Return(true)); EXPECT_CALL(server_stream_callbacks2, onAboveWriteBufferHighWatermark()); EXPECT_CALL(server_callbacks_, newStream(_, _)) .WillOnce(Invoke([&](ResponseEncoder& encoder, bool) -> RequestDecoder& { response_encoder2 = &encoder; encoder.getStream().addCallbacks(server_stream_callbacks2); return request_decoder2; })); EXPECT_CALL(request_decoder2, decodeHeaders_(_, false)); request_encoder2->encodeHeaders(request_headers, false); // Add the stream callbacks belatedly. On creation the stream should have // been noticed that the connection was backed up. Any new subscriber to // stream callbacks should get a callback when they addCallbacks. MockStreamCallbacks callbacks2; EXPECT_CALL(callbacks2, onAboveWriteBufferHighWatermark()); request_encoder_->getStream().addCallbacks(callbacks2); // Add a third callback to make testing removal mid-watermark call below more interesting. MockStreamCallbacks callbacks3; EXPECT_CALL(callbacks3, onAboveWriteBufferHighWatermark()); request_encoder_->getStream().addCallbacks(callbacks3); // Now unblock the server's stream. This will cause the bytes to be consumed, flow control // updates to be sent, and the client to flush all queued data. // For bonus corner case coverage, remove callback2 in the middle of runLowWatermarkCallbacks() // and ensure it is not called. EXPECT_CALL(callbacks, onBelowWriteBufferLowWatermark()).WillOnce(Invoke([&]() -> void { request_encoder_->getStream().removeCallbacks(callbacks2); })); EXPECT_CALL(callbacks2, onBelowWriteBufferLowWatermark()).Times(0); EXPECT_CALL(callbacks3, onBelowWriteBufferLowWatermark()); server_->getStream(1)->readDisable(false); EXPECT_EQ(0, client_->getStream(1)->pending_send_data_.length()); // The extra 1 byte sent won't trigger another window update, so the final window should be the // initial window minus the last 1 byte flush from the client to server. EXPECT_EQ(initial_stream_window - 1, nghttp2_session_get_stream_local_window_size(server_->session(), 1)); EXPECT_EQ(initial_stream_window - 1, nghttp2_session_get_stream_remote_window_size(client_->session(), 1)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, HeaderNameWithUnderscoreAreRejectedByDefault) { headers_with_underscores_action_ = envoy::config::core::v3::HttpProtocolOptions::REJECT_REQUEST; initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); request_headers.addCopy("bad_header", "something"); EXPECT_CALL(server_stream_callbacks_, onResetStream(_, _)).Times(1); request_encoder_->encodeHeaders(request_headers, false); EXPECT_EQ(1, stats_store_.counter("http2.requests_rejected_with_underscores_in_headers").value()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, Invalid204WithContentLength) { initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, true)); request_encoder_->encodeHeaders(request_headers, true); TestResponseHeaderMapImpl response_headers{{":status", "204"}, {"content-length", "3"}}; // What follows is a hack to get headers that should span into continuation frames. The default // maximum frame size is 16K. We will add 3,000 headers that will take us above this size and // not easily compress with HPACK. (I confirmed this generates 26,468 bytes of header data // which should contain a continuation.) for (unsigned i = 1; i < 3000; i++) { response_headers.addCopy(std::to_string(i), std::to_string(i)); } EXPECT_THROW(response_encoder_->encodeHeaders(response_headers, false), ClientCodecError); EXPECT_EQ(1, stats_store_.counter("http2.rx_messaging_error").value()); }; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Http2UpstreamIntegrationTest::manySimultaneousRequests(uint32_t request_bytes, uint32_t) { TestRandomGenerator rand; const uint32_t num_requests = 50; std::vector<Http::RequestEncoder*> encoders; std::vector<IntegrationStreamDecoderPtr> responses; std::vector<int> response_bytes; autonomous_upstream_ = true; initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); for (uint32_t i = 0; i < num_requests; ++i) { response_bytes.push_back(rand.random() % (1024 * 2)); auto headers = Http::TestRequestHeaderMapImpl{ {":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}, {AutonomousStream::RESPONSE_SIZE_BYTES, std::to_string(response_bytes[i])}, {AutonomousStream::EXPECT_REQUEST_SIZE_BYTES, std::to_string(request_bytes)}}; if (i % 2 == 0) { headers.addCopy(AutonomousStream::RESET_AFTER_REQUEST, "yes"); } auto encoder_decoder = codec_client_->startRequest(headers); encoders.push_back(&encoder_decoder.first); responses.push_back(std::move(encoder_decoder.second)); codec_client_->sendData(*encoders[i], request_bytes, true); } for (uint32_t i = 0; i < num_requests; ++i) { responses[i]->waitForEndStream(); if (i % 2 != 0) { EXPECT_TRUE(responses[i]->complete()); EXPECT_EQ("200", responses[i]->headers().getStatusValue()); EXPECT_EQ(response_bytes[i], responses[i]->body().length()); } else { // Upstream stream reset. EXPECT_EQ("503", responses[i]->headers().getStatusValue()); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, InvalidRepeatContinue) { initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, true)); request_encoder_->encodeHeaders(request_headers, true); TestResponseHeaderMapImpl continue_headers{{":status", "100"}}; EXPECT_CALL(response_decoder_, decode100ContinueHeaders_(_)); response_encoder_->encode100ContinueHeaders(continue_headers); EXPECT_THROW(response_encoder_->encodeHeaders(continue_headers, true), ClientCodecError); EXPECT_EQ(1, stats_store_.counter("http2.rx_messaging_error").value()); }; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_P(Http2CodecImplTest, ResponseHeadersFlood) { initialize(); TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, false)); request_encoder_->encodeHeaders(request_headers, false); int frame_count = 0; Buffer::OwnedImpl buffer; ON_CALL(server_connection_, write(_, _)) .WillByDefault(Invoke([&buffer, &frame_count](Buffer::Instance& frame, bool) { ++frame_count; buffer.move(frame); })); TestResponseHeaderMapImpl response_headers{{":status", "200"}}; for (uint32_t i = 0; i < CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_FRAMES + 1; ++i) { EXPECT_NO_THROW(response_encoder_->encodeHeaders(response_headers, false)); } // Presently flood mitigation is done only when processing downstream data // So we need to send stream from downstream client to trigger mitigation EXPECT_EQ(0, nghttp2_submit_ping(client_->session(), NGHTTP2_FLAG_NONE, nullptr)); EXPECT_THROW(client_->sendPendingFrames(), ServerCodecError); EXPECT_EQ(frame_count, CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_FRAMES + 1); EXPECT_EQ(1, stats_store_.counter("http2.outbound_flood").value()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.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: TEST_F(Http1ServerConnectionImplTest, ManyTrailersRejected) { // Send a request with 101 headers. testTrailersExceedLimit(createHeaderFragment(101), true); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.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: TEST_F(Http1ServerConnectionImplTest, ManyTrailersIgnored) { // Send a request with 101 headers. testTrailersExceedLimit(createHeaderFragment(101), false); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ServerConnectionImpl::onUrl(const char* data, size_t length) { if (active_request_.has_value()) { active_request_.value().request_url_.append(data, length); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionImpl::onHeaderField(const char* data, size_t length) { // We previously already finished up the headers, these headers are // now trailers. if (header_parsing_state_ == HeaderParsingState::Done) { if (!enable_trailers_) { // Ignore trailers. return; } processing_trailers_ = true; header_parsing_state_ = HeaderParsingState::Field; } if (header_parsing_state_ == HeaderParsingState::Value) { completeLastHeader(); } current_header_field_.append(data, length); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void maybeAllocTrailers() override { ASSERT(processing_trailers_); if (!absl::holds_alternative<ResponseTrailerMapPtr>(headers_or_trailers_)) { headers_or_trailers_.emplace<ResponseTrailerMapPtr>(ResponseTrailerMapImpl::create()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Http1ServerConnectionImplTest::testTrailersExceedLimit(std::string trailer_string, bool enable_trailers) { initialize(); // Make a new 'codec' with the right settings codec_settings_.enable_trailers_ = enable_trailers; codec_ = std::make_unique<ServerConnectionImpl>( connection_, http1CodecStats(), callbacks_, codec_settings_, max_request_headers_kb_, max_request_headers_count_, envoy::config::core::v3::HttpProtocolOptions::ALLOW); std::string exception_reason; NiceMock<MockRequestDecoder> decoder; EXPECT_CALL(callbacks_, newStream(_, _)) .WillOnce(Invoke([&](ResponseEncoder&, bool) -> RequestDecoder& { return decoder; })); if (enable_trailers) { EXPECT_CALL(decoder, decodeHeaders_(_, false)); EXPECT_CALL(decoder, decodeData(_, false)); } else { EXPECT_CALL(decoder, decodeData(_, false)); EXPECT_CALL(decoder, decodeData(_, true)); } Buffer::OwnedImpl buffer("POST / HTTP/1.1\r\n" "Host: host\r\n" "Transfer-Encoding: chunked\r\n\r\n" "4\r\n" "body\r\n0\r\n"); auto status = codec_->dispatch(buffer); EXPECT_TRUE(status.ok()); buffer = Buffer::OwnedImpl(trailer_string + "\r\n\r\n"); if (enable_trailers) { EXPECT_CALL(decoder, sendLocalReply(_, _, _, _, _, _, _)); status = codec_->dispatch(buffer); EXPECT_TRUE(isCodecProtocolError(status)); EXPECT_EQ(status.message(), "trailers size exceeds limit"); } else { // If trailers are not enabled, we expect Envoy to simply skip over the large // trailers as if nothing has happened! status = codec_->dispatch(buffer); EXPECT_TRUE(status.ok()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionHandlerImpl::ActiveTcpListener::onAccept(Network::ConnectionSocketPtr&& socket) { onAcceptWorker(std::move(socket), config_->handOffRestoredDestinationConnections(), false); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <tony@allen.gg>'</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: TEST_P(ClusterMemoryTestRunner, MemoryLargeClusterSizeWithFakeSymbolTable) { symbol_table_creator_test_peer_.setUseFakeSymbolTables(true); // A unique instance of ClusterMemoryTest allows for multiple runs of Envoy with // differing configuration. This is necessary for measuring the memory consumption // between the different instances within the same test. const size_t m100 = ClusterMemoryTestHelper::computeMemoryDelta(1, 0, 101, 0, true); const size_t m_per_cluster = (m100) / 100; // Note: if you are increasing this golden value because you are adding a // stat, please confirm that this will be generally useful to most Envoy // users. Otherwise you are adding to the per-cluster memory overhead, which // will be significant for Envoy installations that are massively // multi-tenant. // // History of golden values: // // Date PR Bytes Per Cluster Notes // exact upper-bound // ---------- ----- ----------------- ----- // 2019/03/20 6329 59015 Initial version // 2019/04/12 6477 59576 Implementing Endpoint lease... // 2019/04/23 6659 59512 Reintroduce dispatcher stats... // 2019/04/24 6161 49415 Pack tags and tag extracted names // 2019/05/07 6794 49957 Stats for excluded hosts in cluster // 2019/04/27 6733 50213 Use SymbolTable API for HTTP codes // 2019/05/31 6866 50157 libstdc++ upgrade in CI // 2019/06/03 7199 49393 absl update // 2019/06/06 7208 49650 make memory targets approximate // 2019/06/17 7243 49412 49700 macros for exact/upper-bound memory checks // 2019/06/29 7364 45685 46000 combine 2 levels of stat ref-counting into 1 // 2019/06/30 7428 42742 43000 remove stats multiple inheritance, inline HeapStatData // 2019/07/06 7477 42742 43000 fork gauge representation to drop pending_increment_ // 2019/07/15 7555 42806 43000 static link libstdc++ in tests // 2019/07/24 7503 43030 44000 add upstream filters to clusters // 2019/08/13 7877 42838 44000 skip EdfScheduler creation if all host weights equal // 2019/09/02 8118 42830 43000 Share symbol-tables in cluster/host stats. // 2019/09/16 8100 42894 43000 Add transport socket matcher in cluster. // 2019/09/25 8226 43022 44000 dns: enable dns failure refresh rate configuration // 2019/09/30 8354 43310 44000 Implement transport socket match. // 2019/10/17 8537 43308 44000 add new enum value HTTP3 // 2019/10/17 8484 43340 44000 stats: add unit support to histogram // 2019/11/01 8859 43563 44000 build: switch to libc++ by default // 2019/11/15 9040 43371 44000 build: update protobuf to 3.10.1 // 2019/11/15 9031 43403 44000 upstream: track whether cluster is local // 2019/12/10 8779 42919 43500 use var-length coding for name length // 2020/01/07 9069 43413 44000 upstream: Implement retry concurrency budgets // 2020/01/07 9564 43445 44000 use RefcountPtr for CentralCache. // 2020/01/09 8889 43509 44000 api: add UpstreamHttpProtocolOptions message // 2020/01/09 9227 43637 44000 router: per-cluster histograms w/ timeout budget // 2020/01/12 9633 43797 44104 config: support recovery of original message when // upgrading. // 2020/02/13 10042 43797 44136 Metadata: Metadata are shared across different // clusters and hosts. // 2020/03/16 9964 44085 44600 http2: support custom SETTINGS parameters. // 2020/03/24 10501 44261 44600 upstream: upstream_rq_retry_limit_exceeded. // 2020/04/02 10624 43356 44000 Use 100 clusters rather than 1000 to avoid timeouts // 2020/04/07 10661 43349 44000 fix clang tidy on master // 2020/04/23 10531 44169 44600 http: max stream duration upstream support. // 2020/05/05 10908 44233 44600 router: add InternalRedirectPolicy and predicate // 2020/05/13 10531 44425 44600 Refactor resource manager // 2020/05/20 11223 44491 44600 Add primary clusters tracking to cluster manager. // 2020/06/10 11561 44491 44811 Make upstreams pluggable // Note: when adjusting this value: EXPECT_MEMORY_EQ is active only in CI // 'release' builds, where we control the platform and tool-chain. So you // will need to find the correct value only after failing CI and looking // at the logs. // // On a local clang8/libstdc++/linux flow, the memory usage was observed in // June 2019 to be 64 bytes higher than it is in CI/release. Your mileage may // vary. // // If you encounter a failure here, please see // https://github.com/envoyproxy/envoy/blob/master/source/docs/stats.md#stats-memory-tests // for details on how to fix. EXPECT_MEMORY_EQ(m_per_cluster, 44491); EXPECT_MEMORY_LE(m_per_cluster, 46000); // Round up to allow platform variations. } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <tony@allen.gg>'</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 incNumConnections() override { ++num_listener_connections_; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <tony@allen.gg>'</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: ListenerImpl::ListenerImpl(const envoy::config::listener::v3::Listener& config, const std::string& version_info, ListenerManagerImpl& parent, const std::string& name, bool added_via_api, bool workers_started, uint64_t hash, uint32_t concurrency) : parent_(parent), address_(Network::Address::resolveProtoAddress(config.address())), bind_to_port_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.deprecated_v1(), bind_to_port, true)), hand_off_restored_destination_connections_( PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, hidden_envoy_deprecated_use_original_dst, false)), per_connection_buffer_limit_bytes_( PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, per_connection_buffer_limit_bytes, 1024 * 1024)), listener_tag_(parent_.factory_.nextListenerTag()), name_(name), added_via_api_(added_via_api), workers_started_(workers_started), hash_(hash), validation_visitor_( added_via_api_ ? parent_.server_.messageValidationContext().dynamicValidationVisitor() : parent_.server_.messageValidationContext().staticValidationVisitor()), listener_init_target_(fmt::format("Listener-init-target {}", name), [this]() { dynamic_init_manager_->initialize(local_init_watcher_); }), dynamic_init_manager_(std::make_unique<Init::ManagerImpl>( fmt::format("Listener-local-init-manager {} {}", name, hash))), config_(config), version_info_(version_info), listener_filters_timeout_( PROTOBUF_GET_MS_OR_DEFAULT(config, listener_filters_timeout, 15000)), continue_on_listener_filters_timeout_(config.continue_on_listener_filters_timeout()), listener_factory_context_(std::make_shared<PerListenerFactoryContextImpl>( parent.server_, validation_visitor_, config, this, *this, parent.factory_.createDrainManager(config.drain_type()))), filter_chain_manager_(address_, listener_factory_context_->parentFactoryContext(), initManager()), local_init_watcher_(fmt::format("Listener-local-init-watcher {}", name), [this] { if (workers_started_) { parent_.onListenerWarmed(*this); } else { // Notify Server that this listener is // ready. listener_init_target_.ready(); } }) { buildAccessLog(); auto socket_type = Network::Utility::protobufAddressSocketType(config.address()); buildListenSocketOptions(socket_type); buildUdpListenerFactory(socket_type, concurrency); createListenerFilterFactories(socket_type); validateFilterChains(socket_type); buildFilterChains(); if (socket_type == Network::Socket::Type::Datagram) { return; } buildSocketOptions(); buildOriginalDstListenerFilter(); buildProxyProtocolListenerFilter(); buildTlsInspectorListenerFilter(); if (!workers_started_) { // Initialize dynamic_init_manager_ from Server's init manager if it's not initialized. // NOTE: listener_init_target_ should be added to parent's initManager at the end of the // listener constructor so that this listener's children entities could register their targets // with their parent's initManager. parent_.server_.initManager().add(listener_init_target_); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <tony@allen.gg>'</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 decNumConnections() { ASSERT(num_listener_connections_ > 0); --num_listener_connections_; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <tony@allen.gg>'</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: TEST_P(ConnectionLimitIntegrationTest, TestListenerLimit) { setListenerLimit(2); initialize(); std::vector<IntegrationTcpClientPtr> tcp_clients; std::vector<FakeRawConnectionPtr> raw_conns; tcp_clients.emplace_back(makeTcpConnection(lookupPort("listener_0"))); raw_conns.emplace_back(); ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(raw_conns.back())); ASSERT_TRUE(tcp_clients.back()->connected()); tcp_clients.emplace_back(makeTcpConnection(lookupPort("listener_0"))); raw_conns.emplace_back(); ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(raw_conns.back())); ASSERT_TRUE(tcp_clients.back()->connected()); tcp_clients.emplace_back(makeTcpConnection(lookupPort("listener_0"))); raw_conns.emplace_back(); ASSERT_FALSE(fake_upstreams_[0]->waitForRawConnection(raw_conns.back())); tcp_clients.back()->waitForDisconnect(); // Get rid of the client that failed to connect. tcp_clients.back()->close(); tcp_clients.pop_back(); // Close the first connection that was successful so that we can open a new successful connection. tcp_clients.front()->close(); ASSERT_TRUE(raw_conns.front()->close()); ASSERT_TRUE(raw_conns.front()->waitForDisconnect()); tcp_clients.emplace_back(makeTcpConnection(lookupPort("listener_0"))); raw_conns.emplace_back(); ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(raw_conns.back())); ASSERT_TRUE(tcp_clients.back()->connected()); const bool isV4 = (version_ == Network::Address::IpVersion::v4); auto local_address = isV4 ? Network::Utility::getCanonicalIpv4LoopbackAddress() : Network::Utility::getIpv6LoopbackAddress(); const std::string counter_name = isV4 ? ("listener.127.0.0.1_0.downstream_cx_overflow") : ("listener.[__1]_0.downstream_cx_overflow"); test_server_->waitForCounterEq(counter_name, 1); for (auto& tcp_client : tcp_clients) { tcp_client->close(); } tcp_clients.clear(); raw_conns.clear(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'overload: Runtime configurable global connection limits (#147) Signed-off-by: Tony Allen <tony@allen.gg>'</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 ListenerImpl::listenCallback(evconnlistener*, evutil_socket_t fd, sockaddr* remote_addr, int remote_addr_len, void* arg) { ListenerImpl* listener = static_cast<ListenerImpl*>(arg); // Wrap raw socket fd in IoHandle. IoHandlePtr io_handle = SocketInterfaceSingleton::get().socket(fd); // Get the local address from the new socket if the listener is listening on IP ANY // (e.g., 0.0.0.0 for IPv4) (local_address_ is nullptr in this case). const Address::InstanceConstSharedPtr& local_address = listener->local_address_ ? listener->local_address_ : io_handle->localAddress(); // The accept() call that filled in remote_addr doesn't fill in more than the sa_family field // for Unix domain sockets; apparently there isn't a mechanism in the kernel to get the // `sockaddr_un` associated with the client socket when starting from the server socket. // We work around this by using our own name for the socket in this case. // Pass the 'v6only' parameter as true if the local_address is an IPv6 address. This has no effect // if the socket is a v4 socket, but for v6 sockets this will create an IPv4 remote address if an // IPv4 local_address was created from an IPv6 mapped IPv4 address. const Address::InstanceConstSharedPtr& remote_address = (remote_addr->sa_family == AF_UNIX) ? io_handle->peerAddress() : Address::addressFromSockAddr(*reinterpret_cast<const sockaddr_storage*>(remote_addr), remote_addr_len, local_address->ip()->version() == Address::IpVersion::v6); listener->cb_.onAccept( std::make_unique<AcceptedSocketImpl>(std::move(io_handle), local_address, remote_address)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'overload: Runtime configurable global connection limits (#147) Signed-off-by: Tony Allen <tony@allen.gg>'</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: TEST_F(OwnedImplTest, ReadReserveAndCommit) { BufferFragmentImpl frag("", 0, nullptr); Buffer::OwnedImpl buf; buf.add("bbbbb"); os_fd_t pipe_fds[2] = {0, 0}; auto& os_sys_calls = Api::OsSysCallsSingleton::get(); #ifdef WIN32 ASSERT_EQ(os_sys_calls.socketpair(AF_INET, SOCK_STREAM, 0, pipe_fds).rc_, 0); #else ASSERT_EQ(pipe(pipe_fds), 0); #endif Network::IoSocketHandleImpl io_handle(pipe_fds[0]); ASSERT_EQ(os_sys_calls.setsocketblocking(pipe_fds[0], false).rc_, 0); ASSERT_EQ(os_sys_calls.setsocketblocking(pipe_fds[1], false).rc_, 0); const uint32_t read_length = 32768; std::string data = "e"; const ssize_t rc = os_sys_calls.write(pipe_fds[1], data.data(), data.size()).rc_; ASSERT_GT(rc, 0); Api::IoCallUint64Result result = buf.read(io_handle, read_length); ASSERT_EQ(result.rc_, static_cast<uint64_t>(rc)); ASSERT_EQ(os_sys_calls.close(pipe_fds[1]).rc_, 0); EXPECT_EQ("bbbbbe", buf.toString()); expectSlices({{6, 4050, 4056}}, buf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.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: TEST_F(OwnedImplTest, ReserveCommitReuse) { Buffer::OwnedImpl buffer; static constexpr uint64_t NumIovecs = 2; Buffer::RawSlice iovecs[NumIovecs]; // Reserve 8KB and commit all but a few bytes of it, to ensure that // the last slice of the buffer can hold part but not all of the // next reservation. Note that the buffer implementation might // allocate more than the requested 8KB. In case the implementation // uses a power-of-two allocator, the subsequent reservations all // request 16KB. uint64_t num_reserved = buffer.reserve(8192, iovecs, NumIovecs); EXPECT_EQ(1, num_reserved); iovecs[0].len_ = 8000; buffer.commit(iovecs, 1); EXPECT_EQ(8000, buffer.length()); // Reserve 16KB. The resulting reservation should span 2 slices. // Commit part of the first slice and none of the second slice. num_reserved = buffer.reserve(16384, iovecs, NumIovecs); EXPECT_EQ(2, num_reserved); const void* first_slice = iovecs[0].mem_; iovecs[0].len_ = 1; expectSlices({{8000, 4248, 12248}, {0, 12248, 12248}}, buffer); buffer.commit(iovecs, 1); EXPECT_EQ(8001, buffer.length()); EXPECT_EQ(first_slice, iovecs[0].mem_); // The second slice is now released because there's nothing in the second slice. expectSlices({{8001, 4247, 12248}}, buffer); // Reserve 16KB again. num_reserved = buffer.reserve(16384, iovecs, NumIovecs); expectSlices({{8001, 4247, 12248}, {0, 12248, 12248}}, buffer); EXPECT_EQ(2, num_reserved); EXPECT_EQ(static_cast<const uint8_t*>(first_slice) + 1, static_cast<const uint8_t*>(iovecs[0].mem_)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.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: uint64_t append(const void* data, uint64_t size) { uint64_t copy_size = std::min(size, reservableSize()); uint8_t* dest = base_ + reservable_; reservable_ += copy_size; // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) memcpy(dest, data, copy_size); return copy_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionImpl::releaseOutboundControlFrame(const Buffer::OwnedBufferFragmentImpl* fragment) { ASSERT(outbound_control_frames_ >= 1); --outbound_control_frames_; releaseOutboundFrame(fragment); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.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: ConnectionImpl::ConnectionImpl(Network::Connection& connection, CodecStats& stats, const envoy::config::core::v3::Http2ProtocolOptions& http2_options, const uint32_t max_headers_kb, const uint32_t max_headers_count) : stats_(stats), connection_(connection), max_headers_kb_(max_headers_kb), max_headers_count_(max_headers_count), per_stream_buffer_limit_(http2_options.initial_stream_window_size().value()), stream_error_on_invalid_http_messaging_( http2_options.stream_error_on_invalid_http_messaging()), flood_detected_(false), max_outbound_frames_(http2_options.max_outbound_frames().value()), frame_buffer_releasor_([this](const Buffer::OwnedBufferFragmentImpl* fragment) { releaseOutboundFrame(fragment); }), max_outbound_control_frames_(http2_options.max_outbound_control_frames().value()), control_frame_buffer_releasor_([this](const Buffer::OwnedBufferFragmentImpl* fragment) { releaseOutboundControlFrame(fragment); }), max_consecutive_inbound_frames_with_empty_payload_( http2_options.max_consecutive_inbound_frames_with_empty_payload().value()), max_inbound_priority_frames_per_stream_( http2_options.max_inbound_priority_frames_per_stream().value()), max_inbound_window_update_frames_per_data_frame_sent_( http2_options.max_inbound_window_update_frames_per_data_frame_sent().value()), dispatching_(false), raised_goaway_(false), pending_deferred_reset_(false) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.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 expectSlices(std::vector<std::vector<int>> buffer_list, OwnedImpl& buffer) { const auto& buffer_slices = buffer.describeSlicesForTest(); for (uint64_t i = 0; i < buffer_slices.size(); i++) { EXPECT_EQ(buffer_slices[i].data, buffer_list[i][0]); EXPECT_EQ(buffer_slices[i].reservable, buffer_list[i][1]); EXPECT_EQ(buffer_slices[i].capacity, buffer_list[i][2]); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.com>'</s>