text
stringlengths 517
228k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)
{
GF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;
int i;
u32 tmp_strsize;
char *tmp_str;
GF_Err e;
ISOM_DECREASE_SIZE(ptr, 25)
ptr->bootstrapinfo_version = gf_bs_read_u32(bs);
ptr->profile = gf_bs_read_int(bs, 2);
ptr->live = gf_bs_read_int(bs, 1);
ptr->update = gf_bs_read_int(bs, 1);
ptr->reserved = gf_bs_read_int(bs, 4);
ptr->time_scale = gf_bs_read_u32(bs);
ptr->current_media_time = gf_bs_read_u64(bs);
ptr->smpte_time_code_offset = gf_bs_read_u64(bs);
i=0;
if (ptr->size<8) return GF_ISOM_INVALID_FILE;
tmp_strsize =(u32)ptr->size-8;
tmp_str = gf_malloc(sizeof(char)*tmp_strsize);
if (!tmp_str) return GF_OUT_OF_MEM;
memset(tmp_str, 0, sizeof(char)*tmp_strsize);
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[i] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[i])
break;
i++;
}
if (i) {
ptr->movie_identifier = gf_strdup(tmp_str);
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->server_entry_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->server_entry_count; i++) {
int j=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[j] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[j])
break;
j++;
}
if (j) {
gf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);
}
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->quality_entry_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->quality_entry_count; i++) {
int j=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[j] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[j])
break;
j++;
}
if (j) {
gf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);
}
}
i=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[i] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[i])
break;
i++;
}
if (i) {
ptr->drm_data = gf_strdup(tmp_str);
}
i=0;
tmp_strsize=(u32)ptr->size;
while (tmp_strsize) {
ISOM_DECREASE_SIZE(ptr, 1)
tmp_str[i] = gf_bs_read_u8(bs);
tmp_strsize--;
if (!tmp_str[i])
break;
i++;
}
if (i) {
ptr->meta_data = gf_strdup(tmp_str);
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->segment_run_table_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->segment_run_table_count; i++) {
GF_AdobeSegmentRunTableBox *asrt = NULL;
e = gf_isom_box_parse((GF_Box **)&asrt, bs);
if (e) {
if (asrt) gf_isom_box_del((GF_Box*)asrt);
gf_free(tmp_str);
return e;
}
gf_list_add(ptr->segment_run_table_entries, asrt);
}
ISOM_DECREASE_SIZE(ptr, 1)
ptr->fragment_run_table_count = gf_bs_read_u8(bs);
for (i=0; i<ptr->fragment_run_table_count; i++) {
GF_AdobeFragmentRunTableBox *afrt = NULL;
e = gf_isom_box_parse((GF_Box **)&afrt, bs);
if (e) {
if (afrt) gf_isom_box_del((GF_Box*)afrt);
gf_free(tmp_str);
return e;
}
gf_list_add(ptr->fragment_run_table_entries, afrt);
}
gf_free(tmp_str);
return GF_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'fixed #1568'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pthread_mutex_unlock(pthread_mutex_t *mutex)
{
LeaveCriticalSection(mutex);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Make pthread_mutex static initialisation work on Windows.
This takes the dynamic initialisation code added to CRYPTO_lock() in e5081719
and applies it to the Window's pthread_mutex implementation. This allows for
PTHREAD_MUTEX_INITIALIZER to be used on Windows.
bcook has agreed to place this code in the public domain (as per the rest of
the code in pthread.h).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GF_Err schm_box_read(GF_Box *s, GF_BitStream *bs)
{
GF_SchemeTypeBox *ptr = (GF_SchemeTypeBox *)s;
ISOM_DECREASE_SIZE(ptr, 8);
ptr->scheme_type = gf_bs_read_u32(bs);
ptr->scheme_version = gf_bs_read_u32(bs);
if (ptr->size && (ptr->flags & 0x000001)) {
u32 len = (u32) (ptr->size);
ptr->URI = (char*)gf_malloc(sizeof(char)*len);
if (!ptr->URI) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->URI, len);
}
return GF_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'fixed #1879'</s> |
<s>[INST] Given the following code containing errors, provide 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 nlmclnt_unlock_callback(struct rpc_task *task, void *data)
{
struct nlm_rqst *req = data;
u32 status = ntohl(req->a_res.status);
if (RPC_ASSASSINATED(task))
goto die;
if (task->tk_status < 0) {
dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status);
goto retry_rebind;
}
if (status == NLM_LCK_DENIED_GRACE_PERIOD) {
rpc_delay(task, NLMCLNT_GRACE_WAIT);
goto retry_unlock;
}
if (status != NLM_LCK_GRANTED)
printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status);
die:
return;
retry_rebind:
nlm_rebind_host(req->a_host);
retry_unlock:
rpc_restart_call(task);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-399', 'CWE-703'], 'message': 'NLM: Don't hang forever on NLM unlock requests
If the NLM daemon is killed on the NFS server, we can currently end up
hanging forever on an 'unlock' request, instead of aborting. Basically,
if the rpcbind request fails, or the server keeps returning garbage, we
really want to quit instead of retrying.
Tested-by: Vasily Averin <vvs@sw.ru>
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
Cc: stable@kernel.org'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
{
struct ldap_SearchRequest *req = &call->request->r.SearchRequest;
struct ldap_Result *done;
struct ldapsrv_reply *done_r;
TALLOC_CTX *local_ctx;
struct ldapsrv_context *callback_ctx = NULL;
struct ldb_context *samdb = talloc_get_type(call->conn->ldb, struct ldb_context);
struct ldb_dn *basedn;
struct ldb_request *lreq;
struct ldb_control *search_control;
struct ldb_search_options_control *search_options;
struct ldb_control *extended_dn_control;
struct ldb_extended_dn_control *extended_dn_decoded = NULL;
struct ldb_control *notification_control = NULL;
enum ldb_scope scope = LDB_SCOPE_DEFAULT;
const char **attrs = NULL;
const char *scope_str, *errstr = NULL;
int result = -1;
int ldb_ret = -1;
unsigned int i;
int extended_type = 1;
DEBUG(10, ("SearchRequest"));
DEBUGADD(10, (" basedn: %s", req->basedn));
DEBUGADD(10, (" filter: %s\n", ldb_filter_from_tree(call, req->tree)));
local_ctx = talloc_new(call);
NT_STATUS_HAVE_NO_MEMORY(local_ctx);
basedn = ldb_dn_new(local_ctx, samdb, req->basedn);
NT_STATUS_HAVE_NO_MEMORY(basedn);
DEBUG(10, ("SearchRequest: basedn: [%s]\n", req->basedn));
DEBUG(10, ("SearchRequest: filter: [%s]\n", ldb_filter_from_tree(call, req->tree)));
switch (req->scope) {
case LDAP_SEARCH_SCOPE_BASE:
scope_str = "BASE";
scope = LDB_SCOPE_BASE;
break;
case LDAP_SEARCH_SCOPE_SINGLE:
scope_str = "ONE";
scope = LDB_SCOPE_ONELEVEL;
break;
case LDAP_SEARCH_SCOPE_SUB:
scope_str = "SUB";
scope = LDB_SCOPE_SUBTREE;
break;
default:
result = LDAP_PROTOCOL_ERROR;
map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,
&errstr);
errstr = talloc_asprintf(local_ctx,
"%s. Invalid scope", errstr);
goto reply;
}
DEBUG(10,("SearchRequest: scope: [%s]\n", scope_str));
if (req->num_attributes >= 1) {
attrs = talloc_array(local_ctx, const char *, req->num_attributes+1);
NT_STATUS_HAVE_NO_MEMORY(attrs);
for (i=0; i < req->num_attributes; i++) {
DEBUG(10,("SearchRequest: attrs: [%s]\n",req->attributes[i]));
attrs[i] = req->attributes[i];
}
attrs[i] = NULL;
}
DEBUG(5,("ldb_request %s dn=%s filter=%s\n",
scope_str, req->basedn, ldb_filter_from_tree(call, req->tree)));
callback_ctx = talloc_zero(local_ctx, struct ldapsrv_context);
NT_STATUS_HAVE_NO_MEMORY(callback_ctx);
callback_ctx->call = call;
callback_ctx->extended_type = extended_type;
callback_ctx->attributesonly = req->attributesonly;
ldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx,
basedn, scope,
req->tree, attrs,
call->request->controls,
callback_ctx,
ldap_server_search_callback,
NULL);
if (ldb_ret != LDB_SUCCESS) {
goto reply;
}
if (call->conn->global_catalog) {
search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);
search_options = NULL;
if (search_control) {
search_options = talloc_get_type(search_control->data, struct ldb_search_options_control);
search_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT;
} else {
search_options = talloc(lreq, struct ldb_search_options_control);
NT_STATUS_HAVE_NO_MEMORY(search_options);
search_options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
ldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options);
}
} else {
ldb_request_add_control(lreq, DSDB_CONTROL_NO_GLOBAL_CATALOG, false, NULL);
}
extended_dn_control = ldb_request_get_control(lreq, LDB_CONTROL_EXTENDED_DN_OID);
if (extended_dn_control) {
if (extended_dn_control->data) {
extended_dn_decoded = talloc_get_type(extended_dn_control->data, struct ldb_extended_dn_control);
extended_type = extended_dn_decoded->type;
} else {
extended_type = 0;
}
callback_ctx->extended_type = extended_type;
}
notification_control = ldb_request_get_control(lreq, LDB_CONTROL_NOTIFICATION_OID);
if (notification_control != NULL) {
const struct ldapsrv_call *pc = NULL;
size_t count = 0;
for (pc = call->conn->pending_calls; pc != NULL; pc = pc->next) {
count += 1;
}
if (count >= call->conn->limits.max_notifications) {
DEBUG(10,("SearchRequest: error MaxNotificationPerConn\n"));
result = map_ldb_error(local_ctx,
LDB_ERR_ADMIN_LIMIT_EXCEEDED,
"MaxNotificationPerConn reached",
&errstr);
goto reply;
}
/*
* For now we need to do periodic retries on our own.
* As the dsdb_notification module will return after each run.
*/
call->notification.busy = true;
}
{
const char *scheme = NULL;
switch (call->conn->referral_scheme) {
case LDAP_REFERRAL_SCHEME_LDAPS:
scheme = "ldaps";
break;
default:
scheme = "ldap";
}
ldb_ret = ldb_set_opaque(
samdb,
LDAP_REFERRAL_SCHEME_OPAQUE,
discard_const_p(char *, scheme));
if (ldb_ret != LDB_SUCCESS) {
goto reply;
}
}
{
time_t timeout = call->conn->limits.search_timeout;
if (timeout == 0
|| (req->timelimit != 0
&& req->timelimit < timeout))
{
timeout = req->timelimit;
}
ldb_set_timeout(samdb, lreq, timeout);
}
if (!call->conn->is_privileged) {
ldb_req_mark_untrusted(lreq);
}
LDB_REQ_SET_LOCATION(lreq);
ldb_ret = ldb_request(samdb, lreq);
if (ldb_ret != LDB_SUCCESS) {
goto reply;
}
ldb_ret = ldb_wait(lreq->handle, LDB_WAIT_ALL);
if (ldb_ret == LDB_SUCCESS) {
if (call->notification.busy) {
/* Move/Add it to the end */
DLIST_DEMOTE(call->conn->pending_calls, call);
call->notification.generation =
call->conn->service->notification.generation;
if (callback_ctx->count != 0) {
call->notification.generation += 1;
ldapsrv_notification_retry_setup(call->conn->service,
true);
}
talloc_free(local_ctx);
return NT_STATUS_OK;
}
}
reply:
DLIST_REMOVE(call->conn->pending_calls, call);
call->notification.busy = false;
done_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultDone);
NT_STATUS_HAVE_NO_MEMORY(done_r);
done = &done_r->msg->r.SearchResultDone;
done->dn = NULL;
done->referral = NULL;
if (result != -1) {
} else if (ldb_ret == LDB_SUCCESS) {
if (callback_ctx->controls) {
done_r->msg->controls = callback_ctx->controls;
talloc_steal(done_r->msg, callback_ctx->controls);
}
result = LDB_SUCCESS;
} else {
DEBUG(10,("SearchRequest: error\n"));
result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
&errstr);
}
done->resultcode = result;
done->errormessage = (errstr?talloc_strdup(done_r, errstr):NULL);
talloc_free(local_ctx);
return ldapsrv_queue_reply_forced(call, done_r);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'CVE-2021-3670 ldap_server: Remove duplicate print of LDAP search details
BUG: https://bugzilla.samba.org/show_bug.cgi?id=14694
Signed-off-by: Andrew Bartlett <abartlet@samba.org>
Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
(cherry picked from commit 2b3af3b560c9617a233c131376c870fce146c002)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEE_Result syscall_cryp_obj_populate(unsigned long obj,
struct utee_attribute *usr_attrs,
unsigned long attr_count)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *attrs = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_IMPLEMENTED;
attrs = malloc(sizeof(TEE_Attribute) * attr_count);
if (!attrs)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,
attrs);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
attrs, attr_count);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
if (res == TEE_SUCCESS)
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
out:
free(attrs);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'svc: check for allocation overflow in syscall_cryp_obj_populate
Without checking for overflow there is a risk of allocating a buffer
with size smaller than anticipated and as a consequence of that it might
lead to a heap based overflow with attacker controlled data written
outside the boundaries of the buffer.
Fixes: OP-TEE-2018-0009: "Integer overflow in crypto system calls"
Signed-off-by: Joakim Bech <joakim.bech@linaro.org>
Tested-by: Joakim Bech <joakim.bech@linaro.org> (QEMU v7, v8)
Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org>
Reported-by: Riscure <inforequest@riscure.com>
Reported-by: Alyssa Milburn <a.a.milburn@vu.nl>
Acked-by: Etienne Carriere <etienne.carriere@linaro.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: static s32 gf_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos, u32 nal_hdr)
{
AVC_SPS *sps;
s32 mb_width, mb_height, sps_id = -1;
u32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl = 0, cr = 0, ct = 0, cb = 0, luma_bd, chroma_bd;
u8 separate_colour_plane_flag = 0;
if (!vui_flag_pos) {
gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
}
if (!bs) {
return -1;
}
if (!nal_hdr) {
gf_bs_read_int_log(bs, 1, "forbidden_zero_bit");
gf_bs_read_int_log(bs, 2, "nal_ref_idc");
gf_bs_read_int_log(bs, 5, "nal_unit_type");
}
profile_idc = gf_bs_read_int_log(bs, 8, "profile_idc");
pcomp = gf_bs_read_int_log(bs, 8, "profile_compatibility");
/*sanity checks*/
if (pcomp & 0x3)
return -1;
level_idc = gf_bs_read_int_log(bs, 8, "level_idc");
/*SubsetSps is used to be sure that AVC SPS are not going to be scratched
by subset SPS. According to the SVC standard, subset SPS can have the same sps_id
than its base layer, but it does not refer to the same SPS. */
sps_id = gf_bs_read_ue_log(bs, "sps_id") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;
if ((sps_id < 0) || (sps_id >= 32)) {
return -1;
}
luma_bd = chroma_bd = 0;
sps = &avc->sps[sps_id];
chroma_format_idc = sps->ChromaArrayType = 1;
sps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;
/*High Profile and SVC*/
switch (profile_idc) {
case 100:
case 110:
case 122:
case 244:
case 44:
/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/
if (pcomp & 0xE0)
return -1;
case 83:
case 86:
case 118:
case 128:
chroma_format_idc = gf_bs_read_ue_log(bs, "chroma_format_idc");
sps->ChromaArrayType = chroma_format_idc;
if (chroma_format_idc == 3) {
separate_colour_plane_flag = gf_bs_read_int_log(bs, 1, "separate_colour_plane_flag");
/*
Depending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.
\96 If separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.
\96 Otherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.
*/
if (separate_colour_plane_flag) sps->ChromaArrayType = 0;
}
luma_bd = gf_bs_read_ue_log(bs, "luma_bit_depth");
chroma_bd = gf_bs_read_ue_log(bs, "chroma_bit_depth");
/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int_log(bs, 1, "qpprime_y_zero_transform_bypass_flag");
/*seq_scaling_matrix_present_flag*/
if (gf_bs_read_int_log(bs, 1, "seq_scaling_matrix_present_flag")) {
u32 k;
for (k = 0; k < 8; k++) {
if (gf_bs_read_int_log_idx(bs, 1, "seq_scaling_list_present_flag", k)) {
u32 z, last = 8, next = 8;
u32 sl = k < 6 ? 16 : 64;
for (z = 0; z < sl; z++) {
if (next) {
s32 delta = gf_bs_read_se(bs);
next = (last + delta + 256) % 256;
}
last = next ? next : last;
}
}
}
}
break;
}
sps->profile_idc = profile_idc;
sps->level_idc = level_idc;
sps->prof_compat = pcomp;
sps->log2_max_frame_num = gf_bs_read_ue_log(bs, "log2_max_frame_num") + 4;
sps->poc_type = gf_bs_read_ue_log(bs, "poc_type");
sps->chroma_format = chroma_format_idc;
sps->luma_bit_depth_m8 = luma_bd;
sps->chroma_bit_depth_m8 = chroma_bd;
if (sps->poc_type == 0) {
sps->log2_max_poc_lsb = gf_bs_read_ue_log(bs, "log2_max_poc_lsb") + 4;
}
else if (sps->poc_type == 1) {
sps->delta_pic_order_always_zero_flag = gf_bs_read_int_log(bs, 1, "delta_pic_order_always_zero_flag");
sps->offset_for_non_ref_pic = gf_bs_read_se_log(bs, "offset_for_non_ref_pic");
sps->offset_for_top_to_bottom_field = gf_bs_read_se_log(bs, "offset_for_top_to_bottom_field");
sps->poc_cycle_length = gf_bs_read_ue_log(bs, "poc_cycle_length");
if (sps->poc_cycle_length > GF_ARRAY_LENGTH(sps->offset_for_ref_frame)) {
sps->poc_cycle_length = 255;
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] offset_for_ref_frame overflow from poc_cycle_length\n"));
return -1;
}
for (i = 0; i < sps->poc_cycle_length; i++)
sps->offset_for_ref_frame[i] = gf_bs_read_se_log_idx(bs, "offset_for_ref_frame", i);
}
if (sps->poc_type > 2) {
return -1;
}
sps->max_num_ref_frames = gf_bs_read_ue_log(bs, "max_num_ref_frames");
sps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int_log(bs, 1, "gaps_in_frame_num_value_allowed_flag");
mb_width = gf_bs_read_ue_log(bs, "pic_width_in_mbs_minus1") + 1;
mb_height = gf_bs_read_ue_log(bs, "pic_height_in_map_units_minus1") + 1;
sps->frame_mbs_only_flag = gf_bs_read_int_log(bs, 1, "frame_mbs_only_flag");
sps->width = mb_width * 16;
sps->height = (2 - sps->frame_mbs_only_flag) * mb_height * 16;
if (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int_log(bs, 1, "mb_adaptive_frame_field_flag");
gf_bs_read_int_log(bs, 1, "direct_8x8_inference_flag");
if (gf_bs_read_int_log(bs, 1, "frame_cropping_flag")) {
int CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;
if (chroma_format_idc == 1) {
SubWidthC = 2; SubHeightC = 2;
}
else if (chroma_format_idc == 2) {
SubWidthC = 2; SubHeightC = 1;
}
else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {
SubWidthC = 1; SubHeightC = 1;
}
if (sps->ChromaArrayType == 0) {
assert(SubWidthC == -1);
CropUnitX = 1;
CropUnitY = 2 - sps->frame_mbs_only_flag;
}
else {
CropUnitX = SubWidthC;
CropUnitY = SubHeightC * (2 - sps->frame_mbs_only_flag);
}
cl = gf_bs_read_ue_log(bs, "frame_crop_left_offset");
cr = gf_bs_read_ue_log(bs, "frame_crop_right_offset");
ct = gf_bs_read_ue_log(bs, "frame_crop_top_offset");
cb = gf_bs_read_ue_log(bs, "frame_crop_bottom_offset");
sps->width -= CropUnitX * (cl + cr);
sps->height -= CropUnitY * (ct + cb);
cl *= CropUnitX;
cr *= CropUnitX;
ct *= CropUnitY;
cb *= CropUnitY;
}
sps->crop.left = cl;
sps->crop.right = cr;
sps->crop.top = ct;
sps->crop.bottom = cb;
if (vui_flag_pos) {
*vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);
}
/*vui_parameters_present_flag*/
sps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_parameters_present_flag");
if (sps->vui_parameters_present_flag) {
sps->vui.aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, "aspect_ratio_info_present_flag");
if (sps->vui.aspect_ratio_info_present_flag) {
s32 aspect_ratio_idc = gf_bs_read_int_log(bs, 8, "aspect_ratio_idc");
if (aspect_ratio_idc == 255) {
sps->vui.par_num = gf_bs_read_int_log(bs, 16, "aspect_ratio_num");
sps->vui.par_den = gf_bs_read_int_log(bs, 16, "aspect_ratio_den");
}
else if (aspect_ratio_idc < GF_ARRAY_LENGTH(avc_hevc_sar) ) {
sps->vui.par_num = avc_hevc_sar[aspect_ratio_idc].w;
sps->vui.par_den = avc_hevc_sar[aspect_ratio_idc].h;
}
else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] Unknown aspect_ratio_idc: your video may have a wrong aspect ratio. Contact the GPAC team!\n"));
}
}
sps->vui.overscan_info_present_flag = gf_bs_read_int_log(bs, 1, "overscan_info_present_flag");
if (sps->vui.overscan_info_present_flag)
gf_bs_read_int_log(bs, 1, "overscan_appropriate_flag");
/* default values */
sps->vui.video_format = 5;
sps->vui.colour_primaries = 2;
sps->vui.transfer_characteristics = 2;
sps->vui.matrix_coefficients = 2;
/* now read values if possible */
sps->vui.video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, "video_signal_type_present_flag");
if (sps->vui.video_signal_type_present_flag) {
sps->vui.video_format = gf_bs_read_int_log(bs, 3, "video_format");
sps->vui.video_full_range_flag = gf_bs_read_int_log(bs, 1, "video_full_range_flag");
sps->vui.colour_description_present_flag = gf_bs_read_int_log(bs, 1, "colour_description_present_flag");
if (sps->vui.colour_description_present_flag) {
sps->vui.colour_primaries = gf_bs_read_int_log(bs, 8, "colour_primaries");
sps->vui.transfer_characteristics = gf_bs_read_int_log(bs, 8, "transfer_characteristics");
sps->vui.matrix_coefficients = gf_bs_read_int_log(bs, 8, "matrix_coefficients");
}
}
if (gf_bs_read_int_log(bs, 1, "chroma_location_info_present_flag")) {
gf_bs_read_ue_log(bs, "chroma_sample_location_type_top_field");
gf_bs_read_ue_log(bs, "chroma_sample_location_type_bottom_field");
}
sps->vui.timing_info_present_flag = gf_bs_read_int_log(bs, 1, "timing_info_present_flag");
if (sps->vui.timing_info_present_flag) {
sps->vui.num_units_in_tick = gf_bs_read_int_log(bs, 32, "num_units_in_tick");
sps->vui.time_scale = gf_bs_read_int_log(bs, 32, "time_scale");
sps->vui.fixed_frame_rate_flag = gf_bs_read_int_log(bs, 1, "fixed_frame_rate_flag");
}
sps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "nal_hrd_parameters_present_flag");
if (sps->vui.nal_hrd_parameters_present_flag)
if (avc_parse_hrd_parameters(bs, &sps->vui.hrd)<0) return -1;
sps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vcl_hrd_parameters_present_flag");
if (sps->vui.vcl_hrd_parameters_present_flag)
if (avc_parse_hrd_parameters(bs, &sps->vui.hrd)<0) return -1;
if (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)
sps->vui.low_delay_hrd_flag = gf_bs_read_int_log(bs, 1, "low_delay_hrd_flag");
sps->vui.pic_struct_present_flag = gf_bs_read_int_log(bs, 1, "pic_struct_present_flag");
}
/*end of seq_parameter_set_data*/
if (subseq_sps) {
if ((profile_idc == 83) || (profile_idc == 86)) {
u8 extended_spatial_scalability_idc;
/*parsing seq_parameter_set_svc_extension*/
gf_bs_read_int_log(bs, 1, "inter_layer_deblocking_filter_control_present_flag");
extended_spatial_scalability_idc = gf_bs_read_int_log(bs, 2, "extended_spatial_scalability_idc");
if (sps->ChromaArrayType == 1 || sps->ChromaArrayType == 2) {
gf_bs_read_int_log(bs, 1, "chroma_phase_x_plus1_flag");
}
if (sps->ChromaArrayType == 1) {
gf_bs_read_int_log(bs, 2, "chroma_phase_y_plus1");
}
if (extended_spatial_scalability_idc == 1) {
if (sps->ChromaArrayType > 0) {
gf_bs_read_int_log(bs, 1, "seq_ref_layer_chroma_phase_x_plus1_flag");
gf_bs_read_int_log(bs, 2, "seq_ref_layer_chroma_phase_y_plus1");
}
gf_bs_read_se_log(bs, "seq_scaled_ref_layer_left_offset");
gf_bs_read_se_log(bs, "seq_scaled_ref_layer_top_offset");
gf_bs_read_se_log(bs, "seq_scaled_ref_layer_right_offset");
gf_bs_read_se_log(bs, "seq_scaled_ref_layer_bottom_offset");
}
if (gf_bs_read_int_log(bs, 1, "seq_tcoeff_level_prediction_flag")) {
gf_bs_read_int_log(bs, 1, "adaptive_tcoeff_level_prediction_flag");
}
gf_bs_read_int_log(bs, 1, "slice_header_restriction_flag");
if (gf_bs_read_int_log(bs, 1, "svc_vui_parameters_present")) {
u32 vui_ext_num_entries_minus1 = gf_bs_read_ue_log(bs, "vui_ext_num_entries_minus1");
for (i = 0; i <= vui_ext_num_entries_minus1; i++) {
u8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;
gf_bs_read_int_log(bs, 3, "vui_ext_dependency_id");
gf_bs_read_int_log(bs, 4, "vui_ext_quality_id");
gf_bs_read_int_log(bs, 3, "vui_ext_temporal_id");
vui_ext_timing_info_present_flag = gf_bs_read_int_log(bs, 1, "vui_ext_timing_info_present_flag");
if (vui_ext_timing_info_present_flag) {
gf_bs_read_int_log(bs, 32, "vui_ext_num_units_in_tick");
gf_bs_read_int_log(bs, 32, "vui_ext_time_scale");
gf_bs_read_int_log(bs, 1, "vui_ext_fixed_frame_rate_flag");
}
vui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_ext_nal_hrd_parameters_present_flag");
if (vui_ext_nal_hrd_parameters_present_flag) {
//hrd_parameters( )
}
vui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_ext_vcl_hrd_parameters_present_flag");
if (vui_ext_vcl_hrd_parameters_present_flag) {
//hrd_parameters( )
}
if (vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {
gf_bs_read_int_log(bs, 1, "vui_ext_low_delay_hrd_flag");
}
gf_bs_read_int_log(bs, 1, "vui_ext_pic_struct_present_flag");
}
}
}
else if ((profile_idc == 118) || (profile_idc == 128)) {
GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[avc-h264] MVC parsing not implemented - skipping parsing end of Subset SPS\n"));
return sps_id;
}
if (gf_bs_read_int_log(bs, 1, "additional_extension2")) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\n"));
return sps_id;
}
}
return sps_id;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'fixed #2067'</s> |
<s>[INST] Given the following code containing errors, provide 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 fill_thread_core_info(struct elf_thread_core_info *t,
const struct user_regset_view *view,
long signr, size_t *total)
{
unsigned int i;
/*
* NT_PRSTATUS is the one special case, because the regset data
* goes into the pr_reg field inside the note contents, rather
* than being the whole note contents. We fill the reset in here.
* We assume that regset 0 is NT_PRSTATUS.
*/
fill_prstatus(&t->prstatus, t->task, signr);
(void) view->regsets[0].get(t->task, &view->regsets[0],
0, sizeof(t->prstatus.pr_reg),
&t->prstatus.pr_reg, NULL);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
sizeof(t->prstatus), &t->prstatus);
*total += notesize(&t->notes[0]);
do_thread_regset_writeback(t->task, &view->regsets[0]);
/*
* Each other regset might generate a note too. For each regset
* that has no core_note_type or is inactive, we leave t->notes[i]
* all zero and we'll know to skip writing it later.
*/
for (i = 1; i < view->n; ++i) {
const struct user_regset *regset = &view->regsets[i];
do_thread_regset_writeback(t->task, regset);
if (regset->core_note_type &&
(!regset->active || regset->active(t->task, regset))) {
int ret;
size_t size = regset->n * regset->size;
void *data = kmalloc(size, GFP_KERNEL);
if (unlikely(!data))
return 0;
ret = regset->get(t->task, regset,
0, size, data, NULL);
if (unlikely(ret))
kfree(data);
else {
if (regset->core_note_type != NT_PRFPREG)
fill_note(&t->notes[i], "LINUX",
regset->core_note_type,
size, data);
else {
t->prstatus.pr_fpvalid = 1;
fill_note(&t->notes[i], "CORE",
NT_PRFPREG, size, data);
}
*total += notesize(&t->notes[i]);
}
}
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'regset: Prevent null pointer reference on readonly regsets
The regset common infrastructure assumed that regsets would always
have .get and .set methods, but not necessarily .active methods.
Unfortunately people have since written regsets without .set methods.
Rather than putting in stub functions everywhere, handle regsets with
null .get or .set methods explicitly.
Signed-off-by: H. Peter Anvin <hpa@zytor.com>
Reviewed-by: Oleg Nesterov <oleg@redhat.com>
Acked-by: Roland McGrath <roland@hack.frob.com>
Cc: <stable@vger.kernel.org>
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: njs_vmcode_interpreter(njs_vm_t *vm, u_char *pc, void *promise_cap,
void *async_ctx)
{
u_char *catch;
double num, exponent;
int32_t i32;
uint32_t u32;
njs_str_t string;
njs_uint_t hint;
njs_bool_t valid, lambda_call;
njs_value_t *retval, *value1, *value2;
njs_value_t *src, *s1, *s2, dst;
njs_value_t *function, name;
njs_value_t numeric1, numeric2, primitive1, primitive2;
njs_frame_t *frame;
njs_jump_off_t ret;
njs_vmcode_await_t *await;
njs_native_frame_t *previous, *native;
njs_property_next_t *next;
njs_vmcode_import_t *import;
njs_vmcode_finally_t *finally;
njs_vmcode_generic_t *vmcode;
njs_vmcode_variable_t *var;
njs_vmcode_move_arg_t *move_arg;
njs_vmcode_prop_get_t *get;
njs_vmcode_prop_set_t *set;
njs_vmcode_operation_t op;
njs_vmcode_prop_next_t *pnext;
njs_vmcode_test_jump_t *test_jump;
njs_vmcode_equal_jump_t *equal;
njs_vmcode_try_return_t *try_return;
njs_vmcode_method_frame_t *method_frame;
njs_vmcode_function_copy_t *fcopy;
njs_vmcode_prop_accessor_t *accessor;
njs_vmcode_try_trampoline_t *try_trampoline;
njs_vmcode_function_frame_t *function_frame;
njs_vmcode_debug(vm, pc, "ENTER");
next:
for ( ;; ) {
vmcode = (njs_vmcode_generic_t *) pc;
/*
* The first operand is passed as is in value2 to
* NJS_VMCODE_JUMP,
* NJS_VMCODE_IF_TRUE_JUMP,
* NJS_VMCODE_IF_FALSE_JUMP,
* NJS_VMCODE_FUNCTION_FRAME,
* NJS_VMCODE_FUNCTION_CALL,
* NJS_VMCODE_RETURN,
* NJS_VMCODE_TRY_START,
* NJS_VMCODE_TRY_CONTINUE,
* NJS_VMCODE_TRY_BREAK,
* NJS_VMCODE_TRY_END,
* NJS_VMCODE_CATCH,
* NJS_VMCODE_THROW,
* NJS_VMCODE_STOP.
*/
value2 = (njs_value_t *) vmcode->operand1;
value1 = NULL;
switch (vmcode->code.operands) {
case NJS_VMCODE_3OPERANDS:
njs_vmcode_operand(vm, vmcode->operand3, value2);
/* Fall through. */
case NJS_VMCODE_2OPERANDS:
njs_vmcode_operand(vm, vmcode->operand2, value1);
}
op = vmcode->code.operation;
/*
* On success an operation returns size of the bytecode,
* a jump offset or zero after the call or return operations.
* Jumps can return a negative offset. Compilers can generate
* (ret < 0 && ret >= NJS_PREEMPT)
* as a single unsigned comparision.
*/
#ifdef NJS_OPCODE_DEBUG
njs_disassemble(pc, NULL, 1, NULL);
#endif
if (op > NJS_VMCODE_NORET) {
if (op == NJS_VMCODE_MOVE) {
njs_vmcode_operand(vm, vmcode->operand1, retval);
*retval = *value1;
pc += sizeof(njs_vmcode_move_t);
goto next;
}
if (op == NJS_VMCODE_PROPERTY_GET) {
get = (njs_vmcode_prop_get_t *) pc;
njs_vmcode_operand(vm, get->value, retval);
ret = njs_value_property(vm, value1, value2, retval);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
pc += sizeof(njs_vmcode_prop_get_t);
goto next;
}
switch (op) {
case NJS_VMCODE_INCREMENT:
case NJS_VMCODE_POST_INCREMENT:
case NJS_VMCODE_DECREMENT:
case NJS_VMCODE_POST_DECREMENT:
if (njs_slow_path(!njs_is_numeric(value2))) {
ret = njs_value_to_numeric(vm, value2, &numeric1);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
num = njs_number(&numeric1);
} else {
num = njs_number(value2);
}
njs_set_number(value1,
num + (1 - 2 * ((op - NJS_VMCODE_INCREMENT) >> 1)));
njs_vmcode_operand(vm, vmcode->operand1, retval);
if (op & 1) {
njs_set_number(retval, num);
} else {
*retval = *value1;
}
pc += sizeof(njs_vmcode_3addr_t);
goto next;
case NJS_VMCODE_GLOBAL_GET:
get = (njs_vmcode_prop_get_t *) pc;
njs_vmcode_operand(vm, get->value, retval);
ret = njs_value_property(vm, value1, value2, retval);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
pc += sizeof(njs_vmcode_prop_get_t);
if (ret == NJS_OK) {
pc += sizeof(njs_vmcode_error_t);
}
goto next;
/*
* njs_vmcode_try_return() saves a return value to use it later by
* njs_vmcode_finally(), and jumps to the nearest try_break block.
*/
case NJS_VMCODE_TRY_RETURN:
njs_vmcode_operand(vm, vmcode->operand1, retval);
*retval = *value1;
try_return = (njs_vmcode_try_return_t *) pc;
pc += try_return->offset;
goto next;
case NJS_VMCODE_LESS:
case NJS_VMCODE_GREATER:
case NJS_VMCODE_LESS_OR_EQUAL:
case NJS_VMCODE_GREATER_OR_EQUAL:
case NJS_VMCODE_ADDITION:
if (njs_slow_path(!njs_is_primitive(value1))) {
hint = (op == NJS_VMCODE_ADDITION) && njs_is_date(value1);
ret = njs_value_to_primitive(vm, &primitive1, value1, hint);
if (ret != NJS_OK) {
goto error;
}
value1 = &primitive1;
}
if (njs_slow_path(!njs_is_primitive(value2))) {
hint = (op == NJS_VMCODE_ADDITION) && njs_is_date(value2);
ret = njs_value_to_primitive(vm, &primitive2, value2, hint);
if (ret != NJS_OK) {
goto error;
}
value2 = &primitive2;
}
if (njs_slow_path(njs_is_symbol(value1)
|| njs_is_symbol(value2)))
{
njs_symbol_conversion_failed(vm,
(op == NJS_VMCODE_ADDITION) &&
(njs_is_string(value1) || njs_is_string(value2)));
goto error;
}
njs_vmcode_operand(vm, vmcode->operand1, retval);
if (op == NJS_VMCODE_ADDITION) {
if (njs_fast_path(njs_is_numeric(value1)
&& njs_is_numeric(value2)))
{
njs_set_number(retval, njs_number(value1)
+ njs_number(value2));
pc += sizeof(njs_vmcode_3addr_t);
goto next;
}
if (njs_is_string(value1)) {
s1 = value1;
s2 = &dst;
src = value2;
} else {
s1 = &dst;
s2 = value2;
src = value1;
}
ret = njs_primitive_value_to_string(vm, &dst, src);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
ret = njs_string_concat(vm, s1, s2);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
*retval = vm->retval;
pc += ret;
goto next;
}
if ((uint8_t) (op - NJS_VMCODE_GREATER) < 2) {
/* NJS_VMCODE_GREATER, NJS_VMCODE_LESS_OR_EQUAL */
src = value1;
value1 = value2;
value2 = src;
}
ret = njs_primitive_values_compare(vm, value1, value2);
if (op < NJS_VMCODE_LESS_OR_EQUAL) {
ret = ret > 0;
} else {
ret = ret == 0;
}
njs_set_boolean(retval, ret);
pc += sizeof(njs_vmcode_3addr_t);
goto next;
case NJS_VMCODE_EQUAL:
case NJS_VMCODE_NOT_EQUAL:
ret = njs_values_equal(vm, value1, value2);
if (njs_slow_path(ret < 0)) {
goto error;
}
ret ^= op - NJS_VMCODE_EQUAL;
njs_vmcode_operand(vm, vmcode->operand1, retval);
njs_set_boolean(retval, ret);
pc += sizeof(njs_vmcode_3addr_t);
goto next;
case NJS_VMCODE_SUBSTRACTION:
case NJS_VMCODE_MULTIPLICATION:
case NJS_VMCODE_EXPONENTIATION:
case NJS_VMCODE_DIVISION:
case NJS_VMCODE_REMAINDER:
case NJS_VMCODE_BITWISE_AND:
case NJS_VMCODE_BITWISE_OR:
case NJS_VMCODE_BITWISE_XOR:
case NJS_VMCODE_LEFT_SHIFT:
case NJS_VMCODE_RIGHT_SHIFT:
case NJS_VMCODE_UNSIGNED_RIGHT_SHIFT:
if (njs_slow_path(!njs_is_numeric(value1))) {
ret = njs_value_to_numeric(vm, value1, &numeric1);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
value1 = &numeric1;
}
if (njs_slow_path(!njs_is_numeric(value2))) {
ret = njs_value_to_numeric(vm, value2, &numeric2);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
value2 = &numeric2;
}
num = njs_number(value1);
njs_vmcode_operand(vm, vmcode->operand1, retval);
pc += sizeof(njs_vmcode_3addr_t);
switch (op) {
case NJS_VMCODE_SUBSTRACTION:
num -= njs_number(value2);
break;
case NJS_VMCODE_MULTIPLICATION:
num *= njs_number(value2);
break;
case NJS_VMCODE_EXPONENTIATION:
exponent = njs_number(value2);
/*
* According to ES7:
* 1. If exponent is NaN, the result should be NaN;
* 2. The result of +/-1 ** +/-Infinity should be NaN.
*/
valid = njs_expect(1, fabs(num) != 1
|| (!isnan(exponent)
&& !isinf(exponent)));
num = valid ? pow(num, exponent) : NAN;
break;
case NJS_VMCODE_DIVISION:
num /= njs_number(value2);
break;
case NJS_VMCODE_REMAINDER:
num = fmod(num, njs_number(value2));
break;
case NJS_VMCODE_BITWISE_AND:
case NJS_VMCODE_BITWISE_OR:
case NJS_VMCODE_BITWISE_XOR:
i32 = njs_number_to_int32(njs_number(value2));
switch (op) {
case NJS_VMCODE_BITWISE_AND:
i32 &= njs_number_to_int32(num);
break;
case NJS_VMCODE_BITWISE_OR:
i32 |= njs_number_to_int32(num);
break;
case NJS_VMCODE_BITWISE_XOR:
i32 ^= njs_number_to_int32(num);
break;
}
njs_set_int32(retval, i32);
goto next;
default:
u32 = njs_number_to_uint32(njs_number(value2)) & 0x1f;
switch (op) {
case NJS_VMCODE_LEFT_SHIFT:
case NJS_VMCODE_RIGHT_SHIFT:
i32 = njs_number_to_int32(num);
if (op == NJS_VMCODE_LEFT_SHIFT) {
/* Shifting of negative numbers is undefined. */
i32 = (uint32_t) i32 << u32;
} else {
i32 >>= u32;
}
njs_set_int32(retval, i32);
break;
default: /* NJS_VMCODE_UNSIGNED_RIGHT_SHIFT */
njs_set_uint32(retval,
njs_number_to_uint32(num) >> u32);
}
goto next;
}
njs_set_number(retval, num);
goto next;
case NJS_VMCODE_OBJECT_COPY:
ret = njs_vmcode_object_copy(vm, value1, value2);
break;
case NJS_VMCODE_TEMPLATE_LITERAL:
ret = njs_vmcode_template_literal(vm, value1, value2);
break;
case NJS_VMCODE_PROPERTY_IN:
ret = njs_vmcode_property_in(vm, value1, value2);
break;
case NJS_VMCODE_PROPERTY_DELETE:
ret = njs_value_property_delete(vm, value1, value2, NULL, 1);
if (njs_fast_path(ret != NJS_ERROR)) {
vm->retval = njs_value_true;
ret = sizeof(njs_vmcode_3addr_t);
}
break;
case NJS_VMCODE_PROPERTY_FOREACH:
ret = njs_vmcode_property_foreach(vm, value1, value2, pc);
break;
case NJS_VMCODE_STRICT_EQUAL:
case NJS_VMCODE_STRICT_NOT_EQUAL:
ret = njs_values_strict_equal(value1, value2);
ret ^= op - NJS_VMCODE_STRICT_EQUAL;
njs_vmcode_operand(vm, vmcode->operand1, retval);
njs_set_boolean(retval, ret);
pc += sizeof(njs_vmcode_3addr_t);
goto next;
case NJS_VMCODE_TEST_IF_TRUE:
case NJS_VMCODE_TEST_IF_FALSE:
case NJS_VMCODE_COALESCE:
if (op == NJS_VMCODE_COALESCE) {
ret = !njs_is_null_or_undefined(value1);
} else {
ret = njs_is_true(value1);
ret ^= op - NJS_VMCODE_TEST_IF_TRUE;
}
if (ret) {
test_jump = (njs_vmcode_test_jump_t *) pc;
ret = test_jump->offset;
} else {
ret = sizeof(njs_vmcode_3addr_t);
}
njs_vmcode_operand(vm, vmcode->operand1, retval);
*retval = *value1;
pc += ret;
goto next;
case NJS_VMCODE_UNARY_PLUS:
case NJS_VMCODE_UNARY_NEGATION:
case NJS_VMCODE_BITWISE_NOT:
if (njs_slow_path(!njs_is_numeric(value1))) {
ret = njs_value_to_numeric(vm, value1, &numeric1);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
value1 = &numeric1;
}
num = njs_number(value1);
njs_vmcode_operand(vm, vmcode->operand1, retval);
switch (op) {
case NJS_VMCODE_UNARY_NEGATION:
num = -num;
/* Fall through. */
case NJS_VMCODE_UNARY_PLUS:
njs_set_number(retval, num);
break;
case NJS_VMCODE_BITWISE_NOT:
njs_set_int32(retval, ~njs_number_to_uint32(num));
}
pc += sizeof(njs_vmcode_2addr_t);
goto next;
case NJS_VMCODE_LOGICAL_NOT:
njs_vmcode_operand(vm, vmcode->operand1, retval);
njs_set_boolean(retval, !njs_is_true(value1));
pc += sizeof(njs_vmcode_2addr_t);
goto next;
case NJS_VMCODE_OBJECT:
ret = njs_vmcode_object(vm);
break;
case NJS_VMCODE_ARRAY:
ret = njs_vmcode_array(vm, pc);
break;
case NJS_VMCODE_FUNCTION:
ret = njs_vmcode_function(vm, pc);
break;
case NJS_VMCODE_REGEXP:
ret = njs_vmcode_regexp(vm, pc);
break;
case NJS_VMCODE_INSTANCE_OF:
ret = njs_vmcode_instance_of(vm, value1, value2);
break;
case NJS_VMCODE_TYPEOF:
ret = njs_vmcode_typeof(vm, value1, value2);
break;
case NJS_VMCODE_VOID:
njs_set_undefined(&vm->retval);
ret = sizeof(njs_vmcode_2addr_t);
break;
case NJS_VMCODE_DELETE:
njs_release(vm, value1);
vm->retval = njs_value_true;
ret = sizeof(njs_vmcode_2addr_t);
break;
case NJS_VMCODE_DEBUGGER:
ret = njs_vmcode_debugger(vm);
break;
default:
njs_internal_error(vm, "%d has retval", op);
goto error;
}
if (njs_slow_path(ret < 0 && ret >= NJS_PREEMPT)) {
break;
}
njs_vmcode_operand(vm, vmcode->operand1, retval);
njs_release(vm, retval);
*retval = vm->retval;
} else {
switch (op) {
case NJS_VMCODE_MOVE_ARG:
move_arg = (njs_vmcode_move_arg_t *) pc;
native = vm->top_frame;
hint = move_arg->dst;
value1 = &native->arguments_offset[hint];
njs_vmcode_operand(vm, move_arg->src, value2);
*value1 = *value2;
ret = sizeof(njs_vmcode_move_arg_t);
break;
case NJS_VMCODE_STOP:
njs_vmcode_operand(vm, (njs_index_t) value2, value2);
vm->retval = *value2;
njs_vmcode_debug(vm, pc, "EXIT STOP");
return NJS_OK;
case NJS_VMCODE_JUMP:
ret = (njs_jump_off_t) value2;
break;
case NJS_VMCODE_PROPERTY_SET:
set = (njs_vmcode_prop_set_t *) pc;
njs_vmcode_operand(vm, set->value, retval);
ret = njs_value_property_set(vm, value1, value2, retval);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
ret = sizeof(njs_vmcode_prop_set_t);
break;
case NJS_VMCODE_PROPERTY_ACCESSOR:
accessor = (njs_vmcode_prop_accessor_t *) pc;
njs_vmcode_operand(vm, accessor->value, function);
ret = njs_value_to_key(vm, &name, value2);
if (njs_slow_path(ret != NJS_OK)) {
njs_internal_error(vm, "failed conversion of type \"%s\" "
"to string while property define",
njs_type_string(value2->type));
goto error;
}
ret = njs_object_prop_define(vm, value1, &name, function,
accessor->type);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
ret = sizeof(njs_vmcode_prop_accessor_t);
break;
case NJS_VMCODE_IF_TRUE_JUMP:
case NJS_VMCODE_IF_FALSE_JUMP:
ret = njs_is_true(value1);
ret ^= op - NJS_VMCODE_IF_TRUE_JUMP;
ret = ret ? (njs_jump_off_t) value2
: (njs_jump_off_t) sizeof(njs_vmcode_cond_jump_t);
break;
case NJS_VMCODE_IF_EQUAL_JUMP:
if (njs_values_strict_equal(value1, value2)) {
equal = (njs_vmcode_equal_jump_t *) pc;
ret = equal->offset;
} else {
ret = sizeof(njs_vmcode_3addr_t);
}
break;
case NJS_VMCODE_PROPERTY_INIT:
set = (njs_vmcode_prop_set_t *) pc;
njs_vmcode_operand(vm, set->value, retval);
ret = njs_vmcode_property_init(vm, value1, value2, retval);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
break;
case NJS_VMCODE_RETURN:
njs_vmcode_operand(vm, (njs_index_t) value2, value2);
njs_vmcode_debug(vm, pc, "EXIT RETURN");
return njs_vmcode_return(vm, NULL, value2);
case NJS_VMCODE_FUNCTION_COPY:
fcopy = (njs_vmcode_function_copy_t *) pc;
ret = njs_vmcode_function_copy(vm, fcopy->function,
fcopy->retval);
break;
case NJS_VMCODE_FUNCTION_FRAME:
function_frame = (njs_vmcode_function_frame_t *) pc;
/* TODO: external object instead of void this. */
ret = njs_function_frame_create(vm, value1,
&njs_value_undefined,
(uintptr_t) value2,
function_frame->ctor);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
ret = sizeof(njs_vmcode_function_frame_t);
break;
case NJS_VMCODE_METHOD_FRAME:
method_frame = (njs_vmcode_method_frame_t *) pc;
ret = njs_value_property(vm, value1, value2, &dst);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
if (njs_slow_path(!njs_is_function(&dst))) {
ret = njs_value_to_key(vm, &dst, value2);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
njs_key_string_get(vm, &dst, &string);
njs_type_error(vm,
"(intermediate value)[\"%V\"] is not a function",
&string);
goto error;
}
ret = njs_function_frame_create(vm, &dst, value1,
method_frame->nargs,
method_frame->ctor);
if (njs_slow_path(ret != NJS_OK)) {
goto error;
}
ret = sizeof(njs_vmcode_method_frame_t);
break;
case NJS_VMCODE_FUNCTION_CALL:
vm->active_frame->native.pc = pc;
njs_vmcode_operand(vm, (njs_index_t) value2, value2);
ret = njs_function_frame_invoke(vm, value2);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
njs_vmcode_debug(vm, pc, "RESUME");
ret = sizeof(njs_vmcode_function_call_t);
break;
case NJS_VMCODE_PROPERTY_NEXT:
pnext = (njs_vmcode_prop_next_t *) pc;
retval = njs_scope_value(vm, pnext->retval);
njs_assert(njs_is_data(value2, NJS_DATA_TAG_FOREACH_NEXT));
next = njs_data(value2);
if (next->index < next->array->length) {
*retval = next->array->start[next->index++];
ret = pnext->offset;
break;
}
njs_mp_free(vm->mem_pool, next);
ret = sizeof(njs_vmcode_prop_next_t);
break;
case NJS_VMCODE_ARGUMENTS:
ret = njs_vmcode_arguments(vm, pc);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
break;
case NJS_VMCODE_PROTO_INIT:
set = (njs_vmcode_prop_set_t *) pc;
njs_vmcode_operand(vm, set->value, retval);
ret = njs_vmcode_proto_init(vm, value1, value2, retval);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
break;
case NJS_VMCODE_IMPORT:
import = (njs_vmcode_import_t *) pc;
retval = njs_scope_value(vm, import->retval);
ret = njs_vmcode_import(vm, import->module, retval);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
break;
case NJS_VMCODE_AWAIT:
await = (njs_vmcode_await_t *) pc;
njs_vmcode_debug(vm, pc, "EXIT AWAIT");
return njs_vmcode_await(vm, await, promise_cap, async_ctx);
case NJS_VMCODE_TRY_START:
ret = njs_vmcode_try_start(vm, value1, value2, pc);
if (njs_slow_path(ret == NJS_ERROR)) {
goto error;
}
break;
case NJS_VMCODE_THROW:
njs_vmcode_operand(vm, (njs_index_t) value2, value2);
vm->retval = *value2;
goto error;
case NJS_VMCODE_TRY_BREAK:
try_trampoline = (njs_vmcode_try_trampoline_t *) pc;
value1 = njs_scope_value(vm, try_trampoline->exit_value);
ret = njs_vmcode_try_break(vm, value1, value2);
break;
case NJS_VMCODE_TRY_CONTINUE:
try_trampoline = (njs_vmcode_try_trampoline_t *) pc;
value1 = njs_scope_value(vm, try_trampoline->exit_value);
ret = njs_vmcode_try_continue(vm, value1, value2);
break;
case NJS_VMCODE_TRY_END:
ret = njs_vmcode_try_end(vm, value1, value2);
break;
/*
* njs_vmcode_catch() is set on the start of a "catch" block to
* store exception and to remove a "try" block if there is no
* "finally" block or to update a catch address to the start of
* a "finally" block.
* njs_vmcode_catch() is set on the start of a "finally" block
* to store uncaught exception and to remove a "try" block.
*/
case NJS_VMCODE_CATCH:
*value1 = vm->retval;
if ((njs_jump_off_t) value2 == sizeof(njs_vmcode_catch_t)) {
ret = njs_vmcode_try_end(vm, value1, value2);
} else {
frame = (njs_frame_t *) vm->top_frame;
frame->exception.catch = pc + (njs_jump_off_t) value2;
ret = sizeof(njs_vmcode_catch_t);
}
break;
case NJS_VMCODE_FINALLY:
finally = (njs_vmcode_finally_t *) pc;
value1 = njs_scope_value(vm, finally->exit_value);
ret = njs_vmcode_finally(vm, value1, value2, pc);
switch (ret) {
case NJS_OK:
njs_vmcode_debug(vm, pc, "EXIT FINALLY");
return NJS_OK;
case NJS_ERROR:
goto error;
}
break;
case NJS_VMCODE_LET:
var = (njs_vmcode_variable_t *) pc;
value1 = njs_scope_value(vm, var->dst);
if (njs_is_valid(value1)) {
value1 = njs_mp_alloc(vm->mem_pool, sizeof(njs_value_t));
if (njs_slow_path(value1 == NULL)) {
njs_memory_error(vm);
goto error;
}
njs_scope_value_set(vm, var->dst, value1);
}
njs_set_undefined(value1);
ret = sizeof(njs_vmcode_variable_t);
break;
case NJS_VMCODE_LET_UPDATE:
var = (njs_vmcode_variable_t *) pc;
value2 = njs_scope_value(vm, var->dst);
value1 = njs_mp_alloc(vm->mem_pool, sizeof(njs_value_t));
if (njs_slow_path(value1 == NULL)) {
njs_memory_error(vm);
goto error;
}
*value1 = *value2;
njs_scope_value_set(vm, var->dst, value1);
ret = sizeof(njs_vmcode_variable_t);
break;
case NJS_VMCODE_INITIALIZATION_TEST:
var = (njs_vmcode_variable_t *) pc;
value1 = njs_scope_value(vm, var->dst);
if (njs_is_valid(value1)) {
ret = sizeof(njs_vmcode_variable_t);
break;
}
/* Fall through. */
case NJS_VMCODE_NOT_INITIALIZED:
njs_reference_error(vm, "cannot access variable "
"before initialization");
goto error;
case NJS_VMCODE_ERROR:
njs_vmcode_error(vm, pc);
goto error;
case NJS_VMCODE_ASSIGNMENT_ERROR:
njs_type_error(vm, "assignment to constant variable");
goto error;
default:
njs_internal_error(vm, "%d has NO retval", op);
goto error;
}
}
pc += ret;
}
error:
if (njs_is_error(&vm->retval)) {
vm->active_frame->native.pc = pc;
(void) njs_error_stack_attach(vm, &vm->retval);
}
for ( ;; ) {
native = vm->top_frame;
if (!native->native) {
frame = (njs_frame_t *) native;
catch = frame->exception.catch;
if (catch != NULL) {
pc = catch;
goto next;
}
}
previous = native->previous;
if (previous == NULL) {
break;
}
lambda_call = (native == &vm->active_frame->native);
njs_vm_scopes_restore(vm, native, previous);
if (native->size != 0) {
vm->stack_size -= native->size;
njs_mp_free(vm->mem_pool, native);
}
if (lambda_call) {
break;
}
}
njs_vmcode_debug(vm, pc, "EXIT ERROR");
return NJS_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fixed njs_vmcode_interpreter() when await fails.
Previously, while interpreting a user function, njs_vmcode_interpreter()
might return prematurely when an error happens in await instruction.
This is not correct because the current frame has to be unwound (or
exception caught) first.
The fix is to exit through only 5 appropriate exit points to ensure
proper unwinding.
The patch correctly fixes issue reported in 07ef6c1f04f1 (0.7.3).
This closes #506 issue on Github.'</s> |
<s>[INST] Given the following code containing errors, provide 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 do_write_general()
{
if (res.body.length() < res_stream_threshold_)
{
res_body_copy_.swap(res.body);
buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
do_write();
if (need_to_start_read_after_complete_)
{
need_to_start_read_after_complete_ = false;
start_deadline();
do_read();
}
}
else
{
is_writing = true;
asio::write(adaptor_.socket(), buffers_); // Write the response start / headers
cancel_deadline_timer();
if (res.body.length() > 0)
{
std::string buf;
std::vector<asio::const_buffer> buffers;
while (res.body.length() > 16384)
{
//buf.reserve(16385);
buf = res.body.substr(0, 16384);
res.body = res.body.substr(16384);
buffers.clear();
buffers.push_back(asio::buffer(buf));
do_write_sync(buffers);
}
// Collect whatever is left (less than 16KB) and send it down the socket
// buf.reserve(is.length());
buf = res.body;
res.body.clear();
buffers.clear();
buffers.push_back(asio::buffer(buf));
do_write_sync(buffers);
}
is_writing = false;
if (close_connection_)
{
adaptor_.shutdown_readwrite();
adaptor_.close();
CROW_LOG_DEBUG << this << " from write (res_stream)";
check_destroy();
}
res.end();
res.clear();
buffers_.clear();
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Prevent HTTP pipelining which Crow doesn't support.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: s32 gf_media_avc_read_sps(const char *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)
{
AVC_SPS *sps;
u32 ChromaArrayType = 0;
s32 mb_width, mb_height, sps_id = -1;
u32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl=0, cr=0, ct=0, cb=0, luma_bd, chroma_bd;
u8 separate_colour_plane_flag = 0;
GF_BitStream *bs;
char *sps_data_without_emulation_bytes = NULL;
u32 sps_data_without_emulation_bytes_size = 0;
/*SPS still contains emulation bytes*/
sps_data_without_emulation_bytes = gf_malloc(sps_size*sizeof(char));
sps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);
bs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
sps_id = -1;
goto exit;
}
if (vui_flag_pos) *vui_flag_pos = 0;
/*nal hdr*/ gf_bs_read_int(bs, 8);
profile_idc = gf_bs_read_int(bs, 8);
pcomp = gf_bs_read_int(bs, 8);
/*sanity checks*/
if (pcomp & 0x3)
goto exit;
level_idc = gf_bs_read_int(bs, 8);
/*SubsetSps is used to be sure that AVC SPS are not going to be scratched
by subset SPS. According to the SVC standard, subset SPS can have the same sps_id
than its base layer, but it does not refer to the same SPS. */
sps_id = bs_get_ue(bs) + GF_SVC_SSPS_ID_SHIFT * subseq_sps;
if (sps_id >=32) {
sps_id = -1;
goto exit;
}
if (sps_id < 0) {
sps_id = -1;
goto exit;
}
luma_bd = chroma_bd = 0;
chroma_format_idc = ChromaArrayType = 1;
sps = &avc->sps[sps_id];
sps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;
/*High Profile and SVC*/
switch (profile_idc) {
case 100:
case 110:
case 122:
case 244:
case 44:
/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/
if (pcomp & 0xE0)
goto exit;
case 83:
case 86:
case 118:
case 128:
chroma_format_idc = bs_get_ue(bs);
ChromaArrayType = chroma_format_idc;
if (chroma_format_idc == 3) {
separate_colour_plane_flag = gf_bs_read_int(bs, 1);
/*
Depending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.
\96 If separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.
\96 Otherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.
*/
if (separate_colour_plane_flag) ChromaArrayType = 0;
}
luma_bd = bs_get_ue(bs);
chroma_bd = bs_get_ue(bs);
/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int(bs, 1);
/*seq_scaling_matrix_present_flag*/
if (gf_bs_read_int(bs, 1)) {
u32 k;
for (k=0; k<8; k++) {
if (gf_bs_read_int(bs, 1)) {
u32 z, last = 8, next = 8;
u32 sl = k<6 ? 16 : 64;
for (z=0; z<sl; z++) {
if (next) {
s32 delta = bs_get_se(bs);
next = (last + delta + 256) % 256;
}
last = next ? next : last;
}
}
}
}
break;
}
sps->profile_idc = profile_idc;
sps->level_idc = level_idc;
sps->prof_compat = pcomp;
sps->log2_max_frame_num = bs_get_ue(bs) + 4;
sps->poc_type = bs_get_ue(bs);
sps->chroma_format = chroma_format_idc;
sps->luma_bit_depth_m8 = luma_bd;
sps->chroma_bit_depth_m8 = chroma_bd;
if (sps->poc_type == 0) {
sps->log2_max_poc_lsb = bs_get_ue(bs) + 4;
} else if(sps->poc_type == 1) {
sps->delta_pic_order_always_zero_flag = gf_bs_read_int(bs, 1);
sps->offset_for_non_ref_pic = bs_get_se(bs);
sps->offset_for_top_to_bottom_field = bs_get_se(bs);
sps->poc_cycle_length = bs_get_ue(bs);
for(i=0; i<sps->poc_cycle_length; i++) sps->offset_for_ref_frame[i] = bs_get_se(bs);
}
if (sps->poc_type > 2) {
sps_id = -1;
goto exit;
}
sps->max_num_ref_frames = bs_get_ue(bs);
sps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int(bs, 1);
mb_width = bs_get_ue(bs) + 1;
mb_height= bs_get_ue(bs) + 1;
sps->frame_mbs_only_flag = gf_bs_read_int(bs, 1);
sps->width = mb_width * 16;
sps->height = (2-sps->frame_mbs_only_flag) * mb_height * 16;
if (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1); /*direct_8x8_inference_flag*/
if (gf_bs_read_int(bs, 1)) { /*crop*/
int CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;
if (chroma_format_idc == 1) {
SubWidthC = 2, SubHeightC = 2;
} else if (chroma_format_idc == 2) {
SubWidthC = 2, SubHeightC = 1;
} else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {
SubWidthC = 1, SubHeightC = 1;
}
if (ChromaArrayType == 0) {
assert(SubWidthC==-1);
CropUnitX = 1;
CropUnitY = 2-sps->frame_mbs_only_flag;
} else {
CropUnitX = SubWidthC;
CropUnitY = SubHeightC * (2-sps->frame_mbs_only_flag);
}
cl = bs_get_ue(bs); /*crop_left*/
cr = bs_get_ue(bs); /*crop_right*/
ct = bs_get_ue(bs); /*crop_top*/
cb = bs_get_ue(bs); /*crop_bottom*/
sps->width -= CropUnitX * (cl + cr);
sps->height -= CropUnitY * (ct + cb);
cl *= CropUnitX;
cr *= CropUnitX;
ct *= CropUnitY;
cb *= CropUnitY;
}
sps->crop.left = cl;
sps->crop.right = cr;
sps->crop.top = ct;
sps->crop.bottom = cb;
if (vui_flag_pos) {
*vui_flag_pos = (u32) gf_bs_get_bit_offset(bs);
}
/*vui_parameters_present_flag*/
sps->vui_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui_parameters_present_flag) {
sps->vui.aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.aspect_ratio_info_present_flag) {
s32 aspect_ratio_idc = gf_bs_read_int(bs, 8);
if (aspect_ratio_idc == 255) {
sps->vui.par_num = gf_bs_read_int(bs, 16); /*AR num*/
sps->vui.par_den = gf_bs_read_int(bs, 16); /*AR den*/
} else if (aspect_ratio_idc<14) {
sps->vui.par_num = avc_sar[aspect_ratio_idc].w;
sps->vui.par_den = avc_sar[aspect_ratio_idc].h;
}
}
sps->vui.overscan_info_present_flag = gf_bs_read_int(bs, 1);
if(sps->vui.overscan_info_present_flag)
gf_bs_read_int(bs, 1); /* overscan_appropriate_flag */
/* default values */
sps->vui.video_format = 5;
sps->vui.colour_primaries = 2;
sps->vui.transfer_characteristics = 2;
sps->vui.matrix_coefficients = 2;
/* now read values if possible */
sps->vui.video_signal_type_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.video_signal_type_present_flag) {
sps->vui.video_format = gf_bs_read_int(bs, 3);
sps->vui.video_full_range_flag = gf_bs_read_int(bs, 1);
sps->vui.colour_description_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.colour_description_present_flag) {
sps->vui.colour_primaries = gf_bs_read_int(bs, 8);
sps->vui.transfer_characteristics = gf_bs_read_int(bs, 8);
sps->vui.matrix_coefficients = gf_bs_read_int(bs, 8);
}
}
if (gf_bs_read_int(bs, 1)) { /* chroma_location_info_present_flag */
bs_get_ue(bs); /* chroma_sample_location_type_top_field */
bs_get_ue(bs); /* chroma_sample_location_type_bottom_field */
}
sps->vui.timing_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.timing_info_present_flag) {
sps->vui.num_units_in_tick = gf_bs_read_int(bs, 32);
sps->vui.time_scale = gf_bs_read_int(bs, 32);
sps->vui.fixed_frame_rate_flag = gf_bs_read_int(bs, 1);
}
sps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.nal_hrd_parameters_present_flag)
avc_parse_hrd_parameters(bs, &sps->vui.hrd);
sps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.vcl_hrd_parameters_present_flag)
avc_parse_hrd_parameters(bs, &sps->vui.hrd);
if (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)
sps->vui.low_delay_hrd_flag = gf_bs_read_int(bs, 1);
sps->vui.pic_struct_present_flag = gf_bs_read_int(bs, 1);
}
/*end of seq_parameter_set_data*/
if (subseq_sps) {
if ((profile_idc==83) || (profile_idc==86)) {
u8 extended_spatial_scalability_idc;
/*parsing seq_parameter_set_svc_extension*/
/*inter_layer_deblocking_filter_control_present_flag=*/ gf_bs_read_int(bs, 1);
extended_spatial_scalability_idc = gf_bs_read_int(bs, 2);
if (ChromaArrayType == 1 || ChromaArrayType == 2) {
/*chroma_phase_x_plus1_flag*/ gf_bs_read_int(bs, 1);
}
if( ChromaArrayType == 1 ) {
/*chroma_phase_y_plus1*/ gf_bs_read_int(bs, 2);
}
if (extended_spatial_scalability_idc == 1) {
if( ChromaArrayType > 0 ) {
/*seq_ref_layer_chroma_phase_x_plus1_flag*/gf_bs_read_int(bs, 1);
/*seq_ref_layer_chroma_phase_y_plus1*/gf_bs_read_int(bs, 2);
}
/*seq_scaled_ref_layer_left_offset*/ bs_get_se(bs);
/*seq_scaled_ref_layer_top_offset*/bs_get_se(bs);
/*seq_scaled_ref_layer_right_offset*/bs_get_se(bs);
/*seq_scaled_ref_layer_bottom_offset*/bs_get_se(bs);
}
if (/*seq_tcoeff_level_prediction_flag*/gf_bs_read_int(bs, 1)) {
/*adaptive_tcoeff_level_prediction_flag*/ gf_bs_read_int(bs, 1);
}
/*slice_header_restriction_flag*/gf_bs_read_int(bs, 1);
/*svc_vui_parameters_present*/
if (gf_bs_read_int(bs, 1)) {
u32 i, vui_ext_num_entries_minus1;
vui_ext_num_entries_minus1 = bs_get_ue(bs);
for (i=0; i <= vui_ext_num_entries_minus1; i++) {
u8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;
/*u8 vui_ext_dependency_id =*/ gf_bs_read_int(bs, 3);
/*u8 vui_ext_quality_id =*/ gf_bs_read_int(bs, 4);
/*u8 vui_ext_temporal_id =*/ gf_bs_read_int(bs, 3);
vui_ext_timing_info_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_timing_info_present_flag) {
/*u32 vui_ext_num_units_in_tick = */gf_bs_read_int(bs, 32);
/*u32 vui_ext_time_scale = */gf_bs_read_int(bs, 32);
/*u8 vui_ext_fixed_frame_rate_flag = */gf_bs_read_int(bs, 1);
}
vui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_nal_hrd_parameters_present_flag) {
//hrd_parameters( )
}
vui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_vcl_hrd_parameters_present_flag) {
//hrd_parameters( )
}
if ( vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {
/*vui_ext_low_delay_hrd_flag*/gf_bs_read_int(bs, 1);
}
/*vui_ext_pic_struct_present_flag*/gf_bs_read_int(bs, 1);
}
}
}
else if ((profile_idc==118) || (profile_idc==128)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] MVC not supported - skipping parsing end of Subset SPS\n"));
goto exit;
}
if (gf_bs_read_int(bs, 1)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\n"));
goto exit;
}
}
exit:
gf_bs_del(bs);
gf_free(sps_data_without_emulation_bytes);
return sps_id;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fix some exploitable overflows (#994, #997)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: grub_ext2_iterate_dir (grub_fshelp_node_t dir,
int (*hook) (const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node,
void *closure),
void *closure)
{
unsigned int fpos = 0;
struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir;
if (! diro->inode_read)
{
grub_ext2_read_inode (diro->data, diro->ino, &diro->inode);
if (grub_errno)
return 0;
}
/* Search the file. */
if (hook)
while (fpos < grub_le_to_cpu32 (diro->inode.size))
{
struct ext2_dirent dirent;
grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent),
(char *) &dirent);
if (grub_errno)
return 0;
if (dirent.direntlen == 0)
return 0;
if (dirent.namelen != 0)
{
#ifndef _MSC_VER
char filename[dirent.namelen + 1];
#else
char * filename = grub_malloc (dirent.namelen + 1);
#endif
struct grub_fshelp_node *fdiro;
enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN;
grub_ext2_read_file (diro, 0, 0, 0,
fpos + sizeof (struct ext2_dirent),
dirent.namelen, filename);
if (grub_errno)
return 0;
fdiro = grub_malloc (sizeof (struct grub_fshelp_node));
if (! fdiro)
return 0;
fdiro->data = diro->data;
fdiro->ino = grub_le_to_cpu32 (dirent.inode);
filename[dirent.namelen] = '\0';
if (dirent.filetype != FILETYPE_UNKNOWN)
{
fdiro->inode_read = 0;
if (dirent.filetype == FILETYPE_DIRECTORY)
type = GRUB_FSHELP_DIR;
else if (dirent.filetype == FILETYPE_SYMLINK)
type = GRUB_FSHELP_SYMLINK;
else if (dirent.filetype == FILETYPE_REG)
type = GRUB_FSHELP_REG;
}
else
{
/* The filetype can not be read from the dirent, read
the inode to get more information. */
grub_ext2_read_inode (diro->data,
grub_le_to_cpu32 (dirent.inode),
&fdiro->inode);
if (grub_errno)
{
grub_free (fdiro);
return 0;
}
fdiro->inode_read = 1;
if ((grub_le_to_cpu16 (fdiro->inode.mode)
& FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY)
type = GRUB_FSHELP_DIR;
else if ((grub_le_to_cpu16 (fdiro->inode.mode)
& FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK)
type = GRUB_FSHELP_SYMLINK;
else if ((grub_le_to_cpu16 (fdiro->inode.mode)
& FILETYPE_INO_MASK) == FILETYPE_INO_REG)
type = GRUB_FSHELP_REG;
}
if (hook (filename, type, fdiro, closure))
return 1;
}
fpos += grub_le_to_cpu16 (dirent.direntlen);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Fix ext2 buffer overflow in r2_sbu_grub_memmove'</s> |
<s>[INST] Given the following code containing errors, provide 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 addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {
struct addr_t *entry;
int i;
if (!bin->entry && !bin->sects) {
return NULL;
}
if (!(entry = calloc (1, sizeof (struct addr_t)))) {
return NULL;
}
if (bin->entry) {
entry->addr = entry_to_vaddr (bin);
entry->offset = addr_to_offset (bin, entry->addr);
entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0);
}
if (!bin->entry || entry->offset == 0) {
// XXX: section name doesnt matters at all.. just check for exec flags
for (i = 0; i < bin->nsects; i++) {
if (!strncmp (bin->sects[i].sectname, "__text", 6)) {
entry->offset = (ut64)bin->sects[i].offset;
sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0);
entry->addr = (ut64)bin->sects[i].addr;
if (!entry->addr) { // workaround for object files
entry->addr = entry->offset;
}
break;
}
}
bin->entry = entry->addr;
}
return entry;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Fix null deref and uaf in mach0 parser'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gql_eval_sels(agooErr err, gqlDoc doc, gqlRef ref, gqlField field, gqlSel sels, gqlValue result, int depth) {
gqlSel sel;
gqlField sf = NULL;
// TBD if depth over max then return an error
for (sel = sels; NULL != sel; sel = sel->next) {
if (NULL != field) {
if (NULL == sel->name) {
sf = field;
} else {
sf = gql_type_get_field(field->type, sel->name);
}
} else {
sf = NULL;
}
if (NULL != sel->inline_frag) {
if (frag_include(doc, sel->inline_frag, ref)) {
if (AGOO_ERR_OK != gql_eval_sels(err, doc, ref, sf, sel->inline_frag->sels, result, depth)) {
return err->code;
}
}
} else if (NULL != sel->frag) {
gqlFrag frag;
for (frag = doc->frags; NULL != frag; frag = frag->next) {
if (NULL != frag->name && 0 == strcmp(frag->name, sel->frag)) {
if (frag_include(doc, frag, ref)) {
if (AGOO_ERR_OK != gql_eval_sels(err, doc, ref, sf, frag->sels, result, depth)) {
return err->code;
}
}
}
}
} else {
if (AGOO_ERR_OK != doc->funcs.resolve(err, doc, ref, sf, sel, result, depth)) {
return err->code;
}
}
}
return AGOO_ERR_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'Protect against recursive fragment in schema
Really a error on the developers part but this catches the error.'</s> |
<s>[INST] Given the following code containing errors, provide 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 sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sco_pinfo *pi = sco_pi(sk);
lock_sock(sk);
if (sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {
hci_conn_accept(pi->conn->hcon, 0);
sk->sk_state = BT_CONFIG;
release_sock(sk);
return 0;
}
release_sock(sk);
return bt_sock_recvmsg(iocb, sock, msg, len, flags);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Bluetooth: SCO - Fix missing msg_namelen update in sco_sock_recvmsg()
If the socket is in state BT_CONNECT2 and BT_SK_DEFER_SETUP is set in
the flags, sco_sock_recvmsg() returns early with 0 without updating the
possibly set msg_namelen member. This, in turn, leads to a 128 byte
kernel stack leak in net/socket.c.
Fix this by updating msg_namelen in this case. For all other cases it
will be handled in bt_sock_recvmsg().
Cc: Marcel Holtmann <marcel@holtmann.org>
Cc: Gustavo Padovan <gustavo@padovan.org>
Cc: Johan Hedberg <johan.hedberg@gmail.com>
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int oe_iov_sync(
const struct oe_iovec* iov,
int iovcnt,
const void* buf_,
size_t buf_size)
{
struct oe_iovec* buf = (struct oe_iovec*)buf_;
int ret = -1;
int i;
size_t n;
/* Reject invalid parameters. */
if (iovcnt < 0 || (iovcnt > 0 && !iov))
goto done;
/* Synchronize the data. */
for (i = 0, n = buf_size; i < iovcnt; i++)
{
if (buf[i].iov_len != iov[i].iov_len)
goto done;
if (buf[i].iov_len)
{
if (buf[i].iov_base && !iov[i].iov_base)
goto done;
if (!buf[i].iov_base && iov[i].iov_base)
goto done;
if (!buf[i].iov_base)
continue;
/* Fail if buffer data is exhausted. */
if (n < buf[i].iov_len)
goto done;
/* Sync the base data for this element. */
{
/* Note: buf[i].iov_base is an offset here (not a pointer). */
uint8_t* src = (uint8_t*)buf[i].iov_base + (uint64_t)buf;
size_t src_size = buf[i].iov_len;
uint8_t* dest = (uint8_t*)iov[i].iov_base;
size_t dest_size = iov[i].iov_len;
if (src_size != dest_size)
goto done;
if (src < (uint8_t*)buf || src > (uint8_t*)buf + buf_size)
goto done;
if (oe_memcpy_s(dest, dest_size, src, src_size) != OE_OK)
goto done;
}
}
n -= buf[i].iov_len;
}
ret = 0;
done:
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m
Signed-off-by: Ming-Wei Shih <mishih@microsoft.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 ssize_t _hostfs_pwrite(
oe_fd_t* desc,
const void* buf,
size_t count,
oe_off_t offset)
{
ssize_t ret = -1;
file_t* file = _cast_file(desc);
if (!file)
OE_RAISE_ERRNO(OE_EINVAL);
if (oe_syscall_pwrite_ocall(&ret, file->host_fd, buf, count, offset) !=
OE_OK)
OE_RAISE_ERRNO(OE_EINVAL);
done:
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m
Signed-off-by: Ming-Wei Shih <mishih@microsoft.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 ssize_t _hostsock_send(
oe_fd_t* sock_,
const void* buf,
size_t count,
int flags)
{
ssize_t ret = -1;
sock_t* sock = _cast_sock(sock_);
oe_errno = 0;
if (!sock || (count && !buf))
OE_RAISE_ERRNO(OE_EINVAL);
if (oe_syscall_send_ocall(&ret, sock->host_fd, buf, count, flags) != OE_OK)
OE_RAISE_ERRNO(OE_EINVAL);
done:
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m
Signed-off-by: Ming-Wei Shih <mishih@microsoft.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: int main(int argc, char **argv) {
int result;
int error = FALSE;
int display_license = FALSE;
int display_help = FALSE;
int c = 0;
struct tm *tm, tm_s;
time_t now;
char datestring[256];
nagios_macros *mac;
const char *worker_socket = NULL;
int i;
#ifdef HAVE_SIGACTION
struct sigaction sig_action;
#endif
#ifdef HAVE_GETOPT_H
int option_index = 0;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"license", no_argument, 0, 'V'},
{"verify-config", no_argument, 0, 'v'},
{"daemon", no_argument, 0, 'd'},
{"test-scheduling", no_argument, 0, 's'},
{"precache-objects", no_argument, 0, 'p'},
{"use-precached-objects", no_argument, 0, 'u'},
{"enable-timing-point", no_argument, 0, 'T'},
{"worker", required_argument, 0, 'W'},
{0, 0, 0, 0}
};
#define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index)
#endif
memset(&loadctl, 0, sizeof(loadctl));
mac = get_global_macros();
/* make sure we have the correct number of command line arguments */
if(argc < 2)
error = TRUE;
/* get all command line arguments */
while(1) {
c = getopt(argc, argv, "+hVvdspuxTW");
if(c == -1 || c == EOF)
break;
switch(c) {
case '?': /* usage */
case 'h':
display_help = TRUE;
break;
case 'V': /* version */
display_license = TRUE;
break;
case 'v': /* verify */
verify_config++;
break;
case 's': /* scheduling check */
test_scheduling = TRUE;
break;
case 'd': /* daemon mode */
daemon_mode = TRUE;
break;
case 'p': /* precache object config */
precache_objects = TRUE;
break;
case 'u': /* use precached object config */
use_precached_objects = TRUE;
break;
case 'T':
enable_timing_point = TRUE;
break;
case 'W':
worker_socket = optarg;
break;
case 'x':
printf("Warning: -x is deprecated and will be removed\n");
break;
default:
break;
}
}
#ifdef DEBUG_MEMORY
mtrace();
#endif
/* if we're a worker we can skip everything below */
if(worker_socket) {
exit(nagios_core_worker(worker_socket));
}
/* Initialize configuration variables */
init_main_cfg_vars(1);
init_shared_cfg_vars(1);
if(daemon_mode == FALSE) {
printf("\nNagios Core %s\n", PROGRAM_VERSION);
printf("Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\n");
printf("Copyright (c) 1999-2009 Ethan Galstad\n");
printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE);
printf("License: GPL\n\n");
printf("Website: https://www.nagios.org\n");
}
/* just display the license */
if(display_license == TRUE) {
printf("This program is free software; you can redistribute it and/or modify\n");
printf("it under the terms of the GNU General Public License version 2 as\n");
printf("published by the Free Software Foundation.\n\n");
printf("This program is distributed in the hope that it will be useful,\n");
printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
printf("GNU General Public License for more details.\n\n");
printf("You should have received a copy of the GNU General Public License\n");
printf("along with this program; if not, write to the Free Software\n");
printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
exit(OK);
}
/* make sure we got the main config file on the command line... */
if(optind >= argc)
error = TRUE;
/* if there are no command line options (or if we encountered an error), print usage */
if(error == TRUE || display_help == TRUE) {
printf("Usage: %s [options] <main_config_file>\n", argv[0]);
printf("\n");
printf("Options:\n");
printf("\n");
printf(" -v, --verify-config Verify all configuration data (-v -v for more info)\n");
printf(" -s, --test-scheduling Shows projected/recommended check scheduling and other\n");
printf(" diagnostic info based on the current configuration files.\n");
printf(" -T, --enable-timing-point Enable timed commentary on initialization\n");
printf(" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\n");
printf(" -p, --precache-objects Precache object configuration\n");
printf(" -u, --use-precached-objects Use precached object config file\n");
printf(" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\n");
printf(" -W, --worker /path/to/socket Act as a worker for an already running daemon\n");
printf("\n");
printf("Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\n");
printf("releases, online documentation, FAQs, information on subscribing to\n");
printf("the mailing lists, and commercial support options for Nagios.\n");
printf("\n");
exit(ERROR);
}
/*
* config file is last argument specified.
* Make sure it uses an absolute path
*/
config_file = nspath_absolute(argv[optind], NULL);
if(config_file == NULL) {
printf("Error allocating memory.\n");
exit(ERROR);
}
config_file_dir = nspath_absolute_dirname(config_file, NULL);
/*
* Set the signal handler for the SIGXFSZ signal here because
* we may encounter this signal before the other signal handlers
* are set.
*/
#ifdef HAVE_SIGACTION
sig_action.sa_sigaction = NULL;
sig_action.sa_handler = handle_sigxfsz;
sigfillset(&sig_action.sa_mask);
sig_action.sa_flags = SA_NODEFER|SA_RESTART;
sigaction(SIGXFSZ, &sig_action, NULL);
#else
signal(SIGXFSZ, handle_sigxfsz);
#endif
/*
* let's go to town. We'll be noisy if we're verifying config
* or running scheduling tests.
*/
if(verify_config || test_scheduling || precache_objects) {
reset_variables();
/*
* if we don't beef up our resource limits as much as
* we can, it's quite possible we'll run headlong into
* EAGAIN due to too many processes when we try to
* drop privileges later.
*/
set_loadctl_defaults();
if(verify_config)
printf("Reading configuration data...\n");
/* read our config file */
result = read_main_config_file(config_file);
if(result != OK) {
printf(" Error processing main config file!\n\n");
exit(EXIT_FAILURE);
}
if(verify_config)
printf(" Read main config file okay...\n");
/* drop privileges */
if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) {
printf(" Failed to drop privileges. Aborting.");
exit(EXIT_FAILURE);
}
/*
* this must come after dropping privileges, so we make
* sure to test access permissions as the right user.
*/
if (!verify_config && test_configured_paths() == ERROR) {
printf(" One or more path problems detected. Aborting.\n");
exit(EXIT_FAILURE);
}
/* read object config files */
result = read_all_object_data(config_file);
if(result != OK) {
printf(" Error processing object config files!\n\n");
/* if the config filename looks fishy, warn the user */
if(!strstr(config_file, "nagios.cfg")) {
printf("\n***> The name of the main configuration file looks suspicious...\n");
printf("\n");
printf(" Make sure you are specifying the name of the MAIN configuration file on\n");
printf(" the command line and not the name of another configuration file. The\n");
printf(" main configuration file is typically '%s'\n", DEFAULT_CONFIG_FILE);
}
printf("\n***> One or more problems was encountered while processing the config files...\n");
printf("\n");
printf(" Check your configuration file(s) to ensure that they contain valid\n");
printf(" directives and data definitions. If you are upgrading from a previous\n");
printf(" version of Nagios, you should be aware that some variables/definitions\n");
printf(" may have been removed or modified in this version. Make sure to read\n");
printf(" the HTML documentation regarding the config files, as well as the\n");
printf(" 'Whats New' section to find out what has changed.\n\n");
exit(EXIT_FAILURE);
}
if(verify_config) {
printf(" Read object config files okay...\n\n");
printf("Running pre-flight check on configuration data...\n\n");
}
/* run the pre-flight check to make sure things look okay... */
result = pre_flight_check();
if(result != OK) {
printf("\n***> One or more problems was encountered while running the pre-flight check...\n");
printf("\n");
printf(" Check your configuration file(s) to ensure that they contain valid\n");
printf(" directives and data definitions. If you are upgrading from a previous\n");
printf(" version of Nagios, you should be aware that some variables/definitions\n");
printf(" may have been removed or modified in this version. Make sure to read\n");
printf(" the HTML documentation regarding the config files, as well as the\n");
printf(" 'Whats New' section to find out what has changed.\n\n");
exit(EXIT_FAILURE);
}
if(verify_config) {
printf("\nThings look okay - No serious problems were detected during the pre-flight check\n");
}
/* scheduling tests need a bit more than config verifications */
if(test_scheduling == TRUE) {
/* we'll need the event queue here so we can time insertions */
init_event_queue();
timing_point("Done initializing event queue\n");
/* read initial service and host state information */
initialize_retention_data(config_file);
read_initial_state_information();
timing_point("Retention data and initial state parsed\n");
/* initialize the event timing loop */
init_timing_loop();
timing_point("Timing loop initialized\n");
/* display scheduling information */
display_scheduling_info();
}
if(precache_objects) {
result = fcache_objects(object_precache_file);
timing_point("Done precaching objects\n");
if(result == OK) {
printf("Object precache file created:\n%s\n", object_precache_file);
}
else {
printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno));
}
}
/* clean up after ourselves */
cleanup();
/* exit */
timing_point("Exiting\n");
/* make valgrind shut up about still reachable memory */
neb_free_module_list();
free(config_file_dir);
free(config_file);
exit(result);
}
/* else start to monitor things... */
else {
/*
* if we're called with a relative path we must make
* it absolute so we can launch our workers.
* If not, we needn't bother, as we're using execvp()
*/
if (strchr(argv[0], '/'))
nagios_binary_path = nspath_absolute(argv[0], NULL);
else
nagios_binary_path = strdup(argv[0]);
if (!nagios_binary_path) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to allocate memory for nagios_binary_path\n");
exit(EXIT_FAILURE);
}
if (!(nagios_iobs = iobroker_create())) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to create IO broker set: %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
/* keep monitoring things until we get a shutdown command */
do {
/* reset internal book-keeping (in case we're restarting) */
wproc_num_workers_spawned = wproc_num_workers_online = 0;
caught_signal = sigshutdown = FALSE;
sig_id = 0;
/* reset program variables */
reset_variables();
timing_point("Variables reset\n");
/* get PID */
nagios_pid = (int)getpid();
/* read in the configuration files (main and resource config files) */
result = read_main_config_file(config_file);
if (result != OK) {
logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to process config file '%s'. Aborting\n", config_file);
exit(EXIT_FAILURE);
}
timing_point("Main config file read\n");
/* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */
/* get program (re)start time and save as macro */
program_start = time(NULL);
my_free(mac->x[MACRO_PROCESSSTARTTIME]);
asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%llu", (unsigned long long)program_start);
/* drop privileges */
if(drop_privileges(nagios_user, nagios_group) == ERROR) {
logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges. Aborting.");
cleanup();
exit(ERROR);
}
if (test_path_access(nagios_binary_path, X_OK)) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: failed to access() %s: %s\n", nagios_binary_path, strerror(errno));
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Spawning workers will be impossible. Aborting.\n");
exit(EXIT_FAILURE);
}
if (test_configured_paths() == ERROR) {
/* error has already been logged */
exit(EXIT_FAILURE);
}
/* enter daemon mode (unless we're restarting...) */
if(daemon_mode == TRUE && sigrestart == FALSE) {
result = daemon_init();
/* we had an error daemonizing, so bail... */
if(result == ERROR) {
logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid());
cleanup();
exit(EXIT_FAILURE);
}
/* get new PID */
nagios_pid = (int)getpid();
}
/* this must be logged after we read config data, as user may have changed location of main log file */
logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid());
/* log the local time - may be different than clock time due to timezone offset */
now = time(NULL);
tm = localtime_r(&now, &tm_s);
strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm);
logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring);
/* write log version/info */
write_log_file_info(NULL);
/* open debug log now that we're the right user */
open_debug_log();
#ifdef USE_EVENT_BROKER
/* initialize modules */
neb_init_modules();
neb_init_callback_list();
#endif
timing_point("NEB module API initialized\n");
/* handle signals (interrupts) before we do any socket I/O */
setup_sighandler();
/*
* Initialize query handler and event subscription service.
* This must be done before modules are initialized, so
* the modules can use our in-core stuff properly
*/
if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to initialize query handler. Aborting\n");
exit(EXIT_FAILURE);
}
timing_point("Query handler initialized\n");
nerd_init();
timing_point("NERD initialized\n");
/* initialize check workers */
if(init_workers(num_check_workers) < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to spawn workers. Aborting\n");
exit(EXIT_FAILURE);
}
timing_point("%u workers spawned\n", wproc_num_workers_spawned);
i = 0;
while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) {
iobroker_poll(nagios_iobs, 50);
i++;
}
timing_point("%u workers connected\n", wproc_num_workers_online);
/* now that workers have arrived we can set the defaults */
set_loadctl_defaults();
#ifdef USE_EVENT_BROKER
/* load modules */
if (neb_load_all_modules() != OK) {
logit(NSLOG_CONFIG_ERROR, ERROR, "Error: Module loading failed. Aborting.\n");
/* if we're dumping core, we must remove all dl-files */
if (daemon_dumps_core)
neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN);
exit(EXIT_FAILURE);
}
timing_point("Modules loaded\n");
/* send program data to broker */
broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL);
timing_point("First callback made\n");
#endif
/* read in all object config data */
if(result == OK)
result = read_all_object_data(config_file);
/* there was a problem reading the config files */
if(result != OK)
logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid());
else {
/* run the pre-flight check to make sure everything looks okay*/
if((result = pre_flight_check()) != OK)
logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid());
}
/* an error occurred that prevented us from (re)starting */
if(result != OK) {
/* if we were restarting, we need to cleanup from the previous run */
if(sigrestart == TRUE) {
/* clean up the status data */
cleanup_status_data(TRUE);
}
#ifdef USE_EVENT_BROKER
/* send program data to broker */
broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL);
#endif
cleanup();
exit(ERROR);
}
timing_point("Object configuration parsed and understood\n");
/* write the objects.cache file */
fcache_objects(object_cache_file);
timing_point("Objects cached\n");
init_event_queue();
timing_point("Event queue initialized\n");
#ifdef USE_EVENT_BROKER
/* send program data to broker */
broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif
/* initialize status data unless we're starting */
if(sigrestart == FALSE) {
initialize_status_data(config_file);
timing_point("Status data initialized\n");
}
/* initialize scheduled downtime data */
initialize_downtime_data();
timing_point("Downtime data initialized\n");
/* read initial service and host state information */
initialize_retention_data(config_file);
timing_point("Retention data initialized\n");
read_initial_state_information();
timing_point("Initial state information read\n");
/* initialize comment data */
initialize_comment_data();
timing_point("Comment data initialized\n");
/* initialize performance data */
initialize_performance_data(config_file);
timing_point("Performance data initialized\n");
/* initialize the event timing loop */
init_timing_loop();
timing_point("Event timing loop initialized\n");
/* initialize check statistics */
init_check_stats();
timing_point("check stats initialized\n");
/* check for updates */
check_for_nagios_updates(FALSE, TRUE);
timing_point("Update check concluded\n");
/* update all status data (with retained information) */
update_all_status_data();
timing_point("Status data updated\n");
/* log initial host and service state */
log_host_states(INITIAL_STATES, NULL);
log_service_states(INITIAL_STATES, NULL);
timing_point("Initial states logged\n");
/* reset the restart flag */
sigrestart = FALSE;
/* fire up command file worker */
launch_command_file_worker();
timing_point("Command file worker launched\n");
#ifdef USE_EVENT_BROKER
/* send program data to broker */
broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif
/* get event start time and save as macro */
event_start = time(NULL);
my_free(mac->x[MACRO_EVENTSTARTTIME]);
asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%llu", (unsigned long long)event_start);
timing_point("Entering event execution loop\n");
/***** start monitoring all services *****/
/* (doesn't return until a restart or shutdown signal is encountered) */
event_execution_loop();
/*
* immediately deinitialize the query handler so it
* can remove modules that have stashed data with it
*/
qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET);
/* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */
/* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */
/* did we catch a signal? */
if(caught_signal == TRUE) {
if(sig_id == SIGHUP)
logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n");
}
#ifdef USE_EVENT_BROKER
/* send program data to broker */
broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL);
if(sigshutdown == TRUE)
broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL);
else if(sigrestart == TRUE)
broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL);
#endif
/* save service and host state information */
save_state_information(FALSE);
cleanup_retention_data();
/* clean up performance data */
cleanup_performance_data();
/* clean up the scheduled downtime data */
cleanup_downtime_data();
/* clean up the status data unless we're restarting */
if(sigrestart == FALSE) {
cleanup_status_data(TRUE);
}
free_worker_memory(WPROC_FORCE);
/* shutdown stuff... */
if(sigshutdown == TRUE) {
iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS);
nagios_iobs = NULL;
/* log a shutdown message */
logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid());
}
/* clean up after ourselves */
cleanup();
/* close debug log */
close_debug_log();
}
while(sigrestart == TRUE && sigshutdown == FALSE);
if(daemon_mode == TRUE)
unlink(lock_file);
/* free misc memory */
my_free(lock_file);
my_free(config_file);
my_free(config_file_dir);
my_free(nagios_binary_path);
}
return OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665', 'CWE-284'], 'message': 'halfway revert hack/configure changes - switch order of daemon_init/drop_privileges'</s> |
<s>[INST] Given the following code containing errors, provide 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 link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'fs: prevent page refcount overflow in pipe_buf_get
Change pipe_buf_get() to return a bool indicating whether it succeeded
in raising the refcount of the page (if the thing in the pipe is a page).
This removes another mechanism for overflowing the page refcount. All
callers converted to handle a failure.
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Matthew Wilcox <willy@infradead.org>
Cc: stable@kernel.org
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: static int vorbis_header(AVFormatContext *s, int idx)
{
struct ogg *ogg = s->priv_data;
AVStream *st = s->streams[idx];
struct ogg_stream *os = ogg->streams + idx;
struct oggvorbis_private *priv;
int pkt_type = os->buf[os->pstart];
if (!os->private) {
os->private = av_mallocz(sizeof(struct oggvorbis_private));
if (!os->private)
return AVERROR(ENOMEM);
}
if (!(pkt_type & 1))
return 0;
if (os->psize < 1 || pkt_type > 5)
return AVERROR_INVALIDDATA;
priv = os->private;
if (priv->packet[pkt_type >> 1])
return AVERROR_INVALIDDATA;
if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
return AVERROR_INVALIDDATA;
priv->len[pkt_type >> 1] = os->psize;
priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
if (!priv->packet[pkt_type >> 1])
return AVERROR(ENOMEM);
memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
if (os->buf[os->pstart] == 1) {
const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
unsigned blocksize, bs0, bs1;
int srate;
int channels;
if (os->psize != 30)
return AVERROR_INVALIDDATA;
if (bytestream_get_le32(&p) != 0) /* vorbis_version */
return AVERROR_INVALIDDATA;
channels = bytestream_get_byte(&p);
if (st->codec->channels && channels != st->codec->channels) {
av_log(s, AV_LOG_ERROR, "Channel change is not supported\n");
return AVERROR_PATCHWELCOME;
}
st->codec->channels = channels;
srate = bytestream_get_le32(&p);
p += 4; // skip maximum bitrate
st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
p += 4; // skip minimum bitrate
blocksize = bytestream_get_byte(&p);
bs0 = blocksize & 15;
bs1 = blocksize >> 4;
if (bs0 > bs1)
return AVERROR_INVALIDDATA;
if (bs0 < 6 || bs1 > 13)
return AVERROR_INVALIDDATA;
if (bytestream_get_byte(&p) != 1) /* framing_flag */
return AVERROR_INVALIDDATA;
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = AV_CODEC_ID_VORBIS;
if (srate > 0) {
st->codec->sample_rate = srate;
avpriv_set_pts_info(st, 64, 1, srate);
}
} else if (os->buf[os->pstart] == 3) {
if (vorbis_update_metadata(s, idx) >= 0) {
// drop all metadata we parsed and which is not required by libvorbis
unsigned new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
if (new_len >= 16 && new_len < os->psize) {
AV_WL32(priv->packet[1] + new_len - 5, 0);
priv->packet[1][new_len - 1] = 1;
priv->len[1] = new_len;
}
}
} else {
int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);
if (ret < 0) {
st->codec->extradata_size = 0;
return ret;
}
st->codec->extradata_size = ret;
if ((ret = avpriv_vorbis_parse_extradata(st->codec, &priv->vp))) {
av_freep(&st->codec->extradata);
st->codec->extradata_size = 0;
return ret;
}
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'avformat/oggparsevorbis: check packet size before reading new_len from it
Fixes out of array read
Fixes: 34260c7981118fb38fba61809bf4dd5a-asan_heap-oob_93b923_1508_cov_951051643_DivX640x480_oggvorbis.avi
Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s> |
<s>[INST] Given the following code containing errors, provide 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 long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct ion_client *client = filp->private_data;
struct ion_device *dev = client->dev;
struct ion_handle *cleanup_handle = NULL;
int ret = 0;
unsigned int dir;
union {
struct ion_fd_data fd;
struct ion_allocation_data allocation;
struct ion_handle_data handle;
struct ion_custom_data custom;
} data;
dir = ion_ioctl_dir(cmd);
if (_IOC_SIZE(cmd) > sizeof(data))
return -EINVAL;
if (dir & _IOC_WRITE)
if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd)))
return -EFAULT;
switch (cmd) {
case ION_IOC_ALLOC:
{
struct ion_handle *handle;
handle = ion_alloc(client, data.allocation.len,
data.allocation.align,
data.allocation.heap_id_mask,
data.allocation.flags);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.allocation.handle = handle->id;
cleanup_handle = handle;
break;
}
case ION_IOC_FREE:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
ion_free(client, handle);
ion_handle_put(handle);
break;
}
case ION_IOC_SHARE:
case ION_IOC_MAP:
{
struct ion_handle *handle;
handle = ion_handle_get_by_id(client, data.handle.handle);
if (IS_ERR(handle))
return PTR_ERR(handle);
data.fd.fd = ion_share_dma_buf_fd(client, handle);
ion_handle_put(handle);
if (data.fd.fd < 0)
ret = data.fd.fd;
break;
}
case ION_IOC_IMPORT:
{
struct ion_handle *handle;
handle = ion_import_dma_buf_fd(client, data.fd.fd);
if (IS_ERR(handle))
ret = PTR_ERR(handle);
else
data.handle.handle = handle->id;
break;
}
case ION_IOC_SYNC:
{
ret = ion_sync_for_device(client, data.fd.fd);
break;
}
case ION_IOC_CUSTOM:
{
if (!dev->custom_ioctl)
return -ENOTTY;
ret = dev->custom_ioctl(client, data.custom.cmd,
data.custom.arg);
break;
}
default:
return -ENOTTY;
}
if (dir & _IOC_READ) {
if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) {
if (cleanup_handle)
ion_free(client, cleanup_handle);
return -EFAULT;
}
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'staging/android/ion : fix a race condition in the ion driver
There is a use-after-free problem in the ion driver.
This is caused by a race condition in the ion_ioctl()
function.
A handle has ref count of 1 and two tasks on different
cpus calls ION_IOC_FREE simultaneously.
cpu 0 cpu 1
-------------------------------------------------------
ion_handle_get_by_id()
(ref == 2)
ion_handle_get_by_id()
(ref == 3)
ion_free()
(ref == 2)
ion_handle_put()
(ref == 1)
ion_free()
(ref == 0 so ion_handle_destroy() is
called
and the handle is freed.)
ion_handle_put() is called and it
decreases the slub's next free pointer
The problem is detected as an unaligned access in the
spin lock functions since it uses load exclusive
instruction. In some cases it corrupts the slub's
free pointer which causes a mis-aligned access to the
next free pointer.(kmalloc returns a pointer like
ffffc0745b4580aa). And it causes lots of other
hard-to-debug problems.
This symptom is caused since the first member in the
ion_handle structure is the reference count and the
ion driver decrements the reference after it has been
freed.
To fix this problem client->lock mutex is extended
to protect all the codes that uses the handle.
Signed-off-by: Eun Taik Lee <eun.taik.lee@samsung.com>
Reviewed-by: Laura Abbott <labbott@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.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: hash_new_from_values(mrb_state *mrb, mrb_int argc, mrb_value *regs)
{
mrb_value hash = mrb_hash_new_capa(mrb, argc);
while (argc--) {
mrb_hash_set(mrb, hash, regs[0], regs[1]);
regs += 2;
}
return hash;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'vm.c (hash_new_from_regs): stack may be reallocated.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: juniper_services_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_services_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t svc_set_id[2];
uint8_t dir_iif[4];
};
const struct juniper_services_header *sh;
l2info.pictype = DLT_JUNIPER_SERVICES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
sh = (const struct juniper_services_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ",
sh->svc_id,
sh->flags_len,
EXTRACT_16BITS(&sh->svc_set_id),
EXTRACT_24BITS(&sh->dir_iif[1])));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const TensorShape& input_shape = input.shape();
const int32_t input_dims = input_shape.dims();
const Tensor& segment_id = context->input(1);
const TensorShape& segment_id_shape = segment_id.shape();
const int32_t segment_dims = segment_id_shape.dims();
const Tensor& num_segments_tensor = context->input(2);
OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,
errors::InvalidArgument("Number of segments cannot be empty."));
auto num_segments = num_segments_tensor.scalar<NUM_SEGMENTS_TYPE>()();
OP_REQUIRES(context, segment_dims != 0,
errors::InvalidArgument("Segment_id cannot have rank 0"));
OP_REQUIRES(
context, segment_dims <= input_dims,
errors::OutOfRange("Invalid segment_id rank ", segment_dims,
" for input with ", input_dims, " dimension(s)"));
for (auto i = 0; i < segment_dims; i++) {
OP_REQUIRES(
context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),
errors::InvalidArgument(
"Segment dimension is ", segment_id_shape.dim_size(i),
" while input dimension is ", input_dims, " in rank ", i));
}
// Making output tensor.
Tensor* output_tensor = nullptr;
TensorShape output_shape =
GetOutputShape(input_shape, segment_id_shape, num_segments);
OP_REQUIRES_OK(context, context->allocate_output("output", output_shape,
&output_tensor));
// Preparating flat tensors.
auto output_flat = output_tensor->flat<tstring>();
auto flat_segment_id = segment_id.flat<INDICES_TYPE>();
auto flat_input = input.flat<tstring>();
for (int i = 0; i < flat_segment_id.size(); i++) {
OP_REQUIRES(
context,
((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),
errors::InvalidArgument(
"segment_ids are not allowed to exceed num_segments or"
" to have negative values."));
}
int64_t big_stride;
int64_t small_stride;
std::tie(big_stride, small_stride) =
GetStrides<INDICES_TYPE>(input_shape, segment_id_shape);
auto relative_offset_set =
GetFlattenedRelativeOffsets<INDICES_TYPE>(small_stride, big_stride);
for (auto start_offset = 0; start_offset < big_stride; start_offset++) {
for (auto i = 0; i < relative_offset_set.size(); i++) {
auto output_index = start_offset + flat_segment_id(i) * big_stride;
auto offset = start_offset + relative_offset_set[i];
if (output_flat(output_index).length() != 0)
output_flat(output_index).append(separator_.c_str());
output_flat(output_index).append(flat_input(offset));
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Validate `num_segments > 0` in `unsorted_segment_join`
Fixes #55305
PiperOrigin-RevId: 442047005'</s> |
<s>[INST] Given the following code containing errors, provide 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 DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow)
{
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP);
/* cleanup pkt specific part of the patternmatcher */
PacketPatternCleanup(det_ctx);
if (pflow != NULL) {
/* update inspected tracker for raw reassembly */
if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) {
StreamReassembleRawUpdateProgress(pflow->protoctx, p,
det_ctx->raw_stream_progress);
DetectEngineCleanHCBDBuffers(det_ctx);
}
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP);
SCReturn;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-347'], 'message': 'stream: fix false negative on bad RST
If a bad RST was received the stream inspection would not happen
for that packet, but it would still move the 'raw progress' tracker
forward. Following good packets would then fail to detect anything
before the 'raw progress' position.
Bug #2770
Reported-by: Alexey Vishnyakov'</s> |
<s>[INST] Given the following code containing errors, provide 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 SNC_io_parser<EW>::
read_volume(Volume_handle ch) {
bool OK = true;
int index;
char cc;
in >> index;
OK = OK && test_string("{");
in >> cc;
while(isdigit(cc)) {
in.putback(cc);
in >> index;
ch->shell_entry_objects().push_back(make_object(SFace_of[index]));
in >> cc;
}
in >> ch->mark();
return OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix Nef_3'</s> |
<s>[INST] Given the following code containing errors, provide 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 htc_config_pipe_credits(struct htc_target *target)
{
struct sk_buff *skb;
struct htc_config_pipe_msg *cp_msg;
int ret;
unsigned long time_left;
skb = alloc_skb(50 + sizeof(struct htc_frame_hdr), GFP_ATOMIC);
if (!skb) {
dev_err(target->dev, "failed to allocate send buffer\n");
return -ENOMEM;
}
skb_reserve(skb, sizeof(struct htc_frame_hdr));
cp_msg = skb_put(skb, sizeof(struct htc_config_pipe_msg));
cp_msg->message_id = cpu_to_be16(HTC_MSG_CONFIG_PIPE_ID);
cp_msg->pipe_id = USB_WLAN_TX_PIPE;
cp_msg->credits = target->credits;
target->htc_flags |= HTC_OP_CONFIG_PIPE_CREDITS;
ret = htc_issue_send(target, skb, skb->len, 0, ENDPOINT0);
if (ret)
goto err;
time_left = wait_for_completion_timeout(&target->cmd_wait, HZ);
if (!time_left) {
dev_err(target->dev, "HTC credit config timeout\n");
kfree_skb(skb);
return -ETIMEDOUT;
}
return 0;
err:
kfree_skb(skb);
return -EINVAL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'ath9k: Fix use-after-free Read in htc_connect_service
The skb is consumed by htc_send_epid, so it needn't release again.
The case reported by syzbot:
https://lore.kernel.org/linux-usb/000000000000590f6b05a1c05d15@google.com
usb 1-1: ath9k_htc: Firmware ath9k_htc/htc_9271-1.4.0.fw requested
usb 1-1: ath9k_htc: Transferred FW: ath9k_htc/htc_9271-1.4.0.fw, size:
51008
usb 1-1: Service connection timeout for: 256
==================================================================
BUG: KASAN: use-after-free in atomic_read
include/asm-generic/atomic-instrumented.h:26 [inline]
BUG: KASAN: use-after-free in refcount_read include/linux/refcount.h:134
[inline]
BUG: KASAN: use-after-free in skb_unref include/linux/skbuff.h:1042
[inline]
BUG: KASAN: use-after-free in kfree_skb+0x32/0x3d0 net/core/skbuff.c:692
Read of size 4 at addr ffff8881d0957994 by task kworker/1:2/83
Call Trace:
kfree_skb+0x32/0x3d0 net/core/skbuff.c:692
htc_connect_service.cold+0xa9/0x109
drivers/net/wireless/ath/ath9k/htc_hst.c:282
ath9k_wmi_connect+0xd2/0x1a0 drivers/net/wireless/ath/ath9k/wmi.c:265
ath9k_init_htc_services.constprop.0+0xb4/0x650
drivers/net/wireless/ath/ath9k/htc_drv_init.c:146
ath9k_htc_probe_device+0x25a/0x1d80
drivers/net/wireless/ath/ath9k/htc_drv_init.c:959
ath9k_htc_hw_init+0x31/0x60
drivers/net/wireless/ath/ath9k/htc_hst.c:501
ath9k_hif_usb_firmware_cb+0x26b/0x500
drivers/net/wireless/ath/ath9k/hif_usb.c:1187
request_firmware_work_func+0x126/0x242
drivers/base/firmware_loader/main.c:976
process_one_work+0x94b/0x1620 kernel/workqueue.c:2264
worker_thread+0x96/0xe20 kernel/workqueue.c:2410
kthread+0x318/0x420 kernel/kthread.c:255
ret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352
Allocated by task 83:
kmem_cache_alloc_node+0xdc/0x330 mm/slub.c:2814
__alloc_skb+0xba/0x5a0 net/core/skbuff.c:198
alloc_skb include/linux/skbuff.h:1081 [inline]
htc_connect_service+0x2cc/0x840
drivers/net/wireless/ath/ath9k/htc_hst.c:257
ath9k_wmi_connect+0xd2/0x1a0 drivers/net/wireless/ath/ath9k/wmi.c:265
ath9k_init_htc_services.constprop.0+0xb4/0x650
drivers/net/wireless/ath/ath9k/htc_drv_init.c:146
ath9k_htc_probe_device+0x25a/0x1d80
drivers/net/wireless/ath/ath9k/htc_drv_init.c:959
ath9k_htc_hw_init+0x31/0x60
drivers/net/wireless/ath/ath9k/htc_hst.c:501
ath9k_hif_usb_firmware_cb+0x26b/0x500
drivers/net/wireless/ath/ath9k/hif_usb.c:1187
request_firmware_work_func+0x126/0x242
drivers/base/firmware_loader/main.c:976
process_one_work+0x94b/0x1620 kernel/workqueue.c:2264
worker_thread+0x96/0xe20 kernel/workqueue.c:2410
kthread+0x318/0x420 kernel/kthread.c:255
ret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352
Freed by task 0:
kfree_skb+0x102/0x3d0 net/core/skbuff.c:690
ath9k_htc_txcompletion_cb+0x1f8/0x2b0
drivers/net/wireless/ath/ath9k/htc_hst.c:356
hif_usb_regout_cb+0x10b/0x1b0
drivers/net/wireless/ath/ath9k/hif_usb.c:90
__usb_hcd_giveback_urb+0x29a/0x550 drivers/usb/core/hcd.c:1650
usb_hcd_giveback_urb+0x368/0x420 drivers/usb/core/hcd.c:1716
dummy_timer+0x1258/0x32ae drivers/usb/gadget/udc/dummy_hcd.c:1966
call_timer_fn+0x195/0x6f0 kernel/time/timer.c:1404
expire_timers kernel/time/timer.c:1449 [inline]
__run_timers kernel/time/timer.c:1773 [inline]
__run_timers kernel/time/timer.c:1740 [inline]
run_timer_softirq+0x5f9/0x1500 kernel/time/timer.c:1786
__do_softirq+0x21e/0x950 kernel/softirq.c:292
Reported-and-tested-by: syzbot+9505af1ae303dabdc646@syzkaller.appspotmail.com
Signed-off-by: Qiujun Huang <hqjagain@gmail.com>
Signed-off-by: Kalle Valo <kvalo@codeaurora.org>
Link: https://lore.kernel.org/r/20200404041838.10426-2-hqjagain@gmail.com'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: StringMatching::~StringMatching() {
// TODO Auto-generated destructor stub
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387)
* Refs 5346. Blackbox test
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. one-way string compare
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. Do not add partition separator on last partition
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. Uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. Uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Access control unit testing
It only covers Partition and Topic permissions
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs #3680. Fix partition check on Permissions plugin.
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Fix tests on mac
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Fix windows tests
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Avoid memory leak on test
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Proxy data mocks should not return temporary objects
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* refs 3680. uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
Co-authored-by: Miguel Company <MiguelCompany@eprosima.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: string_255 topicName() const
{
return topic_name_;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387)
* Refs 5346. Blackbox test
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. one-way string compare
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. Do not add partition separator on last partition
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. Uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 5346. Uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Access control unit testing
It only covers Partition and Topic permissions
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs #3680. Fix partition check on Permissions plugin.
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Fix tests on mac
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Fix windows tests
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Avoid memory leak on test
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* Refs 3680. Proxy data mocks should not return temporary objects
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
* refs 3680. uncrustify
Signed-off-by: Iker Luengo <ikerluengo@eprosima.com>
Co-authored-by: Miguel Company <MiguelCompany@eprosima.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
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, RE_LEX_ENVIRONMENT *lex_env)
{
YYUSE (yyvaluep);
YYUSE (yyscanner);
YYUSE (lex_env);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
switch (yytype)
{
case 6: /* _CLASS_ */
#line 96 "re_grammar.y" /* yacc.c:1257 */
{ yr_free(((*yyvaluep).class_vector)); }
#line 1045 "re_grammar.c" /* yacc.c:1257 */
break;
case 26: /* alternative */
#line 97 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1051 "re_grammar.c" /* yacc.c:1257 */
break;
case 27: /* concatenation */
#line 98 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1057 "re_grammar.c" /* yacc.c:1257 */
break;
case 28: /* repeat */
#line 99 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1063 "re_grammar.c" /* yacc.c:1257 */
break;
case 29: /* single */
#line 100 "re_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1069 "re_grammar.c" /* yacc.c:1257 */
break;
default:
break;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Fix issue #674. Move regexp limits to limits.h.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dwg_free_object (Dwg_Object *obj)
{
int error = 0;
long unsigned int j;
Dwg_Data *dwg;
Bit_Chain *dat = &pdat;
if (obj && obj->parent)
{
dwg = obj->parent;
dat->version = dwg->header.version;
}
else
return;
if (obj->type == DWG_TYPE_FREED || obj->tio.object == NULL)
return;
dat->from_version = dat->version;
if (obj->supertype == DWG_SUPERTYPE_UNKNOWN)
goto unhandled;
switch (obj->type)
{
case DWG_TYPE_TEXT:
dwg_free_TEXT (dat, obj);
break;
case DWG_TYPE_ATTRIB:
dwg_free_ATTRIB (dat, obj);
break;
case DWG_TYPE_ATTDEF:
dwg_free_ATTDEF (dat, obj);
break;
case DWG_TYPE_BLOCK:
dwg_free_BLOCK (dat, obj);
break;
case DWG_TYPE_ENDBLK:
dwg_free_ENDBLK (dat, obj);
break;
case DWG_TYPE_SEQEND:
dwg_free_SEQEND (dat, obj);
break;
case DWG_TYPE_INSERT:
dwg_free_INSERT (dat, obj);
break;
case DWG_TYPE_MINSERT:
dwg_free_MINSERT (dat, obj);
break;
case DWG_TYPE_VERTEX_2D:
dwg_free_VERTEX_2D (dat, obj);
break;
case DWG_TYPE_VERTEX_3D:
dwg_free_VERTEX_3D (dat, obj);
break;
case DWG_TYPE_VERTEX_MESH:
dwg_free_VERTEX_MESH (dat, obj);
break;
case DWG_TYPE_VERTEX_PFACE:
dwg_free_VERTEX_PFACE (dat, obj);
break;
case DWG_TYPE_VERTEX_PFACE_FACE:
dwg_free_VERTEX_PFACE_FACE (dat, obj);
break;
case DWG_TYPE_POLYLINE_2D:
dwg_free_POLYLINE_2D (dat, obj);
break;
case DWG_TYPE_POLYLINE_3D:
dwg_free_POLYLINE_3D (dat, obj);
break;
case DWG_TYPE_ARC:
dwg_free_ARC (dat, obj);
break;
case DWG_TYPE_CIRCLE:
dwg_free_CIRCLE (dat, obj);
break;
case DWG_TYPE_LINE:
dwg_free_LINE (dat, obj);
break;
case DWG_TYPE_DIMENSION_ORDINATE:
dwg_free_DIMENSION_ORDINATE (dat, obj);
break;
case DWG_TYPE_DIMENSION_LINEAR:
dwg_free_DIMENSION_LINEAR (dat, obj);
break;
case DWG_TYPE_DIMENSION_ALIGNED:
dwg_free_DIMENSION_ALIGNED (dat, obj);
break;
case DWG_TYPE_DIMENSION_ANG3PT:
dwg_free_DIMENSION_ANG3PT (dat, obj);
break;
case DWG_TYPE_DIMENSION_ANG2LN:
dwg_free_DIMENSION_ANG2LN (dat, obj);
break;
case DWG_TYPE_DIMENSION_RADIUS:
dwg_free_DIMENSION_RADIUS (dat, obj);
break;
case DWG_TYPE_DIMENSION_DIAMETER:
dwg_free_DIMENSION_DIAMETER (dat, obj);
break;
case DWG_TYPE_POINT:
dwg_free_POINT (dat, obj);
break;
case DWG_TYPE__3DFACE:
dwg_free__3DFACE (dat, obj);
break;
case DWG_TYPE_POLYLINE_PFACE:
dwg_free_POLYLINE_PFACE (dat, obj);
break;
case DWG_TYPE_POLYLINE_MESH:
dwg_free_POLYLINE_MESH (dat, obj);
break;
case DWG_TYPE_SOLID:
dwg_free_SOLID (dat, obj);
break;
case DWG_TYPE_TRACE:
dwg_free_TRACE (dat, obj);
break;
case DWG_TYPE_SHAPE:
dwg_free_SHAPE (dat, obj);
break;
case DWG_TYPE_VIEWPORT:
dwg_free_VIEWPORT (dat, obj);
break;
case DWG_TYPE_ELLIPSE:
dwg_free_ELLIPSE (dat, obj);
break;
case DWG_TYPE_SPLINE:
dwg_free_SPLINE (dat, obj);
break;
case DWG_TYPE_REGION:
dwg_free_REGION (dat, obj);
break;
case DWG_TYPE__3DSOLID:
dwg_free__3DSOLID (dat, obj);
break; /* Check the type of the object */
case DWG_TYPE_BODY:
dwg_free_BODY (dat, obj);
break;
case DWG_TYPE_RAY:
dwg_free_RAY (dat, obj);
break;
case DWG_TYPE_XLINE:
dwg_free_XLINE (dat, obj);
break;
case DWG_TYPE_DICTIONARY:
dwg_free_DICTIONARY (dat, obj);
break;
case DWG_TYPE_MTEXT:
dwg_free_MTEXT (dat, obj);
break;
case DWG_TYPE_LEADER:
dwg_free_LEADER (dat, obj);
break;
case DWG_TYPE_TOLERANCE:
dwg_free_TOLERANCE (dat, obj);
break;
case DWG_TYPE_MLINE:
dwg_free_MLINE (dat, obj);
break;
case DWG_TYPE_BLOCK_CONTROL:
dwg_free_BLOCK_CONTROL (dat, obj);
break;
case DWG_TYPE_BLOCK_HEADER:
dwg_free_BLOCK_HEADER (dat, obj);
break;
case DWG_TYPE_LAYER_CONTROL:
dwg_free_LAYER_CONTROL (dat, obj);
break;
case DWG_TYPE_LAYER:
dwg_free_LAYER (dat, obj);
break;
case DWG_TYPE_STYLE_CONTROL:
dwg_free_STYLE_CONTROL (dat, obj);
break;
case DWG_TYPE_STYLE:
dwg_free_STYLE (dat, obj);
break;
case DWG_TYPE_LTYPE_CONTROL:
dwg_free_LTYPE_CONTROL (dat, obj);
break;
case DWG_TYPE_LTYPE:
dwg_free_LTYPE (dat, obj);
break;
case DWG_TYPE_VIEW_CONTROL:
dwg_free_VIEW_CONTROL (dat, obj);
break;
case DWG_TYPE_VIEW:
dwg_free_VIEW (dat, obj);
break;
case DWG_TYPE_UCS_CONTROL:
dwg_free_UCS_CONTROL (dat, obj);
break;
case DWG_TYPE_UCS:
dwg_free_UCS (dat, obj);
break;
case DWG_TYPE_VPORT_CONTROL:
dwg_free_VPORT_CONTROL (dat, obj);
break;
case DWG_TYPE_VPORT:
dwg_free_VPORT (dat, obj);
break;
case DWG_TYPE_APPID_CONTROL:
dwg_free_APPID_CONTROL (dat, obj);
break;
case DWG_TYPE_APPID:
dwg_free_APPID (dat, obj);
break;
case DWG_TYPE_DIMSTYLE_CONTROL:
dwg_free_DIMSTYLE_CONTROL (dat, obj);
break;
case DWG_TYPE_DIMSTYLE:
dwg_free_DIMSTYLE (dat, obj);
break;
case DWG_TYPE_VPORT_ENTITY_CONTROL:
dwg_free_VPORT_ENTITY_CONTROL (dat, obj);
break;
case DWG_TYPE_VPORT_ENTITY_HEADER:
dwg_free_VPORT_ENTITY_HEADER (dat, obj);
break;
case DWG_TYPE_GROUP:
dwg_free_GROUP (dat, obj);
break;
case DWG_TYPE_MLINESTYLE:
dwg_free_MLINESTYLE (dat, obj);
break;
case DWG_TYPE_OLE2FRAME:
dwg_free_OLE2FRAME (dat, obj);
break;
case DWG_TYPE_DUMMY:
dwg_free_DUMMY (dat, obj);
break;
case DWG_TYPE_LONG_TRANSACTION:
dwg_free_LONG_TRANSACTION (dat, obj);
break;
case DWG_TYPE_LWPOLYLINE:
dwg_free_LWPOLYLINE (dat, obj);
break;
case DWG_TYPE_HATCH:
dwg_free_HATCH (dat, obj);
break;
case DWG_TYPE_XRECORD:
dwg_free_XRECORD (dat, obj);
break;
case DWG_TYPE_PLACEHOLDER:
dwg_free_PLACEHOLDER (dat, obj);
break;
case DWG_TYPE_OLEFRAME:
dwg_free_OLEFRAME (dat, obj);
break;
#ifdef DEBUG_VBA_PROJECT
case DWG_TYPE_VBA_PROJECT:
dwg_free_VBA_PROJECT (dat, obj);
break;
#endif
case DWG_TYPE_LAYOUT:
dwg_free_LAYOUT (dat, obj);
break;
case DWG_TYPE_PROXY_ENTITY:
dwg_free_PROXY_ENTITY (dat, obj);
break;
case DWG_TYPE_PROXY_OBJECT:
dwg_free_PROXY_OBJECT (dat, obj);
break;
default:
if (obj->type == obj->parent->layout_type)
{
SINCE (R_13)
{
dwg_free_LAYOUT (dat, obj); // XXX avoid double-free, esp. in eed
}
}
else if ((error = dwg_free_variable_type (obj->parent, obj))
& DWG_ERR_UNHANDLEDCLASS)
{
int is_entity;
int i;
Dwg_Class *klass;
unhandled:
is_entity = 0;
i = obj->type - 500;
klass = NULL;
dwg = obj->parent;
if (dwg->dwg_class && i >= 0 && i < (int)dwg->num_classes)
{
klass = &dwg->dwg_class[i];
is_entity = klass ? dwg_class_is_entity (klass) : 0;
}
// indxf (and later injson) already creates some DEBUGGING classes
if (obj->fixedtype == DWG_TYPE_TABLE)
{
// just the preview, i.e. common. plus some colors: leak
dwg_free_UNKNOWN_ENT (dat, obj);
}
else if (obj->fixedtype == DWG_TYPE_DATATABLE)
{
dwg_free_UNKNOWN_OBJ (dat, obj);
}
else if (klass && !is_entity)
{
dwg_free_UNKNOWN_OBJ (dat, obj);
}
else if (klass && is_entity)
{
dwg_free_UNKNOWN_ENT (dat, obj);
}
else // not a class
{
FREE_IF (obj->tio.unknown);
}
}
}
/* With this importer the dxfname is dynamic, just the name is const */
if (dwg->opts & DWG_OPTS_INDXF)
FREE_IF (obj->dxfname);
obj->type = DWG_TYPE_FREED;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'cleanup tio.unknown
not needed anymore, we only have UNKNOWN_OBJ or UNKNOWN_ENT with full common
entity_data.
Fixes GH #178 heap_overflow2'</s> |
<s>[INST] Given the following code containing errors, provide 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 userfaultfd_unregister(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_range uffdio_unregister;
unsigned long new_flags;
bool found;
unsigned long start, end, vma_end;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
goto out;
ret = validate_range(mm, uffdio_unregister.start,
uffdio_unregister.len);
if (ret)
goto out;
start = uffdio_unregister.start;
end = start + uffdio_unregister.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
ret = -EINVAL;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/*
* Check not compatible vmas, not strictly required
* here as not compatible vmas cannot have an
* userfaultfd_ctx registered on them, but this
* provides for more strict behavior to notice
* unregistration errors.
*/
if (!vma_can_userfault(cur))
goto out_unlock;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (!vma->vm_userfaultfd_ctx.ctx)
goto skip;
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
if (userfaultfd_missing(vma)) {
/*
* Wake any concurrent pending userfault while
* we unregister, so they will not hang
* permanently and it avoids userland to call
* UFFDIO_WAKE explicitly.
*/
struct userfaultfd_wake_range range;
range.start = start;
range.len = vma_end - start;
wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
out:
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-863'], 'message': 'userfaultfd: shmem/hugetlbfs: only allow to register VM_MAYWRITE vmas
After the VMA to register the uffd onto is found, check that it has
VM_MAYWRITE set before allowing registration. This way we inherit all
common code checks before allowing to fill file holes in shmem and
hugetlbfs with UFFDIO_COPY.
The userfaultfd memory model is not applicable for readonly files unless
it's a MAP_PRIVATE.
Link: http://lkml.kernel.org/r/20181126173452.26955-4-aarcange@redhat.com
Fixes: ff62a3421044 ("hugetlb: implement memfd sealing")
Signed-off-by: Andrea Arcangeli <aarcange@redhat.com>
Reviewed-by: Mike Rapoport <rppt@linux.ibm.com>
Reviewed-by: Hugh Dickins <hughd@google.com>
Reported-by: Jann Horn <jannh@google.com>
Fixes: 4c27fe4c4c84 ("userfaultfd: shmem: add shmem_mcopy_atomic_pte for userfaultfd support")
Cc: <stable@vger.kernel.org>
Cc: "Dr. David Alan Gilbert" <dgilbert@redhat.com>
Cc: Mike Kravetz <mike.kravetz@oracle.com>
Cc: Peter Xu <peterx@redhat.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
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: inline bool ResolveAxis(const int num_dims, const int* axis,
const int64_t num_axis, int* out_axis,
int* out_num_axis) {
*out_num_axis = 0; // Just in case.
// Short-circuit axis resolution for scalars; the axis will go unused.
if (num_dims == 0) {
return true;
}
// o(n^2) is fine since out_num_axis should be really small, mostly <= 4
for (int64_t idx = 0; idx < num_axis; ++idx) {
// Handle negative index. A positive index 'p_idx' can be represented as a
// negative index 'n_idx' as: n_idx = p_idx-num_dims
// eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */
int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx];
TFLITE_DCHECK(current >= 0 && current < num_dims);
bool is_dup = false;
for (int j = 0; j < *out_num_axis; ++j) {
if (out_axis[j] == current) {
is_dup = true;
break;
}
}
if (!is_dup) {
out_axis[*out_num_axis] = current;
*out_num_axis += 1;
}
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[tflite] Ensure `ResolveAxis` properly handles negative inputs.
In Python, a list `l` of length `n` allows indexing with negative indices, `l[i]`. The only constraint is that `n + i` becomes positive. Code in `ResolveAxis` assumes the constraints and only checks it using a `DCHECK`. But the macro is a no-op in non-debug builds and that can result in reading from negative offsets (buffer underflows).
PiperOrigin-RevId: 332530683
Change-Id: I464e073fee618054ae3719a3679739007bb3f3bc'</s> |
<s>[INST] Given the following code containing errors, provide 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 TestGatherNd(int* param_dims, const ParamType* param_data, int* index_dims,
const IndexType* index_data, int* output_dims,
ParamType* output_data,
const ParamType* expected_output_data) {
TfLiteIntArray* pdims = IntArrayFromInts(param_dims);
TfLiteIntArray* idims = IntArrayFromInts(index_dims);
TfLiteIntArray* odims = IntArrayFromInts(output_dims);
constexpr int inputs_size = 2;
constexpr int outputs_size = 1;
constexpr int tensors_size = inputs_size + outputs_size;
TfLiteTensor tensors[tensors_size] = {
CreateTensor(param_data, pdims),
CreateTensor(index_data, idims),
CreateTensor(output_data, odims),
};
int inputs_array_data[] = {2, 0, 1};
TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);
int outputs_array_data[] = {1, 2};
TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);
const TfLiteRegistration registration = Register_GATHER_ND();
micro::KernelRunner runner(registration, tensors, tensors_size, inputs_array,
outputs_array, /*builtin_data=*/nullptr);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare());
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke());
// The output tensor's data and shape have been updated by the kernel.
TfLiteTensor* actual_output_tensor = &tensors[2];
TfLiteIntArray* actual_output_dims = actual_output_tensor->dims;
const int output_size = ElementCount(*actual_output_dims);
for (int i = 0; i < output_size; ++i) {
TF_LITE_MICRO_EXPECT_EQ(expected_output_data[i], output_data[i]);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': 'GatherNd verifies that an index is valid before reading. (#1286)'</s> |
<s>[INST] Given the following code containing errors, provide 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 get_alen(char *arg, int default_len)
{
int j;
int alen;
alen = default_len;
for (j = 0; j < 8; j++) {
if (arg[j] == '.') {
alen = arg[j+1] - '0';
break;
} else if (arg[j] == '\0')
break;
}
return alen;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'i2c: fix stack buffer overflow vulnerability in i2c md command
When running "i2c md 0 0 80000100", the function do_i2c_md parses the
length into an unsigned int variable named length. The value is then
moved to a signed variable:
int nbytes = length;
#define DISP_LINE_LEN 16
int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;
ret = dm_i2c_read(dev, addr, linebuf, linebytes);
On systems where integers are 32 bits wide, 0x80000100 is a negative
value to "nbytes > DISP_LINE_LEN" is false and linebytes gets assigned
0x80000100 instead of 16.
The consequence is that the function which reads from the i2c device
(dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill
but with a size parameter which is too large. In some cases, this could
trigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c
(used with "nexell,s5pxx18-i2c" bus), the size is actually truncated to
a 16-bit integer. This is because function i2c_transfer expects an
unsigned short length. In such a case, an attacker who can control the
response of an i2c device can overwrite the return address of a function
and execute arbitrary code through Return-Oriented Programming.
Fix this issue by using unsigned integers types in do_i2c_md. While at
it, make also alen unsigned, as signed sizes can cause vulnerabilities
when people forgot to check that they can be negative.
Signed-off-by: Nicolas Iooss <nicolas.iooss+uboot@ledger.fr>
Reviewed-by: Heiko Schocher <hs@denx.de>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)
{
return &crypto_rng_tfm(tfm)->__crt_alg->cra_rng;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s> |
<s>[INST] Given the following code containing errors, provide 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 grubfs_free (GrubFS *gf) {
if (gf) {
if (gf->file && gf->file->device)
free (gf->file->device->disk);
//free (gf->file->device);
free (gf->file);
free (gf);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #7723 - crash in ext2 GRUB code because of variable size array in stack'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: njs_typed_array_alloc(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
njs_bool_t zeroing, njs_object_type_t type)
{
double num;
int64_t i, length;
uint32_t element_size;
uint64_t size, offset;
njs_int_t ret;
njs_value_t *value, prop;
njs_array_t *src_array;
njs_typed_array_t *array, *src_tarray;
njs_array_buffer_t *buffer;
size = 0;
length = 0;
offset = 0;
buffer = NULL;
src_array = NULL;
src_tarray = NULL;
element_size = njs_typed_array_element_size(type);
value = njs_arg(args, nargs, 0);
if (njs_is_array_buffer(value)) {
buffer = njs_array_buffer(value);
ret = njs_value_to_index(vm, njs_arg(args, nargs, 1), &offset);
if (njs_slow_path(ret != NJS_OK)) {
return NULL;
}
if (njs_slow_path((offset % element_size) != 0)) {
njs_range_error(vm, "start offset must be multiple of %uD",
element_size);
return NULL;
}
if (njs_is_defined(njs_arg(args, nargs, 2))) {
ret = njs_value_to_index(vm, njs_argument(args, 2), &size);
if (njs_slow_path(ret != NJS_OK)) {
return NULL;
}
}
if (njs_slow_path(njs_is_detached_buffer(buffer))) {
njs_type_error(vm, "detached buffer");
return NULL;
}
if (njs_is_defined(njs_arg(args, nargs, 2))) {
ret = njs_value_to_index(vm, njs_argument(args, 2), &size);
if (njs_slow_path(ret != NJS_OK)) {
return NULL;
}
size *= element_size;
if (njs_slow_path((offset + size) > buffer->size)) {
njs_range_error(vm, "Invalid typed array length: %uL", size);
return NULL;
}
} else {
if (njs_slow_path((buffer->size % element_size) != 0)) {
njs_range_error(vm, "byteLength of buffer must be "
"multiple of %uD", element_size);
return NULL;
}
if (offset > buffer->size) {
njs_range_error(vm, "byteOffset %uL is outside the bound of "
"the buffer", offset);
return NULL;
}
size = buffer->size - offset;
}
} else if (njs_is_typed_array(value)) {
src_tarray = njs_typed_array(value);
if (njs_slow_path(njs_is_detached_buffer(src_tarray->buffer))) {
njs_type_error(vm, "detached buffer");
return NULL;
}
size = (uint64_t) njs_typed_array_length(src_tarray) * element_size;
} else if (njs_is_object(value)) {
if (njs_is_fast_array(value)) {
src_array = njs_array(value);
length = src_array->length;
} else {
ret = njs_object_length(vm, value, &length);
if (njs_slow_path(ret == NJS_ERROR)) {
return NULL;
}
}
size = length * element_size;
} else {
ret = njs_value_to_index(vm, value, &size);
if (njs_slow_path(ret != NJS_OK)) {
return NULL;
}
size *= element_size;
}
if (buffer == NULL) {
buffer = njs_array_buffer_alloc(vm, size, zeroing);
if (njs_slow_path(buffer == NULL)) {
return NULL;
}
}
array = njs_mp_zalloc(vm->mem_pool, sizeof(njs_typed_array_t));
if (njs_slow_path(array == NULL)) {
goto memory_error;
}
array->buffer = buffer;
array->offset = offset / element_size;
array->byte_length = size;
array->type = type;
if (src_tarray != NULL) {
if (type != src_tarray->type) {
length = njs_typed_array_length(src_tarray);
for (i = 0; i < length; i++) {
njs_typed_array_prop_set(vm, array, i,
njs_typed_array_prop(src_tarray, i));
}
} else {
memcpy(&buffer->u.u8[0], &src_tarray->buffer->u.u8[0], size);
}
} else if (src_array != NULL) {
for (i = 0; i < length; i++) {
ret = njs_value_to_number(vm, &src_array->start[i], &num);
if (njs_slow_path(ret == NJS_ERROR)) {
return NULL;
}
if (ret == NJS_OK) {
njs_typed_array_prop_set(vm, array, i, num);
}
}
} else if (!njs_is_array_buffer(value) && njs_is_object(value)) {
for (i = 0; i < length; i++) {
ret = njs_value_property_i64(vm, value, i, &prop);
if (njs_slow_path(ret == NJS_ERROR)) {
return NULL;
}
num = NAN;
if (ret == NJS_OK) {
ret = njs_value_to_number(vm, &prop, &num);
if (njs_slow_path(ret == NJS_ERROR)) {
return NULL;
}
}
njs_typed_array_prop_set(vm, array, i, num);
}
}
njs_lvlhsh_init(&array->object.hash);
njs_lvlhsh_init(&array->object.shared_hash);
array->object.__proto__ = &vm->prototypes[type].object;
array->object.type = NJS_TYPED_ARRAY;
array->object.extensible = 1;
array->object.fast_array = 1;
return array;
memory_error:
njs_memory_error(vm);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fixed typed-array ctor when source array is changed while iterating.
Previously, the function used optimization for ordinary arrays with no
gaps (so called fast arrays). For a fast array code took elements
directly from internal flat C array. The direct pointer may become
invalid as side-effect of custom valueOf() method for an element.
The fix is to eliminate the micro-optimization which uses direct
pointers.
The problem is similar to the 9578cc729205 (0.7.2) commit.
This closes #523 issue on Github.'</s> |
<s>[INST] Given the following code containing errors, provide 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 l2cap_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {
err = -EBADFD;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
if (!l2cap_pi(sk)->psm) {
bdaddr_t *src = &bt_sk(sk)->src;
u16 psm;
err = -EINVAL;
write_lock_bh(&l2cap_sk_list.lock);
for (psm = 0x1001; psm < 0x1100; psm += 2)
if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {
l2cap_pi(sk)->psm = cpu_to_le16(psm);
l2cap_pi(sk)->sport = cpu_to_le16(psm);
err = 0;
break;
}
write_unlock_bh(&l2cap_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-119', 'CWE-787'], 'message': 'Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <gustavo@las.ic.unicamp.br>
Signed-off-by: Marcel Holtmann <marcel@holtmann.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void test_base64_decode(void)
{
char buffer[16];
int len = mutt_b64_decode(buffer, encoded);
if (!TEST_CHECK(len == sizeof(clear) - 1))
{
TEST_MSG("Expected: %zu", sizeof(clear) - 1);
TEST_MSG("Actual : %zu", len);
}
buffer[len] = '\0';
if (!TEST_CHECK(strcmp(buffer, clear) == 0))
{
TEST_MSG("Expected: %s", clear);
TEST_MSG("Actual : %s", buffer);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.'</s> |
<s>[INST] Given the following code containing errors, provide 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 directblockRead(struct READER *reader, struct DATAOBJECT *dataobject,
struct FRACTALHEAP *fractalheap) {
char buf[4], *name, *value;
int size, offset_size, length_size, err, len;
uint8_t typeandversion;
uint64_t unknown, heap_header_address, block_offset, block_size, offset,
length;
long store;
struct DIR *dir;
struct MYSOFA_ATTRIBUTE *attr;
UNUSED(offset);
UNUSED(block_size);
UNUSED(block_offset);
/* read signature */
if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FHDB", 4)) {
log("cannot read signature of fractal heap indirect block\n");
return MYSOFA_INVALID_FORMAT;
}
log("%08" PRIX64 " %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf);
if (fgetc(reader->fhd) != 0) {
log("object FHDB must have version 0\n");
return MYSOFA_UNSUPPORTED_FORMAT;
}
/* ignore heap_header_address */
if (fseek(reader->fhd, reader->superblock.size_of_offsets, SEEK_CUR) < 0)
return errno;
size = (fractalheap->maximum_heap_size + 7) / 8;
block_offset = readValue(reader, size);
if (fractalheap->flags & 2)
if (fseek(reader->fhd, 4, SEEK_CUR))
return errno;
offset_size = ceilf(log2f(fractalheap->maximum_heap_size) / 8);
if (fractalheap->maximum_direct_block_size < fractalheap->maximum_size)
length_size = ceilf(log2f(fractalheap->maximum_direct_block_size) / 8);
else
length_size = ceilf(log2f(fractalheap->maximum_size) / 8);
log(" %d %" PRIu64 " %d\n",size,block_offset,offset_size);
/*
* 00003e00 00 46 48 44 42 00 40 02 00 00 00 00 00 00 00 00 |.FHDB.@.........|
00003e10 00 00 00 83 8d ac f6 >03 00 0c 00 08 00 04 00 00 |................|
00003e20 43 6f 6e 76 65 6e 74 69 6f 6e 73 00 13 00 00 00 |Conventions.....|
00003e30 04 00 00 00 02 00 00 00 53 4f 46 41< 03 00 08 00 |........SOFA....|
00003e40 08 00 04 00 00 56 65 72 73 69 6f 6e 00 13 00 00 |.....Version....|
00003e50 00 03 00 00 00 02 00 00 00 30 2e 36 03 00 10 00 |.........0.6....|
00003e60 08 00 04 00 00 53 4f 46 41 43 6f 6e 76 65 6e 74 |.....SOFAConvent|
00003e70 69 6f 6e 73 00 13 00 00 00 13 00 00 00 02 00 00 |ions............|
00003e80 00 53 69 6d 70 6c 65 46 72 65 65 46 69 65 6c 64 |.SimpleFreeField|
00003e90 48 52 49 52 03 00 17 00 08 00 04 00 00 53 4f 46 |HRIR.........SOF|
00003ea0 41 43 6f 6e 76 65 6e 74 69 6f 6e 73 56 65 72 73 |AConventionsVers|
00003eb0 69 6f 6e 00 13 00 00 00 03 00 00 00 02 00 00 00 |ion.............|
*
*/
do {
typeandversion = (uint8_t) fgetc(reader->fhd);
offset = readValue(reader, offset_size);
length = readValue(reader, length_size);
if (offset > 0x10000000 || length > 0x10000000)
return MYSOFA_UNSUPPORTED_FORMAT;
log(" %d %4" PRIX64 " %" PRIX64 " %08lX\n",typeandversion,offset,length,ftell(reader->fhd));
/* TODO: for the following part, the specification is incomplete */
if (typeandversion == 3) {
/*
* this seems to be a name and value pair
*/
if (readValue(reader, 5) != 0x0000040008) {
log("FHDB type 3 unsupported values");
return MYSOFA_UNSUPPORTED_FORMAT;
}
if (!(name = malloc(length+1)))
return MYSOFA_NO_MEMORY;
if (fread(name, 1, length, reader->fhd) != length) {
free(name);
return MYSOFA_READ_ERROR;
}
name[length]=0;
if (readValue(reader, 4) != 0x00000013) {
log("FHDB type 3 unsupported values");
free(name);
return MYSOFA_UNSUPPORTED_FORMAT;
}
len = (int) readValue(reader, 2);
if (len > 0x1000 || len < 0) {
free(name);
return MYSOFA_UNSUPPORTED_FORMAT;
}
/* TODO: Get definition of this field */
unknown = readValue(reader, 6);
if (unknown == 0x000000020200)
value = NULL;
else if (unknown == 0x000000020000) {
if (!(value = malloc(len + 1))) {
free(name);
return MYSOFA_NO_MEMORY;
}
if (fread(value, 1, len, reader->fhd) != len) {
free(value);
free(name);
return MYSOFA_READ_ERROR;
}
value[len] = 0;
} else if (unknown == 0x20000020000) {
if (!(value = malloc(5))) {
free(name);
return MYSOFA_NO_MEMORY;
}
strcpy(value, "");
} else {
log("FHDB type 3 unsupported values: %12" PRIX64 "\n",unknown);
free(name);
/* TODO: return MYSOFA_UNSUPPORTED_FORMAT; */
return MYSOFA_OK;
}
log(" %s = %s\n", name, value);
attr = malloc(sizeof(struct MYSOFA_ATTRIBUTE));
attr->name = name;
attr->value = value;
attr->next = dataobject->attributes;
dataobject->attributes = attr;
} else if (typeandversion == 1) {
/*
* pointer to another data object
*/
unknown = readValue(reader, 6);
if (unknown) {
log("FHDB type 1 unsupported values\n");
return MYSOFA_UNSUPPORTED_FORMAT;
}
len = fgetc(reader->fhd);
if (len < 0)
return MYSOFA_READ_ERROR;
assert(len < 0x100);
if (!(name = malloc(len + 1)))
return MYSOFA_NO_MEMORY;
if (fread(name, 1, len, reader->fhd) != len) {
free(name);
return MYSOFA_READ_ERROR;
}
name[len] = 0;
heap_header_address = readValue(reader,
reader->superblock.size_of_offsets);
log("\nfractal head type 1 length %4" PRIX64 " name %s address %" PRIX64 "\n", length, name, heap_header_address);
dir = malloc(sizeof(struct DIR));
if (!dir) {
free(name);
return MYSOFA_NO_MEMORY;
}
memset(dir, 0, sizeof(*dir));
dir->next = dataobject->directory;
dataobject->directory = dir;
store = ftell(reader->fhd);
if (fseek(reader->fhd, heap_header_address, SEEK_SET)) {
free(name);
return errno;
}
err = dataobjectRead(reader, &dir->dataobject, name);
if (err) {
return err;
}
if (store < 0) {
return errno;
}
if (fseek(reader->fhd, store, SEEK_SET) < 0)
return errno;
} else if (typeandversion != 0) {
/* TODO is must be avoided somehow */
log("fractal head unknown type %d\n", typeandversion);
/* return MYSOFA_UNSUPPORTED_FORMAT; */
return MYSOFA_OK;
}
} while (typeandversion != 0);
return MYSOFA_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': 'Fixed recursive function calls'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gstd_accept(int fd, char **display_creds, char **export_name, char **mech)
{
gss_name_t client;
gss_OID mech_oid;
struct gstd_tok *tok;
gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
gss_buffer_desc in, out;
OM_uint32 maj, min;
int ret;
*display_creds = NULL;
*export_name = NULL;
out.length = 0;
in.length = 0;
read_packet(fd, &in, 60000, 1);
again:
while ((ret = read_packet(fd, &in, 60000, 0)) == -2)
;
if (ret < 1)
return NULL;
maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL,
&in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL,
NULL, NULL);
if (out.length && write_packet(fd, &out)) {
gss_release_buffer(&min, &out);
return NULL;
}
GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context");
if (maj & GSS_S_CONTINUE_NEEDED)
goto again;
*display_creds = gstd_get_display_name(client);
*export_name = gstd_get_export_name(client);
*mech = gstd_get_mech(mech_oid);
gss_release_name(&min, &client);
SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept");
return tok;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'knc: fix a couple of memory leaks.
One of these can be remotely triggered during the authentication
phase which leads to a remote DoS possibility.
Pointed out by: Imre Rad <radimre83@gmail.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int get_bitmap_file(struct mddev *mddev, void __user * arg)
{
mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
char *ptr;
int err;
file = kmalloc(sizeof(*file), GFP_NOIO);
if (!file)
return -ENOMEM;
err = 0;
spin_lock(&mddev->lock);
/* bitmap disabled, zero the first byte and copy out */
if (!mddev->bitmap_info.file)
file->pathname[0] = '\0';
else if ((ptr = file_path(mddev->bitmap_info.file,
file->pathname, sizeof(file->pathname))),
IS_ERR(ptr))
err = PTR_ERR(ptr);
else
memmove(file->pathname, ptr,
sizeof(file->pathname)-(ptr-file->pathname));
spin_unlock(&mddev->lock);
if (err == 0 &&
copy_to_user(arg, file, sizeof(*file)))
err = -EFAULT;
kfree(file);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr>
Signed-off-by: NeilBrown <neilb@suse.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 l2cap_sock_teardown_cb(struct l2cap_chan *chan, int err)
{
struct sock *sk = chan->data;
struct sock *parent;
BT_DBG("chan %p state %s", chan, state_to_string(chan->state));
/* This callback can be called both for server (BT_LISTEN)
* sockets as well as "normal" ones. To avoid lockdep warnings
* with child socket locking (through l2cap_sock_cleanup_listen)
* we need separation into separate nesting levels. The simplest
* way to accomplish this is to inherit the nesting level used
* for the channel.
*/
lock_sock_nested(sk, atomic_read(&chan->nesting));
parent = bt_sk(sk)->parent;
switch (chan->state) {
case BT_OPEN:
case BT_BOUND:
case BT_CLOSED:
break;
case BT_LISTEN:
l2cap_sock_cleanup_listen(sk);
sk->sk_state = BT_CLOSED;
chan->state = BT_CLOSED;
break;
default:
sk->sk_state = BT_CLOSED;
chan->state = BT_CLOSED;
sk->sk_err = err;
if (parent) {
bt_accept_unlink(sk);
parent->sk_data_ready(parent);
} else {
sk->sk_state_change(sk);
}
break;
}
release_sock(sk);
/* Only zap after cleanup to avoid use after free race */
sock_set_flag(sk, SOCK_ZAPPED);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: fix use-after-free error in lock_sock_nested()
use-after-free error in lock_sock_nested is reported:
[ 179.140137][ T3731] =====================================================
[ 179.142675][ T3731] BUG: KMSAN: use-after-free in lock_sock_nested+0x280/0x2c0
[ 179.145494][ T3731] CPU: 4 PID: 3731 Comm: kworker/4:2 Not tainted 5.12.0-rc6+ #54
[ 179.148432][ T3731] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014
[ 179.151806][ T3731] Workqueue: events l2cap_chan_timeout
[ 179.152730][ T3731] Call Trace:
[ 179.153301][ T3731] dump_stack+0x24c/0x2e0
[ 179.154063][ T3731] kmsan_report+0xfb/0x1e0
[ 179.154855][ T3731] __msan_warning+0x5c/0xa0
[ 179.155579][ T3731] lock_sock_nested+0x280/0x2c0
[ 179.156436][ T3731] ? kmsan_get_metadata+0x116/0x180
[ 179.157257][ T3731] l2cap_sock_teardown_cb+0xb8/0x890
[ 179.158154][ T3731] ? __msan_metadata_ptr_for_load_8+0x10/0x20
[ 179.159141][ T3731] ? kmsan_get_metadata+0x116/0x180
[ 179.159994][ T3731] ? kmsan_get_shadow_origin_ptr+0x84/0xb0
[ 179.160959][ T3731] ? l2cap_sock_recv_cb+0x420/0x420
[ 179.161834][ T3731] l2cap_chan_del+0x3e1/0x1d50
[ 179.162608][ T3731] ? kmsan_get_metadata+0x116/0x180
[ 179.163435][ T3731] ? kmsan_get_shadow_origin_ptr+0x84/0xb0
[ 179.164406][ T3731] l2cap_chan_close+0xeea/0x1050
[ 179.165189][ T3731] ? kmsan_internal_unpoison_shadow+0x42/0x70
[ 179.166180][ T3731] l2cap_chan_timeout+0x1da/0x590
[ 179.167066][ T3731] ? __msan_metadata_ptr_for_load_8+0x10/0x20
[ 179.168023][ T3731] ? l2cap_chan_create+0x560/0x560
[ 179.168818][ T3731] process_one_work+0x121d/0x1ff0
[ 179.169598][ T3731] worker_thread+0x121b/0x2370
[ 179.170346][ T3731] kthread+0x4ef/0x610
[ 179.171010][ T3731] ? process_one_work+0x1ff0/0x1ff0
[ 179.171828][ T3731] ? kthread_blkcg+0x110/0x110
[ 179.172587][ T3731] ret_from_fork+0x1f/0x30
[ 179.173348][ T3731]
[ 179.173752][ T3731] Uninit was created at:
[ 179.174409][ T3731] kmsan_internal_poison_shadow+0x5c/0xf0
[ 179.175373][ T3731] kmsan_slab_free+0x76/0xc0
[ 179.176060][ T3731] kfree+0x3a5/0x1180
[ 179.176664][ T3731] __sk_destruct+0x8af/0xb80
[ 179.177375][ T3731] __sk_free+0x812/0x8c0
[ 179.178032][ T3731] sk_free+0x97/0x130
[ 179.178686][ T3731] l2cap_sock_release+0x3d5/0x4d0
[ 179.179457][ T3731] sock_close+0x150/0x450
[ 179.180117][ T3731] __fput+0x6bd/0xf00
[ 179.180787][ T3731] ____fput+0x37/0x40
[ 179.181481][ T3731] task_work_run+0x140/0x280
[ 179.182219][ T3731] do_exit+0xe51/0x3e60
[ 179.182930][ T3731] do_group_exit+0x20e/0x450
[ 179.183656][ T3731] get_signal+0x2dfb/0x38f0
[ 179.184344][ T3731] arch_do_signal_or_restart+0xaa/0xe10
[ 179.185266][ T3731] exit_to_user_mode_prepare+0x2d2/0x560
[ 179.186136][ T3731] syscall_exit_to_user_mode+0x35/0x60
[ 179.186984][ T3731] do_syscall_64+0xc5/0x140
[ 179.187681][ T3731] entry_SYSCALL_64_after_hwframe+0x44/0xae
[ 179.188604][ T3731] =====================================================
In our case, there are two Thread A and B:
Context: Thread A: Context: Thread B:
l2cap_chan_timeout() __se_sys_shutdown()
l2cap_chan_close() l2cap_sock_shutdown()
l2cap_chan_del() l2cap_chan_close()
l2cap_sock_teardown_cb() l2cap_sock_teardown_cb()
Once l2cap_sock_teardown_cb() excuted, this sock will be marked as SOCK_ZAPPED,
and can be treated as killable in l2cap_sock_kill() if sock_orphan() has
excuted, at this time we close sock through sock_close() which end to call
l2cap_sock_kill() like Thread C:
Context: Thread C:
sock_close()
l2cap_sock_release()
sock_orphan()
l2cap_sock_kill() #free sock if refcnt is 1
If C completed, Once A or B reaches l2cap_sock_teardown_cb() again,
use-after-free happened.
We should set chan->data to NULL if sock is destructed, for telling teardown
operation is not allowed in l2cap_sock_teardown_cb(), and also we should
avoid killing an already killed socket in l2cap_sock_close_cb().
Signed-off-by: Wang ShaoBo <bobo.shaobowang@huawei.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Marcel Holtmann <marcel@holtmann.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: asmlinkage long sys_oabi_semtimedop(int semid,
struct oabi_sembuf __user *tsops,
unsigned nsops,
const struct timespec __user *timeout)
{
struct sembuf *sops;
struct timespec local_timeout;
long err;
int i;
if (nsops < 1)
return -EINVAL;
sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL);
if (!sops)
return -ENOMEM;
err = 0;
for (i = 0; i < nsops; i++) {
__get_user_error(sops[i].sem_num, &tsops->sem_num, err);
__get_user_error(sops[i].sem_op, &tsops->sem_op, err);
__get_user_error(sops[i].sem_flg, &tsops->sem_flg, err);
tsops++;
}
if (timeout) {
/* copy this as well before changing domain protection */
err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout));
timeout = &local_timeout;
}
if (err) {
err = -EFAULT;
} else {
mm_segment_t fs = get_fs();
set_fs(KERNEL_DS);
err = sys_semtimedop(semid, sops, nsops, timeout);
set_fs(fs);
}
kfree(sops);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ARM: 6891/1: prevent heap corruption in OABI semtimedop
When CONFIG_OABI_COMPAT is set, the wrapper for semtimedop does not
bound the nsops argument. A sufficiently large value will cause an
integer overflow in allocation size, followed by copying too much data
into the allocated buffer. Fix this by restricting nsops to SEMOPM.
Untested.
Cc: stable@kernel.org
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ip))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <hawkes@google.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.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: static inline bool unconditional(const struct ipt_ip *ip)
{
static const struct ipt_ip uncond;
return memcmp(ip, &uncond, sizeof(uncond)) == 0;
#undef FWINV
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <hawkes@google.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.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: static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if ((num_pages != size) ||
(num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'macvtap: zerocopy: validate vectors before building skb
There're several reasons that the vectors need to be validated:
- Return error when caller provides vectors whose num is greater than UIO_MAXIOV.
- Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS.
- Return error when userspace provides vectors whose total length may exceed
- MAX_SKB_FRAGS * PAGE_SIZE.
Signed-off-by: Jason Wang <jasowang@redhat.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteLocalResponseNormParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type == kTfLiteFloat32) {
#define TF_LITE_LOCAL_RESPONSE_NORM(type) \
tflite::LocalResponseNormalizationParams op_params; \
op_params.range = params->radius; \
op_params.bias = params->bias; \
op_params.alpha = params->alpha; \
op_params.beta = params->beta; \
type::LocalResponseNormalization( \
op_params, GetTensorShape(input), GetTensorData<float>(input), \
GetTensorShape(output), GetTensorData<float>(output))
if (kernel_type == kReference) {
TF_LITE_LOCAL_RESPONSE_NORM(reference_ops);
}
if (kernel_type == kGenericOptimized) {
TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops);
}
#undef TF_LITE_LOCAL_RESPONSE_NORM
} else {
context->ReportError(context, "Output type is %d, requires float.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus EvalQuantized(TfLiteContext* context, TfLiteNode* node,
OpData* data, const RuntimeShape& lhs_shape,
const TfLiteTensor* lhs,
const RuntimeShape& rhs_shape,
const TfLiteTensor* rhs, TfLiteTensor* output) {
if (lhs->type == kTfLiteFloat32) {
TfLiteTensor* input_quantized = GetTemporary(context, node, /*index=*/2);
TfLiteTensor* scaling_factors = GetTemporary(context, node, /*index=*/3);
TfLiteTensor* accum_scratch = GetTemporary(context, node, /*index=*/4);
TfLiteTensor* input_offsets = GetTemporary(context, node, /*index=*/5);
TfLiteTensor* row_sums = GetTemporary(context, node, /*index=*/6);
return EvalHybrid<kernel_type>(
context, node, data, lhs_shape, lhs, rhs_shape, rhs, input_quantized,
scaling_factors, accum_scratch, row_sums, input_offsets, output);
} else if (lhs->type == kTfLiteInt8) {
return EvalInt8<kernel_type>(context, data, lhs_shape, lhs, rhs_shape, rhs,
GetTensorShape(output), output);
} else {
TF_LITE_KERNEL_LOG(
context, "Currently only hybrid and int8 quantization is supported.\n");
return kTfLiteError;
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (type == kGenericOptimized) {
optimized_ops::Floor(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
} else {
reference_ops::Floor(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
output->type = input2->type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
if (output->type == kTfLiteUInt8) {
TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
context, params->activation, output, &data->output_activation_min,
&data->output_activation_max));
const double real_multiplier =
input1->params.scale / (input2->params.scale * output->params.scale);
QuantizeMultiplier(real_multiplier, &data->output_multiplier,
&data->output_shift);
}
return context->ResizeTensor(context, output, output_size);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* begin = GetInput(context, node, kBeginTensor);
const TfLiteTensor* size = GetInput(context, node, kSizeTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context,
ResizeOutputShape(context, input, begin, size, output));
}
std::vector<int> begins;
begins.reserve(kMaxDim);
std::vector<int> sizes;
sizes.reserve(kMaxDim);
for (int i = NumDimensions(input); i < kMaxDim; ++i) {
begins.push_back(0);
sizes.push_back(1);
}
if (begin->type == kTfLiteInt32) {
GetBeginAndSizeVectors<int32_t>(NumDimensions(input), begin, size, &begins,
&sizes);
} else if (begin->type == kTfLiteInt64) {
GetBeginAndSizeVectors<int64_t>(NumDimensions(input), begin, size, &begins,
&sizes);
} else {
context->ReportError(
context, "Type %d is currently not supported by Slice.", begin->type);
return kTfLiteError;
}
// The original Slice op implementation only accepted 4-D sizes. That
// constraint is, for the present, maintained here.
//
// The dimensions in the kernel used to be in reverse-order, and TFLite
// arranged the begins and sizes vectors accordingly. This macro incorporates
// the needed reversing.
#define TF_LITE_SLICE(data_type, kernel_type) \
{ \
TF_LITE_ENSURE_EQ(context, begins.size(), 4); \
TF_LITE_ENSURE_EQ(context, sizes.size(), 4); \
tflite::SliceParams op_params; \
op_params.begin_count = 4; \
op_params.size_count = 4; \
for (int i = 0; i < 4; ++i) { \
op_params.begin[i] = begins[i]; \
op_params.size[i] = sizes[i]; \
} \
\
if (kernel_type == kGenericOptimized) { \
optimized_ops::Slice<data_type>(op_params, GetTensorShape(input), input, \
GetTensorShape(output), output); \
} else { \
reference_ops::Slice<data_type>(op_params, GetTensorShape(input), input, \
GetTensorShape(output), output); \
} \
}
switch (input->type) {
case kTfLiteFloat32:
TF_LITE_SLICE(float, kernel_type);
break;
case kTfLiteInt32:
TF_LITE_SLICE(int32_t, kernel_type);
break;
case kTfLiteInt64:
TF_LITE_SLICE(int64_t, kernel_type);
break;
case kTfLiteInt8:
TF_LITE_SLICE(int8_t, kernel_type);
break;
case kTfLiteInt16:
TF_LITE_SLICE(int16_t, kernel_type);
break;
case kTfLiteUInt8:
TF_LITE_SLICE(uint8_t, kernel_type);
break;
case kTfLiteBool:
TF_LITE_SLICE(bool, kernel_type);
break;
case kTfLiteString:
TF_LITE_SLICE(string, kernel_type);
break;
default:
context->ReportError(
context, "Type %d is currently not supported by Slice.", input->type);
return kTfLiteError;
}
#undef TF_LITE_SLICE
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* cond_tensor =
GetInput(context, node, kInputConditionTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (cond_tensor->type != kTfLiteBool) {
context->ReportError(context,
"Condition tensor must be of type bool, but saw '%s'.",
TfLiteTypeGetName(cond_tensor->type));
return kTfLiteError;
}
// As output will be a 2D tensor of indices, use int64 to be consistent with
// tensorflow.
output->type = kTfLiteInt64;
// Exit early if cond is a non-const tensor. Set output tensor to dynamic so
// output size can be determined in Eval.
if (!IsConstantTensor(cond_tensor)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, cond_tensor, output);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteSkipGramParams*>(node->builtin_data);
// Split sentence to words.
std::vector<StringRef> words;
tflite::StringRef strref = tflite::GetString(GetInput(context, node, 0), 0);
int prev_idx = 0;
for (int i = 1; i < strref.len; i++) {
if (isspace(*(strref.str + i))) {
if (i > prev_idx && !isspace(*(strref.str + prev_idx))) {
words.push_back({strref.str + prev_idx, i - prev_idx});
}
prev_idx = i + 1;
}
}
if (strref.len > prev_idx) {
words.push_back({strref.str + prev_idx, strref.len - prev_idx});
}
// Generate n-grams recursively.
tflite::DynamicBuffer buf;
if (words.size() < params->ngram_size) {
buf.WriteToTensorAsVector(GetOutput(context, node, 0));
return kTfLiteOk;
}
// Stack stores the index of word used to generate ngram.
// The size of stack is the size of ngram.
std::vector<int> stack(params->ngram_size, 0);
// Stack index that indicates which depth the recursion is operating at.
int stack_idx = 1;
int num_words = words.size();
while (stack_idx >= 0) {
if (ShouldStepInRecursion(params, stack, stack_idx, num_words)) {
// When current depth can fill with a new word
// and the new word is within the max range to skip,
// fill this word to stack, recurse into next depth.
stack[stack_idx]++;
stack_idx++;
if (stack_idx < params->ngram_size) {
stack[stack_idx] = stack[stack_idx - 1];
}
} else {
if (ShouldIncludeCurrentNgram(params, stack_idx)) {
// Add n-gram to tensor buffer when the stack has filled with enough
// words to generate the ngram.
std::vector<StringRef> gram(stack_idx);
for (int i = 0; i < stack_idx; i++) {
gram[i] = words[stack[i]];
}
buf.AddJoinedString(gram, ' ');
}
// When current depth cannot fill with a valid new word,
// and not in last depth to generate ngram,
// step back to previous depth to iterate to next possible word.
stack_idx--;
}
}
buf.WriteToTensorAsVector(GetOutput(context, node, 0));
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (input->type) {
case kTfLiteInt64:
reference_ops::Negate(
GetTensorShape(input), GetTensorData<int64_t>(input),
GetTensorShape(output), GetTensorData<int64_t>(output));
break;
case kTfLiteInt32:
reference_ops::Negate(
GetTensorShape(input), GetTensorData<int32_t>(input),
GetTensorShape(output), GetTensorData<int32_t>(output));
break;
case kTfLiteFloat32:
reference_ops::Negate(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output),
GetTensorData<float>(output));
break;
default:
context->ReportError(
context,
"Neg only currently supports int64, int32, and float32, got %d.",
input->type);
return kTfLiteError;
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* lookup = GetInput(context, node, 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);
TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);
const TfLiteTensor* value = GetInput(context, node, 1);
TF_LITE_ENSURE(context, NumDimensions(value) >= 2);
TfLiteTensor* output = GetOutput(context, node, 0);
TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));
outputSize->data[0] = SizeOfDimension(lookup, 0);
outputSize->data[1] = SizeOfDimension(value, 1);
for (int i = 2; i < NumDimensions(value); i++) {
outputSize->data[i] = SizeOfDimension(value, i);
}
return context->ResizeTensor(context, output, outputSize);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);
const TfLiteTensor* lookup = GetInput(context, node, 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);
TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);
const TfLiteTensor* key = GetInput(context, node, 1);
TF_LITE_ENSURE_EQ(context, NumDimensions(key), 1);
TF_LITE_ENSURE_EQ(context, key->type, kTfLiteInt32);
const TfLiteTensor* value = GetInput(context, node, 2);
TF_LITE_ENSURE(context, NumDimensions(value) >= 1);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(key, 0),
SizeOfDimension(value, 0));
if (value->type == kTfLiteString) {
TF_LITE_ENSURE_EQ(context, NumDimensions(value), 1);
}
TfLiteTensor* hits = GetOutput(context, node, 1);
TF_LITE_ENSURE_EQ(context, hits->type, kTfLiteUInt8);
TfLiteIntArray* hitSize = TfLiteIntArrayCreate(1);
hitSize->data[0] = SizeOfDimension(lookup, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE_EQ(context, value->type, output->type);
TfLiteStatus status = kTfLiteOk;
if (output->type != kTfLiteString) {
TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));
outputSize->data[0] = SizeOfDimension(lookup, 0);
for (int i = 1; i < NumDimensions(value); i++) {
outputSize->data[i] = SizeOfDimension(value, i);
}
status = context->ResizeTensor(context, output, outputSize);
}
if (context->ResizeTensor(context, hits, hitSize) != kTfLiteOk) {
status = kTfLiteError;
}
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: inline TfLiteStatus EvalImpl(TfLiteContext* context, TfLiteNode* node,
std::function<T(T)> func,
TfLiteType expected_type) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, expected_type);
const int64_t num_elements = NumElements(input);
const T* in_data = GetTensorData<T>(input);
T* out_data = GetTensorData<T>(output);
for (int64_t i = 0; i < num_elements; ++i) {
out_data[i] = func(in_data[i]);
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus HardSwishEval(TfLiteContext* context, TfLiteNode* node) {
HardSwishData* data = static_cast<HardSwishData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
switch (input->type) {
case kTfLiteFloat32: {
if (kernel_type == kReference) {
reference_ops::HardSwish(
GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
} else {
optimized_ops::HardSwish(
GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
}
return kTfLiteOk;
} break;
case kTfLiteUInt8: {
HardSwishParams& params = data->params;
if (kernel_type == kReference) {
reference_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<uint8_t>(input),
GetTensorShape(output), GetTensorData<uint8_t>(output));
} else {
optimized_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<uint8_t>(input),
GetTensorShape(output), GetTensorData<uint8_t>(output));
}
return kTfLiteOk;
} break;
case kTfLiteInt8: {
HardSwishParams& params = data->params;
if (kernel_type == kReference) {
reference_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<int8_t>(input),
GetTensorShape(output), GetTensorData<int8_t>(output));
} else {
optimized_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<int8_t>(input),
GetTensorShape(output), GetTensorData<int8_t>(output));
}
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(
context,
"Only float32, uint8 and int8 are supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
output->type = input2->type;
const bool requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
// 8bit -> 8bit general quantized path, with general rescalings
// as well as, int16 -> int16 with general rescalings
bool pot_scale_int16 = true;
bool input1_scale_is_pot = false;
bool input2_scale_is_pot = false;
bool output_scale_is_pot = false;
int input1_scale_log2_rounded{0};
int input2_scale_log2_rounded{0};
int output_scale_log2_rounded{0};
if (input1->type == kTfLiteInt16 && input2->type == kTfLiteInt16 &&
output->type == kTfLiteInt16) {
// In case of 16-bit, there are two implementation:
// the scale parameter is a general number
// the scale parameter is POT and
// zero_point is zero for inputs/output.
pot_scale_int16 = (input1->params.zero_point == 0) &&
(input2->params.zero_point == 0) &&
(output->params.zero_point == 0);
input1_scale_is_pot =
CheckedLog2(input1->params.scale, &input1_scale_log2_rounded);
input2_scale_is_pot =
CheckedLog2(input2->params.scale, &input2_scale_log2_rounded);
output_scale_is_pot =
CheckedLog2(output->params.scale, &output_scale_log2_rounded);
pot_scale_int16 &=
input1_scale_is_pot && input2_scale_is_pot && output_scale_is_pot;
}
data->pot_scale_int16 = pot_scale_int16;
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||
!pot_scale_int16) {
// 8bit -> 8bit general quantized path, with general rescalings
// as well as, 16bit -> 16bit with general rescalings
data->input1_offset = -input1->params.zero_point;
data->input2_offset = -input2->params.zero_point;
data->output_offset = output->params.zero_point;
// The shift is set to 15 for 16-bit and 20 in case of 8-bit, accordingly.
// In case of 16-bit we have 65535 << 15 which is less than 1 << 31,
// therefore the addition will still fit in a 32 bit accumulator.
data->left_shift = !pot_scale_int16 ? 15 : 20;
const double twice_max_input_scale =
2 * std::max(input1->params.scale, input2->params.scale);
const double real_input1_multiplier =
input1->params.scale / twice_max_input_scale;
const double real_input2_multiplier =
input2->params.scale / twice_max_input_scale;
const double real_output_multiplier =
twice_max_input_scale /
((1 << data->left_shift) * output->params.scale);
QuantizeMultiplierSmallerThanOneExp(
real_input1_multiplier, &data->input1_multiplier, &data->input1_shift);
QuantizeMultiplierSmallerThanOneExp(
real_input2_multiplier, &data->input2_multiplier, &data->input2_shift);
QuantizeMultiplierSmallerThanOneExp(
real_output_multiplier, &data->output_multiplier, &data->output_shift);
TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
context, params->activation, output, &data->output_activation_min,
&data->output_activation_max));
} else if (output->type == kTfLiteInt16) {
// 16bit -> 16bit special quantized path, supporting only a rather
// narrow case of quantization parameters: zero_points must all be 0
// ("symmetric quantization") and scales must be power-of-two (which
// we abbreviate as "POT" below). The intended use case for this path
// is in LSTM cells, where, due to the constraints of implementing
// some of the math in these LSTM cells in fixed-point arithmetic,
// we need to have such symmetric, power-of-two quantization
// (Fixed-point formats are inherently symmetric, power-of-two).
TF_LITE_ENSURE_EQ(context, input1->params.zero_point, 0);
TF_LITE_ENSURE_EQ(context, input2->params.zero_point, 0);
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);
TF_LITE_ENSURE(context, input1_scale_is_pot);
TF_LITE_ENSURE(context, input2_scale_is_pot);
TF_LITE_ENSURE(context, output_scale_is_pot);
data->input1_shift = input1_scale_log2_rounded - output_scale_log2_rounded;
data->input2_shift = input2_scale_log2_rounded - output_scale_log2_rounded;
// Shifting of one input is supported. The graph quantization should ensure
// that the other input matches the output.
TF_LITE_ENSURE(context, data->input1_shift == 0 || data->input2_shift == 0);
TF_LITE_ENSURE(context, data->input1_shift <= 0);
TF_LITE_ENSURE(context, data->input2_shift <= 0);
TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
context, params->activation, output, &data->output_activation_min,
&data->output_activation_max));
}
return context->ResizeTensor(context, output, output_size);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
// Retrieve tensors (All should be allocated by now)
const TfLiteTensor* output_shape =
GetInput(context, node, kOutputShapeTensor);
const TfLiteTensor* weights = GetInput(context, node, kWeightsTensor);
const TfLiteTensor* input = GetInput(context, node, kDataInputTensor);
const TfLiteTensor* bias =
(NumInputs(node) == 4)
? GetOptionalInputTensor(context, node, kBiasTensor)
: nullptr;
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* col2im = data->has_col2im
? GetTemporary(context, node, data->col2im_index)
: nullptr;
TfLiteTensor* transposed_weights =
data->weights_are_transposed
? GetTemporary(context, node, data->transposed_weights_index)
: nullptr;
const auto* params =
reinterpret_cast<TfLiteTransposeConvParams*>(node->builtin_data);
// Resize any deferred dynamic tensors
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));
}
if (data->has_col2im && IsDynamicTensor(col2im)) {
TF_LITE_ENSURE_OK(context, ResizeCol2ImTensor(context, output_shape,
weights, input, col2im));
}
// Get height and width of the output image.
const int width = SizeOfDimension(output, 2);
const int height = SizeOfDimension(output, 1);
const int filter_width = SizeOfDimension(weights, 2);
const int filter_height = SizeOfDimension(weights, 1);
int unused_output_height, unused_output_width;
data->padding = ComputePaddingHeightWidth(
params->stride_height, params->stride_width, 1, 1, height, width,
filter_height, filter_width, params->padding, &unused_output_height,
&unused_output_width);
// Currently support float32, uint8, int8, int16.
switch (input->type) {
case kTfLiteFloat32: {
// Only for GenericOptimized path, we use transposed weights.
if (data->weights_are_transposed) {
if (!IsConstantTensor(weights)) {
ResizeAndTransposeWeights(context, weights, transposed_weights);
}
}
EvalFloat<kernel_type>(context, params, data, input, weights, bias,
transposed_weights, col2im, output);
break;
}
case kTfLiteUInt8: {
TfLiteTensor* scratch_buffer =
GetTemporary(context, node, data->scratch_tensor_index);
if (IsDynamicTensor(scratch_buffer)) {
TF_LITE_ENSURE_OK(context,
ResizeTensor(context, output_shape, scratch_buffer));
}
if (data->weights_are_transposed) {
if (!IsConstantTensor(weights)) {
ResizeAndTransposeWeights(context, weights, transposed_weights);
}
}
EvalQuantized<kernel_type>(context, params, data, input, weights,
transposed_weights, bias, col2im, output,
scratch_buffer);
break;
}
case kTfLiteInt8: {
TfLiteTensor* scratch_buffer =
GetTemporary(context, node, data->scratch_tensor_index);
if (IsDynamicTensor(scratch_buffer)) {
TF_LITE_ENSURE_OK(context,
ResizeTensor(context, output_shape, scratch_buffer));
}
if (data->weights_are_transposed && !IsConstantTensor(weights)) {
ResizeAndTransposeWeights(context, weights, transposed_weights);
}
EvalQuantizedPerChannel<kernel_type>(context, params, data, input,
weights, transposed_weights, bias,
col2im, output, scratch_buffer);
break;
}
case kTfLiteInt16: {
TfLiteTensor* scratch_buffer =
GetTemporary(context, node, data->scratch_tensor_index);
if (IsDynamicTensor(scratch_buffer)) {
TF_LITE_ENSURE_OK(context,
ResizeTensor(context, output_shape, scratch_buffer));
}
if (data->weights_are_transposed && !IsConstantTensor(weights)) {
ResizeAndTransposeWeights(context, weights, transposed_weights);
}
EvalQuantizedPerChannel16x8(context, params, data, input, weights,
transposed_weights, bias, col2im, output,
scratch_buffer);
break;
}
default:
context->ReportError(context, "Type '%s' is not currently supported.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const auto* params = reinterpret_cast<TfLiteSVDFParams*>(node->builtin_data);
OpData* op_data = reinterpret_cast<OpData*>(node->user_data);
int scratch_tensor_index = op_data->scratch_tensor_index;
// Check we have all the inputs and outputs we need.
TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);
TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* weights_feature =
GetInput(context, node, kWeightsFeatureTensor);
const TfLiteTensor* weights_time =
GetInput(context, node, kWeightsTimeTensor);
TF_LITE_ENSURE(context,
input->type == kTfLiteFloat32 || input->type == kTfLiteInt8);
// Check all the parameters of tensor match within themselves and match the
// input configuration.
const int rank = params->rank;
const int batch_size = input->dims->data[0];
const int num_filters = weights_feature->dims->data[0];
TF_LITE_ENSURE_EQ(context, num_filters % rank, 0);
const int num_units = num_filters / rank;
const int memory_size = weights_time->dims->data[1];
TF_LITE_ENSURE_EQ(context, input->dims->data[1],
weights_feature->dims->data[1]);
TF_LITE_ENSURE_EQ(context, weights_time->dims->data[0], num_filters);
const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
if (bias) {
TF_LITE_ENSURE_EQ(context, bias->dims->data[0], num_units);
}
const TfLiteTensor* state = GetInput(context, node, kStateTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
// Check the shape of input state tensors.
TF_LITE_ENSURE_EQ(context, NumDimensions(state), 2);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 0), batch_size);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(state, 1),
memory_size * num_filters);
// Resize output.
TfLiteIntArray* output_size_array = TfLiteIntArrayCreate(2);
output_size_array->data[0] = batch_size;
output_size_array->data[1] = num_units;
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, output, output_size_array));
// The weights are of consistent type, so it suffices to check one.
const bool is_hybrid_op = IsHybridOp(input, weights_feature);
const bool is_full_integer = input->type == kTfLiteInt8;
// Resize scratch.
TfLiteIntArrayFree(node->temporaries);
if (is_hybrid_op) {
node->temporaries = TfLiteIntArrayCreate(6);
} else if (is_full_integer) {
node->temporaries = TfLiteIntArrayCreate(2);
} else {
node->temporaries = TfLiteIntArrayCreate(1);
}
node->temporaries->data[0] = scratch_tensor_index;
TfLiteIntArray* scratch_size_array = TfLiteIntArrayCreate(2);
scratch_size_array->data[0] = batch_size;
scratch_size_array->data[1] = num_filters;
TfLiteTensor* scratch_tensor = GetTemporary(context, node, /*index=*/0);
// The scratch buffer is of type int32 for full integer svdf and it's of type
// float32 for hybrid and float case.
if (is_full_integer) {
scratch_tensor->type = kTfLiteInt32;
} else {
scratch_tensor->type = kTfLiteFloat32;
}
scratch_tensor->allocation_type = kTfLiteArenaRw;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scratch_tensor,
scratch_size_array));
if (is_hybrid_op) {
op_data->compute_row_sums = true;
// Tell interpreter to allocate temporary tensors to store quantized values
// of input tensors.
node->temporaries->data[1] = scratch_tensor_index + 1;
TfLiteTensor* input_quantized = GetTemporary(context, node, /*index=*/1);
input_quantized->type = weights_feature->type;
input_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {
TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,
input_quantized_size));
}
// Tell interpreter to allocate temporary tensors to store scaling factors.
node->temporaries->data[2] = scratch_tensor_index + 2;
TfLiteTensor* scaling_factors = GetTemporary(context, node, /*index=*/2);
scaling_factors->type = kTfLiteFloat32;
scaling_factors->allocation_type = kTfLiteArenaRw;
int scaling_dims[1] = {batch_size};
if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {
TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);
scaling_factors_size->data[0] = batch_size;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,
scaling_factors_size));
}
// Used to store dequantized weights_time matrix for hybrid computation of
// matmul(state, weights_time), which occurs in floating point.
node->temporaries->data[3] = scratch_tensor_index + 3;
TfLiteTensor* float_weights_time = GetTemporary(context, node, /*index=*/3);
float_weights_time->type = kTfLiteFloat32;
// Persistent so that we can compute the dequantized weights only once.
float_weights_time->allocation_type = kTfLiteArenaRwPersistent;
if (!TfLiteIntArrayEqual(float_weights_time->dims, weights_time->dims)) {
TfLiteIntArray* float_weights_time_size =
TfLiteIntArrayCopy(weights_time->dims);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, float_weights_time,
float_weights_time_size));
}
node->temporaries->data[4] = scratch_tensor_index + 4;
TfLiteTensor* zero_points = GetTemporary(context, node, /*index=*/4);
zero_points->type = kTfLiteFloat32;
zero_points->allocation_type = kTfLiteArenaRw;
int zero_points_dims[1] = {batch_size};
if (!TfLiteIntArrayEqualsArray(zero_points->dims, 1, zero_points_dims)) {
TfLiteIntArray* zero_points_size = TfLiteIntArrayCreate(1);
zero_points_size->data[0] = zero_points_dims[0];
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, zero_points,
zero_points_size));
}
node->temporaries->data[5] = scratch_tensor_index + 5;
TfLiteTensor* row_sums = GetTemporary(context, node, /*index=*/5);
row_sums->type = kTfLiteFloat32;
row_sums->allocation_type = kTfLiteArenaRwPersistent;
int row_sums_dims[1] = {num_filters};
if (!TfLiteIntArrayEqualsArray(row_sums->dims, 1, row_sums_dims)) {
TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(1);
row_sums_size->data[0] = row_sums_dims[0];
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, row_sums, row_sums_size));
}
}
if (is_full_integer) {
// Allocated one extra tensor.
TfLiteIntArray* output_temp_size_array = TfLiteIntArrayCreate(2);
output_temp_size_array->data[0] = num_units;
output_temp_size_array->data[1] = batch_size;
node->temporaries->data[1] = scratch_tensor_index + 1;
TfLiteTensor* output_temp = GetTemporary(context, node, /*index=*/1);
output_temp->type = kTfLiteInt32;
output_temp->allocation_type = kTfLiteArenaRw;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_temp,
output_temp_size_array));
// Calculate effective scales.
auto* input_params =
reinterpret_cast<TfLiteAffineQuantization*>(input->quantization.params);
auto* weights_feature_params = reinterpret_cast<TfLiteAffineQuantization*>(
weights_feature->quantization.params);
auto* state_params =
reinterpret_cast<TfLiteAffineQuantization*>(state->quantization.params);
auto* weight_time_params = reinterpret_cast<TfLiteAffineQuantization*>(
weights_time->quantization.params);
auto* output_params = reinterpret_cast<TfLiteAffineQuantization*>(
output->quantization.params);
const double effective_scale_1 = input_params->scale->data[0] *
weights_feature_params->scale->data[0] /
state_params->scale->data[0];
const double effective_scale_2 = state_params->scale->data[0] *
weight_time_params->scale->data[0] /
output_params->scale->data[0];
QuantizeMultiplier(effective_scale_1, &op_data->effective_scale_1_a,
&op_data->effective_scale_1_b);
QuantizeMultiplier(effective_scale_2, &op_data->effective_scale_2_a,
&op_data->effective_scale_2_b);
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
bool has_bias = NumInputs(node) == 4;
// Sanity checks on op
TF_LITE_ENSURE(context, has_bias || NumInputs(node) == 3);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Retrieve tensors
const TfLiteTensor* output_shape =
GetInput(context, node, kOutputShapeTensor);
const TfLiteTensor* weights = GetInput(context, node, kWeightsTensor);
const TfLiteTensor* input = GetInput(context, node, kDataInputTensor);
const TfLiteTensor* bias = nullptr;
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
// Tensor sanity checks
TF_LITE_ENSURE_EQ(context, NumDimensions(output_shape), 1);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);
TF_LITE_ENSURE_EQ(context, NumDimensions(weights), 4);
TF_LITE_ENSURE(context,
input->type == kTfLiteFloat32 || input->type == kTfLiteUInt8 ||
input->type == kTfLiteInt8 || input->type == kTfLiteInt16);
if (has_bias) {
bias = GetOptionalInputTensor(context, node, kBiasTensor);
if (bias) {
if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {
TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);
if (input->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);
}
} else if (input->type == kTfLiteInt16) {
TF_LITE_ENSURE_EQ(context, bias->type, kTfLiteInt64);
TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);
} else {
TF_LITE_ENSURE_TYPES_EQ(context, bias->type, input->type);
}
TF_LITE_ENSURE_EQ(context, NumElements(bias),
SizeOfDimension(weights, 0));
}
}
if (input->type == kTfLiteInt16) {
TF_LITE_ENSURE_EQ(context, weights->type, kTfLiteInt8);
TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);
} else {
TF_LITE_ENSURE_TYPES_EQ(context, weights->type, input->type);
}
TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);
// Ensure that weights and inputs have the same channel dimension.
// Note: TOCO will reorder weights in the following format: OHWI.
TF_LITE_ENSURE_EQ(context, SizeOfDimension(input, 3),
SizeOfDimension(weights, 3));
// Allocate col2Im, transposed_weights & scratch Tensor.
TF_LITE_ENSURE_STATUS(AllocateTemporaryTensorsIfRequired<kernel_type>(
context, input->type, weights->type, node));
OpData* user_data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* col2im = nullptr;
if (data->has_col2im) {
node->temporaries->data[data->col2im_index] = data->col2im_id;
col2im = GetTemporary(context, node, user_data->col2im_index);
}
if (!IsConstantTensor(output_shape)) {
// Defer resizing until Eval().
SetTensorToDynamic(output);
if (data->has_col2im) {
SetTensorToDynamic(col2im);
}
} else {
TF_LITE_ENSURE_STATUS(ResizeTensor(context, output_shape, output));
if (data->has_col2im) {
TF_LITE_ENSURE_STATUS(
ResizeCol2ImTensor(context, output_shape, weights, input, col2im));
}
}
if (data->weights_are_transposed) {
node->temporaries->data[data->transposed_weights_index] =
data->transposed_weights_id;
TfLiteTensor* transposed_weights =
GetTemporary(context, node, user_data->transposed_weights_index);
if (!IsConstantTensor(weights)) {
SetTensorToDynamic(transposed_weights);
} else {
ResizeAndTransposeWeights(context, weights, transposed_weights);
}
}
if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8 ||
input->type == kTfLiteInt16) {
node->temporaries->data[data->scratch_tensor_index] =
data->scratch_tensor_id;
TfLiteTensor* scratch_buffer =
GetTemporary(context, node, data->scratch_tensor_index);
if (input->type == kTfLiteInt16) {
scratch_buffer->type = kTfLiteInt64;
} else {
scratch_buffer->type = kTfLiteInt32;
}
scratch_buffer->allocation_type = kTfLiteDynamic;
if (!IsConstantTensor(output_shape)) {
SetTensorToDynamic(scratch_buffer);
} else {
TF_LITE_ENSURE_STATUS(
ResizeTensor(context, output_shape, scratch_buffer));
}
TF_LITE_ENSURE_EQ(context, weights->quantization.type,
kTfLiteAffineQuantization);
const auto* affine_quantization =
reinterpret_cast<TfLiteAffineQuantization*>(
weights->quantization.params);
TF_LITE_ENSURE(context, affine_quantization);
TF_LITE_ENSURE(context, affine_quantization->scale);
const int number_channel = affine_quantization->scale->size;
data->per_channel_output_multiplier.resize(number_channel);
data->per_channel_output_shift.resize(number_channel);
TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(
context, input, weights, bias, output, kTfLiteActNone,
&data->output_multiplier, &data->output_shift,
&data->output_activation_min, &data->output_activation_max,
data->per_channel_output_multiplier.data(),
data->per_channel_output_shift.data()));
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node, bool is_arg_max) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* axis = GetInput(context, node, kAxis);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_STATUS(ResizeOutput(context, input, axis, output));
}
#define TF_LITE_ARG_MIN_MAX(data_type, axis_type, output_type) \
optimized_ops::ArgMinMax( \
GetTensorShape(input), GetTensorData<data_type>(input), \
GetTensorData<axis_type>(axis), GetTensorShape(output), \
GetTensorData<output_type>(output), \
GetComparefunction<data_type>(is_arg_max))
if (axis->type == kTfLiteInt32) {
switch (output->type) {
case kTfLiteInt32: {
switch (input->type) {
case kTfLiteFloat32:
TF_LITE_ARG_MIN_MAX(float, int32_t, int32_t);
break;
case kTfLiteUInt8:
TF_LITE_ARG_MIN_MAX(uint8_t, int32_t, int32_t);
break;
case kTfLiteInt8:
TF_LITE_ARG_MIN_MAX(int8_t, int32_t, int32_t);
break;
case kTfLiteInt32:
TF_LITE_ARG_MIN_MAX(int32_t, int32_t, int32_t);
break;
default:
context->ReportError(context,
"Only float32, uint8, int8 and int32 are "
"supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} break;
case kTfLiteInt64: {
switch (input->type) {
case kTfLiteFloat32:
TF_LITE_ARG_MIN_MAX(float, int32_t, int64_t);
break;
case kTfLiteUInt8:
TF_LITE_ARG_MIN_MAX(uint8_t, int32_t, int64_t);
break;
case kTfLiteInt8:
TF_LITE_ARG_MIN_MAX(int8_t, int32_t, int64_t);
break;
case kTfLiteInt32:
TF_LITE_ARG_MIN_MAX(int32_t, int32_t, int64_t);
break;
default:
context->ReportError(context,
"Only float32, uint8, int8 and int32 are "
"supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} break;
default:
context->ReportError(
context, "Only int32 and int64 are supported currently, got %s.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
} else {
switch (output->type) {
case kTfLiteInt32: {
switch (input->type) {
case kTfLiteFloat32:
TF_LITE_ARG_MIN_MAX(float, int64_t, int32_t);
break;
case kTfLiteUInt8:
TF_LITE_ARG_MIN_MAX(uint8_t, int64_t, int32_t);
break;
case kTfLiteInt8:
TF_LITE_ARG_MIN_MAX(int8_t, int64_t, int32_t);
break;
case kTfLiteInt32:
TF_LITE_ARG_MIN_MAX(int32_t, int64_t, int32_t);
break;
default:
context->ReportError(context,
"Only float32, uint8, int8 and int32 are "
"supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} break;
case kTfLiteInt64: {
switch (input->type) {
case kTfLiteFloat32:
TF_LITE_ARG_MIN_MAX(float, int64_t, int64_t);
break;
case kTfLiteUInt8:
TF_LITE_ARG_MIN_MAX(uint8_t, int64_t, int64_t);
break;
case kTfLiteInt8:
TF_LITE_ARG_MIN_MAX(int8_t, int64_t, int64_t);
break;
case kTfLiteInt32:
TF_LITE_ARG_MIN_MAX(int32_t, int64_t, int64_t);
break;
default:
context->ReportError(context,
"Only float32, uint8, int8 and int32 are "
"supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} break;
default:
context->ReportError(
context, "Only int32 and int64 are supported currently, got %s.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
#undef TF_LITE_ARG_MIN_MAX
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TfLiteTensor* output = GetOutput(context, node, 0);
const TfLiteTensor* input = GetInput(context, node, 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
int batches = input->dims->data[0];
int height = input->dims->data[1];
int width = input->dims->data[2];
int channels_out = input->dims->data[3];
// Matching GetWindowedOutputSize in TensorFlow.
auto padding = params->padding;
int out_width, out_height;
data->padding = ComputePaddingHeightWidth(
params->stride_height, params->stride_width, 1, 1, height, width,
params->filter_height, params->filter_width, padding, &out_height,
&out_width);
if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {
if (pool_type == kAverage || pool_type == kMax) {
TFLITE_DCHECK_LE(std::abs(input->params.scale - output->params.scale),
1.0e-6);
TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point);
}
if (pool_type == kL2) {
// We currently don't have a quantized implementation of L2Pool
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
}
}
TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
output_size->data[0] = batches;
output_size->data[1] = out_height;
output_size->data[2] = out_width;
output_size->data[3] = channels_out;
return context->ResizeTensor(context, output, output_size);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus LogicalImpl(TfLiteContext* context, TfLiteNode* node,
bool (*func)(bool, bool)) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (data->requires_broadcast) {
reference_ops::BroadcastBinaryFunction4DSlow<bool, bool, bool>(
GetTensorShape(input1), GetTensorData<bool>(input1),
GetTensorShape(input2), GetTensorData<bool>(input2),
GetTensorShape(output), GetTensorData<bool>(output), func);
} else {
reference_ops::BinaryFunction<bool, bool, bool>(
GetTensorShape(input1), GetTensorData<bool>(input1),
GetTensorShape(input2), GetTensorData<bool>(input2),
GetTensorShape(output), GetTensorData<bool>(output), func);
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
OpData* op_data = reinterpret_cast<OpData*>(node->user_data);
int num_inputs = node->inputs->size;
// The number of outputs should be the same as number of inputs.
TF_LITE_ENSURE_EQ(context, node->outputs->size, num_inputs);
// Check subgraph indices and get subgraphs.
Subgraph* this_subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto* subgraphs = this_subgraph->GetSubgraphs();
TF_LITE_ENSURE(context, op_data->cond_subgraph_index < subgraphs->size());
TF_LITE_ENSURE(context, op_data->body_subgraph_index < subgraphs->size());
Subgraph* cond_subgraph = (*subgraphs)[op_data->cond_subgraph_index].get();
Subgraph* body_subgraph = (*subgraphs)[op_data->body_subgraph_index].get();
// Check input & output count of the condition subgraph.
TF_LITE_ENSURE_EQ(context, cond_subgraph->inputs().size(), num_inputs);
TF_LITE_ENSURE_EQ(context, cond_subgraph->outputs().size(), 1);
// Check input & output count of the body subgraph.
TF_LITE_ENSURE_EQ(context, body_subgraph->inputs().size(), num_inputs);
TF_LITE_ENSURE_EQ(context, body_subgraph->outputs().size(), num_inputs);
// Prepare and check the condition subgraph.
TF_LITE_ENSURE_OK(
context, CopyTensorsShapeAndType(
context, this_subgraph, TfLiteIntArrayView(node->inputs),
cond_subgraph, cond_subgraph->inputs(), true));
TF_LITE_ENSURE_OK(context, cond_subgraph->AllocateTensors());
TfLiteTensor* cond_output =
cond_subgraph->tensor(cond_subgraph->outputs()[0]);
// TODO(ycling): Handle the case the cond subgraph has dynamic tensor outputs.
// This should rarely happens. In most cases the output is static with shape
// [1]. However theoretically intermediate tensors in the cond subgraph
// can be dynamic.
if (IsDynamicTensor(cond_output)) {
op_data->cond_has_dynamic_output_tensors = true;
} else {
TF_LITE_ENSURE_STATUS(CheckCondOutput(context, cond_output));
}
// Prepare and check the body subgraph.
TF_LITE_ENSURE_OK(
context, CopyTensorsShapeAndType(
context, this_subgraph, TfLiteIntArrayView(node->inputs),
body_subgraph, body_subgraph->inputs(), true));
TF_LITE_ENSURE_OK(context, body_subgraph->AllocateTensors());
if (body_subgraph->HasDynamicTensors()) {
op_data->body_has_dynamic_output_tensors = true;
} else {
for (int i = 0; i < num_inputs; ++i) {
TfLiteTensor* body_input =
body_subgraph->tensor(body_subgraph->inputs()[i]);
TfLiteTensor* body_output =
body_subgraph->tensor(body_subgraph->outputs()[i]);
TF_LITE_ENSURE_TYPES_EQ(context, body_input->type, body_output->type);
// TODO(ycling): Support dynamic sized body subgraph.
TF_LITE_ENSURE(context, !IsDynamicTensor(body_output));
if (!TfLiteIntArrayEqual(body_input->dims, body_output->dims)) {
// If the output shape of the body subgraph is static w.r.t. a fixed
// input size, but it's different from input size, it's still considered
// dynamic. For example: If a subgraph keeps padding its input with a
// fixed padding, the output shape is static w.r.t the input shape and
// padding, but running it in a loop will keep bloating the tensor.
op_data->body_has_dynamic_output_tensors = true;
break;
}
}
}
for (int i = 0; i < num_inputs; ++i) {
TfLiteTensor* output = GetOutput(context, node, i);
if (op_data->body_has_dynamic_output_tensors) {
SetTensorToDynamic(output);
} else {
TfLiteTensor* body_output =
body_subgraph->tensor(body_subgraph->outputs()[i]);
TfLiteIntArray* output_size = TfLiteIntArrayCopy(body_output->dims);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, output, output_size));
}
}
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
// TODO(ahentz): these two checks would make the new implementation
// incompatible with some existing models, where params is not specified. It
// is OK not to have them because toco would have set input and output types
// to match the parameters.
// auto* params = reinterpret_cast<TfLiteCastParams*>(node->builtin_data);
// TF_LITE_ENSURE_EQ(context, input->type, params->in_data_type);
// TF_LITE_ENSURE_EQ(context, output->type, params->out_data_type);
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
// There are two ways in which the 'output' can be made dynamic: it could be
// a string tensor, or its shape cannot be calculated during Prepare(). In
// either case, we now have all the information to calculate its shape.
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
}
// Note that string tensors are always "dynamic" in the sense that their size
// is not known until we have all the content. This applies even when their
// shape is known ahead of time. As a result, a string tensor is never given
// any memory by ResizeOutput(), and we need to do it manually here. Since
// reshape doesn't change the data, the output tensor needs exactly as many
// bytes as the input tensor.
if (output->type == kTfLiteString) {
auto bytes_required = input->bytes;
TfLiteTensorRealloc(bytes_required, output);
output->bytes = bytes_required;
}
memcpy(output->data.raw, input->data.raw, input->bytes);
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (input->type != kTfLiteFloat32) {
TF_LITE_UNSUPPORTED_TYPE(context, input->type, "Ceil");
}
optimized_ops::Ceil(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
return kTfLiteOk;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.
As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.
We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).
PiperOrigin-RevId: 332521299
Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
size_t offset, const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
ut64 abbr_code;
size_t i;
if (cu->hdr.length > debug_str_len) {
//avoid oob read
return NULL;
}
while (buf && buf < buf_end && buf >= obuf) {
if (cu->length && cu->capacity == cu->length) {
r_bin_dwarf_expand_cu (cu);
}
buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
if (abbr_code > da->length || !buf) {
return NULL;
}
r_bin_dwarf_init_die (&cu->dies[cu->length]);
if (!abbr_code) {
cu->dies[cu->length].abbrev_code = 0;
cu->length++;
buf++;
continue;
}
cu->dies[cu->length].abbrev_code = abbr_code;
cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
abbr_code += offset;
if (da->capacity < abbr_code) {
return NULL;
}
for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
r_bin_dwarf_expand_die (&cu->dies[cu->length]);
}
if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
break;
}
memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i]));
buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
&da->decls[abbr_code - 1].specs[i],
&cu->dies[cu->length].attr_values[i],
&cu->hdr, debug_str, debug_str_len);
if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
sdb_set (s, "DW_AT_comp_dir", name, 0);
}
cu->dies[cu->length].length++;
}
cu->length++;
}
return buf;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Fix #10465 - Avoid string on low addresses (workaround) for corrupted dwarf (#10478)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data,
krb5_kvno mkvno) {
struct berval **ret = NULL;
int currkvno;
int num_versions = 1;
int i, j, last;
krb5_error_code err = 0;
krb5_key_data *key_data;
if (n_key_data <= 0)
return NULL;
/* Make a shallow copy of the key data so we can alter it. */
key_data = k5calloc(n_key_data, sizeof(*key_data), &err);
if (key_data_in == NULL)
goto cleanup;
memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data));
/* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt
* field. For compatibility, always encode a salt field. */
for (i = 0; i < n_key_data; i++) {
if (key_data[i].key_data_ver == 1) {
key_data[i].key_data_ver = 2;
key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL;
key_data[i].key_data_length[1] = 0;
key_data[i].key_data_contents[1] = NULL;
}
}
/* Find the number of key versions */
for (i = 0; i < n_key_data - 1; i++)
if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno)
num_versions++;
ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *));
if (ret == NULL) {
err = ENOMEM;
goto cleanup;
}
for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) {
krb5_data *code;
if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) {
ret[j] = k5alloc(sizeof(struct berval), &err);
if (ret[j] == NULL)
goto cleanup;
err = asn1_encode_sequence_of_keys(key_data + last,
(krb5_int16)i - last + 1,
mkvno, &code);
if (err)
goto cleanup;
/*CHECK_NULL(ret[j]); */
ret[j]->bv_len = code->length;
ret[j]->bv_val = code->data;
free(code);
j++;
last = i + 1;
currkvno = key_data[i].key_data_kvno;
}
}
ret[num_versions] = NULL;
cleanup:
free(key_data);
if (err != 0) {
if (ret != NULL) {
for (i = 0; i <= num_versions; i++)
if (ret[i] != NULL)
free (ret[i]);
free (ret);
ret = NULL;
}
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fix LDAP key data segmentation [CVE-2014-4345]
For principal entries having keys with multiple kvnos (due to use of
-keepold), the LDAP KDB module makes an attempt to store all the keys
having the same kvno into a single krbPrincipalKey attribute value.
There is a fencepost error in the loop, causing currkvno to be set to
the just-processed value instead of the next kvno. As a result, the
second and all following groups of multiple keys by kvno are each
stored in two krbPrincipalKey attribute values. Fix the loop to use
the correct kvno value.
CVE-2014-4345:
In MIT krb5, when kadmind is configured to use LDAP for the KDC
database, an authenticated remote attacker can cause it to perform an
out-of-bounds write (buffer overrun) by performing multiple cpw
-keepold operations. An off-by-one error while copying key
information to the new database entry results in keys sharing a common
kvno being written to different array buckets, in an array whose size
is determined by the number of kvnos present. After sufficient
iterations, the extra writes extend past the end of the
(NULL-terminated) array. The NULL terminator is always written after
the end of the loop, so no out-of-bounds data is read, it is only
written.
Historically, it has been possible to convert an out-of-bounds write
into remote code execution in some cases, though the necessary
exploits must be tailored to the individual application and are
usually quite complicated. Depending on the allocated length of the
array, an out-of-bounds write may also cause a segmentation fault
and/or application crash.
CVSSv2 Vector: AV:N/AC:M/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C
[ghudson@mit.edu: clarified commit message]
[kaduk@mit.edu: CVE summary, CVSSv2 vector]
(cherry picked from commit 81c332e29f10887c6b9deb065f81ba259f4c7e03)
ticket: 7980
version_fixed: 1.12.2
status: resolved'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: local void process(char *path)
{
int method = -1; /* get_header() return value */
size_t len; /* length of base name (minus suffix) */
struct stat st; /* to get file type and mod time */
/* all compressed suffixes for decoding search, in length order */
static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz",
".zip", ".ZIP", ".tgz", NULL};
/* open input file with name in, descriptor ind -- set name and mtime */
if (path == NULL) {
strcpy(g.inf, "<stdin>");
g.ind = 0;
g.name = NULL;
g.mtime = g.headis & 2 ?
(fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0;
len = 0;
}
else {
/* set input file name (already set if recursed here) */
if (path != g.inf) {
strncpy(g.inf, path, sizeof(g.inf));
if (g.inf[sizeof(g.inf) - 1])
bail("name too long: ", path);
}
len = strlen(g.inf);
/* try to stat input file -- if not there and decoding, look for that
name with compressed suffixes */
if (lstat(g.inf, &st)) {
if (errno == ENOENT && (g.list || g.decode)) {
char **try = sufs;
do {
if (*try == NULL || len + strlen(*try) >= sizeof(g.inf))
break;
strcpy(g.inf + len, *try++);
errno = 0;
} while (lstat(g.inf, &st) && errno == ENOENT);
}
#ifdef EOVERFLOW
if (errno == EOVERFLOW || errno == EFBIG)
bail(g.inf,
" too large -- not compiled with large file support");
#endif
if (errno) {
g.inf[len] = 0;
complain("%s does not exist -- skipping", g.inf);
return;
}
len = strlen(g.inf);
}
/* only process regular files, but allow symbolic links if -f,
recurse into directory if -r */
if ((st.st_mode & S_IFMT) != S_IFREG &&
(st.st_mode & S_IFMT) != S_IFLNK &&
(st.st_mode & S_IFMT) != S_IFDIR) {
complain("%s is a special file or device -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) {
complain("%s is a symbolic link -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) {
complain("%s is a directory -- skipping", g.inf);
return;
}
/* recurse into directory (assumes Unix) */
if ((st.st_mode & S_IFMT) == S_IFDIR) {
char *roll, *item, *cut, *base, *bigger;
size_t len, hold;
DIR *here;
struct dirent *next;
/* accumulate list of entries (need to do this, since readdir()
behavior not defined if directory modified between calls) */
here = opendir(g.inf);
if (here == NULL)
return;
hold = 512;
roll = MALLOC(hold);
if (roll == NULL)
bail("not enough memory", "");
*roll = 0;
item = roll;
while ((next = readdir(here)) != NULL) {
if (next->d_name[0] == 0 ||
(next->d_name[0] == '.' && (next->d_name[1] == 0 ||
(next->d_name[1] == '.' && next->d_name[2] == 0))))
continue;
len = strlen(next->d_name) + 1;
if (item + len + 1 > roll + hold) {
do { /* make roll bigger */
hold <<= 1;
} while (item + len + 1 > roll + hold);
bigger = REALLOC(roll, hold);
if (bigger == NULL) {
FREE(roll);
bail("not enough memory", "");
}
item = bigger + (item - roll);
roll = bigger;
}
strcpy(item, next->d_name);
item += len;
*item = 0;
}
closedir(here);
/* run process() for each entry in the directory */
cut = base = g.inf + strlen(g.inf);
if (base > g.inf && base[-1] != (unsigned char)'/') {
if ((size_t)(base - g.inf) >= sizeof(g.inf))
bail("path too long", g.inf);
*base++ = '/';
}
item = roll;
while (*item) {
strncpy(base, item, sizeof(g.inf) - (base - g.inf));
if (g.inf[sizeof(g.inf) - 1]) {
strcpy(g.inf + (sizeof(g.inf) - 4), "...");
bail("path too long: ", g.inf);
}
process(g.inf);
item += strlen(item) + 1;
}
*cut = 0;
/* release list of entries */
FREE(roll);
return;
}
/* don't compress .gz (or provided suffix) files, unless -f */
if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) &&
strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) {
complain("%s ends with %s -- skipping", g.inf, g.sufx);
return;
}
/* create output file only if input file has compressed suffix */
if (g.decode == 1 && !g.pipeout && !g.list) {
int suf = compressed_suffix(g.inf);
if (suf == 0) {
complain("%s does not have compressed suffix -- skipping",
g.inf);
return;
}
len -= suf;
}
/* open input file */
g.ind = open(g.inf, O_RDONLY, 0);
if (g.ind < 0)
bail("read error on ", g.inf);
/* prepare gzip header information for compression */
g.name = g.headis & 1 ? justname(g.inf) : NULL;
g.mtime = g.headis & 2 ? st.st_mtime : 0;
}
SET_BINARY_MODE(g.ind);
/* if decoding or testing, try to read gzip header */
g.hname = NULL;
if (g.decode) {
in_init();
method = get_header(1);
if (method != 8 && method != 257 &&
/* gzip -cdf acts like cat on uncompressed input */
!(method == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)) {
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
if (method != -1)
complain(method < 0 ? "%s is not compressed -- skipping" :
"%s has unknown compression method -- skipping",
g.inf);
return;
}
/* if requested, test input file (possibly a special list) */
if (g.decode == 2) {
if (method == 8)
infchk();
else {
unlzw();
if (g.list) {
g.in_tot -= 3;
show_info(method, 0, g.out_tot, 0);
}
}
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
}
/* if requested, just list information about input file */
if (g.list) {
list_info();
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* create output file out, descriptor outd */
if (path == NULL || g.pipeout) {
/* write to stdout */
g.outf = MALLOC(strlen("<stdout>") + 1);
if (g.outf == NULL)
bail("not enough memory", "");
strcpy(g.outf, "<stdout>");
g.outd = 1;
if (!g.decode && !g.force && isatty(g.outd))
bail("trying to write compressed data to a terminal",
" (use -f to force)");
}
else {
char *to, *repl;
/* use header name for output when decompressing with -N */
to = g.inf;
if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) {
to = g.hname;
len = strlen(g.hname);
}
/* replace .tgz with .tar when decoding */
repl = g.decode && strcmp(to + len, ".tgz") ? "" : ".tar";
/* create output file and open to write */
g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1);
if (g.outf == NULL)
bail("not enough memory", "");
memcpy(g.outf, to, len);
strcpy(g.outf + len, g.decode ? repl : g.sufx);
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY |
(g.force ? 0 : O_EXCL), 0600);
/* if exists and not -f, give user a chance to overwrite */
if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) {
int ch, reply;
fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf);
fflush(stderr);
reply = -1;
do {
ch = getchar();
if (reply < 0 && ch != ' ' && ch != '\t')
reply = ch == 'y' || ch == 'Y' ? 1 : 0;
} while (ch != EOF && ch != '\n' && ch != '\r');
if (reply == 1)
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY,
0600);
}
/* if exists and no overwrite, report and go on to next */
if (g.outd < 0 && errno == EEXIST) {
complain("%s exists -- skipping", g.outf);
RELEASE(g.outf);
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* if some other error, give up */
if (g.outd < 0)
bail("write error on ", g.outf);
}
SET_BINARY_MODE(g.outd);
RELEASE(g.hname);
/* process ind to outd */
if (g.verbosity > 1)
fprintf(stderr, "%s to %s ", g.inf, g.outf);
if (g.decode) {
if (method == 8)
infchk();
else if (method == 257)
unlzw();
else
cat();
}
#ifndef NOTHREAD
else if (g.procs > 1)
parallel_compress();
#endif
else
single_compress(0);
if (g.verbosity > 1) {
putc('\n', stderr);
fflush(stderr);
}
/* finish up, copy attributes, set times, delete original */
if (g.ind != 0)
close(g.ind);
if (g.outd != 1) {
if (close(g.outd))
bail("write error on ", g.outf);
g.outd = -1; /* now prevent deletion on interrupt */
if (g.ind != 0) {
copymeta(g.inf, g.outf);
if (!g.keep)
unlink(g.inf);
}
if (g.decode && (g.headis & 2) != 0 && g.stamp)
touch(g.outf, g.stamp);
}
RELEASE(g.outf);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-22'], 'message': 'When decompressing with -N or -NT, strip any path from header name.
This uses the path of the compressed file combined with the name
from the header as the name of the decompressed output file. Any
path information in the header name is stripped. This avoids a
possible vulnerability where absolute or descending paths are put
in the gzip header.'</s> |
<s>[INST] Given the following code containing errors, provide 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 nhmldump_send_header(GF_NHMLDumpCtx *ctx)
{
GF_FilterPacket *dst_pck;
char nhml[1024];
u32 size;
u8 *output;
const GF_PropertyValue *p;
ctx->szRootName = "NHNTStream";
if (ctx->dims) {
ctx->szRootName = "DIMSStream";
}
if (!ctx->filep) {
sprintf(nhml, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
/*write header*/
sprintf(nhml, "<%s version=\"1.0\" ", ctx->szRootName);
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
NHML_PRINT_UINT(GF_PROP_PID_ID, NULL, "trackID")
NHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, "timeScale")
p = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD);
if (p && p->value.boolean) {
sprintf(nhml, "inRootOD=\"yes\" ");
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
if (ctx->oti && (ctx->oti<GF_CODECID_LAST_MPEG4_MAPPING)) {
sprintf(nhml, "streamType=\"%d\" objectTypeIndication=\"%d\" ", ctx->streamtype, ctx->oti);
gf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml));
} else {
p = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE);
if (p) {
sprintf(nhml, "%s=\"%s\" ", "mediaType", gf_4cc_to_str(p->value.uint));
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
NHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, "mediaSubType", "mediaSubType")
} else {
NHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, "codecID")
}
}
if (ctx->w && ctx->h) {
//compatibility with old arch, we might want to remove this
switch (ctx->streamtype) {
case GF_STREAM_VISUAL:
case GF_STREAM_SCENE:
sprintf(nhml, "width=\"%d\" height=\"%d\" ", ctx->w, ctx->h);
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
break;
default:
break;
}
}
else if (ctx->sr && ctx->chan) {
sprintf(nhml, "sampleRate=\"%d\" numChannels=\"%d\" ", ctx->sr, ctx->chan);
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
sprintf(nhml, "sampleRate=\"%d\" numChannels=\"%d\" ", ctx->sr, ctx->chan);
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
p = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT);
sprintf(nhml, "bitsPerSample=\"%d\" ", gf_audio_fmt_bit_depth(p->value.uint));
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
NHML_PRINT_4CC(0, "codec_vendor", "codecVendor")
NHML_PRINT_UINT(0, "codec_version", "codecVersion")
NHML_PRINT_UINT(0, "codec_revision", "codecRevision")
NHML_PRINT_STRING(0, "compressor_name", "compressorName")
NHML_PRINT_UINT(0, "temporal_quality", "temporalQuality")
NHML_PRINT_UINT(0, "spatial_quality", "spatialQuality")
NHML_PRINT_UINT(0, "hres", "horizontalResolution")
NHML_PRINT_UINT(0, "vres", "verticalResolution")
NHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, "bitDepth")
NHML_PRINT_STRING(0, "meta:xmlns", "xml_namespace")
NHML_PRINT_STRING(0, "meta:schemaloc", "xml_schema_location")
NHML_PRINT_STRING(0, "meta:mime", "mime_type")
NHML_PRINT_STRING(0, "meta:config", "config")
NHML_PRINT_STRING(0, "meta:aux_mimes", "aux_mime_type")
if (ctx->codecid == GF_CODECID_DIMS) {
if (gf_filter_pid_get_property_str(ctx->ipid, "meta:xmlns")==NULL) {
sprintf(nhml, "xmlns=\"http://www.3gpp.org/richmedia\" ");
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
NHML_PRINT_UINT(0, "dims:profile", "profile")
NHML_PRINT_UINT(0, "dims:level", "level")
NHML_PRINT_UINT(0, "dims:pathComponents", "pathComponents")
p = gf_filter_pid_get_property_str(ctx->ipid, "dims:fullRequestHost");
if (p) {
sprintf(nhml, "useFullRequestHost=\"%s\" ", p->value.boolean ? "yes" : "no");
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
p = gf_filter_pid_get_property_str(ctx->ipid, "dims:streamType");
if (p) {
sprintf(nhml, "stream_type=\"%s\" ", p->value.boolean ? "primary" : "secondary");
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
p = gf_filter_pid_get_property_str(ctx->ipid, "dims:redundant");
if (p) {
sprintf(nhml, "contains_redundant=\"%s\" ", (p->value.uint==1) ? "main" : ((p->value.uint==1) ? "redundant" : "main+redundant") );
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
NHML_PRINT_UINT(0, "dims:scriptTypes", "scriptTypes")
}
//send DCD
if (ctx->opid_info) {
sprintf(nhml, "specificInfoFile=\"%s\" ", gf_file_basename(ctx->info_file) );
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
dst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL);
gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);
gf_filter_pck_set_readonly(dst_pck);
gf_filter_pck_send(dst_pck);
}
NHML_PRINT_STRING(0, "meta:encoding", "encoding")
NHML_PRINT_STRING(0, "meta:contentEncoding", "content_encoding")
ctx->uncompress = GF_FALSE;
if (p) {
if (!strcmp(p->value.string, "deflate")) ctx->uncompress = GF_TRUE;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, ("[NHMLMx] content_encoding %s not supported\n", p->value.string ));
}
}
if (ctx->opid_mdia) {
sprintf(nhml, "baseMediaFile=\"%s\" ", gf_file_basename(ctx->media_file) );
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
}
sprintf(nhml, ">\n");
gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));
gf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);
if (ctx->filep) {
gf_fwrite(ctx->nhml_buffer, size, ctx->filep);
return;
}
dst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);
memcpy(output, ctx->nhml_buffer, size);
gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);
gf_filter_pck_send(dst_pck);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1565'</s> |
<s>[INST] Given the following code containing errors, provide 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 Helper::processExec(QProcess *process, const QString &command, int timeout, QIODevice::OpenMode mode)
{
m_processStandardOutput.clear();
m_processStandardError.clear();
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(timeout);
timer.connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
loop.connect(process, static_cast<void(QProcess::*)(int)>(&QProcess::finished), &loop, &QEventLoop::exit);
// 防止子进程输出信息将管道塞满导致进程阻塞
process->connect(process, &QProcess::readyReadStandardError, process, [process] {
m_processStandardError.append(process->readAllStandardError());
});
process->connect(process, &QProcess::readyReadStandardOutput, process, [process] {
m_processStandardOutput.append(process->readAllStandardOutput());
});
if (timeout > 0) {
timer.start();
} else {
QTimer::singleShot(10000, process, [process] {
dCWarning("\"%s %s\" running for more than 10 seconds, state=%d, pid_file_exist=%d",
qPrintable(process->program()), qPrintable(process->arguments().join(" ")),
(int)process->state(), (int)QFile::exists(QString("/proc/%1").arg(process->pid())));
});
}
if (Global::debugLevel > 1)
dCDebug("Exec: \"%s\", timeout: %d", qPrintable(command), timeout);
process->start(command, mode);
process->waitForStarted();
if (process->error() != QProcess::UnknownError) {
dCError(process->errorString());
return -1;
}
if (process->state() == QProcess::Running) {
loop.exec();
}
if (process->state() != QProcess::NotRunning) {
dCDebug("The \"%s\" timeout, timeout: %d", qPrintable(command), timeout);
if (QFile::exists(QString("/proc/%1").arg(process->pid()))) {
process->terminate();
process->waitForFinished();
} else {
dCDebug("The \"%s\" is quit, but the QProcess object state is not NotRunning");
}
}
m_processStandardOutput.append(process->readAllStandardOutput());
m_processStandardError.append(process->readAllStandardError());
if (Global::debugLevel > 1) {
dCDebug("Done: \"%s\", exit code: %d", qPrintable(command), process->exitCode());
if (process->exitCode() != 0) {
dCError("error: \"%s\"\nstdout: \"%s\"", qPrintable(m_processStandardError), qPrintable(m_processStandardOutput));
}
}
return process->exitCode();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'fix: Do not use the "/tmp" directory
https://github.com/linuxdeepin/deepin-clone/issues/16
https://bugzilla.opensuse.org/show_bug.cgi?id=1130388'</s> |
<s>[INST] Given the following code containing errors, provide 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 fx_TypedArray(txMachine* the)
{
txSlot* instance = fxConstructTypedArray(the);
txSlot* dispatch = instance->next;
txSlot* view = dispatch->next;
txSlot* buffer = view->next;
txSlot* data = C_NULL;
txU2 shift = dispatch->value.typedArray.dispatch->shift;
txSlot* slot;
if ((mxArgc > 0) && (mxArgv(0)->kind == XS_REFERENCE_KIND)) {
slot = mxArgv(0)->value.reference->next;
if (slot && ((slot->kind == XS_ARRAY_BUFFER_KIND) || (slot->kind == XS_HOST_KIND))) {
txInteger offset = fxArgToByteLength(the, 1, 0);
txInteger size;
txSlot* info;
if (offset & ((1 << shift) - 1))
mxRangeError("invalid byteOffset %ld", offset);
size = fxArgToByteLength(the, 2, -1);
info = fxGetBufferInfo(the, mxArgv(0));
if (size >= 0) {
size <<= shift;
if (info->value.bufferInfo.length < (offset + size))
mxRangeError("out of range byteLength %ld", size);
}
else {
if (info->value.bufferInfo.length & ((1 << shift) - 1))
mxRangeError("invalid byteLength %ld", info->value.bufferInfo.length);
size = info->value.bufferInfo.length - offset;
if (size < 0)
mxRangeError("out of range byteLength %ld", size);
if (info->value.bufferInfo.maxLength >= 0)
size = -1;
}
view->value.dataView.offset = offset;
view->value.dataView.size = size;
buffer->kind = XS_REFERENCE_KIND;
buffer->value.reference = mxArgv(0)->value.reference;
}
else if (slot && (slot->kind == XS_TYPED_ARRAY_KIND)) {
txSlot* sourceDispatch = slot;
txSlot* sourceView = sourceDispatch->next;
txSlot* sourceBuffer = sourceView->next;
txU2 sourceShift = sourceDispatch->value.typedArray.dispatch->shift;
txInteger sourceLength = fxCheckDataViewSize(the, sourceView, sourceBuffer, XS_IMMUTABLE) >> sourceShift;
txSlot* sourceData = sourceBuffer->value.reference->next;
txInteger sourceDelta = sourceDispatch->value.typedArray.dispatch->size;
txInteger sourceOffset = sourceView->value.dataView.offset;
txInteger offset = 0;
txInteger size = sourceLength << shift;
/* THIS */
mxPushUninitialized();
/* FUNCTION */
mxPush(mxArrayBufferConstructor);
/* TARGET */
if (sourceData->kind == XS_ARRAY_BUFFER_KIND) {
mxPushSlot(sourceBuffer);
mxGetID(mxID(_constructor));
fxToSpeciesConstructor(the, &mxArrayBufferConstructor);
}
else
mxPush(mxArrayBufferConstructor);
/* RESULT */
mxPushUndefined();
mxPushUninitialized();
mxPushUninitialized();
/* ARGUMENTS */
sourceLength = fxGetDataViewSize(the, sourceView, sourceBuffer) >> sourceShift;
size = sourceLength << shift;
mxPushInteger(size);
mxRunCount(1);
mxPullSlot(buffer);
sourceLength = fxCheckDataViewSize(the, sourceView, sourceBuffer, XS_IMMUTABLE) >> sourceShift;
size = sourceLength << shift;
data = fxCheckArrayBufferDetached(the, buffer, XS_MUTABLE);
view->value.dataView.offset = offset;
view->value.dataView.size = size;
if (dispatch == sourceDispatch)
c_memcpy(data->value.arrayBuffer.address + offset, sourceData->value.arrayBuffer.address + sourceOffset, size);
else {
txBoolean contentType = (dispatch->value.typedArray.dispatch->constructorID == _BigInt64Array)
|| (dispatch->value.typedArray.dispatch->constructorID == _BigUint64Array);
txBoolean sourceContentType = (sourceDispatch->value.typedArray.dispatch->constructorID == _BigInt64Array)
|| (sourceDispatch->value.typedArray.dispatch->constructorID == _BigUint64Array);
if (contentType != sourceContentType)
mxTypeError("incompatible content type");
mxPushUndefined();
while (offset < size) {
(*sourceDispatch->value.typedArray.dispatch->getter)(the, sourceData, sourceOffset, the->stack, EndianNative);
(*dispatch->value.typedArray.dispatch->coerce)(the, the->stack);
(*dispatch->value.typedArray.dispatch->setter)(the, data, offset, the->stack, EndianNative);
sourceOffset += sourceDelta;
offset += 1 << shift;
}
mxPop();
}
}
else {
fx_TypedArray_from_object(the, instance, C_NULL, C_NULL);
}
}
else {
txInteger length = fxArgToByteLength(the, 0, 0);
if (length & (((1 << shift) - 1) << (32 - shift)))
mxRangeError("out of range byteLength");
length <<= shift;
mxPush(mxArrayBufferConstructor);
mxNew();
mxPushInteger(length);
mxRunCount(1);
mxPullSlot(buffer);
view->value.dataView.offset = 0;
view->value.dataView.size = length;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'XS: #896'</s> |
<s>[INST] Given the following code containing errors, provide 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 wvlan_uil_put_info(struct uilreq *urq, struct wl_private *lp)
{
int result = 0;
ltv_t *pLtv;
bool_t ltvAllocated = FALSE;
ENCSTRCT sEncryption;
#ifdef USE_WDS
hcf_16 hcfPort = HCF_PORT_0;
#endif /* USE_WDS */
/*------------------------------------------------------------------------*/
DBG_FUNC("wvlan_uil_put_info");
DBG_ENTER(DbgInfo);
if (urq->hcfCtx == &(lp->hcfCtx)) {
if (capable(CAP_NET_ADMIN)) {
if ((urq->data != NULL) && (urq->len != 0)) {
/* Make sure that we have at least a command and length to send. */
if (urq->len < (sizeof(hcf_16) * 2)) {
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
DBG_ERROR(DbgInfo, "No Length/Type in LTV!!!\n");
DBG_ERROR(DbgInfo, "UIL_ERR_LEN\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* Verify the user buffer */
result = verify_area(VERIFY_READ, urq->data, urq->len);
if (result != 0) {
urq->result = UIL_FAILURE;
DBG_ERROR(DbgInfo, "verify_area(), VERIFY_READ FAILED\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* Get only the command and length information. */
copy_from_user(&(lp->ltvRecord), urq->data, sizeof(hcf_16) * 2);
/* Make sure the incoming LTV record length is within the bounds of the
IOCTL length */
if (((lp->ltvRecord.len + 1) * sizeof(hcf_16)) > urq->len) {
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
DBG_ERROR(DbgInfo, "UIL_ERR_LEN\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* If the requested length is greater than the size of our local
LTV record, try to allocate it from the kernel stack.
Otherwise, we just use our local LTV record. */
if (urq->len > sizeof(lp->ltvRecord)) {
pLtv = kmalloc(urq->len, GFP_KERNEL);
if (pLtv != NULL) {
ltvAllocated = TRUE;
} else {
DBG_ERROR(DbgInfo, "Alloc FAILED\n");
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
result = -ENOMEM;
DBG_LEAVE(DbgInfo);
return result;
}
} else {
pLtv = &(lp->ltvRecord);
}
/* Copy the data from the user's buffer into the local LTV
record data area. */
copy_from_user(pLtv, urq->data, urq->len);
/* We need to snoop the commands to see if there is anything we
need to store for the purposes of a reset or start/stop
sequence. Perform endian translation as needed */
switch (pLtv->typ) {
case CFG_CNF_PORT_TYPE:
lp->PortType = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_OWN_MAC_ADDR:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CNF_OWN_CHANNEL:
lp->Channel = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* CFG_CNF_OWN_SSID currently same as CNF_DESIRED_SSID. Do we
need separate storage for this? */
/* case CFG_CNF_OWN_SSID: */
case CFG_CNF_OWN_ATIM_WINDOW:
lp->atimWindow = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_SYSTEM_SCALE:
lp->DistanceBetweenAPs = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
case CFG_CNF_MAX_DATA_LEN:
/* TODO: determine if we are going to store anything based
on this */
break;
case CFG_CNF_PM_ENABLED:
lp->PMEnabled = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MCAST_RX:
lp->MulticastReceive = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MAX_SLEEP_DURATION:
lp->MaxSleepDuration = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_HOLDOVER_DURATION:
lp->holdoverDuration = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_OWN_NAME:
memset(lp->StationName, 0, sizeof(lp->StationName));
memcpy((void *)lp->StationName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_LOAD_BALANCING:
lp->loadBalancing = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MEDIUM_DISTRIBUTION:
lp->mediumDistribution = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef WARP
case CFG_CNF_TX_POW_LVL:
lp->txPowLevel = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* case CFG_CNF_SHORT_RETRY_LIMIT: */ /* Short Retry Limit */
/* case 0xFC33: */ /* Long Retry Limit */
case CFG_SUPPORTED_RATE_SET_CNTL: /* Supported Rate Set Control */
lp->srsc[0] = pLtv->u.u16[0];
lp->srsc[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_BASIC_RATE_SET_CNTL: /* Basic Rate Set Control */
lp->brsc[0] = pLtv->u.u16[0];
lp->brsc[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_CNF_CONNECTION_CNTL:
lp->connectionControl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* case CFG_PROBE_DATA_RATE: */
#endif /* HERMES25 */
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_CNF_OWN_DTIM_PERIOD:
lp->DTIMPeriod = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef WARP
case CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */
lp->ownBeaconInterval = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif /* WARP */
case CFG_COEXISTENSE_BEHAVIOUR: /* Coexistence behavior */
lp->coexistence = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef USE_WDS
case CFG_CNF_WDS_ADDR1:
memcpy(&lp->wds_port[0].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_1;
break;
case CFG_CNF_WDS_ADDR2:
memcpy(&lp->wds_port[1].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_2;
break;
case CFG_CNF_WDS_ADDR3:
memcpy(&lp->wds_port[2].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_3;
break;
case CFG_CNF_WDS_ADDR4:
memcpy(&lp->wds_port[3].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_4;
break;
case CFG_CNF_WDS_ADDR5:
memcpy(&lp->wds_port[4].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_5;
break;
case CFG_CNF_WDS_ADDR6:
memcpy(&lp->wds_port[5].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_6;
break;
#endif /* USE_WDS */
case CFG_CNF_MCAST_PM_BUF:
lp->multicastPMBuffering = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_REJECT_ANY:
lp->RejectAny = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif
case CFG_CNF_ENCRYPTION:
lp->EnableEncryption = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_AUTHENTICATION:
lp->authentication = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
/* case CFG_CNF_EXCL_UNENCRYPTED:
lp->ExcludeUnencrypted = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break; */
case CFG_CNF_MCAST_RATE:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CNF_INTRA_BSS_RELAY:
lp->intraBSSRelay = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif
case CFG_CNF_MICRO_WAVE:
/* TODO: determine if we are going to store anything based on this */
break;
/*case CFG_CNF_LOAD_BALANCING:*/
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_MEDIUM_DISTRIBUTION: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_COUNTRY_INFO: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
case CFG_CNF_OWN_SSID:
/* case CNF_DESIRED_SSID: */
case CFG_DESIRED_SSID:
memset(lp->NetworkName, 0, sizeof(lp->NetworkName));
memcpy((void *)lp->NetworkName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
/* take care of the special network name "ANY" case */
if ((strlen(&pLtv->u.u8[2]) == 0) ||
(strcmp(&pLtv->u.u8[2], "ANY") == 0) ||
(strcmp(&pLtv->u.u8[2], "any") == 0)) {
/* set the SSID_STRCT llen field (u16[0]) to zero, and the
effectually null the string u8[2] */
pLtv->u.u16[0] = 0;
pLtv->u.u8[2] = 0;
}
break;
case CFG_GROUP_ADDR:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CREATE_IBSS:
lp->CreateIBSS = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_RTS_THRH:
lp->RTSThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_TX_RATE_CNTL:
lp->TxRateControl[0] = pLtv->u.u16[0];
lp->TxRateControl[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_PROMISCUOUS_MODE:
/* TODO: determine if we are going to store anything based on this */
break;
/* case CFG_WAKE_ON_LAN: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
#if 1 /* ;? #if (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_RTS_THRH0:
lp->RTSThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_TX_RATE_CNTL0:
/*;?no idea what this should be, get going so comment it out lp->TxRateControl = pLtv->u.u16[0];*/
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef USE_WDS
case CFG_RTS_THRH1:
lp->wds_port[0].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_1;
break;
case CFG_RTS_THRH2:
lp->wds_port[1].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_2;
break;
case CFG_RTS_THRH3:
lp->wds_port[2].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_3;
break;
case CFG_RTS_THRH4:
lp->wds_port[3].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_4;
break;
case CFG_RTS_THRH5:
lp->wds_port[4].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_5;
break;
case CFG_RTS_THRH6:
lp->wds_port[5].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_6;
break;
case CFG_TX_RATE_CNTL1:
lp->wds_port[0].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_1;
break;
case CFG_TX_RATE_CNTL2:
lp->wds_port[1].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_2;
break;
case CFG_TX_RATE_CNTL3:
lp->wds_port[2].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_3;
break;
case CFG_TX_RATE_CNTL4:
lp->wds_port[3].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_4;
break;
case CFG_TX_RATE_CNTL5:
lp->wds_port[4].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_5;
break;
case CFG_TX_RATE_CNTL6:
lp->wds_port[5].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_6;
break;
#endif /* USE_WDS */
#endif /* (HCF_TYPE) & HCF_TYPE_AP */
case CFG_DEFAULT_KEYS:
{
CFG_DEFAULT_KEYS_STRCT *pKeys = (CFG_DEFAULT_KEYS_STRCT *)pLtv;
pKeys->key[0].len = CNV_INT_TO_LITTLE(pKeys->key[0].len);
pKeys->key[1].len = CNV_INT_TO_LITTLE(pKeys->key[1].len);
pKeys->key[2].len = CNV_INT_TO_LITTLE(pKeys->key[2].len);
pKeys->key[3].len = CNV_INT_TO_LITTLE(pKeys->key[3].len);
memcpy((void *)&(lp->DefaultKeys), (void *)pKeys,
sizeof(CFG_DEFAULT_KEYS_STRCT));
}
break;
case CFG_TX_KEY_ID:
lp->TransmitKeyID = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_SCAN_SSID:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_TICK_TIME:
/* TODO: determine if we are going to store anything based on this */
break;
/* these RIDS are Info RIDs, and should they be allowed for puts??? */
case CFG_MAX_LOAD_TIME:
case CFG_DL_BUF:
/* case CFG_HSI_SUP_RANGE: */
case CFG_NIC_SERIAL_NUMBER:
case CFG_NIC_IDENTITY:
case CFG_NIC_MFI_SUP_RANGE:
case CFG_NIC_CFI_SUP_RANGE:
case CFG_NIC_TEMP_TYPE:
case CFG_NIC_PROFILE:
case CFG_FW_IDENTITY:
case CFG_FW_SUP_RANGE:
case CFG_MFI_ACT_RANGES_STA:
case CFG_CFI_ACT_RANGES_STA:
case CFG_PORT_STAT:
case CFG_CUR_SSID:
case CFG_CUR_BSSID:
case CFG_COMMS_QUALITY:
case CFG_CUR_TX_RATE:
case CFG_CUR_BEACON_INTERVAL:
case CFG_CUR_SCALE_THRH:
case CFG_PROTOCOL_RSP_TIME:
case CFG_CUR_SHORT_RETRY_LIMIT:
case CFG_CUR_LONG_RETRY_LIMIT:
case CFG_MAX_TX_LIFETIME:
case CFG_MAX_RX_LIFETIME:
case CFG_CF_POLLABLE:
case CFG_AUTHENTICATION_ALGORITHMS:
case CFG_PRIVACY_OPT_IMPLEMENTED:
/* case CFG_CURRENT_REMOTE_RATES: */
/* case CFG_CURRENT_USED_RATES: */
/* case CFG_CURRENT_SYSTEM_SCALE: */
/* case CFG_CURRENT_TX_RATE1: */
/* case CFG_CURRENT_TX_RATE2: */
/* case CFG_CURRENT_TX_RATE3: */
/* case CFG_CURRENT_TX_RATE4: */
/* case CFG_CURRENT_TX_RATE5: */
/* case CFG_CURRENT_TX_RATE6: */
case CFG_NIC_MAC_ADDR:
case CFG_PCF_INFO:
/* case CFG_CURRENT_COUNTRY_INFO: */
case CFG_PHY_TYPE:
case CFG_CUR_CHANNEL:
/* case CFG_CURRENT_POWER_STATE: */
/* case CFG_CCAMODE: */
case CFG_SUPPORTED_DATA_RATES:
break;
case CFG_AP_MODE:
/*;? lp->DownloadFirmware = (pLtv->u.u16[0]) + 1; */
DBG_ERROR(DbgInfo, "set CFG_AP_MODE no longer supported\n");
break;
case CFG_ENCRYPT_STRING:
/* TODO: ENDIAN TRANSLATION HERE??? */
memset(lp->szEncryption, 0, sizeof(lp->szEncryption));
memcpy((void *)lp->szEncryption, (void *)&pLtv->u.u8[0],
(pLtv->len * sizeof(hcf_16)));
wl_wep_decode(CRYPT_CODE, &sEncryption,
lp->szEncryption);
/* the Linux driver likes to use 1-4 for the key IDs, and then
convert to 0-3 when sending to the card. The Windows code
base used 0-3 in the API DLL, which was ported to Linux. For
the sake of the user experience, we decided to keep 0-3 as the
numbers used in the DLL; and will perform the +1 conversion here.
We could have converted the entire Linux driver, but this is
less obtrusive. This may be a "todo" to convert the whole driver */
lp->TransmitKeyID = sEncryption.wTxKeyID + 1;
lp->EnableEncryption = sEncryption.wEnabled;
memcpy(&lp->DefaultKeys, &sEncryption.EncStr,
sizeof(CFG_DEFAULT_KEYS_STRCT));
break;
/*case CFG_COUNTRY_STRING:
memset(lp->countryString, 0, sizeof(lp->countryString));
memcpy((void *)lp->countryString, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
break;
*/
case CFG_DRIVER_ENABLE:
lp->driverEnable = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_WOLAS_ENABLE:
lp->wolasEnable = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_SET_WPA_AUTH_KEY_MGMT_SUITE:
lp->AuthKeyMgmtSuite = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_DISASSOCIATE_ADDR:
pLtv->u.u16[ETH_ALEN / 2] = CNV_INT_TO_LITTLE(pLtv->u.u16[ETH_ALEN / 2]);
break;
case CFG_ADD_TKIP_DEFAULT_KEY:
case CFG_REMOVE_TKIP_DEFAULT_KEY:
/* Endian convert the Tx Key Information */
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_ADD_TKIP_MAPPED_KEY:
break;
case CFG_REMOVE_TKIP_MAPPED_KEY:
break;
/* some RIDs just can't be put */
case CFG_MB_INFO:
case CFG_IFB:
default:
break;
}
/* This code will prevent Static Configuration Entities from
being sent to the card, as they require a call to
UIL_ACT_APPLY to take effect. Dynamic Entities will be sent
immediately */
switch (pLtv->typ) {
case CFG_CNF_PORT_TYPE:
case CFG_CNF_OWN_MAC_ADDR:
case CFG_CNF_OWN_CHANNEL:
case CFG_CNF_OWN_SSID:
case CFG_CNF_OWN_ATIM_WINDOW:
case CFG_CNF_SYSTEM_SCALE:
case CFG_CNF_MAX_DATA_LEN:
case CFG_CNF_PM_ENABLED:
case CFG_CNF_MCAST_RX:
case CFG_CNF_MAX_SLEEP_DURATION:
case CFG_CNF_HOLDOVER_DURATION:
case CFG_CNF_OWN_NAME:
case CFG_CNF_LOAD_BALANCING:
case CFG_CNF_MEDIUM_DISTRIBUTION:
#ifdef WARP
case CFG_CNF_TX_POW_LVL:
case CFG_CNF_CONNECTION_CNTL:
/*case CFG_PROBE_DATA_RATE: */
#endif /* HERMES25 */
#if 1 /*;? (HCF_TYPE) & HCF_TYPE_AP */
/*;?should we restore this to allow smaller memory footprint */
case CFG_CNF_OWN_DTIM_PERIOD:
#ifdef WARP
case CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */
#endif /* WARP */
#ifdef USE_WDS
case CFG_CNF_WDS_ADDR1:
case CFG_CNF_WDS_ADDR2:
case CFG_CNF_WDS_ADDR3:
case CFG_CNF_WDS_ADDR4:
case CFG_CNF_WDS_ADDR5:
case CFG_CNF_WDS_ADDR6:
#endif
case CFG_CNF_MCAST_PM_BUF:
case CFG_CNF_REJECT_ANY:
#endif
case CFG_CNF_ENCRYPTION:
case CFG_CNF_AUTHENTICATION:
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_CNF_EXCL_UNENCRYPTED:
case CFG_CNF_MCAST_RATE:
case CFG_CNF_INTRA_BSS_RELAY:
#endif
case CFG_CNF_MICRO_WAVE:
/* case CFG_CNF_LOAD_BALANCING: */
/* case CFG_CNF_MEDIUM_DISTRIBUTION: */
/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */
/* case CFG_CNF_COUNTRY_INFO: */
/* case CFG_COUNTRY_STRING: */
case CFG_AP_MODE:
case CFG_ENCRYPT_STRING:
/* case CFG_DRIVER_ENABLE: */
case CFG_WOLAS_ENABLE:
case CFG_MB_INFO:
case CFG_IFB:
break;
/* Deal with this dynamic MSF RID, as it's required for WPA */
case CFG_DRIVER_ENABLE:
if (lp->driverEnable) {
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_ENABLE | HCF_PORT_0);
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_CONNECT);
} else {
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISABLE | HCF_PORT_0);
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISCONNECT);
}
break;
default:
wl_act_int_off(lp);
urq->result = hcf_put_info(&(lp->hcfCtx), (LTVP) pLtv);
wl_act_int_on(lp);
break;
}
if (ltvAllocated)
kfree(pLtv);
} else {
urq->result = UIL_FAILURE;
}
} else {
DBG_ERROR(DbgInfo, "EPERM\n");
urq->result = UIL_FAILURE;
result = -EPERM;
}
} else {
DBG_ERROR(DbgInfo, "UIL_ERR_WRONG_IFB\n");
urq->result = UIL_ERR_WRONG_IFB;
}
DBG_LEAVE(DbgInfo);
return result;
} /* wvlan_uil_put_info */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'staging: wlags49_h2: buffer overflow setting station name
We need to check the length parameter before doing the memcpy(). I've
actually changed it to strlcpy() as well so that it's NUL terminated.
You need CAP_NET_ADMIN to trigger these so it's not the end of the
world.
Reported-by: Nico Golde <nico@ngolde.de>
Reported-by: Fabian Yamaguchi <fabs@goesec.de>
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Cc: stable@kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
{
vcpu->arch.apic->vapic_addr = vapic_addr;
if (vapic_addr)
__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
else
__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <ahonig@google.com>
Cc: stable@vger.kernel.org
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_MAXSIZE_GEN];
#endif
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/*generate 8 extra bytes to mitigate bias from the modulo operation below*/
/*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/
size += 8;
/* make up random string */
err = wc_RNG_GenerateBlock(rng, buf, size);
/* load random buffer data into k */
if (err == 0)
err = mp_read_unsigned_bin(k, (byte*)buf, size);
/* quick sanity check to make sure we're not dealing with a 0 key */
if (err == MP_OKAY) {
if (mp_iszero(k) == MP_YES)
err = MP_ZERO_E;
}
/* the key should be smaller than the order of base point */
if (err == MP_OKAY) {
if (mp_cmp(k, order) != MP_LT) {
err = mp_mod(k, order, k);
}
}
ForceZero(buf, ECC_MAXSIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Change ECDSA signing to use blinding.'</s> |
<s>[INST] Given the following code containing errors, provide 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 ComputeAsync(OpKernelContext* context, DoneCallback done) override {
// The shape of 'grads' is [num_boxes, crop_height, crop_width, depth].
const Tensor& grads = context->input(0);
// The shape of 'boxes' is [num_boxes, 4].
const Tensor& boxes = context->input(1);
// The shape of 'box_index' is [num_boxes].
const Tensor& box_index = context->input(2);
// The shape of 'image_size' is [4].
const Tensor& image_size = context->input(3);
// Validate input shapes.
OP_REQUIRES_ASYNC(context, grads.dims() == 4,
errors::InvalidArgument("grads image must be 4-D",
grads.shape().DebugString()),
done);
const int crop_height = grads.dim_size(1);
const int crop_width = grads.dim_size(2);
OP_REQUIRES_ASYNC(
context, crop_height > 0 && crop_width > 0,
errors::InvalidArgument("grads dimensions must be positive"), done);
int num_boxes = 0;
OP_REQUIRES_OK_ASYNC(
context, ParseAndCheckBoxSizes(boxes, box_index, &num_boxes), done);
OP_REQUIRES_ASYNC(
context, grads.dim_size(0) == num_boxes,
errors::InvalidArgument("boxes and grads have incompatible shape"),
done);
OP_REQUIRES_ASYNC(context, image_size.dims() == 1,
errors::InvalidArgument("image_size must be 1-D",
image_size.shape().DebugString()),
done);
OP_REQUIRES_ASYNC(context, image_size.dim_size(0) == 4,
errors::InvalidArgument("image_size must have 4 elements",
image_size.shape().DebugString()),
done);
auto image_size_vec = image_size.vec<int32>();
const int batch_size = internal::SubtleMustCopy(image_size_vec(0));
const int image_height = internal::SubtleMustCopy(image_size_vec(1));
const int image_width = internal::SubtleMustCopy(image_size_vec(2));
const int depth = internal::SubtleMustCopy(image_size_vec(3));
OP_REQUIRES_ASYNC(
context, image_height > 0 && image_width > 0,
errors::InvalidArgument("image dimensions must be positive"), done);
OP_REQUIRES_ASYNC(
context, grads.dim_size(3) == depth,
errors::InvalidArgument("image_size and grads are incompatible"), done);
if (std::is_same<Device, GPUDevice>::value) {
OP_REQUIRES_ASYNC(
context, !OpDeterminismRequired(),
errors::Unimplemented(
"Deterministic GPU implementation of CropAndResizeBackpropImage"
" not available."),
done);
}
// Allocate output tensor.
Tensor* output = nullptr;
OP_REQUIRES_OK_ASYNC(
context,
context->allocate_output(
0, TensorShape({batch_size, image_height, image_width, depth}),
&output),
done);
auto compute_callback = [this, context, output]() {
const Tensor& grads = context->input(0);
const Tensor& boxes = context->input(1);
const Tensor& box_index = context->input(2);
const bool status = functor::CropAndResizeBackpropImage<Device, T>()(
context, grads.tensor<float, 4>(), boxes.tensor<float, 2>(),
box_index.tensor<int32, 1>(), output->tensor<T, 4>(), method_);
if (!status) {
context->SetStatus(errors::Internal(
"Failed to launch CropAndResizeBackpropImage kernel."));
}
};
RunIfBoxIndexIsValid<Device>(context, box_index.tensor<int32, 1>(),
batch_size, std::move(compute_callback),
std::move(done));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'PR #51732: Fix crash of tf.image.crop_and_resize when input is large number
Imported from GitHub PR https://github.com/tensorflow/tensorflow/pull/51732
This PR is part of the effort in #46890 where
tf.image.crop_and_resize will crash if shape consists of large number.
Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
Copybara import of the project:
--
c8d87055a56d8740d27ad8bdc74a7459ede6900e by Yong Tang <yong.tang.github@outlook.com>:
Fix crash of tf.image.crop_and_resize when input is large number
This PR is part of the effort in 46890 where
tf.image.crop_and_resize will crash if shape consists of large number.
Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/tensorflow/pull/51732 from yongtang:46890-tf.image.crop_and_resize c8d87055a56d8740d27ad8bdc74a7459ede6900e
PiperOrigin-RevId: 394109830
Change-Id: If049dad0844df9353722029ee95bc76819eda1f4'</s> |
<s>[INST] Given the following code containing errors, provide 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 tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
void *raw;
} h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_LOSING|TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timeval tv;
struct timespec ts;
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
macoff = netoff - maclen;
}
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) + skb->truesize <
(unsigned)sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_frame(po, &po->rx_ring, TP_STATUS_KERNEL);
if (!h.raw)
goto ring_is_full;
packet_increment_head(&po->rx_ring);
po->stats.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
if (!po->stats.tp_drops)
status &= ~TP_STATUS_LOSING;
spin_unlock(&sk->sk_receive_queue.lock);
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
tv = ktime_to_timeval(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
tv = ktime_to_timeval(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
tv = ktime_to_timeval(skb->tstamp);
else
do_gettimeofday(&tv);
h.h1->tp_sec = tv.tv_sec;
h.h1->tp_usec = tv.tv_usec;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
ts = ktime_to_timespec(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
ts = ktime_to_timespec(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
ts = ktime_to_timespec(skb->tstamp);
else
getnstimeofday(&ts);
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (vlan_tx_tag_present(skb)) {
h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
status |= TP_STATUS_VLAN_VALID;
} else {
h.h2->tp_vlan_tci = 0;
}
hdrlen = sizeof(*h.h2);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
__packet_set_status(po, h.raw, status);
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
{
u8 *start, *end;
end = (u8 *)PAGE_ALIGN((unsigned long)h.raw + macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
#endif
sk->sk_data_ready(sk, 0);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
kfree_skb(skb);
return 0;
ring_is_full:
po->stats.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk, 0);
kfree_skb(copy_skb);
goto drop_n_restore;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-264'], 'message': 'af_packet: prevent information leak
In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)
added a small information leak.
Add padding field and make sure its zeroed before copy to user.
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
CC: Patrick McHardy <kaber@trash.net>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: explicit DataFormatDimMapOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(strings::StrCat(
"Source format must of length 4 or 5, received "
"src_format = ",
src_format)));
OP_REQUIRES(
context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument(strings::StrCat(
"Destination format must of length 4 or 5, received dst_format = ",
dst_format)));
dst_idx_ = Tensor(DT_INT32, {static_cast<int64>(src_format.size())});
for (int i = 0; i < src_format.size(); ++i) {
for (int j = 0; j < dst_format.size(); ++j) {
if (dst_format[j] == src_format[i]) {
dst_idx_.vec<int>()(i) = j;
break;
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Validate that `DataFormat*` attributes form a permutation.
The `src_format` and `dst_format` attributes for the `DataFormatDimMap` and `DataFormatVecPermute` raw ops are supposed to determine a permutation. However, this was not validated and could result in unitialized memory accesses as well as writes outside of bounds and potential crashes.
While here, we also test that the format attributes have the needed length, add tests for all validation failure cases, remove unnecessary calls to `strings::StrCat`, and fix a few grammar errors.
This will be cherry-picked on the supported release branches.
PiperOrigin-RevId: 346135579
Change-Id: I1c76392382c89ad8f072d5bc93d70669851eb404'</s> |
<s>[INST] Given the following code containing errors, provide 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 log_replay(struct ntfs_inode *ni, bool *initialized)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ntfs_log *log;
struct restart_info rst_info, rst_info2;
u64 rec_lsn, ra_lsn, checkpt_lsn = 0, rlsn = 0;
struct ATTR_NAME_ENTRY *attr_names = NULL;
struct ATTR_NAME_ENTRY *ane;
struct RESTART_TABLE *dptbl = NULL;
struct RESTART_TABLE *trtbl = NULL;
const struct RESTART_TABLE *rt;
struct RESTART_TABLE *oatbl = NULL;
struct inode *inode;
struct OpenAttr *oa;
struct ntfs_inode *ni_oe;
struct ATTRIB *attr = NULL;
u64 size, vcn, undo_next_lsn;
CLST rno, lcn, lcn0, len0, clen;
void *data;
struct NTFS_RESTART *rst = NULL;
struct lcb *lcb = NULL;
struct OPEN_ATTR_ENRTY *oe;
struct TRANSACTION_ENTRY *tr;
struct DIR_PAGE_ENTRY *dp;
u32 i, bytes_per_attr_entry;
u32 l_size = ni->vfs_inode.i_size;
u32 orig_file_size = l_size;
u32 page_size, vbo, tail, off, dlen;
u32 saved_len, rec_len, transact_id;
bool use_second_page;
struct RESTART_AREA *ra2, *ra = NULL;
struct CLIENT_REC *ca, *cr;
__le16 client;
struct RESTART_HDR *rh;
const struct LFS_RECORD_HDR *frh;
const struct LOG_REC_HDR *lrh;
bool is_mapped;
bool is_ro = sb_rdonly(sbi->sb);
u64 t64;
u16 t16;
u32 t32;
/* Get the size of page. NOTE: To replay we can use default page. */
#if PAGE_SIZE >= DefaultLogPageSize && PAGE_SIZE <= DefaultLogPageSize * 2
page_size = norm_file_page(PAGE_SIZE, &l_size, true);
#else
page_size = norm_file_page(PAGE_SIZE, &l_size, false);
#endif
if (!page_size)
return -EINVAL;
log = kzalloc(sizeof(struct ntfs_log), GFP_NOFS);
if (!log)
return -ENOMEM;
log->ni = ni;
log->l_size = l_size;
log->one_page_buf = kmalloc(page_size, GFP_NOFS);
if (!log->one_page_buf) {
err = -ENOMEM;
goto out;
}
log->page_size = page_size;
log->page_mask = page_size - 1;
log->page_bits = blksize_bits(page_size);
/* Look for a restart area on the disk. */
err = log_read_rst(log, l_size, true, &rst_info);
if (err)
goto out;
/* remember 'initialized' */
*initialized = rst_info.initialized;
if (!rst_info.restart) {
if (rst_info.initialized) {
/* No restart area but the file is not initialized. */
err = -EINVAL;
goto out;
}
log_init_pg_hdr(log, page_size, page_size, 1, 1);
log_create(log, l_size, 0, get_random_int(), false, false);
log->ra = ra;
ra = log_create_ra(log);
if (!ra) {
err = -ENOMEM;
goto out;
}
log->ra = ra;
log->init_ra = true;
goto process_log;
}
/*
* If the restart offset above wasn't zero then we won't
* look for a second restart.
*/
if (rst_info.vbo)
goto check_restart_area;
err = log_read_rst(log, l_size, false, &rst_info2);
/* Determine which restart area to use. */
if (!rst_info2.restart || rst_info2.last_lsn <= rst_info.last_lsn)
goto use_first_page;
use_second_page = true;
if (rst_info.chkdsk_was_run && page_size != rst_info.vbo) {
struct RECORD_PAGE_HDR *sp = NULL;
bool usa_error;
if (!read_log_page(log, page_size, &sp, &usa_error) &&
sp->rhdr.sign == NTFS_CHKD_SIGNATURE) {
use_second_page = false;
}
kfree(sp);
}
if (use_second_page) {
kfree(rst_info.r_page);
memcpy(&rst_info, &rst_info2, sizeof(struct restart_info));
rst_info2.r_page = NULL;
}
use_first_page:
kfree(rst_info2.r_page);
check_restart_area:
/*
* If the restart area is at offset 0, we want
* to write the second restart area first.
*/
log->init_ra = !!rst_info.vbo;
/* If we have a valid page then grab a pointer to the restart area. */
ra2 = rst_info.valid_page
? Add2Ptr(rst_info.r_page,
le16_to_cpu(rst_info.r_page->ra_off))
: NULL;
if (rst_info.chkdsk_was_run ||
(ra2 && ra2->client_idx[1] == LFS_NO_CLIENT_LE)) {
bool wrapped = false;
bool use_multi_page = false;
u32 open_log_count;
/* Do some checks based on whether we have a valid log page. */
if (!rst_info.valid_page) {
open_log_count = get_random_int();
goto init_log_instance;
}
open_log_count = le32_to_cpu(ra2->open_log_count);
/*
* If the restart page size isn't changing then we want to
* check how much work we need to do.
*/
if (page_size != le32_to_cpu(rst_info.r_page->sys_page_size))
goto init_log_instance;
init_log_instance:
log_init_pg_hdr(log, page_size, page_size, 1, 1);
log_create(log, l_size, rst_info.last_lsn, open_log_count,
wrapped, use_multi_page);
ra = log_create_ra(log);
if (!ra) {
err = -ENOMEM;
goto out;
}
log->ra = ra;
/* Put the restart areas and initialize
* the log file as required.
*/
goto process_log;
}
if (!ra2) {
err = -EINVAL;
goto out;
}
/*
* If the log page or the system page sizes have changed, we can't
* use the log file. We must use the system page size instead of the
* default size if there is not a clean shutdown.
*/
t32 = le32_to_cpu(rst_info.r_page->sys_page_size);
if (page_size != t32) {
l_size = orig_file_size;
page_size =
norm_file_page(t32, &l_size, t32 == DefaultLogPageSize);
}
if (page_size != t32 ||
page_size != le32_to_cpu(rst_info.r_page->page_size)) {
err = -EINVAL;
goto out;
}
/* If the file size has shrunk then we won't mount it. */
if (l_size < le64_to_cpu(ra2->l_size)) {
err = -EINVAL;
goto out;
}
log_init_pg_hdr(log, page_size, page_size,
le16_to_cpu(rst_info.r_page->major_ver),
le16_to_cpu(rst_info.r_page->minor_ver));
log->l_size = le64_to_cpu(ra2->l_size);
log->seq_num_bits = le32_to_cpu(ra2->seq_num_bits);
log->file_data_bits = sizeof(u64) * 8 - log->seq_num_bits;
log->seq_num_mask = (8 << log->file_data_bits) - 1;
log->last_lsn = le64_to_cpu(ra2->current_lsn);
log->seq_num = log->last_lsn >> log->file_data_bits;
log->ra_off = le16_to_cpu(rst_info.r_page->ra_off);
log->restart_size = log->sys_page_size - log->ra_off;
log->record_header_len = le16_to_cpu(ra2->rec_hdr_len);
log->ra_size = le16_to_cpu(ra2->ra_len);
log->data_off = le16_to_cpu(ra2->data_off);
log->data_size = log->page_size - log->data_off;
log->reserved = log->data_size - log->record_header_len;
vbo = lsn_to_vbo(log, log->last_lsn);
if (vbo < log->first_page) {
/* This is a pseudo lsn. */
log->l_flags |= NTFSLOG_NO_LAST_LSN;
log->next_page = log->first_page;
goto find_oldest;
}
/* Find the end of this log record. */
off = final_log_off(log, log->last_lsn,
le32_to_cpu(ra2->last_lsn_data_len));
/* If we wrapped the file then increment the sequence number. */
if (off <= vbo) {
log->seq_num += 1;
log->l_flags |= NTFSLOG_WRAPPED;
}
/* Now compute the next log page to use. */
vbo &= ~log->sys_page_mask;
tail = log->page_size - (off & log->page_mask) - 1;
/*
*If we can fit another log record on the page,
* move back a page the log file.
*/
if (tail >= log->record_header_len) {
log->l_flags |= NTFSLOG_REUSE_TAIL;
log->next_page = vbo;
} else {
log->next_page = next_page_off(log, vbo);
}
find_oldest:
/*
* Find the oldest client lsn. Use the last
* flushed lsn as a starting point.
*/
log->oldest_lsn = log->last_lsn;
oldest_client_lsn(Add2Ptr(ra2, le16_to_cpu(ra2->client_off)),
ra2->client_idx[1], &log->oldest_lsn);
log->oldest_lsn_off = lsn_to_vbo(log, log->oldest_lsn);
if (log->oldest_lsn_off < log->first_page)
log->l_flags |= NTFSLOG_NO_OLDEST_LSN;
if (!(ra2->flags & RESTART_SINGLE_PAGE_IO))
log->l_flags |= NTFSLOG_WRAPPED | NTFSLOG_MULTIPLE_PAGE_IO;
log->current_openlog_count = le32_to_cpu(ra2->open_log_count);
log->total_avail_pages = log->l_size - log->first_page;
log->total_avail = log->total_avail_pages >> log->page_bits;
log->max_current_avail = log->total_avail * log->reserved;
log->total_avail = log->total_avail * log->data_size;
log->current_avail = current_log_avail(log);
ra = kzalloc(log->restart_size, GFP_NOFS);
if (!ra) {
err = -ENOMEM;
goto out;
}
log->ra = ra;
t16 = le16_to_cpu(ra2->client_off);
if (t16 == offsetof(struct RESTART_AREA, clients)) {
memcpy(ra, ra2, log->ra_size);
} else {
memcpy(ra, ra2, offsetof(struct RESTART_AREA, clients));
memcpy(ra->clients, Add2Ptr(ra2, t16),
le16_to_cpu(ra2->ra_len) - t16);
log->current_openlog_count = get_random_int();
ra->open_log_count = cpu_to_le32(log->current_openlog_count);
log->ra_size = offsetof(struct RESTART_AREA, clients) +
sizeof(struct CLIENT_REC);
ra->client_off =
cpu_to_le16(offsetof(struct RESTART_AREA, clients));
ra->ra_len = cpu_to_le16(log->ra_size);
}
le32_add_cpu(&ra->open_log_count, 1);
/* Now we need to walk through looking for the last lsn. */
err = last_log_lsn(log);
if (err)
goto out;
log->current_avail = current_log_avail(log);
/* Remember which restart area to write first. */
log->init_ra = rst_info.vbo;
process_log:
/* 1.0, 1.1, 2.0 log->major_ver/minor_ver - short values. */
switch ((log->major_ver << 16) + log->minor_ver) {
case 0x10000:
case 0x10001:
case 0x20000:
break;
default:
ntfs_warn(sbi->sb, "\x24LogFile version %d.%d is not supported",
log->major_ver, log->minor_ver);
err = -EOPNOTSUPP;
log->set_dirty = true;
goto out;
}
/* One client "NTFS" per logfile. */
ca = Add2Ptr(ra, le16_to_cpu(ra->client_off));
for (client = ra->client_idx[1];; client = cr->next_client) {
if (client == LFS_NO_CLIENT_LE) {
/* Insert "NTFS" client LogFile. */
client = ra->client_idx[0];
if (client == LFS_NO_CLIENT_LE) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(client);
cr = ca + t16;
remove_client(ca, cr, &ra->client_idx[0]);
cr->restart_lsn = 0;
cr->oldest_lsn = cpu_to_le64(log->oldest_lsn);
cr->name_bytes = cpu_to_le32(8);
cr->name[0] = cpu_to_le16('N');
cr->name[1] = cpu_to_le16('T');
cr->name[2] = cpu_to_le16('F');
cr->name[3] = cpu_to_le16('S');
add_client(ca, t16, &ra->client_idx[1]);
break;
}
cr = ca + le16_to_cpu(client);
if (cpu_to_le32(8) == cr->name_bytes &&
cpu_to_le16('N') == cr->name[0] &&
cpu_to_le16('T') == cr->name[1] &&
cpu_to_le16('F') == cr->name[2] &&
cpu_to_le16('S') == cr->name[3])
break;
}
/* Update the client handle with the client block information. */
log->client_id.seq_num = cr->seq_num;
log->client_id.client_idx = client;
err = read_rst_area(log, &rst, &ra_lsn);
if (err)
goto out;
if (!rst)
goto out;
bytes_per_attr_entry = !rst->major_ver ? 0x2C : 0x28;
checkpt_lsn = le64_to_cpu(rst->check_point_start);
if (!checkpt_lsn)
checkpt_lsn = ra_lsn;
/* Allocate and Read the Transaction Table. */
if (!rst->transact_table_len)
goto check_dirty_page_table;
t64 = le64_to_cpu(rst->transact_table_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(lrh->redo_off);
rt = Add2Ptr(lrh, t16);
t32 = rec_len - t16;
/* Now check that this is a valid restart table. */
if (!check_rstbl(rt, t32)) {
err = -EINVAL;
goto out;
}
trtbl = kmemdup(rt, t32, GFP_NOFS);
if (!trtbl) {
err = -ENOMEM;
goto out;
}
lcb_put(lcb);
lcb = NULL;
check_dirty_page_table:
/* The next record back should be the Dirty Pages Table. */
if (!rst->dirty_pages_len)
goto check_attribute_names;
t64 = le64_to_cpu(rst->dirty_pages_table_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(lrh->redo_off);
rt = Add2Ptr(lrh, t16);
t32 = rec_len - t16;
/* Now check that this is a valid restart table. */
if (!check_rstbl(rt, t32)) {
err = -EINVAL;
goto out;
}
dptbl = kmemdup(rt, t32, GFP_NOFS);
if (!dptbl) {
err = -ENOMEM;
goto out;
}
/* Convert Ra version '0' into version '1'. */
if (rst->major_ver)
goto end_conv_1;
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
struct DIR_PAGE_ENTRY_32 *dp0 = (struct DIR_PAGE_ENTRY_32 *)dp;
// NOTE: Danger. Check for of boundary.
memmove(&dp->vcn, &dp0->vcn_low,
2 * sizeof(u64) +
le32_to_cpu(dp->lcns_follow) * sizeof(u64));
}
end_conv_1:
lcb_put(lcb);
lcb = NULL;
/*
* Go through the table and remove the duplicates,
* remembering the oldest lsn values.
*/
if (sbi->cluster_size <= log->page_size)
goto trace_dp_table;
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
struct DIR_PAGE_ENTRY *next = dp;
while ((next = enum_rstbl(dptbl, next))) {
if (next->target_attr == dp->target_attr &&
next->vcn == dp->vcn) {
if (le64_to_cpu(next->oldest_lsn) <
le64_to_cpu(dp->oldest_lsn)) {
dp->oldest_lsn = next->oldest_lsn;
}
free_rsttbl_idx(dptbl, PtrOffset(dptbl, next));
}
}
}
trace_dp_table:
check_attribute_names:
/* The next record should be the Attribute Names. */
if (!rst->attr_names_len)
goto check_attr_table;
t64 = le64_to_cpu(rst->attr_names_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t32 = lrh_length(lrh);
rec_len -= t32;
attr_names = kmemdup(Add2Ptr(lrh, t32), rec_len, GFP_NOFS);
lcb_put(lcb);
lcb = NULL;
check_attr_table:
/* The next record should be the attribute Table. */
if (!rst->open_attr_len)
goto check_attribute_names2;
t64 = le64_to_cpu(rst->open_attr_table_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(lrh->redo_off);
rt = Add2Ptr(lrh, t16);
t32 = rec_len - t16;
if (!check_rstbl(rt, t32)) {
err = -EINVAL;
goto out;
}
oatbl = kmemdup(rt, t32, GFP_NOFS);
if (!oatbl) {
err = -ENOMEM;
goto out;
}
log->open_attr_tbl = oatbl;
/* Clear all of the Attr pointers. */
oe = NULL;
while ((oe = enum_rstbl(oatbl, oe))) {
if (!rst->major_ver) {
struct OPEN_ATTR_ENRTY_32 oe0;
/* Really 'oe' points to OPEN_ATTR_ENRTY_32. */
memcpy(&oe0, oe, SIZEOF_OPENATTRIBUTEENTRY0);
oe->bytes_per_index = oe0.bytes_per_index;
oe->type = oe0.type;
oe->is_dirty_pages = oe0.is_dirty_pages;
oe->name_len = 0;
oe->ref = oe0.ref;
oe->open_record_lsn = oe0.open_record_lsn;
}
oe->is_attr_name = 0;
oe->ptr = NULL;
}
lcb_put(lcb);
lcb = NULL;
check_attribute_names2:
if (!rst->attr_names_len)
goto trace_attribute_table;
ane = attr_names;
if (!oatbl)
goto trace_attribute_table;
while (ane->off) {
/* TODO: Clear table on exit! */
oe = Add2Ptr(oatbl, le16_to_cpu(ane->off));
t16 = le16_to_cpu(ane->name_bytes);
oe->name_len = t16 / sizeof(short);
oe->ptr = ane->name;
oe->is_attr_name = 2;
ane = Add2Ptr(ane, sizeof(struct ATTR_NAME_ENTRY) + t16);
}
trace_attribute_table:
/*
* If the checkpt_lsn is zero, then this is a freshly
* formatted disk and we have no work to do.
*/
if (!checkpt_lsn) {
err = 0;
goto out;
}
if (!oatbl) {
oatbl = init_rsttbl(bytes_per_attr_entry, 8);
if (!oatbl) {
err = -ENOMEM;
goto out;
}
}
log->open_attr_tbl = oatbl;
/* Start the analysis pass from the Checkpoint lsn. */
rec_lsn = checkpt_lsn;
/* Read the first lsn. */
err = read_log_rec_lcb(log, checkpt_lsn, lcb_ctx_next, &lcb);
if (err)
goto out;
/* Loop to read all subsequent records to the end of the log file. */
next_log_record_analyze:
err = read_next_log_rec(log, lcb, &rec_lsn);
if (err)
goto out;
if (!rec_lsn)
goto end_log_records_enumerate;
frh = lcb->lrh;
transact_id = le32_to_cpu(frh->transact_id);
rec_len = le32_to_cpu(frh->client_data_len);
lrh = lcb->log_rec;
if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
/*
* The first lsn after the previous lsn remembered
* the checkpoint is the first candidate for the rlsn.
*/
if (!rlsn)
rlsn = rec_lsn;
if (LfsClientRecord != frh->record_type)
goto next_log_record_analyze;
/*
* Now update the Transaction Table for this transaction. If there
* is no entry present or it is unallocated we allocate the entry.
*/
if (!trtbl) {
trtbl = init_rsttbl(sizeof(struct TRANSACTION_ENTRY),
INITIAL_NUMBER_TRANSACTIONS);
if (!trtbl) {
err = -ENOMEM;
goto out;
}
}
tr = Add2Ptr(trtbl, transact_id);
if (transact_id >= bytes_per_rt(trtbl) ||
tr->next != RESTART_ENTRY_ALLOCATED_LE) {
tr = alloc_rsttbl_from_idx(&trtbl, transact_id);
if (!tr) {
err = -ENOMEM;
goto out;
}
tr->transact_state = TransactionActive;
tr->first_lsn = cpu_to_le64(rec_lsn);
}
tr->prev_lsn = tr->undo_next_lsn = cpu_to_le64(rec_lsn);
/*
* If this is a compensation log record, then change
* the undo_next_lsn to be the undo_next_lsn of this record.
*/
if (lrh->undo_op == cpu_to_le16(CompensationLogRecord))
tr->undo_next_lsn = frh->client_undo_next_lsn;
/* Dispatch to handle log record depending on type. */
switch (le16_to_cpu(lrh->redo_op)) {
case InitializeFileRecordSegment:
case DeallocateFileRecordSegment:
case WriteEndOfFileRecordSegment:
case CreateAttribute:
case DeleteAttribute:
case UpdateResidentValue:
case UpdateNonresidentValue:
case UpdateMappingPairs:
case SetNewAttributeSizes:
case AddIndexEntryRoot:
case DeleteIndexEntryRoot:
case AddIndexEntryAllocation:
case DeleteIndexEntryAllocation:
case WriteEndOfIndexBuffer:
case SetIndexEntryVcnRoot:
case SetIndexEntryVcnAllocation:
case UpdateFileNameRoot:
case UpdateFileNameAllocation:
case SetBitsInNonresidentBitMap:
case ClearBitsInNonresidentBitMap:
case UpdateRecordDataRoot:
case UpdateRecordDataAllocation:
case ZeroEndOfFileRecord:
t16 = le16_to_cpu(lrh->target_attr);
t64 = le64_to_cpu(lrh->target_vcn);
dp = find_dp(dptbl, t16, t64);
if (dp)
goto copy_lcns;
/*
* Calculate the number of clusters per page the system
* which wrote the checkpoint, possibly creating the table.
*/
if (dptbl) {
t32 = (le16_to_cpu(dptbl->size) -
sizeof(struct DIR_PAGE_ENTRY)) /
sizeof(u64);
} else {
t32 = log->clst_per_page;
kfree(dptbl);
dptbl = init_rsttbl(struct_size(dp, page_lcns, t32),
32);
if (!dptbl) {
err = -ENOMEM;
goto out;
}
}
dp = alloc_rsttbl_idx(&dptbl);
if (!dp) {
err = -ENOMEM;
goto out;
}
dp->target_attr = cpu_to_le32(t16);
dp->transfer_len = cpu_to_le32(t32 << sbi->cluster_bits);
dp->lcns_follow = cpu_to_le32(t32);
dp->vcn = cpu_to_le64(t64 & ~((u64)t32 - 1));
dp->oldest_lsn = cpu_to_le64(rec_lsn);
copy_lcns:
/*
* Copy the Lcns from the log record into the Dirty Page Entry.
* TODO: For different page size support, must somehow make
* whole routine a loop, case Lcns do not fit below.
*/
t16 = le16_to_cpu(lrh->lcns_follow);
for (i = 0; i < t16; i++) {
size_t j = (size_t)(le64_to_cpu(lrh->target_vcn) -
le64_to_cpu(dp->vcn));
dp->page_lcns[j + i] = lrh->page_lcns[i];
}
goto next_log_record_analyze;
case DeleteDirtyClusters: {
u32 range_count =
le16_to_cpu(lrh->redo_len) / sizeof(struct LCN_RANGE);
const struct LCN_RANGE *r =
Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));
/* Loop through all of the Lcn ranges this log record. */
for (i = 0; i < range_count; i++, r++) {
u64 lcn0 = le64_to_cpu(r->lcn);
u64 lcn_e = lcn0 + le64_to_cpu(r->len) - 1;
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
u32 j;
t32 = le32_to_cpu(dp->lcns_follow);
for (j = 0; j < t32; j++) {
t64 = le64_to_cpu(dp->page_lcns[j]);
if (t64 >= lcn0 && t64 <= lcn_e)
dp->page_lcns[j] = 0;
}
}
}
goto next_log_record_analyze;
;
}
case OpenNonresidentAttribute:
t16 = le16_to_cpu(lrh->target_attr);
if (t16 >= bytes_per_rt(oatbl)) {
/*
* Compute how big the table needs to be.
* Add 10 extra entries for some cushion.
*/
u32 new_e = t16 / le16_to_cpu(oatbl->size);
new_e += 10 - le16_to_cpu(oatbl->used);
oatbl = extend_rsttbl(oatbl, new_e, ~0u);
log->open_attr_tbl = oatbl;
if (!oatbl) {
err = -ENOMEM;
goto out;
}
}
/* Point to the entry being opened. */
oe = alloc_rsttbl_from_idx(&oatbl, t16);
log->open_attr_tbl = oatbl;
if (!oe) {
err = -ENOMEM;
goto out;
}
/* Initialize this entry from the log record. */
t16 = le16_to_cpu(lrh->redo_off);
if (!rst->major_ver) {
/* Convert version '0' into version '1'. */
struct OPEN_ATTR_ENRTY_32 *oe0 = Add2Ptr(lrh, t16);
oe->bytes_per_index = oe0->bytes_per_index;
oe->type = oe0->type;
oe->is_dirty_pages = oe0->is_dirty_pages;
oe->name_len = 0; //oe0.name_len;
oe->ref = oe0->ref;
oe->open_record_lsn = oe0->open_record_lsn;
} else {
memcpy(oe, Add2Ptr(lrh, t16), bytes_per_attr_entry);
}
t16 = le16_to_cpu(lrh->undo_len);
if (t16) {
oe->ptr = kmalloc(t16, GFP_NOFS);
if (!oe->ptr) {
err = -ENOMEM;
goto out;
}
oe->name_len = t16 / sizeof(short);
memcpy(oe->ptr,
Add2Ptr(lrh, le16_to_cpu(lrh->undo_off)), t16);
oe->is_attr_name = 1;
} else {
oe->ptr = NULL;
oe->is_attr_name = 0;
}
goto next_log_record_analyze;
case HotFix:
t16 = le16_to_cpu(lrh->target_attr);
t64 = le64_to_cpu(lrh->target_vcn);
dp = find_dp(dptbl, t16, t64);
if (dp) {
size_t j = le64_to_cpu(lrh->target_vcn) -
le64_to_cpu(dp->vcn);
if (dp->page_lcns[j])
dp->page_lcns[j] = lrh->page_lcns[0];
}
goto next_log_record_analyze;
case EndTopLevelAction:
tr = Add2Ptr(trtbl, transact_id);
tr->prev_lsn = cpu_to_le64(rec_lsn);
tr->undo_next_lsn = frh->client_undo_next_lsn;
goto next_log_record_analyze;
case PrepareTransaction:
tr = Add2Ptr(trtbl, transact_id);
tr->transact_state = TransactionPrepared;
goto next_log_record_analyze;
case CommitTransaction:
tr = Add2Ptr(trtbl, transact_id);
tr->transact_state = TransactionCommitted;
goto next_log_record_analyze;
case ForgetTransaction:
free_rsttbl_idx(trtbl, transact_id);
goto next_log_record_analyze;
case Noop:
case OpenAttributeTableDump:
case AttributeNamesDump:
case DirtyPageTableDump:
case TransactionTableDump:
/* The following cases require no action the Analysis Pass. */
goto next_log_record_analyze;
default:
/*
* All codes will be explicitly handled.
* If we see a code we do not expect, then we are trouble.
*/
goto next_log_record_analyze;
}
end_log_records_enumerate:
lcb_put(lcb);
lcb = NULL;
/*
* Scan the Dirty Page Table and Transaction Table for
* the lowest lsn, and return it as the Redo lsn.
*/
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
t64 = le64_to_cpu(dp->oldest_lsn);
if (t64 && t64 < rlsn)
rlsn = t64;
}
tr = NULL;
while ((tr = enum_rstbl(trtbl, tr))) {
t64 = le64_to_cpu(tr->first_lsn);
if (t64 && t64 < rlsn)
rlsn = t64;
}
/*
* Only proceed if the Dirty Page Table or Transaction
* table are not empty.
*/
if ((!dptbl || !dptbl->total) && (!trtbl || !trtbl->total))
goto end_reply;
sbi->flags |= NTFS_FLAGS_NEED_REPLAY;
if (is_ro)
goto out;
/* Reopen all of the attributes with dirty pages. */
oe = NULL;
next_open_attribute:
oe = enum_rstbl(oatbl, oe);
if (!oe) {
err = 0;
dp = NULL;
goto next_dirty_page;
}
oa = kzalloc(sizeof(struct OpenAttr), GFP_NOFS);
if (!oa) {
err = -ENOMEM;
goto out;
}
inode = ntfs_iget5(sbi->sb, &oe->ref, NULL);
if (IS_ERR(inode))
goto fake_attr;
if (is_bad_inode(inode)) {
iput(inode);
fake_attr:
if (oa->ni) {
iput(&oa->ni->vfs_inode);
oa->ni = NULL;
}
attr = attr_create_nonres_log(sbi, oe->type, 0, oe->ptr,
oe->name_len, 0);
if (!attr) {
kfree(oa);
err = -ENOMEM;
goto out;
}
oa->attr = attr;
oa->run1 = &oa->run0;
goto final_oe;
}
ni_oe = ntfs_i(inode);
oa->ni = ni_oe;
attr = ni_find_attr(ni_oe, NULL, NULL, oe->type, oe->ptr, oe->name_len,
NULL, NULL);
if (!attr)
goto fake_attr;
t32 = le32_to_cpu(attr->size);
oa->attr = kmemdup(attr, t32, GFP_NOFS);
if (!oa->attr)
goto fake_attr;
if (!S_ISDIR(inode->i_mode)) {
if (attr->type == ATTR_DATA && !attr->name_len) {
oa->run1 = &ni_oe->file.run;
goto final_oe;
}
} else {
if (attr->type == ATTR_ALLOC &&
attr->name_len == ARRAY_SIZE(I30_NAME) &&
!memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME))) {
oa->run1 = &ni_oe->dir.alloc_run;
goto final_oe;
}
}
if (attr->non_res) {
u16 roff = le16_to_cpu(attr->nres.run_off);
CLST svcn = le64_to_cpu(attr->nres.svcn);
err = run_unpack(&oa->run0, sbi, inode->i_ino, svcn,
le64_to_cpu(attr->nres.evcn), svcn,
Add2Ptr(attr, roff), t32 - roff);
if (err < 0) {
kfree(oa->attr);
oa->attr = NULL;
goto fake_attr;
}
err = 0;
}
oa->run1 = &oa->run0;
attr = oa->attr;
final_oe:
if (oe->is_attr_name == 1)
kfree(oe->ptr);
oe->is_attr_name = 0;
oe->ptr = oa;
oe->name_len = attr->name_len;
goto next_open_attribute;
/*
* Now loop through the dirty page table to extract all of the Vcn/Lcn.
* Mapping that we have, and insert it into the appropriate run.
*/
next_dirty_page:
dp = enum_rstbl(dptbl, dp);
if (!dp)
goto do_redo_1;
oe = Add2Ptr(oatbl, le32_to_cpu(dp->target_attr));
if (oe->next != RESTART_ENTRY_ALLOCATED_LE)
goto next_dirty_page;
oa = oe->ptr;
if (!oa)
goto next_dirty_page;
i = -1;
next_dirty_page_vcn:
i += 1;
if (i >= le32_to_cpu(dp->lcns_follow))
goto next_dirty_page;
vcn = le64_to_cpu(dp->vcn) + i;
size = (vcn + 1) << sbi->cluster_bits;
if (!dp->page_lcns[i])
goto next_dirty_page_vcn;
rno = ino_get(&oe->ref);
if (rno <= MFT_REC_MIRR &&
size < (MFT_REC_VOL + 1) * sbi->record_size &&
oe->type == ATTR_DATA) {
goto next_dirty_page_vcn;
}
lcn = le64_to_cpu(dp->page_lcns[i]);
if ((!run_lookup_entry(oa->run1, vcn, &lcn0, &len0, NULL) ||
lcn0 != lcn) &&
!run_add_entry(oa->run1, vcn, lcn, 1, false)) {
err = -ENOMEM;
goto out;
}
attr = oa->attr;
t64 = le64_to_cpu(attr->nres.alloc_size);
if (size > t64) {
attr->nres.valid_size = attr->nres.data_size =
attr->nres.alloc_size = cpu_to_le64(size);
}
goto next_dirty_page_vcn;
do_redo_1:
/*
* Perform the Redo Pass, to restore all of the dirty pages to the same
* contents that they had immediately before the crash. If the dirty
* page table is empty, then we can skip the entire Redo Pass.
*/
if (!dptbl || !dptbl->total)
goto do_undo_action;
rec_lsn = rlsn;
/*
* Read the record at the Redo lsn, before falling
* into common code to handle each record.
*/
err = read_log_rec_lcb(log, rlsn, lcb_ctx_next, &lcb);
if (err)
goto out;
/*
* Now loop to read all of our log records forwards, until
* we hit the end of the file, cleaning up at the end.
*/
do_action_next:
frh = lcb->lrh;
if (LfsClientRecord != frh->record_type)
goto read_next_log_do_action;
transact_id = le32_to_cpu(frh->transact_id);
rec_len = le32_to_cpu(frh->client_data_len);
lrh = lcb->log_rec;
if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
/* Ignore log records that do not update pages. */
if (lrh->lcns_follow)
goto find_dirty_page;
goto read_next_log_do_action;
find_dirty_page:
t16 = le16_to_cpu(lrh->target_attr);
t64 = le64_to_cpu(lrh->target_vcn);
dp = find_dp(dptbl, t16, t64);
if (!dp)
goto read_next_log_do_action;
if (rec_lsn < le64_to_cpu(dp->oldest_lsn))
goto read_next_log_do_action;
t16 = le16_to_cpu(lrh->target_attr);
if (t16 >= bytes_per_rt(oatbl)) {
err = -EINVAL;
goto out;
}
oe = Add2Ptr(oatbl, t16);
if (oe->next != RESTART_ENTRY_ALLOCATED_LE) {
err = -EINVAL;
goto out;
}
oa = oe->ptr;
if (!oa) {
err = -EINVAL;
goto out;
}
attr = oa->attr;
vcn = le64_to_cpu(lrh->target_vcn);
if (!run_lookup_entry(oa->run1, vcn, &lcn, NULL, NULL) ||
lcn == SPARSE_LCN) {
goto read_next_log_do_action;
}
/* Point to the Redo data and get its length. */
data = Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));
dlen = le16_to_cpu(lrh->redo_len);
/* Shorten length by any Lcns which were deleted. */
saved_len = dlen;
for (i = le16_to_cpu(lrh->lcns_follow); i; i--) {
size_t j;
u32 alen, voff;
voff = le16_to_cpu(lrh->record_off) +
le16_to_cpu(lrh->attr_off);
voff += le16_to_cpu(lrh->cluster_off) << SECTOR_SHIFT;
/* If the Vcn question is allocated, we can just get out. */
j = le64_to_cpu(lrh->target_vcn) - le64_to_cpu(dp->vcn);
if (dp->page_lcns[j + i - 1])
break;
if (!saved_len)
saved_len = 1;
/*
* Calculate the allocated space left relative to the
* log record Vcn, after removing this unallocated Vcn.
*/
alen = (i - 1) << sbi->cluster_bits;
/*
* If the update described this log record goes beyond
* the allocated space, then we will have to reduce the length.
*/
if (voff >= alen)
dlen = 0;
else if (voff + dlen > alen)
dlen = alen - voff;
}
/*
* If the resulting dlen from above is now zero,
* we can skip this log record.
*/
if (!dlen && saved_len)
goto read_next_log_do_action;
t16 = le16_to_cpu(lrh->redo_op);
if (can_skip_action(t16))
goto read_next_log_do_action;
/* Apply the Redo operation a common routine. */
err = do_action(log, oe, lrh, t16, data, dlen, rec_len, &rec_lsn);
if (err)
goto out;
/* Keep reading and looping back until end of file. */
read_next_log_do_action:
err = read_next_log_rec(log, lcb, &rec_lsn);
if (!err && rec_lsn)
goto do_action_next;
lcb_put(lcb);
lcb = NULL;
do_undo_action:
/* Scan Transaction Table. */
tr = NULL;
transaction_table_next:
tr = enum_rstbl(trtbl, tr);
if (!tr)
goto undo_action_done;
if (TransactionActive != tr->transact_state || !tr->undo_next_lsn) {
free_rsttbl_idx(trtbl, PtrOffset(trtbl, tr));
goto transaction_table_next;
}
log->transaction_id = PtrOffset(trtbl, tr);
undo_next_lsn = le64_to_cpu(tr->undo_next_lsn);
/*
* We only have to do anything if the transaction has
* something its undo_next_lsn field.
*/
if (!undo_next_lsn)
goto commit_undo;
/* Read the first record to be undone by this transaction. */
err = read_log_rec_lcb(log, undo_next_lsn, lcb_ctx_undo_next, &lcb);
if (err)
goto out;
/*
* Now loop to read all of our log records forwards,
* until we hit the end of the file, cleaning up at the end.
*/
undo_action_next:
lrh = lcb->log_rec;
frh = lcb->lrh;
transact_id = le32_to_cpu(frh->transact_id);
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
if (lrh->undo_op == cpu_to_le16(Noop))
goto read_next_log_undo_action;
oe = Add2Ptr(oatbl, le16_to_cpu(lrh->target_attr));
oa = oe->ptr;
t16 = le16_to_cpu(lrh->lcns_follow);
if (!t16)
goto add_allocated_vcns;
is_mapped = run_lookup_entry(oa->run1, le64_to_cpu(lrh->target_vcn),
&lcn, &clen, NULL);
/*
* If the mapping isn't already the table or the mapping
* corresponds to a hole the mapping, we need to make sure
* there is no partial page already memory.
*/
if (is_mapped && lcn != SPARSE_LCN && clen >= t16)
goto add_allocated_vcns;
vcn = le64_to_cpu(lrh->target_vcn);
vcn &= ~(log->clst_per_page - 1);
add_allocated_vcns:
for (i = 0, vcn = le64_to_cpu(lrh->target_vcn),
size = (vcn + 1) << sbi->cluster_bits;
i < t16; i++, vcn += 1, size += sbi->cluster_size) {
attr = oa->attr;
if (!attr->non_res) {
if (size > le32_to_cpu(attr->res.data_size))
attr->res.data_size = cpu_to_le32(size);
} else {
if (size > le64_to_cpu(attr->nres.data_size))
attr->nres.valid_size = attr->nres.data_size =
attr->nres.alloc_size =
cpu_to_le64(size);
}
}
t16 = le16_to_cpu(lrh->undo_op);
if (can_skip_action(t16))
goto read_next_log_undo_action;
/* Point to the Redo data and get its length. */
data = Add2Ptr(lrh, le16_to_cpu(lrh->undo_off));
dlen = le16_to_cpu(lrh->undo_len);
/* It is time to apply the undo action. */
err = do_action(log, oe, lrh, t16, data, dlen, rec_len, NULL);
read_next_log_undo_action:
/*
* Keep reading and looping back until we have read the
* last record for this transaction.
*/
err = read_next_log_rec(log, lcb, &rec_lsn);
if (err)
goto out;
if (rec_lsn)
goto undo_action_next;
lcb_put(lcb);
lcb = NULL;
commit_undo:
free_rsttbl_idx(trtbl, log->transaction_id);
log->transaction_id = 0;
goto transaction_table_next;
undo_action_done:
ntfs_update_mftmirr(sbi, 0);
sbi->flags &= ~NTFS_FLAGS_NEED_REPLAY;
end_reply:
err = 0;
if (is_ro)
goto out;
rh = kzalloc(log->page_size, GFP_NOFS);
if (!rh) {
err = -ENOMEM;
goto out;
}
rh->rhdr.sign = NTFS_RSTR_SIGNATURE;
rh->rhdr.fix_off = cpu_to_le16(offsetof(struct RESTART_HDR, fixups));
t16 = (log->page_size >> SECTOR_SHIFT) + 1;
rh->rhdr.fix_num = cpu_to_le16(t16);
rh->sys_page_size = cpu_to_le32(log->page_size);
rh->page_size = cpu_to_le32(log->page_size);
t16 = ALIGN(offsetof(struct RESTART_HDR, fixups) + sizeof(short) * t16,
8);
rh->ra_off = cpu_to_le16(t16);
rh->minor_ver = cpu_to_le16(1); // 0x1A:
rh->major_ver = cpu_to_le16(1); // 0x1C:
ra2 = Add2Ptr(rh, t16);
memcpy(ra2, ra, sizeof(struct RESTART_AREA));
ra2->client_idx[0] = 0;
ra2->client_idx[1] = LFS_NO_CLIENT_LE;
ra2->flags = cpu_to_le16(2);
le32_add_cpu(&ra2->open_log_count, 1);
ntfs_fix_pre_write(&rh->rhdr, log->page_size);
err = ntfs_sb_write_run(sbi, &ni->file.run, 0, rh, log->page_size, 0);
if (!err)
err = ntfs_sb_write_run(sbi, &log->ni->file.run, log->page_size,
rh, log->page_size, 0);
kfree(rh);
if (err)
goto out;
out:
kfree(rst);
if (lcb)
lcb_put(lcb);
/*
* Scan the Open Attribute Table to close all of
* the open attributes.
*/
oe = NULL;
while ((oe = enum_rstbl(oatbl, oe))) {
rno = ino_get(&oe->ref);
if (oe->is_attr_name == 1) {
kfree(oe->ptr);
oe->ptr = NULL;
continue;
}
if (oe->is_attr_name)
continue;
oa = oe->ptr;
if (!oa)
continue;
run_close(&oa->run0);
kfree(oa->attr);
if (oa->ni)
iput(&oa->ni->vfs_inode);
kfree(oa);
}
kfree(trtbl);
kfree(oatbl);
kfree(dptbl);
kfree(attr_names);
kfree(rst_info.r_page);
kfree(ra);
kfree(log->one_page_buf);
if (err)
sbi->flags |= NTFS_FLAGS_NEED_REPLAY;
if (err == -EROFS)
err = 0;
else if (log->set_dirty)
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
kfree(log);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'fs/ntfs3: Fix invalid free in log_replay
log_read_rst() returns ENOMEM error when there is not enough memory.
In this case, if info is returned without initialization,
it attempts to kfree the uninitialized info->r_page pointer. This patch
moves the memset initialization code to before log_read_rst() is called.
Reported-by: Gerald Lee <sundaywind2004@gmail.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
Signed-off-by: Konstantin Komarov <almaz.alexandrovich@paragon-software.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int __driver_rfc4106_decrypt(struct aead_request *req)
{
u8 one_entry_in_sg = 0;
u8 *src, *dst, *assoc;
unsigned long tempCipherLen = 0;
__be32 counter = cpu_to_be32(1);
int retval = 0;
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
struct aesni_rfc4106_gcm_ctx *ctx = aesni_rfc4106_gcm_ctx_get(tfm);
u32 key_len = ctx->aes_key_expanded.key_length;
void *aes_ctx = &(ctx->aes_key_expanded);
unsigned long auth_tag_len = crypto_aead_authsize(tfm);
u8 iv_and_authTag[32+AESNI_ALIGN];
u8 *iv = (u8 *) PTR_ALIGN((u8 *)iv_and_authTag, AESNI_ALIGN);
u8 *authTag = iv + 16;
struct scatter_walk src_sg_walk;
struct scatter_walk assoc_sg_walk;
struct scatter_walk dst_sg_walk;
unsigned int i;
if (unlikely((req->cryptlen < auth_tag_len) ||
(req->assoclen != 8 && req->assoclen != 12)))
return -EINVAL;
if (unlikely(auth_tag_len != 8 && auth_tag_len != 12 && auth_tag_len != 16))
return -EINVAL;
if (unlikely(key_len != AES_KEYSIZE_128 &&
key_len != AES_KEYSIZE_192 &&
key_len != AES_KEYSIZE_256))
return -EINVAL;
/* Assuming we are supporting rfc4106 64-bit extended */
/* sequence numbers We need to have the AAD length */
/* equal to 8 or 12 bytes */
tempCipherLen = (unsigned long)(req->cryptlen - auth_tag_len);
/* IV below built */
for (i = 0; i < 4; i++)
*(iv+i) = ctx->nonce[i];
for (i = 0; i < 8; i++)
*(iv+4+i) = req->iv[i];
*((__be32 *)(iv+12)) = counter;
if ((sg_is_last(req->src)) && (sg_is_last(req->assoc))) {
one_entry_in_sg = 1;
scatterwalk_start(&src_sg_walk, req->src);
scatterwalk_start(&assoc_sg_walk, req->assoc);
src = scatterwalk_map(&src_sg_walk);
assoc = scatterwalk_map(&assoc_sg_walk);
dst = src;
if (unlikely(req->src != req->dst)) {
scatterwalk_start(&dst_sg_walk, req->dst);
dst = scatterwalk_map(&dst_sg_walk);
}
} else {
/* Allocate memory for src, dst, assoc */
src = kmalloc(req->cryptlen + req->assoclen, GFP_ATOMIC);
if (!src)
return -ENOMEM;
assoc = (src + req->cryptlen + auth_tag_len);
scatterwalk_map_and_copy(src, req->src, 0, req->cryptlen, 0);
scatterwalk_map_and_copy(assoc, req->assoc, 0,
req->assoclen, 0);
dst = src;
}
aesni_gcm_dec_tfm(aes_ctx, dst, src, tempCipherLen, iv,
ctx->hash_subkey, assoc, (unsigned long)req->assoclen,
authTag, auth_tag_len);
/* Compare generated tag with passed in tag. */
retval = crypto_memneq(src + tempCipherLen, authTag, auth_tag_len) ?
-EBADMSG : 0;
if (one_entry_in_sg) {
if (unlikely(req->src != req->dst)) {
scatterwalk_unmap(dst);
scatterwalk_done(&dst_sg_walk, 0, 0);
}
scatterwalk_unmap(src);
scatterwalk_unmap(assoc);
scatterwalk_done(&src_sg_walk, 0, 0);
scatterwalk_done(&assoc_sg_walk, 0, 0);
} else {
scatterwalk_map_and_copy(dst, req->dst, 0, req->cryptlen, 1);
kfree(src);
}
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'crypto: aesni - fix memory usage in GCM decryption
The kernel crypto API logic requires the caller to provide the
length of (ciphertext || authentication tag) as cryptlen for the
AEAD decryption operation. Thus, the cipher implementation must
calculate the size of the plaintext output itself and cannot simply use
cryptlen.
The RFC4106 GCM decryption operation tries to overwrite cryptlen memory
in req->dst. As the destination buffer for decryption only needs to hold
the plaintext memory but cryptlen references the input buffer holding
(ciphertext || authentication tag), the assumption of the destination
buffer length in RFC4106 GCM operation leads to a too large size. This
patch simply uses the already calculated plaintext size.
In addition, this patch fixes the offset calculation of the AAD buffer
pointer: as mentioned before, cryptlen already includes the size of the
tag. Thus, the tag does not need to be added. With the addition, the AAD
will be written beyond the already allocated buffer.
Note, this fixes a kernel crash that can be triggered from user space
via AF_ALG(aead) -- simply use the libkcapi test application
from [1] and update it to use rfc4106-gcm-aes.
Using [1], the changes were tested using CAVS vectors to demonstrate
that the crypto operation still delivers the right results.
[1] http://www.chronox.de/libkcapi.html
CC: Tadeusz Struk <tadeusz.struk@intel.com>
Cc: stable@vger.kernel.org
Signed-off-by: Stephan Mueller <smueller@chronox.de>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Status CalculateOutputIndex(OpKernelContext* context, int dimension,
const vector<INDEX_TYPE>& parent_output_index,
INDEX_TYPE output_index_multiplier,
INDEX_TYPE output_size,
vector<INDEX_TYPE>* result) {
const RowPartitionTensor row_partition_tensor =
GetRowPartitionTensor(context, dimension);
auto partition_type = GetRowPartitionTypeByDimension(dimension);
switch (partition_type) {
case RowPartitionType::VALUE_ROWIDS:
CalculateOutputIndexValueRowID(
context, row_partition_tensor, parent_output_index,
output_index_multiplier, output_size, result);
return tensorflow::Status::OK();
case RowPartitionType::ROW_SPLITS:
if (row_partition_tensor.size() - 1 > parent_output_index.size()) {
return errors::InvalidArgument(
"Row partition size is greater than output size: ",
row_partition_tensor.size() - 1, " > ",
parent_output_index.size());
}
CalculateOutputIndexRowSplit(
context, row_partition_tensor, parent_output_index,
output_index_multiplier, output_size, result);
return tensorflow::Status::OK();
default:
return errors::InvalidArgument(
"Unsupported partition type:",
RowPartitionTypeToString(partition_type));
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-131', 'CWE-787'], 'message': 'Fix heap OOB / undefined behavior in `RaggedTensorToTensor`
PiperOrigin-RevId: 373244623
Change-Id: I2d6cbbc8c67b238a8815bf58097f7586d87c54f2'</s> |
<s>[INST] Given the following code containing errors, provide 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 yam_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct yam_port *yp = netdev_priv(dev);
struct yamdrv_ioctl_cfg yi;
struct yamdrv_ioctl_mcs *ym;
int ioctl_cmd;
if (copy_from_user(&ioctl_cmd, ifr->ifr_data, sizeof(int)))
return -EFAULT;
if (yp->magic != YAM_MAGIC)
return -EINVAL;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd != SIOCDEVPRIVATE)
return -EINVAL;
switch (ioctl_cmd) {
case SIOCYAMRESERVED:
return -EINVAL; /* unused */
case SIOCYAMSMCS:
if (netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((ym = kmalloc(sizeof(struct yamdrv_ioctl_mcs), GFP_KERNEL)) == NULL)
return -ENOBUFS;
if (copy_from_user(ym, ifr->ifr_data, sizeof(struct yamdrv_ioctl_mcs))) {
kfree(ym);
return -EFAULT;
}
if (ym->bitrate > YAM_MAXBITRATE) {
kfree(ym);
return -EINVAL;
}
/* setting predef as 0 for loading userdefined mcs data */
add_mcs(ym->bits, ym->bitrate, 0);
kfree(ym);
break;
case SIOCYAMSCFG:
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&yi, ifr->ifr_data, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
if ((yi.cfg.mask & YAM_IOBASE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_IRQ) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BITRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BAUDRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if (yi.cfg.mask & YAM_IOBASE) {
yp->iobase = yi.cfg.iobase;
dev->base_addr = yi.cfg.iobase;
}
if (yi.cfg.mask & YAM_IRQ) {
if (yi.cfg.irq > 15)
return -EINVAL;
yp->irq = yi.cfg.irq;
dev->irq = yi.cfg.irq;
}
if (yi.cfg.mask & YAM_BITRATE) {
if (yi.cfg.bitrate > YAM_MAXBITRATE)
return -EINVAL;
yp->bitrate = yi.cfg.bitrate;
}
if (yi.cfg.mask & YAM_BAUDRATE) {
if (yi.cfg.baudrate > YAM_MAXBAUDRATE)
return -EINVAL;
yp->baudrate = yi.cfg.baudrate;
}
if (yi.cfg.mask & YAM_MODE) {
if (yi.cfg.mode > YAM_MAXMODE)
return -EINVAL;
yp->dupmode = yi.cfg.mode;
}
if (yi.cfg.mask & YAM_HOLDDLY) {
if (yi.cfg.holddly > YAM_MAXHOLDDLY)
return -EINVAL;
yp->holdd = yi.cfg.holddly;
}
if (yi.cfg.mask & YAM_TXDELAY) {
if (yi.cfg.txdelay > YAM_MAXTXDELAY)
return -EINVAL;
yp->txd = yi.cfg.txdelay;
}
if (yi.cfg.mask & YAM_TXTAIL) {
if (yi.cfg.txtail > YAM_MAXTXTAIL)
return -EINVAL;
yp->txtail = yi.cfg.txtail;
}
if (yi.cfg.mask & YAM_PERSIST) {
if (yi.cfg.persist > YAM_MAXPERSIST)
return -EINVAL;
yp->pers = yi.cfg.persist;
}
if (yi.cfg.mask & YAM_SLOTTIME) {
if (yi.cfg.slottime > YAM_MAXSLOTTIME)
return -EINVAL;
yp->slot = yi.cfg.slottime;
yp->slotcnt = yp->slot / 10;
}
break;
case SIOCYAMGCFG:
yi.cfg.mask = 0xffffffff;
yi.cfg.iobase = yp->iobase;
yi.cfg.irq = yp->irq;
yi.cfg.bitrate = yp->bitrate;
yi.cfg.baudrate = yp->baudrate;
yi.cfg.mode = yp->dupmode;
yi.cfg.txdelay = yp->txd;
yi.cfg.holddly = yp->holdd;
yi.cfg.txtail = yp->txtail;
yi.cfg.persist = yp->pers;
yi.cfg.slottime = yp->slot;
if (copy_to_user(ifr->ifr_data, &yi, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
break;
default:
return -EINVAL;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'hamradio/yam: fix info leak in ioctl
The yam_ioctl() code fails to initialise the cmd field
of the struct yamdrv_ioctl_cfg. Add an explicit memset(0)
before filling the structure to avoid the 4-byte info leak.
Signed-off-by: Salva Peiró <speiro@ai2.upv.es>
Signed-off-by: David S. Miller <davem@davemloft.net>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Proper fix for #248'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
{
const struct sched_class *class;
if (p->sched_class == rq->curr->sched_class) {
rq->curr->sched_class->check_preempt_curr(rq, p, flags);
} else {
for_each_class(class) {
if (class == rq->curr->sched_class)
break;
if (class == p->sched_class) {
resched_task(rq->curr);
break;
}
}
}
/*
* A queue event has occurred, and we're going to schedule. In
* this case, we can save a useless back to back clock update.
*/
if (test_tsk_need_resched(rq->curr))
rq->skip_clock_update = 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <efault@gmx.de>
Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com>
Tested-by: Yong Zhang <yong.zhang0@gmail.com>
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: stable@kernel.org
LKML-Reference: <1291802742.1417.9.camel@marge.simson.net>
Signed-off-by: Ingo Molnar <mingo@elte.hu>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: switch (yych) {
case 'a': goto yy52;
default: goto yy48;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.
Historically this was allowed and re2c swapped the bounds. However, it
most likely indicates an error in user code and there is only a single
occurrence in the tests (and the test in an artificial one), so although
the change is backwards incompatible there is low chance of breaking
real-world code.
This fixes second test case in the bug #394 "Stack overflow due to
recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size
but the test also has counted repetition with swapped bounds).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool Scanner::lex_str_chr(char quote, ASTChar &ast)
{
tok = cur;
ast.loc = cur_loc();
#line 837 "../src/parse/lex.re"
if (globopts->input_encoding == Enc::ASCII) {
#line 4645 "src/parse/lex.cc"
{
unsigned char yych;
unsigned int yyaccept = 0;
if ((lim - cur) < 10) { if (!fill(10)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= '\f') {
if (yych <= 0x00) goto yy711;
if (yych == '\n') goto yy715;
goto yy713;
} else {
if (yych <= '\r') goto yy717;
if (yych == '\\') goto yy718;
goto yy713;
}
yy711:
++cur;
#line 819 "../src/parse/lex.re"
{ fail_if_eof(); ast.chr = 0; return true; }
#line 4664 "src/parse/lex.cc"
yy713:
++cur;
yy714:
#line 821 "../src/parse/lex.re"
{ ast.chr = decode(tok); return tok[0] != quote; }
#line 4670 "src/parse/lex.cc"
yy715:
++cur;
#line 813 "../src/parse/lex.re"
{ msg.error(ast.loc, "newline in character string"); exit(1); }
#line 4675 "src/parse/lex.cc"
yy717:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy715;
goto yy714;
yy718:
yych = (unsigned char)*++cur;
if (yych <= '`') {
if (yych <= '3') {
if (yych <= '\n') {
if (yych <= 0x00) goto yy719;
if (yych <= '\t') goto yy720;
goto yy715;
} else {
if (yych == '\r') goto yy722;
if (yych <= '/') goto yy720;
goto yy723;
}
} else {
if (yych <= 'W') {
if (yych <= '7') goto yy725;
if (yych == 'U') goto yy726;
goto yy720;
} else {
if (yych <= 'X') goto yy728;
if (yych == '\\') goto yy729;
goto yy720;
}
}
} else {
if (yych <= 'q') {
if (yych <= 'e') {
if (yych <= 'a') goto yy731;
if (yych <= 'b') goto yy733;
goto yy720;
} else {
if (yych <= 'f') goto yy735;
if (yych == 'n') goto yy737;
goto yy720;
}
} else {
if (yych <= 'u') {
if (yych <= 'r') goto yy739;
if (yych <= 's') goto yy720;
if (yych <= 't') goto yy741;
goto yy728;
} else {
if (yych <= 'v') goto yy743;
if (yych == 'x') goto yy745;
goto yy720;
}
}
}
yy719:
#line 816 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error in escape sequence"); exit(1); }
#line 4731 "src/parse/lex.cc"
yy720:
++cur;
yy721:
#line 832 "../src/parse/lex.re"
{
ast.chr = decode(tok + 1);
if (tok[1] != quote) msg.warn.useless_escape(ast.loc, tok, cur);
return true;
}
#line 4741 "src/parse/lex.cc"
yy722:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy715;
goto yy721;
yy723:
yyaccept = 0;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '/') goto yy724;
if (yych <= '7') goto yy746;
yy724:
#line 815 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error in octal escape sequence"); exit(1); }
#line 4754 "src/parse/lex.cc"
yy725:
++cur;
goto yy724;
yy726:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '@') {
if (yych <= '/') goto yy727;
if (yych <= '9') goto yy748;
} else {
if (yych <= 'F') goto yy748;
if (yych <= '`') goto yy727;
if (yych <= 'f') goto yy748;
}
yy727:
#line 814 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error in hexadecimal escape sequence"); exit(1); }
#line 4772 "src/parse/lex.cc"
yy728:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '@') {
if (yych <= '/') goto yy727;
if (yych <= '9') goto yy749;
goto yy727;
} else {
if (yych <= 'F') goto yy749;
if (yych <= '`') goto yy727;
if (yych <= 'f') goto yy749;
goto yy727;
}
yy729:
++cur;
#line 831 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\\'); return true; }
#line 4790 "src/parse/lex.cc"
yy731:
++cur;
#line 824 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\a'); return true; }
#line 4795 "src/parse/lex.cc"
yy733:
++cur;
#line 825 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\b'); return true; }
#line 4800 "src/parse/lex.cc"
yy735:
++cur;
#line 826 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\f'); return true; }
#line 4805 "src/parse/lex.cc"
yy737:
++cur;
#line 827 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\n'); return true; }
#line 4810 "src/parse/lex.cc"
yy739:
++cur;
#line 828 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\r'); return true; }
#line 4815 "src/parse/lex.cc"
yy741:
++cur;
#line 829 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\t'); return true; }
#line 4820 "src/parse/lex.cc"
yy743:
++cur;
#line 830 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\v'); return true; }
#line 4825 "src/parse/lex.cc"
yy745:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '@') {
if (yych <= '/') goto yy727;
if (yych <= '9') goto yy750;
goto yy727;
} else {
if (yych <= 'F') goto yy750;
if (yych <= '`') goto yy727;
if (yych <= 'f') goto yy750;
goto yy727;
}
yy746:
yych = (unsigned char)*++cur;
if (yych <= '/') goto yy747;
if (yych <= '7') goto yy751;
yy747:
cur = mar;
if (yyaccept == 0) {
goto yy724;
} else {
goto yy727;
}
yy748:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych <= '9') goto yy753;
goto yy747;
} else {
if (yych <= 'F') goto yy753;
if (yych <= '`') goto yy747;
if (yych <= 'f') goto yy753;
goto yy747;
}
yy749:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych <= '9') goto yy754;
goto yy747;
} else {
if (yych <= 'F') goto yy754;
if (yych <= '`') goto yy747;
if (yych <= 'f') goto yy754;
goto yy747;
}
yy750:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych <= '9') goto yy755;
goto yy747;
} else {
if (yych <= 'F') goto yy755;
if (yych <= '`') goto yy747;
if (yych <= 'f') goto yy755;
goto yy747;
}
yy751:
++cur;
#line 823 "../src/parse/lex.re"
{ ast.chr = unesc_oct(tok, cur); return true; }
#line 4890 "src/parse/lex.cc"
yy753:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych <= '9') goto yy757;
goto yy747;
} else {
if (yych <= 'F') goto yy757;
if (yych <= '`') goto yy747;
if (yych <= 'f') goto yy757;
goto yy747;
}
yy754:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych <= '9') goto yy750;
goto yy747;
} else {
if (yych <= 'F') goto yy750;
if (yych <= '`') goto yy747;
if (yych <= 'f') goto yy750;
goto yy747;
}
yy755:
++cur;
#line 822 "../src/parse/lex.re"
{ ast.chr = unesc_hex(tok, cur); return true; }
#line 4919 "src/parse/lex.cc"
yy757:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych >= ':') goto yy747;
} else {
if (yych <= 'F') goto yy758;
if (yych <= '`') goto yy747;
if (yych >= 'g') goto yy747;
}
yy758:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy747;
if (yych <= '9') goto yy749;
goto yy747;
} else {
if (yych <= 'F') goto yy749;
if (yych <= '`') goto yy747;
if (yych <= 'f') goto yy749;
goto yy747;
}
}
#line 839 "../src/parse/lex.re"
}
else {
#line 4948 "src/parse/lex.cc"
{
unsigned char yych;
unsigned int yyaccept = 0;
if ((lim - cur) < 10) { if (!fill(10)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x7F) {
if (yych <= '\f') {
if (yych <= 0x00) goto yy761;
if (yych == '\n') goto yy765;
goto yy763;
} else {
if (yych <= '\r') goto yy767;
if (yych == '\\') goto yy768;
goto yy763;
}
} else {
if (yych <= 0xEF) {
if (yych <= 0xC1) goto yy770;
if (yych <= 0xDF) goto yy772;
if (yych <= 0xE0) goto yy773;
goto yy774;
} else {
if (yych <= 0xF0) goto yy775;
if (yych <= 0xF3) goto yy776;
if (yych <= 0xF4) goto yy777;
goto yy770;
}
}
yy761:
++cur;
#line 819 "../src/parse/lex.re"
{ fail_if_eof(); ast.chr = 0; return true; }
#line 4981 "src/parse/lex.cc"
yy763:
++cur;
yy764:
#line 821 "../src/parse/lex.re"
{ ast.chr = decode(tok); return tok[0] != quote; }
#line 4987 "src/parse/lex.cc"
yy765:
++cur;
#line 813 "../src/parse/lex.re"
{ msg.error(ast.loc, "newline in character string"); exit(1); }
#line 4992 "src/parse/lex.cc"
yy767:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy765;
goto yy764;
yy768:
yyaccept = 0;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 'f') {
if (yych <= 'T') {
if (yych <= '\f') {
if (yych <= 0x00) goto yy769;
if (yych == '\n') goto yy765;
goto yy778;
} else {
if (yych <= '/') {
if (yych <= '\r') goto yy780;
goto yy778;
} else {
if (yych <= '3') goto yy781;
if (yych <= '7') goto yy783;
goto yy778;
}
}
} else {
if (yych <= '\\') {
if (yych <= 'W') {
if (yych <= 'U') goto yy784;
goto yy778;
} else {
if (yych <= 'X') goto yy786;
if (yych <= '[') goto yy778;
goto yy787;
}
} else {
if (yych <= 'a') {
if (yych <= '`') goto yy778;
goto yy789;
} else {
if (yych <= 'b') goto yy791;
if (yych <= 'e') goto yy778;
goto yy793;
}
}
}
} else {
if (yych <= 'w') {
if (yych <= 'r') {
if (yych == 'n') goto yy795;
if (yych <= 'q') goto yy778;
goto yy797;
} else {
if (yych <= 't') {
if (yych <= 's') goto yy778;
goto yy799;
} else {
if (yych <= 'u') goto yy786;
if (yych <= 'v') goto yy801;
goto yy778;
}
}
} else {
if (yych <= 0xE0) {
if (yych <= 0x7F) {
if (yych <= 'x') goto yy803;
goto yy778;
} else {
if (yych <= 0xC1) goto yy769;
if (yych <= 0xDF) goto yy804;
goto yy806;
}
} else {
if (yych <= 0xF0) {
if (yych <= 0xEF) goto yy807;
goto yy808;
} else {
if (yych <= 0xF3) goto yy809;
if (yych <= 0xF4) goto yy810;
}
}
}
}
yy769:
#line 816 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error in escape sequence"); exit(1); }
#line 5077 "src/parse/lex.cc"
yy770:
++cur;
yy771:
#line 817 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error"); exit(1); }
#line 5083 "src/parse/lex.cc"
yy772:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy771;
if (yych <= 0xBF) goto yy763;
goto yy771;
yy773:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 0x9F) goto yy771;
if (yych <= 0xBF) goto yy811;
goto yy771;
yy774:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 0x7F) goto yy771;
if (yych <= 0xBF) goto yy811;
goto yy771;
yy775:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 0x8F) goto yy771;
if (yych <= 0xBF) goto yy812;
goto yy771;
yy776:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 0x7F) goto yy771;
if (yych <= 0xBF) goto yy812;
goto yy771;
yy777:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 0x7F) goto yy771;
if (yych <= 0x8F) goto yy812;
goto yy771;
yy778:
++cur;
yy779:
#line 832 "../src/parse/lex.re"
{
ast.chr = decode(tok + 1);
if (tok[1] != quote) msg.warn.useless_escape(ast.loc, tok, cur);
return true;
}
#line 5128 "src/parse/lex.cc"
yy780:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy765;
goto yy779;
yy781:
yyaccept = 2;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '/') goto yy782;
if (yych <= '7') goto yy813;
yy782:
#line 815 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error in octal escape sequence"); exit(1); }
#line 5141 "src/parse/lex.cc"
yy783:
++cur;
goto yy782;
yy784:
yyaccept = 3;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '@') {
if (yych <= '/') goto yy785;
if (yych <= '9') goto yy814;
} else {
if (yych <= 'F') goto yy814;
if (yych <= '`') goto yy785;
if (yych <= 'f') goto yy814;
}
yy785:
#line 814 "../src/parse/lex.re"
{ msg.error(ast.loc, "syntax error in hexadecimal escape sequence"); exit(1); }
#line 5159 "src/parse/lex.cc"
yy786:
yyaccept = 3;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '@') {
if (yych <= '/') goto yy785;
if (yych <= '9') goto yy815;
goto yy785;
} else {
if (yych <= 'F') goto yy815;
if (yych <= '`') goto yy785;
if (yych <= 'f') goto yy815;
goto yy785;
}
yy787:
++cur;
#line 831 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\\'); return true; }
#line 5177 "src/parse/lex.cc"
yy789:
++cur;
#line 824 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\a'); return true; }
#line 5182 "src/parse/lex.cc"
yy791:
++cur;
#line 825 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\b'); return true; }
#line 5187 "src/parse/lex.cc"
yy793:
++cur;
#line 826 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\f'); return true; }
#line 5192 "src/parse/lex.cc"
yy795:
++cur;
#line 827 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\n'); return true; }
#line 5197 "src/parse/lex.cc"
yy797:
++cur;
#line 828 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\r'); return true; }
#line 5202 "src/parse/lex.cc"
yy799:
++cur;
#line 829 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\t'); return true; }
#line 5207 "src/parse/lex.cc"
yy801:
++cur;
#line 830 "../src/parse/lex.re"
{ ast.chr = static_cast<uint8_t>('\v'); return true; }
#line 5212 "src/parse/lex.cc"
yy803:
yyaccept = 3;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '@') {
if (yych <= '/') goto yy785;
if (yych <= '9') goto yy816;
goto yy785;
} else {
if (yych <= 'F') goto yy816;
if (yych <= '`') goto yy785;
if (yych <= 'f') goto yy816;
goto yy785;
}
yy804:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy805;
if (yych <= 0xBF) goto yy778;
yy805:
cur = mar;
if (yyaccept <= 1) {
if (yyaccept == 0) {
goto yy769;
} else {
goto yy771;
}
} else {
if (yyaccept == 2) {
goto yy782;
} else {
goto yy785;
}
}
yy806:
yych = (unsigned char)*++cur;
if (yych <= 0x9F) goto yy805;
if (yych <= 0xBF) goto yy804;
goto yy805;
yy807:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy805;
if (yych <= 0xBF) goto yy804;
goto yy805;
yy808:
yych = (unsigned char)*++cur;
if (yych <= 0x8F) goto yy805;
if (yych <= 0xBF) goto yy807;
goto yy805;
yy809:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy805;
if (yych <= 0xBF) goto yy807;
goto yy805;
yy810:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy805;
if (yych <= 0x8F) goto yy807;
goto yy805;
yy811:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy805;
if (yych <= 0xBF) goto yy763;
goto yy805;
yy812:
yych = (unsigned char)*++cur;
if (yych <= 0x7F) goto yy805;
if (yych <= 0xBF) goto yy811;
goto yy805;
yy813:
yych = (unsigned char)*++cur;
if (yych <= '/') goto yy805;
if (yych <= '7') goto yy817;
goto yy805;
yy814:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych <= '9') goto yy819;
goto yy805;
} else {
if (yych <= 'F') goto yy819;
if (yych <= '`') goto yy805;
if (yych <= 'f') goto yy819;
goto yy805;
}
yy815:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych <= '9') goto yy820;
goto yy805;
} else {
if (yych <= 'F') goto yy820;
if (yych <= '`') goto yy805;
if (yych <= 'f') goto yy820;
goto yy805;
}
yy816:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych <= '9') goto yy821;
goto yy805;
} else {
if (yych <= 'F') goto yy821;
if (yych <= '`') goto yy805;
if (yych <= 'f') goto yy821;
goto yy805;
}
yy817:
++cur;
#line 823 "../src/parse/lex.re"
{ ast.chr = unesc_oct(tok, cur); return true; }
#line 5325 "src/parse/lex.cc"
yy819:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych <= '9') goto yy823;
goto yy805;
} else {
if (yych <= 'F') goto yy823;
if (yych <= '`') goto yy805;
if (yych <= 'f') goto yy823;
goto yy805;
}
yy820:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych <= '9') goto yy816;
goto yy805;
} else {
if (yych <= 'F') goto yy816;
if (yych <= '`') goto yy805;
if (yych <= 'f') goto yy816;
goto yy805;
}
yy821:
++cur;
#line 822 "../src/parse/lex.re"
{ ast.chr = unesc_hex(tok, cur); return true; }
#line 5354 "src/parse/lex.cc"
yy823:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych >= ':') goto yy805;
} else {
if (yych <= 'F') goto yy824;
if (yych <= '`') goto yy805;
if (yych >= 'g') goto yy805;
}
yy824:
yych = (unsigned char)*++cur;
if (yych <= '@') {
if (yych <= '/') goto yy805;
if (yych <= '9') goto yy815;
goto yy805;
} else {
if (yych <= 'F') goto yy815;
if (yych <= '`') goto yy805;
if (yych <= 'f') goto yy815;
goto yy805;
}
}
#line 842 "../src/parse/lex.re"
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.
Historically this was allowed and re2c swapped the bounds. However, it
most likely indicates an error in user code and there is only a single
occurrence in the tests (and the test in an artificial one), so although
the change is backwards incompatible there is low chance of breaking
real-world code.
This fixes second test case in the bug #394 "Stack overflow due to
recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size
but the test also has counted repetition with swapped bounds).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int Scanner::scan()
{
const char *p, *x, *y;
scan:
tok = cur;
location = cur_loc();
#line 1706 "src/parse/lex.cc"
{
unsigned char yych;
unsigned int yyaccept = 0;
static const unsigned char yybm[] = {
0, 128, 128, 128, 128, 128, 128, 128,
128, 144, 0, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
144, 128, 0, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
224, 224, 224, 224, 224, 224, 224, 224,
224, 224, 128, 128, 128, 128, 128, 128,
128, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 128, 0, 128, 128, 160,
128, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
};
if ((lim - cur) < 9) { if (!fill(9)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yybm[0+yych] & 16) {
goto yy278;
}
if (yych <= '9') {
if (yych <= '$') {
if (yych <= '\r') {
if (yych <= 0x08) goto yy276;
if (yych <= '\n') goto yy281;
if (yych >= '\r') goto yy283;
} else {
if (yych <= '!') {
if (yych >= ' ') goto yy284;
} else {
if (yych <= '"') goto yy285;
if (yych <= '#') goto yy287;
goto yy288;
}
}
} else {
if (yych <= '*') {
if (yych <= '&') {
if (yych <= '%') goto yy290;
} else {
if (yych <= '\'') goto yy291;
if (yych <= ')') goto yy288;
goto yy293;
}
} else {
if (yych <= '-') {
if (yych <= '+') goto yy288;
} else {
if (yych <= '.') goto yy294;
if (yych <= '/') goto yy296;
}
}
}
} else {
if (yych <= '[') {
if (yych <= '=') {
if (yych <= ':') goto yy297;
if (yych <= ';') goto yy288;
if (yych <= '<') goto yy298;
goto yy300;
} else {
if (yych <= '?') {
if (yych >= '?') goto yy288;
} else {
if (yych <= '@') goto yy287;
if (yych <= 'Z') goto yy301;
goto yy304;
}
}
} else {
if (yych <= 'q') {
if (yych <= '^') {
if (yych <= '\\') goto yy288;
} else {
if (yych != '`') goto yy301;
}
} else {
if (yych <= 'z') {
if (yych <= 'r') goto yy306;
goto yy301;
} else {
if (yych <= '{') goto yy307;
if (yych <= '|') goto yy288;
}
}
}
}
yy276:
++cur;
yy277:
#line 569 "../src/parse/lex.re"
{
msg.error(tok_loc(), "unexpected character: '%c'", *tok);
exit(1);
}
#line 1824 "src/parse/lex.cc"
yy278:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yybm[0+yych] & 16) {
goto yy278;
}
#line 551 "../src/parse/lex.re"
{ goto scan; }
#line 1834 "src/parse/lex.cc"
yy281:
yyaccept = 0;
yych = (unsigned char)*(mar = ++cur);
if (yych <= 0x1F) {
if (yych == '\t') goto yy309;
} else {
if (yych <= ' ') goto yy309;
if (yych == '#') goto yy312;
}
yy282:
#line 558 "../src/parse/lex.re"
{
next_line();
if (lexer_state == LEX_FLEX_NAME) {
lexer_state = LEX_NORMAL;
return TOKEN_FID_END;
}
else {
goto scan;
}
}
#line 1856 "src/parse/lex.cc"
yy283:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy281;
goto yy277;
yy284:
yyaccept = 1;
yych = (unsigned char)*(mar = ++cur);
if (yych == 'i') goto yy314;
if (yych == 'u') goto yy315;
goto yy277;
yy285:
++cur;
#line 443 "../src/parse/lex.re"
{ yylval.regexp = lex_str('"'); return TOKEN_REGEXP; }
#line 1871 "src/parse/lex.cc"
yy287:
yych = (unsigned char)*++cur;
if (yych <= '^') {
if (yych <= '@') goto yy277;
if (yych <= 'Z') goto yy316;
goto yy277;
} else {
if (yych == '`') goto yy277;
if (yych <= 'z') goto yy316;
goto yy277;
}
yy288:
++cur;
yy289:
#line 452 "../src/parse/lex.re"
{ return *tok; }
#line 1888 "src/parse/lex.cc"
yy290:
yych = (unsigned char)*++cur;
if (yych == '}') goto yy319;
goto yy277;
yy291:
++cur;
#line 442 "../src/parse/lex.re"
{ yylval.regexp = lex_str('\''); return TOKEN_REGEXP; }
#line 1897 "src/parse/lex.cc"
yy293:
yych = (unsigned char)*++cur;
if (yych == '/') goto yy319;
goto yy289;
yy294:
++cur;
#line 546 "../src/parse/lex.re"
{
yylval.regexp = ast_dot(tok_loc());
return TOKEN_REGEXP;
}
#line 1909 "src/parse/lex.cc"
yy296:
yych = (unsigned char)*++cur;
if (yych == '*') goto yy321;
if (yych == '/') goto yy323;
goto yy289;
yy297:
yych = (unsigned char)*++cur;
if (yych == '=') goto yy325;
goto yy277;
yy298:
++cur;
#line 435 "../src/parse/lex.re"
{ return lex_clist(); }
#line 1923 "src/parse/lex.cc"
yy300:
yyaccept = 2;
yych = (unsigned char)*(mar = ++cur);
if (yych == '>') goto yy327;
goto yy289;
yy301:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
yy302:
if (yybm[0+yych] & 32) {
goto yy301;
}
#line 501 "../src/parse/lex.re"
{
if (!globopts->FFlag || lex_namedef_context_re2c()) {
yylval.str = newstr(tok, cur);
return TOKEN_ID;
}
else if (lex_namedef_context_flex()) {
yylval.str = newstr(tok, cur);
lexer_state = LEX_FLEX_NAME;
return TOKEN_FID;
}
else {
// consume one character, otherwise we risk breaking operator
// precedence in cases like ab*: it should be a(b)*, not (ab)*
cur = tok + 1;
ASTChar c = {static_cast<uint8_t>(tok[0]), tok_loc()};
std::vector<ASTChar> *str = new std::vector<ASTChar>;
str->push_back(c);
yylval.regexp = ast_str(tok_loc(), str, false);
return TOKEN_REGEXP;
}
}
#line 1960 "src/parse/lex.cc"
yy304:
yych = (unsigned char)*++cur;
if (yych == '^') goto yy329;
#line 444 "../src/parse/lex.re"
{ yylval.regexp = lex_cls(false); return TOKEN_REGEXP; }
#line 1966 "src/parse/lex.cc"
yy306:
yych = (unsigned char)*++cur;
if (yych == 'e') goto yy331;
goto yy302;
yy307:
yyaccept = 3;
yych = (unsigned char)*(mar = ++cur);
if (yybm[0+yych] & 64) {
goto yy334;
}
if (yych <= 'Z') {
if (yych == ',') goto yy332;
if (yych >= 'A') goto yy336;
} else {
if (yych <= '_') {
if (yych >= '_') goto yy336;
} else {
if (yych <= '`') goto yy308;
if (yych <= 'z') goto yy336;
}
}
yy308:
#line 427 "../src/parse/lex.re"
{ lex_code_in_braces(); return TOKEN_CODE; }
#line 1991 "src/parse/lex.cc"
yy309:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x1F) {
if (yych == '\t') goto yy309;
} else {
if (yych <= ' ') goto yy309;
if (yych == '#') goto yy312;
}
yy311:
cur = mar;
if (yyaccept <= 3) {
if (yyaccept <= 1) {
if (yyaccept == 0) {
goto yy282;
} else {
goto yy277;
}
} else {
if (yyaccept == 2) {
goto yy289;
} else {
goto yy308;
}
}
} else {
if (yyaccept <= 5) {
if (yyaccept == 4) {
goto yy326;
} else {
goto yy333;
}
} else {
if (yyaccept == 6) {
goto yy353;
} else {
goto yy379;
}
}
}
yy312:
++cur;
if ((lim - cur) < 5) { if (!fill(5)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x1F) {
if (yych == '\t') goto yy312;
goto yy311;
} else {
if (yych <= ' ') goto yy312;
if (yych == 'l') goto yy338;
goto yy311;
}
yy314:
yych = (unsigned char)*++cur;
if (yych == 'n') goto yy339;
goto yy311;
yy315:
yych = (unsigned char)*++cur;
if (yych == 's') goto yy340;
goto yy311;
yy316:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 'Z') {
if (yych <= '/') goto yy318;
if (yych <= '9') goto yy316;
if (yych >= 'A') goto yy316;
} else {
if (yych <= '_') {
if (yych >= '_') goto yy316;
} else {
if (yych <= '`') goto yy318;
if (yych <= 'z') goto yy316;
}
}
yy318:
#line 447 "../src/parse/lex.re"
{
yylval.regexp = ast_tag(tok_loc(), newstr(tok + 1, cur), tok[0] == '#');
return TOKEN_REGEXP;
}
#line 2075 "src/parse/lex.cc"
yy319:
++cur;
#line 440 "../src/parse/lex.re"
{ tok = cur; return 0; }
#line 2080 "src/parse/lex.cc"
yy321:
++cur;
#line 438 "../src/parse/lex.re"
{ lex_c_comment(); goto scan; }
#line 2085 "src/parse/lex.cc"
yy323:
++cur;
#line 437 "../src/parse/lex.re"
{ lex_cpp_comment(); goto scan; }
#line 2090 "src/parse/lex.cc"
yy325:
yyaccept = 4;
yych = (unsigned char)*(mar = ++cur);
if (yych == '>') goto yy327;
yy326:
#line 428 "../src/parse/lex.re"
{ lex_code_indented(); return TOKEN_CODE; }
#line 2098 "src/parse/lex.cc"
yy327:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= '@') {
if (yych <= '\t') {
if (yych <= 0x08) goto yy311;
goto yy327;
} else {
if (yych == ' ') goto yy327;
goto yy311;
}
} else {
if (yych <= '_') {
if (yych <= 'Z') {
yyt1 = cur;
goto yy341;
}
if (yych <= '^') goto yy311;
yyt1 = cur;
goto yy341;
} else {
if (yych <= '`') goto yy311;
if (yych <= 'z') {
yyt1 = cur;
goto yy341;
}
goto yy311;
}
}
yy329:
++cur;
#line 445 "../src/parse/lex.re"
{ yylval.regexp = lex_cls(true); return TOKEN_REGEXP; }
#line 2133 "src/parse/lex.cc"
yy331:
yych = (unsigned char)*++cur;
if (yych == '2') goto yy344;
goto yy302;
yy332:
++cur;
yy333:
#line 484 "../src/parse/lex.re"
{
msg.error(tok_loc(), "illegal closure form, use '{n}', '{n,}', '{n,m}' "
"where n and m are numbers");
exit(1);
}
#line 2147 "src/parse/lex.cc"
yy334:
++cur;
if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yybm[0+yych] & 64) {
goto yy334;
}
if (yych == ',') {
yyt1 = cur;
goto yy345;
}
if (yych == '}') goto yy346;
goto yy311;
yy336:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= '^') {
if (yych <= '9') {
if (yych <= '/') goto yy311;
goto yy336;
} else {
if (yych <= '@') goto yy311;
if (yych <= 'Z') goto yy336;
goto yy311;
}
} else {
if (yych <= 'z') {
if (yych == '`') goto yy311;
goto yy336;
} else {
if (yych == '}') goto yy348;
goto yy311;
}
}
yy338:
yych = (unsigned char)*++cur;
if (yych == 'i') goto yy350;
goto yy311;
yy339:
yych = (unsigned char)*++cur;
if (yych == 'c') goto yy351;
goto yy311;
yy340:
yych = (unsigned char)*++cur;
if (yych == 'e') goto yy352;
goto yy311;
yy341:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 'Z') {
if (yych <= '/') goto yy343;
if (yych <= '9') goto yy341;
if (yych >= 'A') goto yy341;
} else {
if (yych <= '_') {
if (yych >= '_') goto yy341;
} else {
if (yych <= '`') goto yy343;
if (yych <= 'z') goto yy341;
}
}
yy343:
p = yyt1;
#line 430 "../src/parse/lex.re"
{
yylval.str = newstr(p, cur);
return tok[0] == ':' ? TOKEN_CJUMP : TOKEN_CNEXT;
}
#line 2218 "src/parse/lex.cc"
yy344:
yych = (unsigned char)*++cur;
if (yych == 'c') goto yy354;
goto yy302;
yy345:
yyaccept = 5;
yych = (unsigned char)*(mar = ++cur);
if (yych <= '/') goto yy333;
if (yych <= '9') goto yy355;
if (yych == '}') goto yy357;
goto yy333;
yy346:
++cur;
#line 454 "../src/parse/lex.re"
{
if (!s_to_u32_unsafe (tok + 1, cur - 1, yylval.bounds.min)) {
msg.error(tok_loc(), "repetition count overflow");
exit(1);
}
yylval.bounds.max = yylval.bounds.min;
return TOKEN_CLOSESIZE;
}
#line 2241 "src/parse/lex.cc"
yy348:
++cur;
#line 490 "../src/parse/lex.re"
{
if (!globopts->FFlag) {
msg.error(tok_loc(), "curly braces for names only allowed with -F switch");
exit(1);
}
yylval.str = newstr(tok + 1, cur - 1);
return TOKEN_ID;
}
#line 2253 "src/parse/lex.cc"
yy350:
yych = (unsigned char)*++cur;
if (yych == 'n') goto yy359;
goto yy311;
yy351:
yych = (unsigned char)*++cur;
if (yych == 'l') goto yy360;
goto yy311;
yy352:
yyaccept = 6;
yych = (unsigned char)*(mar = ++cur);
if (yych == ':') goto yy361;
yy353:
#line 539 "../src/parse/lex.re"
{
msg.error(tok_loc(), "ill-formed use directive: expected `!use`"
" followed by a colon, a block name, optional spaces, a semicolon,"
" and finally a space, a newline, or the end of block");
exit(1);
}
#line 2274 "src/parse/lex.cc"
yy354:
yych = (unsigned char)*++cur;
if (yych == ':') goto yy362;
goto yy302;
yy355:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= '/') goto yy311;
if (yych <= '9') goto yy355;
if (yych == '}') goto yy364;
goto yy311;
yy357:
++cur;
#line 475 "../src/parse/lex.re"
{
if (!s_to_u32_unsafe (tok + 1, cur - 2, yylval.bounds.min)) {
msg.error(tok_loc(), "repetition lower bound overflow");
exit(1);
}
yylval.bounds.max = std::numeric_limits<uint32_t>::max();
return TOKEN_CLOSESIZE;
}
#line 2298 "src/parse/lex.cc"
yy359:
yych = (unsigned char)*++cur;
if (yych == 'e') goto yy366;
goto yy311;
yy360:
yych = (unsigned char)*++cur;
if (yych == 'u') goto yy367;
goto yy311;
yy361:
yych = (unsigned char)*++cur;
if (yych <= '^') {
if (yych <= '@') goto yy311;
if (yych <= 'Z') {
yyt1 = cur;
goto yy368;
}
goto yy311;
} else {
if (yych == '`') goto yy311;
if (yych <= 'z') {
yyt1 = cur;
goto yy368;
}
goto yy311;
}
yy362:
++cur;
#line 499 "../src/parse/lex.re"
{ return TOKEN_CONF; }
#line 2328 "src/parse/lex.cc"
yy364:
++cur;
p = yyt1;
#line 463 "../src/parse/lex.re"
{
if (!s_to_u32_unsafe (tok + 1, p, yylval.bounds.min)) {
msg.error(tok_loc(), "repetition lower bound overflow");
exit(1);
}
if (!s_to_u32_unsafe (p + 1, cur - 1, yylval.bounds.max)) {
msg.error(tok_loc(), "repetition upper bound overflow");
exit(1);
}
return TOKEN_CLOSESIZE;
}
#line 2344 "src/parse/lex.cc"
yy366:
yych = (unsigned char)*++cur;
if (yych <= '0') goto yy371;
if (yych <= '9') goto yy311;
goto yy371;
yy367:
yych = (unsigned char)*++cur;
if (yych == 'd') goto yy372;
goto yy311;
yy368:
++cur;
if ((lim - cur) < 3) { if (!fill(3)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= ':') {
if (yych <= 0x1F) {
if (yych == '\t') {
yyt2 = cur;
goto yy373;
}
goto yy311;
} else {
if (yych <= ' ') {
yyt2 = cur;
goto yy373;
}
if (yych <= '/') goto yy311;
if (yych <= '9') goto yy368;
goto yy311;
}
} else {
if (yych <= '^') {
if (yych <= ';') {
yyt2 = cur;
goto yy375;
}
if (yych <= '@') goto yy311;
if (yych <= 'Z') goto yy368;
goto yy311;
} else {
if (yych == '`') goto yy311;
if (yych <= 'z') goto yy368;
goto yy311;
}
}
yy370:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
yy371:
if (yych <= 0x1F) {
if (yych == '\t') goto yy370;
goto yy311;
} else {
if (yych <= ' ') goto yy370;
if (yych <= '0') goto yy311;
if (yych <= '9') {
yyt1 = cur;
goto yy376;
}
goto yy311;
}
yy372:
yych = (unsigned char)*++cur;
if (yych == 'e') goto yy378;
goto yy311;
yy373:
++cur;
if ((lim - cur) < 3) { if (!fill(3)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x1F) {
if (yych == '\t') goto yy373;
goto yy311;
} else {
if (yych <= ' ') goto yy373;
if (yych != ';') goto yy311;
}
yy375:
yych = (unsigned char)*++cur;
if (yych <= '\r') {
if (yych <= 0x08) goto yy311;
if (yych <= '\n') {
yyt3 = cur;
goto yy380;
}
if (yych <= '\f') goto yy311;
yyt3 = cur;
goto yy380;
} else {
if (yych <= ' ') {
if (yych <= 0x1F) goto yy311;
yyt3 = cur;
goto yy380;
} else {
if (yych == '*') {
yyt3 = cur;
goto yy382;
}
goto yy311;
}
}
yy376:
++cur;
if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= '\r') {
if (yych <= '\t') {
if (yych <= 0x08) goto yy311;
goto yy383;
} else {
if (yych <= '\n') goto yy385;
if (yych <= '\f') goto yy311;
goto yy387;
}
} else {
if (yych <= ' ') {
if (yych <= 0x1F) goto yy311;
goto yy383;
} else {
if (yych <= '/') goto yy311;
if (yych <= '9') goto yy376;
goto yy311;
}
}
yy378:
yyaccept = 7;
yych = (unsigned char)*(mar = ++cur);
if (yych == '\t') goto yy388;
if (yych == ' ') goto yy388;
yy379:
#line 528 "../src/parse/lex.re"
{
msg.error(tok_loc(), "ill-formed include directive: expected `!include`"
" followed by spaces, a double-quoted file path, optional spaces, a"
" semicolon, and finally a space, a newline, or the end of block");
exit(1);
}
#line 2481 "src/parse/lex.cc"
yy380:
++cur;
x = yyt1;
y = yyt2;
cur = yyt3;
#line 535 "../src/parse/lex.re"
{
yylval.str = newstr(x, y); // save the name of the used block
return TOKEN_BLOCK;
}
#line 2492 "src/parse/lex.cc"
yy382:
yych = (unsigned char)*++cur;
if (yych == '/') goto yy380;
goto yy311;
yy383:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x1F) {
if (yych == '\t') goto yy383;
goto yy311;
} else {
if (yych <= ' ') goto yy383;
if (yych == '"') goto yy390;
goto yy311;
}
yy385:
++cur;
cur = yyt1;
#line 553 "../src/parse/lex.re"
{
set_sourceline ();
return TOKEN_LINE_INFO;
}
#line 2517 "src/parse/lex.cc"
yy387:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy385;
goto yy311;
yy388:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x1F) {
if (yych == '\t') goto yy388;
goto yy311;
} else {
if (yych <= ' ') goto yy388;
if (yych == '"') {
yyt1 = cur;
goto yy392;
}
goto yy311;
}
yy390:
++cur;
if ((lim - cur) < 3) { if (!fill(3)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yybm[0+yych] & 128) {
goto yy390;
}
if (yych <= '\n') goto yy311;
if (yych <= '"') goto yy394;
goto yy395;
yy392:
++cur;
if ((lim - cur) < 4) { if (!fill(4)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= '!') {
if (yych <= 0x00) goto yy311;
if (yych == '\n') goto yy311;
goto yy392;
} else {
if (yych <= '"') goto yy396;
if (yych == '\\') goto yy397;
goto yy392;
}
yy394:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy385;
if (yych == '\r') goto yy387;
goto yy311;
yy395:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x00) goto yy311;
if (yych == '\n') goto yy311;
goto yy390;
yy396:
yych = (unsigned char)*++cur;
if (yych <= 0x1F) {
if (yych == '\t') {
yyt2 = cur;
goto yy398;
}
goto yy311;
} else {
if (yych <= ' ') {
yyt2 = cur;
goto yy398;
}
if (yych == ';') {
yyt2 = cur;
goto yy400;
}
goto yy311;
}
yy397:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x00) goto yy311;
if (yych == '\n') goto yy311;
goto yy392;
yy398:
++cur;
if ((lim - cur) < 3) { if (!fill(3)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yych <= 0x1F) {
if (yych == '\t') goto yy398;
goto yy311;
} else {
if (yych <= ' ') goto yy398;
if (yych != ';') goto yy311;
}
yy400:
yych = (unsigned char)*++cur;
if (yych <= '\r') {
if (yych <= 0x08) goto yy311;
if (yych <= '\n') {
yyt3 = cur;
goto yy401;
}
if (yych <= '\f') goto yy311;
yyt3 = cur;
} else {
if (yych <= ' ') {
if (yych <= 0x1F) goto yy311;
yyt3 = cur;
} else {
if (yych == '*') {
yyt3 = cur;
goto yy403;
}
goto yy311;
}
}
yy401:
++cur;
x = yyt1;
y = yyt2;
cur = yyt3;
#line 524 "../src/parse/lex.re"
{
include(getstr(x + 1, y - 1), tok);
goto scan;
}
#line 2641 "src/parse/lex.cc"
yy403:
yych = (unsigned char)*++cur;
if (yych == '/') goto yy401;
goto yy311;
}
#line 573 "../src/parse/lex.re"
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.
Historically this was allowed and re2c swapped the bounds. However, it
most likely indicates an error in user code and there is only a single
occurrence in the tests (and the test in an artificial one), so although
the change is backwards incompatible there is low chance of breaking
real-world code.
This fixes second test case in the bug #394 "Stack overflow due to
recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size
but the test also has counted repetition with swapped bounds).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool Scanner::lex_block_end(Output &out, bool allow_garbage)
{
bool multiline = false;
loop:
#line 1419 "src/parse/lex.cc"
{
unsigned char yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yybm[0+yych] & 128) {
goto yy234;
}
if (yych <= '\f') {
if (yych <= 0x08) goto yy232;
if (yych <= '\n') goto yy237;
} else {
if (yych <= '\r') goto yy239;
if (yych == '*') goto yy240;
}
yy232:
++cur;
yy233:
#line 356 "../src/parse/lex.re"
{
if (allow_garbage && !is_eof()) goto loop;
msg.error(cur_loc(), "ill-formed end of block: expected optional"
" whitespaces followed by `*" "/`");
return false;
}
#line 1478 "src/parse/lex.cc"
yy234:
++cur;
if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } }
yych = (unsigned char)*cur;
if (yybm[0+yych] & 128) {
goto yy234;
}
#line 366 "../src/parse/lex.re"
{ goto loop; }
#line 1488 "src/parse/lex.cc"
yy237:
++cur;
#line 367 "../src/parse/lex.re"
{ next_line(); multiline = true; goto loop; }
#line 1493 "src/parse/lex.cc"
yy239:
yych = (unsigned char)*++cur;
if (yych == '\n') goto yy237;
goto yy233;
yy240:
yych = (unsigned char)*++cur;
if (yych != '/') goto yy233;
++cur;
#line 362 "../src/parse/lex.re"
{
if (multiline) out.wdelay_stmt(0, code_line_info_input(out.allocator, cur_loc()));
return true;
}
#line 1507 "src/parse/lex.cc"
}
#line 368 "../src/parse/lex.re"
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.
Historically this was allowed and re2c swapped the bounds. However, it
most likely indicates an error in user code and there is only a single
occurrence in the tests (and the test in an artificial one), so although
the change is backwards incompatible there is low chance of breaking
real-world code.
This fixes second test case in the bug #394 "Stack overflow due to
recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size
but the test also has counted repetition with swapped bounds).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: switch (yych) {
case 'a': goto yy6;
default: goto yy5;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.
Historically this was allowed and re2c swapped the bounds. However, it
most likely indicates an error in user code and there is only a single
occurrence in the tests (and the test in an artificial one), so although
the change is backwards incompatible there is low chance of breaking
real-world code.
This fixes second test case in the bug #394 "Stack overflow due to
recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size
but the test also has counted repetition with swapped bounds).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_F(RouterTest, RetryUpstreamResetResponseStarted) {
NiceMock<Http::MockRequestEncoder> encoder1;
Http::ResponseDecoder* response_decoder = nullptr;
EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_, newStream(_, _))
.WillOnce(Invoke(
[&](Http::ResponseDecoder& decoder,
Http::ConnectionPool::Callbacks& callbacks) -> Http::ConnectionPool::Cancellable* {
response_decoder = &decoder;
callbacks.onPoolReady(encoder1, cm_.thread_local_cluster_.conn_pool_.host_,
upstream_stream_info_, Http::Protocol::Http10);
return nullptr;
}));
expectResponseTimerCreate();
Http::TestRequestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}};
HttpTestUtility::addDefaultHeaders(headers);
router_.decodeHeaders(headers, true);
EXPECT_EQ(1U,
callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());
// Since the response is already started we don't retry.
EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _)).WillOnce(Return(RetryStatus::No));
EXPECT_CALL(callbacks_, encodeHeaders_(_, false));
Http::ResponseHeaderMapPtr response_headers(
new Http::TestResponseHeaderMapImpl{{":status", "200"}});
EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,
putHttpResponseCode(200));
response_decoder->decodeHeaders(std::move(response_headers), false);
EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,
putResult(Upstream::Outlier::Result::LocalOriginConnectFailed, _));
// Normally, sendLocalReply will actually send the reply, but in this case the
// HCM will detect the headers have already been sent and not route through
// the encoder again.
EXPECT_CALL(callbacks_, sendLocalReply(_, _, _, _, _)).WillOnce(testing::InvokeWithoutArgs([] {
}));
encoder1.stream_.resetStream(Http::StreamResetReason::RemoteReset);
// For normal HTTP, once we have a 200 we consider this a success, even if a
// later reset occurs.
EXPECT_TRUE(verifyHostUpstreamStats(1, 0));
EXPECT_EQ(1U,
callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703'], 'message': '[1.18] CVE-2022-21655
Crash with direct_response
Signed-off-by: Otto van der Schaaf <ovanders@redhat.com>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: */
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if(!ent->data) {
break;
}
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
ent->varname = NULL;
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
}
efree(tmp);
}
break;
default:
break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72749: wddx_deserialize allows illegal memory access'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
if (olen != 2) {
ND_PRINT((ndo, "ERROR: Option Length != 2 Bytes (%u)", olen));
} else {
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
}
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
}
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: DefineSequence(ParseState *pstate, CreateSeqStmt *seq)
{
FormData_pg_sequence seqform;
FormData_pg_sequence_data seqdataform;
bool need_seq_rewrite;
List *owned_by;
CreateStmt *stmt = makeNode(CreateStmt);
Oid seqoid;
ObjectAddress address;
Relation rel;
HeapTuple tuple;
TupleDesc tupDesc;
Datum value[SEQ_COL_LASTCOL];
bool null[SEQ_COL_LASTCOL];
Datum pgs_values[Natts_pg_sequence];
bool pgs_nulls[Natts_pg_sequence];
int i;
/* Unlogged sequences are not implemented -- not clear if useful. */
if (seq->sequence->relpersistence == RELPERSISTENCE_UNLOGGED)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("unlogged sequences are not supported")));
/*
* If if_not_exists was given and a relation with the same name already
* exists, bail out. (Note: we needn't check this when not if_not_exists,
* because DefineRelation will complain anyway.)
*/
if (seq->if_not_exists)
{
RangeVarGetAndCheckCreationNamespace(seq->sequence, NoLock, &seqoid);
if (OidIsValid(seqoid))
{
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_TABLE),
errmsg("relation \"%s\" already exists, skipping",
seq->sequence->relname)));
return InvalidObjectAddress;
}
}
/* Check and set all option values */
init_params(pstate, seq->options, seq->for_identity, true,
&seqform, &seqdataform,
&need_seq_rewrite, &owned_by);
/*
* Create relation (and fill value[] and null[] for the tuple)
*/
stmt->tableElts = NIL;
for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
{
ColumnDef *coldef = makeNode(ColumnDef);
coldef->inhcount = 0;
coldef->is_local = true;
coldef->is_not_null = true;
coldef->is_from_type = false;
coldef->storage = 0;
coldef->raw_default = NULL;
coldef->cooked_default = NULL;
coldef->collClause = NULL;
coldef->collOid = InvalidOid;
coldef->constraints = NIL;
coldef->location = -1;
null[i - 1] = false;
switch (i)
{
case SEQ_COL_LASTVAL:
coldef->typeName = makeTypeNameFromOid(INT8OID, -1);
coldef->colname = "last_value";
value[i - 1] = Int64GetDatumFast(seqdataform.last_value);
break;
case SEQ_COL_LOG:
coldef->typeName = makeTypeNameFromOid(INT8OID, -1);
coldef->colname = "log_cnt";
value[i - 1] = Int64GetDatum((int64) 0);
break;
case SEQ_COL_CALLED:
coldef->typeName = makeTypeNameFromOid(BOOLOID, -1);
coldef->colname = "is_called";
value[i - 1] = BoolGetDatum(false);
break;
}
stmt->tableElts = lappend(stmt->tableElts, coldef);
}
stmt->relation = seq->sequence;
stmt->inhRelations = NIL;
stmt->constraints = NIL;
stmt->options = NIL;
stmt->oncommit = ONCOMMIT_NOOP;
stmt->tablespacename = NULL;
stmt->if_not_exists = seq->if_not_exists;
address = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);
seqoid = address.objectId;
Assert(seqoid != InvalidOid);
rel = heap_open(seqoid, AccessExclusiveLock);
tupDesc = RelationGetDescr(rel);
/* now initialize the sequence's data */
tuple = heap_form_tuple(tupDesc, value, null);
fill_seq_with_data(rel, tuple);
/* process OWNED BY if given */
if (owned_by)
process_owned_by(rel, owned_by, seq->for_identity);
heap_close(rel, NoLock);
/* fill in pg_sequence */
rel = heap_open(SequenceRelationId, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
memset(pgs_nulls, 0, sizeof(pgs_nulls));
pgs_values[Anum_pg_sequence_seqrelid - 1] = ObjectIdGetDatum(seqoid);
pgs_values[Anum_pg_sequence_seqtypid - 1] = ObjectIdGetDatum(seqform.seqtypid);
pgs_values[Anum_pg_sequence_seqstart - 1] = Int64GetDatumFast(seqform.seqstart);
pgs_values[Anum_pg_sequence_seqincrement - 1] = Int64GetDatumFast(seqform.seqincrement);
pgs_values[Anum_pg_sequence_seqmax - 1] = Int64GetDatumFast(seqform.seqmax);
pgs_values[Anum_pg_sequence_seqmin - 1] = Int64GetDatumFast(seqform.seqmin);
pgs_values[Anum_pg_sequence_seqcache - 1] = Int64GetDatumFast(seqform.seqcache);
pgs_values[Anum_pg_sequence_seqcycle - 1] = BoolGetDatum(seqform.seqcycle);
tuple = heap_form_tuple(tupDesc, pgs_values, pgs_nulls);
CatalogTupleInsert(rel, tuple);
heap_freetuple(tuple);
heap_close(rel, RowExclusiveLock);
return address;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.
Previously, if an extension script did CREATE OR REPLACE and there was
an existing object not belonging to the extension, it would overwrite
the object and adopt it into the extension. This is problematic, first
because the overwrite is probably unintentional, and second because we
didn't change the object's ownership. Thus a hostile user could create
an object in advance of an expected CREATE EXTENSION command, and would
then have ownership rights on an extension object, which could be
modified for trojan-horse-type attacks.
Hence, forbid CREATE OR REPLACE of an existing object unless it already
belongs to the extension. (Note that we've always forbidden replacing
an object that belongs to some other extension; only the behavior for
previously-free-standing objects changes here.)
For the same reason, also fail CREATE IF NOT EXISTS when there is
an existing object that doesn't belong to the extension.
Our thanks to Sven Klemm for reporting this problem.
Security: CVE-2022-2625'</s> |