text
stringlengths
478
227k
<s>[INST] Given the following code containing errors, provide 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 serdes_probe(struct platform_device *pdev) { struct phy_provider *provider; struct serdes_ctrl *ctrl; unsigned int i; int ret; ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL); if (!ctrl) return -ENOMEM; ctrl->dev = &pdev->dev; ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node); if (IS_ERR(ctrl->regs)) return PTR_ERR(ctrl->regs); for (i = 0; i <= SERDES_MAX; i++) { ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]); if (ret) return ret; } dev_set_drvdata(&pdev->dev, ctrl); provider = devm_of_phy_provider_register(ctrl->dev, serdes_simple_xlate); return PTR_ERR_OR_ZERO(provider); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'phy: ocelot-serdes: fix out-of-bounds read Currently, there is an out-of-bounds read on array ctrl->phys, once variable i reaches the maximum array size of SERDES_MAX in the for loop. Fix this by changing the condition in the for loop from i <= SERDES_MAX to i < SERDES_MAX. Addresses-Coverity-ID: 1473966 ("Out-of-bounds read") Addresses-Coverity-ID: 1473959 ("Out-of-bounds read") Fixes: 51f6b410fc22 ("phy: add driver for Microsemi Ocelot SerDes muxing") Reviewed-by: Quentin Schulz <quentin.schulz@bootlin.com> Signed-off-by: Gustavo A. R. Silva <gustavo@embeddedor.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: apr_status_t h2_session_process(h2_session *session, int async) { apr_status_t status = APR_SUCCESS; conn_rec *c = session->c; int rv, mpm_state, trace = APLOGctrace3(c); apr_time_t now; if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, H2_SSSN_MSG(session, "process start, async=%d"), async); } while (session->state != H2_SESSION_ST_DONE) { now = apr_time_now(); session->have_read = session->have_written = 0; if (session->local.accepting && !ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state)) { if (mpm_state == AP_MPMQ_STOPPING) { dispatch_event(session, H2_SESSION_EV_MPM_STOPPING, 0, NULL); } } session->status[0] = '\0'; switch (session->state) { case H2_SESSION_ST_INIT: ap_update_child_status_from_conn(c->sbh, SERVER_BUSY_READ, c); if (!h2_is_acceptable_connection(c, session->r, 1)) { update_child_status(session, SERVER_BUSY_READ, "inadequate security"); h2_session_shutdown(session, NGHTTP2_INADEQUATE_SECURITY, NULL, 1); } else { update_child_status(session, SERVER_BUSY_READ, "init"); status = h2_session_start(session, &rv); ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c, H2_SSSN_LOG(APLOGNO(03079), session, "started on %s:%d"), session->s->server_hostname, c->local_addr->port); if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } dispatch_event(session, H2_SESSION_EV_INIT, 0, NULL); } break; case H2_SESSION_ST_IDLE: if (session->idle_until && (apr_time_now() + session->idle_delay) > session->idle_until) { ap_log_cerror( APLOG_MARK, APLOG_TRACE1, status, c, H2_SSSN_MSG(session, "idle, timeout reached, closing")); if (session->idle_delay) { apr_table_setn(session->c->notes, "short-lingering-close", "1"); } dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, "timeout"); goto out; } if (session->idle_delay) { /* we are less interested in spending time on this connection */ ap_log_cerror( APLOG_MARK, APLOG_TRACE2, status, c, H2_SSSN_MSG(session, "session is idle (%ld ms), idle wait %ld sec left"), (long)apr_time_as_msec(session->idle_delay), (long)apr_time_sec(session->idle_until - now)); apr_sleep(session->idle_delay); session->idle_delay = 0; } h2_conn_io_flush(&session->io); if (async && !session->r && (now > session->idle_sync_until)) { if (trace) { ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c, H2_SSSN_MSG(session, "nonblock read, %d streams open"), session->open_streams); } status = h2_session_read(session, 0); if (status == APR_SUCCESS) { session->have_read = 1; } else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) { status = APR_EAGAIN; goto out; } else { ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c, H2_SSSN_LOG(APLOGNO(03403), session, "no data, error")); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, "timeout"); } } else { /* make certain, we send everything before we idle */ if (trace) { ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c, H2_SSSN_MSG(session, "sync, stutter 1-sec, %d streams open"), session->open_streams); } /* We wait in smaller increments, using a 1 second timeout. * That gives us the chance to check for MPMQ_STOPPING often. */ status = h2_mplx_idle(session->mplx); if (status == APR_EAGAIN) { break; } else if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, H2_ERR_ENHANCE_YOUR_CALM, "less is more"); } h2_filter_cin_timeout_set(session->cin, apr_time_from_sec(1)); status = h2_session_read(session, 1); if (status == APR_SUCCESS) { session->have_read = 1; } else if (status == APR_EAGAIN) { /* nothing to read */ } else if (APR_STATUS_IS_TIMEUP(status)) { /* continue reading handling */ } else if (APR_STATUS_IS_ECONNABORTED(status) || APR_STATUS_IS_ECONNRESET(status) || APR_STATUS_IS_EOF(status) || APR_STATUS_IS_EBADF(status)) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, H2_SSSN_MSG(session, "input gone")); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } else { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, H2_SSSN_MSG(session, "(1 sec timeout) read failed")); dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, "error"); } } if (nghttp2_session_want_write(session->ngh2)) { ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL); status = h2_session_send(session); if (status == APR_SUCCESS) { status = h2_conn_io_flush(&session->io); } if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, H2_ERR_INTERNAL_ERROR, "writing"); break; } } break; case H2_SESSION_ST_BUSY: if (nghttp2_session_want_read(session->ngh2)) { ap_update_child_status(session->c->sbh, SERVER_BUSY_READ, NULL); h2_filter_cin_timeout_set(session->cin, session->s->timeout); status = h2_session_read(session, 0); if (status == APR_SUCCESS) { session->have_read = 1; } else if (status == APR_EAGAIN) { /* nothing to read */ } else if (APR_STATUS_IS_TIMEUP(status)) { dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, NULL); break; } else { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } } status = dispatch_master(session); if (status != APR_SUCCESS && status != APR_EAGAIN) { break; } if (nghttp2_session_want_write(session->ngh2)) { ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL); status = h2_session_send(session); if (status == APR_SUCCESS) { status = h2_conn_io_flush(&session->io); } if (status != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, H2_ERR_INTERNAL_ERROR, "writing"); break; } } if (session->have_read || session->have_written) { if (session->wait_us) { session->wait_us = 0; } } else if (!nghttp2_session_want_write(session->ngh2)) { dispatch_event(session, H2_SESSION_EV_NO_IO, 0, NULL); } break; case H2_SESSION_ST_WAIT: if (session->wait_us <= 0) { session->wait_us = 10; if (h2_conn_io_flush(&session->io) != APR_SUCCESS) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); break; } } else { /* repeating, increase timer for graceful backoff */ session->wait_us = H2MIN(session->wait_us*2, MAX_WAIT_MICROS); } if (trace) { ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c, "h2_session: wait for data, %ld micros", (long)session->wait_us); } status = h2_mplx_out_trywait(session->mplx, session->wait_us, session->iowait); if (status == APR_SUCCESS) { session->wait_us = 0; dispatch_event(session, H2_SESSION_EV_STREAM_CHANGE, 0, NULL); } else if (APR_STATUS_IS_TIMEUP(status)) { /* go back to checking all inputs again */ transit(session, "wait cycle", session->local.shutdown? H2_SESSION_ST_DONE : H2_SESSION_ST_BUSY); } else if (APR_STATUS_IS_ECONNRESET(status) || APR_STATUS_IS_ECONNABORTED(status)) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } else { ap_log_cerror(APLOG_MARK, APLOG_WARNING, status, c, H2_SSSN_LOG(APLOGNO(03404), session, "waiting on conditional")); h2_session_shutdown(session, H2_ERR_INTERNAL_ERROR, "cond wait error", 0); } break; default: ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, c, H2_SSSN_LOG(APLOGNO(03080), session, "unknown state")); dispatch_event(session, H2_SESSION_EV_PROTO_ERROR, 0, NULL); break; } if (!nghttp2_session_want_read(session->ngh2) && !nghttp2_session_want_write(session->ngh2)) { dispatch_event(session, H2_SESSION_EV_NGH2_DONE, 0, NULL); } if (session->reprioritize) { h2_mplx_reprioritize(session->mplx, stream_pri_cmp, session); session->reprioritize = 0; } } out: if (trace) { ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c, H2_SSSN_MSG(session, "process returns")); } if ((session->state != H2_SESSION_ST_DONE) && (APR_STATUS_IS_EOF(status) || APR_STATUS_IS_ECONNRESET(status) || APR_STATUS_IS_ECONNABORTED(status))) { dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL); } return (session->state == H2_SESSION_ST_DONE)? APR_EOF : APR_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now, mpm event backport to 2.4.x up for vote). * Fixes stream cleanup when connection throttling is in place. * Counts stream resets by client on streams initiated by client as cause for connection throttling. * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann) * Header length is checked also on the merged value from several header instances and results in a 431 response.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: apr_status_t h2_task_do(h2_task *task, apr_thread_t *thread, int worker_id) { conn_rec *c; ap_assert(task); c = task->c; task->worker_started = 1; task->started_at = apr_time_now(); if (c->master) { /* Each conn_rec->id is supposed to be unique at a point in time. Since * some modules (and maybe external code) uses this id as an identifier * for the request_rec they handle, it needs to be unique for slave * connections also. * The connection id is generated by the MPM and most MPMs use the formula * id := (child_num * max_threads) + thread_num * which means that there is a maximum id of about * idmax := max_child_count * max_threads * If we assume 2024 child processes with 2048 threads max, we get * idmax ~= 2024 * 2048 = 2 ** 22 * On 32 bit systems, we have not much space left, but on 64 bit systems * (and higher?) we can use the upper 32 bits without fear of collision. * 32 bits is just what we need, since a connection can only handle so * many streams. */ int slave_id, free_bits; task->id = apr_psprintf(task->pool, "%ld-%d", c->master->id, task->stream_id); if (sizeof(unsigned long) >= 8) { free_bits = 32; slave_id = task->stream_id; } else { /* Assume we have a more limited number of threads/processes * and h2 workers on a 32-bit system. Use the worker instead * of the stream id. */ free_bits = 8; slave_id = worker_id; } task->c->id = (c->master->id << free_bits)^slave_id; } h2_beam_create(&task->output.beam, c->pool, task->stream_id, "output", H2_BEAM_OWNER_SEND, 0, task->timeout); if (!task->output.beam) { return APR_ENOMEM; } h2_beam_buffer_size_set(task->output.beam, task->output.max_buffer); h2_beam_send_from(task->output.beam, task->pool); h2_ctx_create_for(c, task); apr_table_setn(c->notes, H2_TASK_ID_NOTE, task->id); h2_slave_run_pre_connection(c, ap_get_conn_socket(c)); task->input.bb = apr_brigade_create(task->pool, c->bucket_alloc); if (task->request->serialize) { ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c, "h2_task(%s): serialize request %s %s", task->id, task->request->method, task->request->path); apr_brigade_printf(task->input.bb, NULL, NULL, "%s %s HTTP/1.1\r\n", task->request->method, task->request->path); apr_table_do(input_ser_header, task, task->request->headers, NULL); apr_brigade_puts(task->input.bb, NULL, NULL, "\r\n"); } ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c, "h2_task(%s): process connection", task->id); task->c->current_thread = thread; ap_run_process_connection(c); ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c, "h2_task(%s): processing done", task->id); return output_finish(task); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now, mpm event backport to 2.4.x up for vote). * Fixes stream cleanup when connection throttling is in place. * Counts stream resets by client on streams initiated by client as cause for connection throttling. * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann) * Header length is checked also on the merged value from several header instances and results in a 431 response.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void pdf_summarize( FILE *fp, const pdf_t *pdf, const char *name, pdf_flag_t flags) { int i, j, page, n_versions, n_entries; FILE *dst, *out; char *dst_name, *c; dst = NULL; dst_name = NULL; if (name) { dst_name = malloc(strlen(name) * 2 + 16); sprintf(dst_name, "%s/%s", name, name); if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0)) *c = '\0'; strcat(dst_name, ".summary"); if (!(dst = fopen(dst_name, "w"))) { ERR("Could not open file '%s' for writing\n", dst_name); return; } } /* Send output to file or stdout */ out = (dst) ? dst : stdout; /* Count versions */ n_versions = pdf->n_xrefs; if (n_versions && pdf->xrefs[0].is_linear) --n_versions; /* Ignore bad xref entry */ for (i=1; i<pdf->n_xrefs; ++i) if (pdf->xrefs[i].end == 0) --n_versions; /* If we have no valid versions but linear, count that */ if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear)) n_versions = 1; /* Compare each object (if we dont have xref streams) */ n_entries = 0; for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++) { if (flags & PDF_FLAG_QUIET) continue; for (j=0; j<pdf->xrefs[i].n_entries; j++) { ++n_entries; fprintf(out, "%s: --%c-- Version %d -- Object %d (%s)", pdf->name, pdf_get_object_status(pdf, i, j), pdf->xrefs[i].version, pdf->xrefs[i].entries[j].obj_id, get_type(fp, pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i])); /* TODO page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]); */ if (0 /*page*/) fprintf(out, " Page(%d)\n", page); else fprintf(out, "\n"); } } /* Trailing summary */ if (!(flags & PDF_FLAG_QUIET)) { /* Let the user know that we cannot we print a per-object summary. * If we have a 1.5 PDF using streams for xref, we have not objects * to display, so let the user know whats up. */ if (pdf->has_xref_streams || !n_entries) fprintf(out, "%s: This PDF contains potential cross reference streams.\n" "%s: An object summary is not available.\n", pdf->name, pdf->name); fprintf(out, "---------- %s ----------\n" "Versions: %d\n", pdf->name, n_versions); /* Count entries for summary */ if (!pdf->has_xref_streams) for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].is_linear) continue; n_entries = pdf->xrefs[i].n_entries; /* If we are a linearized PDF, all versions are made from those * objects too. So count em' */ if (pdf->xrefs[0].is_linear) n_entries += pdf->xrefs[0].n_entries; if (pdf->xrefs[i].version && n_entries) fprintf(out, "Version %d -- %d objects\n", pdf->xrefs[i].version, n_entries); } } else /* Quiet output */ fprintf(out, "%s: %d\n", pdf->name, n_versions); if (dst) { fclose(dst); free(dst_name); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf'</s>
<s>[INST] Given the following code containing errors, provide 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 pdf_load_pages_kids(FILE *fp, pdf_t *pdf) { int i, id, dummy; char *buf, *c; long start, sz; start = ftell(fp); /* Load all kids for all xref tables (versions) */ for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0)) { fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to trailer */ /* Get root catalog */ sz = pdf->xrefs[i].end - ftell(fp); buf = malloc(sz + 1); SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n"); buf[sz] = '\0'; if (!(c = strstr(buf, "/Root"))) { free(buf); continue; } /* Jump to catalog (root) */ id = atoi(c + strlen("/Root") + 1); free(buf); buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy); if (!buf || !(c = strstr(buf, "/Pages"))) { free(buf); continue; } /* Start at the first Pages obj and get kids */ id = atoi(c + strlen("/Pages") + 1); load_kids(fp, id, &pdf->xrefs[i]); free(buf); } } fseek(fp, start, SEEK_SET); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line, u32 level, const char *fmt, ...) { va_list va; struct va_format vaf; char nfunc[32]; memset(nfunc, 0, sizeof(nfunc)); memcpy(nfunc, func, sizeof(nfunc) - 1); va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & level)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), nfunc, line, qedi->host_no, &vaf); else pr_info("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf); ret: va_end(va); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'scsi: qedi: remove memset/memcpy to nfunc and use func instead KASAN reports this: BUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi] Read of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429 CPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 print_address_description+0x1c4/0x270 mm/kasan/report.c:187 kasan_report+0x149/0x18d mm/kasan/report.c:317 memcpy+0x1f/0x50 mm/kasan/common.c:130 qedi_dbg_err+0xda/0x330 [qedi] ? 0xffffffffc12d0000 qedi_init+0x118/0x1000 [qedi] ? 0xffffffffc12d0000 ? 0xffffffffc12d0000 ? 0xffffffffc12d0000 do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003 RBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 The buggy address belongs to the variable: __func__.67584+0x0/0xffffffffffffd520 [qedi] Memory state around the buggy address: ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa > ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa ^ ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa Currently the qedi_dbg_* family of functions can overrun the end of the source string if it is less than the destination buffer length because of the use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc and just use func instead as it is always a null terminated string. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: ace7f46ba5fd ("scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Reviewed-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ath10k_usb_alloc_urb_from_pipe(struct ath10k_usb_pipe *pipe) { struct ath10k_urb_context *urb_context = NULL; unsigned long flags; spin_lock_irqsave(&pipe->ar_usb->cs_lock, flags); if (!list_empty(&pipe->urb_list_head)) { urb_context = list_first_entry(&pipe->urb_list_head, struct ath10k_urb_context, link); list_del(&urb_context->link); pipe->urb_cnt--; } spin_unlock_irqrestore(&pipe->ar_usb->cs_lock, flags); return urb_context; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'ath10k: Fix a NULL-ptr-deref bug in ath10k_usb_alloc_urb_from_pipe The `ar_usb` field of `ath10k_usb_pipe_usb_pipe` objects are initialized to point to the containing `ath10k_usb` object according to endpoint descriptors read from the device side, as shown below in `ath10k_usb_setup_pipe_resources`: for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; // get the address from endpoint descriptor pipe_num = ath10k_usb_get_logical_pipe_num(ar_usb, endpoint->bEndpointAddress, &urbcount); ...... // select the pipe object pipe = &ar_usb->pipes[pipe_num]; // initialize the ar_usb field pipe->ar_usb = ar_usb; } The driver assumes that the addresses reported in endpoint descriptors from device side to be complete. If a device is malicious and does not report complete addresses, it may trigger NULL-ptr-deref `ath10k_usb_alloc_urb_from_pipe` and `ath10k_usb_free_urb_to_pipe`. This patch fixes the bug by preventing potential NULL-ptr-deref. Signed-off-by: Hui Peng <benquike@gmail.com> Reported-by: Hui Peng <benquike@gmail.com> Reported-by: Mathias Payer <mathias.payer@nebelwelt.net> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> [groeck: Add driver tag to subject, fix build warning] Signed-off-by: Guenter Roeck <linux@roeck-us.net> Signed-off-by: Kalle Valo <kvalo@codeaurora.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: mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and mwifiex_set_wmm_params() call memcpy() without checking the destination size.Since the source is given from user-space, this may trigger a heap buffer overflow. Fix them by putting the length check before performing memcpy(). This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816. Signed-off-by: Wen Huang <huangwenabc@gmail.com> Acked-by: Ganapathi Bhat <gbhat@marvell.comg> Signed-off-by: Kalle Valo <kvalo@codeaurora.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status AuthorizationManagerImpl::_initializeUserFromPrivilegeDocument(User* user, const BSONObj& privDoc) { V2UserDocumentParser parser; std::string userName = parser.extractUserNameFromUserDocument(privDoc); if (userName != user->getName().getUser()) { return Status(ErrorCodes::BadValue, mongoutils::str::stream() << "User name from privilege document \"" << userName << "\" doesn't match name of provided User \"" << user->getName().getUser() << "\""); } Status status = parser.initializeUserCredentialsFromUserDocument(user, privDoc); if (!status.isOK()) { return status; } status = parser.initializeUserRolesFromUserDocument(privDoc, user); if (!status.isOK()) { return status; } status = parser.initializeUserIndirectRolesFromUserDocument(privDoc, user); if (!status.isOK()) { return status; } status = parser.initializeUserPrivilegesFromUserDocument(privDoc, user); if (!status.isOK()) { return status; } status = parser.initializeAuthenticationRestrictionsFromUserDocument(privDoc, user); if (!status.isOK()) { return status; } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'</s>
<s>[INST] Given the following code containing errors, provide 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 run(OperationContext* txn, const string& dbname, BSONObj& cmdObj, int options, string& errmsg, BSONObjBuilder& result) { auth::CreateOrUpdateUserArgs args; Status status = auth::parseCreateOrUpdateUserCommands(cmdObj, "createUser", dbname, &args); if (!status.isOK()) { return appendCommandStatus(result, status); } if (args.userName.getDB() == "local") { return appendCommandStatus( result, Status(ErrorCodes::BadValue, "Cannot create users in the local database")); } if (!args.hasHashedPassword && args.userName.getDB() != "$external") { return appendCommandStatus( result, Status(ErrorCodes::BadValue, "Must provide a 'pwd' field for all user documents, except those" " with '$external' as the user's source db")); } if ((args.hasHashedPassword) && args.userName.getDB() == "$external") { return appendCommandStatus( result, Status(ErrorCodes::BadValue, "Cannot set the password for users defined on the '$external' " "database")); } if (!args.hasRoles) { return appendCommandStatus( result, Status(ErrorCodes::BadValue, "\"createUser\" command requires a \"roles\" array")); } #ifdef MONGO_CONFIG_SSL if (args.userName.getDB() == "$external" && getSSLManager() && getSSLManager()->getSSLConfiguration().isClusterMember(args.userName.getUser())) { return appendCommandStatus(result, Status(ErrorCodes::BadValue, "Cannot create an x.509 user with a subjectname " "that would be recognized as an internal " "cluster member.")); } #endif BSONObjBuilder userObjBuilder; userObjBuilder.append( "_id", str::stream() << args.userName.getDB() << "." << args.userName.getUser()); userObjBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, args.userName.getUser()); userObjBuilder.append(AuthorizationManager::USER_DB_FIELD_NAME, args.userName.getDB()); ServiceContext* serviceContext = txn->getClient()->getServiceContext(); AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext); int authzVersion; status = authzManager->getAuthorizationVersion(txn, &authzVersion); if (!status.isOK()) { return appendCommandStatus(result, status); } BSONObjBuilder credentialsBuilder(userObjBuilder.subobjStart("credentials")); if (!args.hasHashedPassword) { // Must be an external user credentialsBuilder.append("external", true); } else { // Add SCRAM credentials for appropriate authSchemaVersions. if (authzVersion > AuthorizationManager::schemaVersion26Final) { BSONObj scramCred = scram::generateCredentials( args.hashedPassword, saslGlobalParams.scramIterationCount); credentialsBuilder.append("SCRAM-SHA-1", scramCred); } else { // Otherwise default to MONGODB-CR. credentialsBuilder.append("MONGODB-CR", args.hashedPassword); } } credentialsBuilder.done(); if (args.hasCustomData) { userObjBuilder.append("customData", args.customData); } userObjBuilder.append("roles", rolesVectorToBSONArray(args.roles)); BSONObj userObj = userObjBuilder.obj(); V2UserDocumentParser parser; status = parser.checkValidUserDocument(userObj); if (!status.isOK()) { return appendCommandStatus(result, status); } stdx::lock_guard<stdx::mutex> lk(getAuthzDataMutex(serviceContext)); status = requireAuthSchemaVersion26Final(txn, authzManager); if (!status.isOK()) { return appendCommandStatus(result, status); } // Role existence has to be checked after acquiring the update lock for (size_t i = 0; i < args.roles.size(); ++i) { BSONObj ignored; status = authzManager->getRoleDescription( txn, args.roles[i], PrivilegeFormat::kOmit, &ignored); if (!status.isOK()) { return appendCommandStatus(result, status); } } audit::logCreateUser(Client::getCurrent(), args.userName, args.hasHashedPassword, args.hasCustomData ? &args.customData : NULL, args.roles); status = insertPrivilegeDocument(txn, userObj); return appendCommandStatus(result, status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit (cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'</s>
<s>[INST] Given the following code containing errors, provide 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 uac_mixer_unit_get_channels(struct mixer_build *state, struct uac_mixer_unit_descriptor *desc) { int mu_channels; void *c; if (desc->bLength < sizeof(*desc)) return -EINVAL; if (!desc->bNrInPins) return -EINVAL; switch (state->mixer->protocol) { case UAC_VERSION_1: case UAC_VERSION_2: default: if (desc->bLength < sizeof(*desc) + desc->bNrInPins + 1) return 0; /* no bmControls -> skip */ mu_channels = uac_mixer_unit_bNrChannels(desc); break; case UAC_VERSION_3: mu_channels = get_cluster_channels_v3(state, uac3_mixer_unit_wClusterDescrID(desc)); break; } if (!mu_channels) return 0; c = uac_mixer_unit_bmControls(desc, state->mixer->protocol); if (c - (void *)desc + (mu_channels - 1) / 8 >= desc->bLength) return 0; /* no bmControls -> skip */ return mu_channels; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'ALSA: usb-audio: Fix an OOB bug in parse_audio_mixer_unit The `uac_mixer_unit_descriptor` shown as below is read from the device side. In `parse_audio_mixer_unit`, `baSourceID` field is accessed from index 0 to `bNrInPins` - 1, the current implementation assumes that descriptor is always valid (the length of descriptor is no shorter than 5 + `bNrInPins`). If a descriptor read from the device side is invalid, it may trigger out-of-bound memory access. ``` struct uac_mixer_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bUnitID; __u8 bNrInPins; __u8 baSourceID[]; } ``` This patch fixes the bug by add a sanity check on the length of the descriptor. Reported-by: Hui Peng <benquike@gmail.com> Reported-by: Mathias Payer <mathias.payer@nebelwelt.net> Cc: <stable@vger.kernel.org> Signed-off-by: Hui Peng <benquike@gmail.com> Signed-off-by: Takashi Iwai <tiwai@suse.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 void p54u_load_firmware_cb(const struct firmware *firmware, void *context) { struct p54u_priv *priv = context; struct usb_device *udev = priv->udev; int err; complete(&priv->fw_wait_load); if (firmware) { priv->fw = firmware; err = p54u_start_ops(priv); } else { err = -ENOENT; dev_err(&udev->dev, "Firmware not found.\n"); } if (err) { struct device *parent = priv->udev->dev.parent; dev_err(&udev->dev, "failed to initialize device (%d)\n", err); if (parent) device_lock(parent); device_release_driver(&udev->dev); /* * At this point p54u_disconnect has already freed * the "priv" context. Do not use it anymore! */ priv = NULL; if (parent) device_unlock(parent); } usb_put_dev(udev); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'p54usb: Fix race between disconnect and firmware loading The syzbot fuzzer found a bug in the p54 USB wireless driver. The issue involves a race between disconnect and the firmware-loader callback routine, and it has several aspects. One big problem is that when the firmware can't be loaded, the callback routine tries to unbind the driver from the USB _device_ (by calling device_release_driver) instead of from the USB _interface_ to which it is actually bound (by calling usb_driver_release_interface). The race involves access to the private data structure. The driver's disconnect handler waits for a completion that is signalled by the firmware-loader callback routine. As soon as the completion is signalled, you have to assume that the private data structure may have been deallocated by the disconnect handler -- even if the firmware was loaded without errors. However, the callback routine does access the private data several times after that point. Another problem is that, in order to ensure that the USB device structure hasn't been freed when the callback routine runs, the driver takes a reference to it. This isn't good enough any more, because now that the callback routine calls usb_driver_release_interface, it has to ensure that the interface structure hasn't been freed. Finally, the driver takes an unnecessary reference to the USB device structure in the probe function and drops the reference in the disconnect handler. This extra reference doesn't accomplish anything, because the USB core already guarantees that a device structure won't be deallocated while a driver is still bound to any of its interfaces. To fix these problems, this patch makes the following changes: Call usb_driver_release_interface() rather than device_release_driver(). Don't signal the completion until after the important information has been copied out of the private data structure, and don't refer to the private data at all thereafter. Lock udev (the interface's parent) before unbinding the driver instead of locking udev->parent. During the firmware loading process, take a reference to the USB interface instead of the USB device. Don't take an unnecessary reference to the device during probe (and then don't drop it during disconnect). Signed-off-by: Alan Stern <stern@rowland.harvard.edu> Reported-and-tested-by: syzbot+200d4bb11b23d929335f@syzkaller.appspotmail.com CC: <stable@vger.kernel.org> Acked-by: Christian Lamparter <chunkeey@gmail.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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 line6_disconnect(struct usb_interface *interface) { struct usb_line6 *line6 = usb_get_intfdata(interface); struct usb_device *usbdev = interface_to_usbdev(interface); if (!line6) return; if (WARN_ON(usbdev != line6->usbdev)) return; if (line6->urb_listen != NULL) line6_stop_listen(line6); snd_card_disconnect(line6->card); if (line6->line6pcm) line6_pcm_disconnect(line6->line6pcm); if (line6->disconnect) line6->disconnect(line6); dev_info(&interface->dev, "Line 6 %s now disconnected\n", line6->properties->name); /* make sure the device isn't destructed twice: */ usb_set_intfdata(interface, NULL); snd_card_free_when_closed(line6->card); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'ALSA: line6: Assure canceling delayed work at disconnection The current code performs the cancel of a delayed work at the late stage of disconnection procedure, which may lead to the access to the already cleared state. This patch assures to call cancel_delayed_work_sync() at the beginning of the disconnection procedure for avoiding that race. The delayed work object is now assigned in the common line6 object instead of its derivative, so that we can call cancel_delayed_work_sync(). Along with the change, the startup function is called via the new callback instead. This will make it easier to port other LINE6 drivers to use the delayed work for startup in later patches. Reported-by: syzbot+5255458d5e0a2b10bbb9@syzkaller.appspotmail.com Fixes: 7f84ff68be05 ("ALSA: line6: toneport: Fix broken usage of timer for delayed execution") Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.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: bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned subcode, byte *data, unsigned len) { byte argbuf[256], *t = argbuf; unsigned i; /* Don't report Cease messages generated by myself */ if (code == 6 && class == BE_BGP_TX) return; /* Reset shutdown message */ if ((code == 6) && ((subcode == 2) || (subcode == 4))) proto_set_message(&p->p, NULL, 0); if (len) { /* Bad peer AS - we would like to print the AS */ if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4))) { t += bsprintf(t, ": %u", (len == 2) ? get_u16(data) : get_u32(data)); goto done; } /* RFC 8203 - shutdown communication */ if (((code == 6) && ((subcode == 2) || (subcode == 4)))) if (bgp_handle_message(p, data, len, &t)) goto done; *t++ = ':'; *t++ = ' '; if (len > 16) len = 16; for (i=0; i<len; i++) t += bsprintf(t, "%02x", data[i]); } done: *t = 0; const byte *dsc = bgp_error_dsc(code, subcode); log(L_REMOTE "%s: %s: %s%s", p->p.name, msg, dsc, argbuf); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'BGP: Fix bugs in handling of shutdown messages There is an improper check for valid message size, which may lead to stack overflow and buffer leaks to log when a large message is received. Thanks to Daniel McCarney for bugreport and analysis.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: externalParEntProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { const char *next = s; int tok; tok = XmlPrologTok(parser->m_encoding, s, end, &next); if (tok <= 0) { if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case XML_TOK_NONE: /* start == end */ default: break; } } /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. However, when parsing an external subset, doProlog will not accept a BOM as valid, and report a syntax error, so we have to skip the BOM */ else if (tok == XML_TOK_BOM) { s = next; tok = XmlPrologTok(parser->m_encoding, s, end, &next); } parser->m_processor = prologProcessor; return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-611', 'CWE-776', 'CWE-415', 'CWE-125'], 'message': 'xmlparse.c: Deny internal entities closing the doctype'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse( const Http::TestHeaderMapImpl& request_headers, uint32_t request_body_size, const Http::TestHeaderMapImpl& response_headers, uint32_t response_size, int upstream_index) { ASSERT(codec_client_ != nullptr); // Send the request to Envoy. IntegrationStreamDecoderPtr response; if (request_body_size) { response = codec_client_->makeRequestWithBody(request_headers, request_body_size); } else { response = codec_client_->makeHeaderOnlyRequest(request_headers); } waitForNextUpstreamRequest(upstream_index); // Send response headers, and end_stream if there is no response body. upstream_request_->encodeHeaders(response_headers, response_size == 0); // Send any response data, with end_stream true. if (response_size) { upstream_request_->encodeData(response_size, true); } // Wait for the response to be read by the codec client. response->waitForEndStream(); return response; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally. Introduces a cached byte size updated internally in HeaderMap. The value is stored as an optional, and is cleared whenever a non-const pointer or reference to a HeaderEntry is accessed. The cached value can be set with refreshByteSize() which performs an iteration over the HeaderMap to sum the size of each key and value in the HeaderMap. Signed-off-by: Asra Ali <asraa@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST(HeaderMapImplTest, SetReferenceKey) { HeaderMapImpl headers; LowerCaseString foo("hello"); headers.setReferenceKey(foo, "world"); EXPECT_NE("world", headers.get(foo)->value().getStringView().data()); EXPECT_EQ("world", headers.get(foo)->value().getStringView()); headers.setReferenceKey(foo, "monde"); EXPECT_NE("monde", headers.get(foo)->value().getStringView().data()); EXPECT_EQ("monde", headers.get(foo)->value().getStringView()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally. Introduces a cached byte size updated internally in HeaderMap. The value is stored as an optional, and is cleared whenever a non-const pointer or reference to a HeaderEntry is accessed. The cached value can be set with refreshByteSize() which performs an iteration over the HeaderMap to sum the size of each key and value in the HeaderMap. Signed-off-by: Asra Ali <asraa@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_P(Http2CodecImplTest, TestLargeRequestHeadersAtLimitAccepted) { uint32_t codec_limit_kb = 64; max_request_headers_kb_ = codec_limit_kb; initialize(); TestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); std::string key = "big"; uint32_t head_room = 77; uint32_t long_string_length = codec_limit_kb * 1024 - request_headers.byteSize() - key.length() - head_room; std::string long_string = std::string(long_string_length, 'q'); request_headers.addCopy(key, long_string); // The amount of data sent to the codec is not equivalent to the size of the // request headers that Envoy computes, as the codec limits based on the // entire http2 frame. The exact head room needed (76) was found through iteration. ASSERT_EQ(request_headers.byteSize() + head_room, codec_limit_kb * 1024); EXPECT_CALL(request_decoder_, decodeHeaders_(_, _)); request_encoder_->encodeHeaders(request_headers, true); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally. Introduces a cached byte size updated internally in HeaderMap. The value is stored as an optional, and is cleared whenever a non-const pointer or reference to a HeaderEntry is accessed. The cached value can be set with refreshByteSize() which performs an iteration over the HeaderMap to sum the size of each key and value in the HeaderMap. Signed-off-by: Asra Ali <asraa@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST(HeaderMapImplTest, DoubleCookieAdd) { HeaderMapImpl headers; const std::string foo("foo"); const std::string bar("bar"); const LowerCaseString& set_cookie = Http::Headers::get().SetCookie; headers.addReference(set_cookie, foo); headers.addReference(set_cookie, bar); EXPECT_EQ(2UL, headers.size()); std::vector<absl::string_view> out; Http::HeaderUtility::getAllOfHeader(headers, "set-cookie", out); ASSERT_EQ(out.size(), 2); ASSERT_EQ(out[0], "foo"); ASSERT_EQ(out[1], "bar"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally. Introduces a cached byte size updated internally in HeaderMap. The value is stored as an optional, and is cleared whenever a non-const pointer or reference to a HeaderEntry is accessed. The cached value can be set with refreshByteSize() which performs an iteration over the HeaderMap to sum the size of each key and value in the HeaderMap. Signed-off-by: Asra Ali <asraa@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: http1_dissect_hdrs(struct http *hp, char *p, struct http_conn *htc, unsigned maxhdr) { char *q, *r, *s; int i; assert(p > htc->rxbuf_b); assert(p <= htc->rxbuf_e); hp->nhd = HTTP_HDR_FIRST; r = NULL; /* For FlexeLint */ for (; p < htc->rxbuf_e; p = r) { /* Find end of next header */ q = r = p; if (vct_iscrlf(p, htc->rxbuf_e)) break; while (r < htc->rxbuf_e) { if (!vct_isctl(*r) || vct_issp(*r)) { r++; continue; } if (!vct_iscrlf(r, htc->rxbuf_e)) { VSLb(hp->vsl, SLT_BogoHeader, "Header has ctrl char 0x%02x", *r); return (400); } q = r; assert(r < htc->rxbuf_e); r = vct_skipcrlf(r, htc->rxbuf_e); if (r >= htc->rxbuf_e) break; if (vct_iscrlf(r, htc->rxbuf_e)) break; /* If line does not continue: got it. */ if (!vct_issp(*r)) break; /* Clear line continuation LWS to spaces */ while (q < r) *q++ = ' '; while (q < htc->rxbuf_e && vct_issp(*q)) *q++ = ' '; } /* Empty header = end of headers */ if (p == q) break; if (q - p > maxhdr) { VSLb(hp->vsl, SLT_BogoHeader, "Header too long: %.*s", (int)(q - p > 20 ? 20 : q - p), p); return (400); } if (vct_islws(*p)) { VSLb(hp->vsl, SLT_BogoHeader, "1st header has white space: %.*s", (int)(q - p > 20 ? 20 : q - p), p); return (400); } if (*p == ':') { VSLb(hp->vsl, SLT_BogoHeader, "Missing header name: %.*s", (int)(q - p > 20 ? 20 : q - p), p); return (400); } while (q > p && vct_issp(q[-1])) q--; *q = '\0'; for (s = p; *s != ':' && s < q; s++) { if (!vct_istchar(*s)) { VSLb(hp->vsl, SLT_BogoHeader, "Illegal char 0x%02x in header name", *s); return (400); } } if (*s != ':') { VSLb(hp->vsl, SLT_BogoHeader, "Header without ':' %.*s", (int)(q - p > 20 ? 20 : q - p), p); return (400); } if (hp->nhd < hp->shd) { hp->hdf[hp->nhd] = 0; hp->hd[hp->nhd].b = p; hp->hd[hp->nhd].e = q; hp->nhd++; } else { VSLb(hp->vsl, SLT_BogoHeader, "Too many headers: %.*s", (int)(q - p > 20 ? 20 : q - p), p); return (400); } } i = vct_iscrlf(p, htc->rxbuf_e); assert(i > 0); /* HTTP1_Complete guarantees this */ p += i; HTC_RxPipeline(htc, p); htc->rxbuf_e = p; return (0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Avoid some code duplication Apply some adjustments to recent patches based off of review by Nils Goroll at UPLEX (@nigoroll)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: plugin_close (struct backend *b, struct connection *conn) { struct backend_plugin *p = container_of (b, struct backend_plugin, backend); assert (connection_get_handle (conn, 0)); debug ("close"); if (p->plugin.close) p->plugin.close (connection_get_handle (conn, 0)); backend_set_handle (b, conn, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO Most known NBD clients do not bother with NBD_OPT_INFO (except for clients like 'qemu-nbd --list' that don't ever intend to connect), but go straight to NBD_OPT_GO. However, it's not too hard to hack up qemu to add in an extra client step (whether info on the same name, or more interestingly, info on a different name), as a patch against qemu commit 6f214b30445: | diff --git i/nbd/client.c w/nbd/client.c | index f6733962b49b..425292ac5ea9 100644 | --- i/nbd/client.c | +++ w/nbd/client.c | @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc, | * TLS). If it is not available, fall back to | * NBD_OPT_LIST for nicer error messages about a missing | * export, then use NBD_OPT_EXPORT_NAME. */ | + if (getenv ("HACK")) | + info->name[0]++; | + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp); | + if (getenv ("HACK")) | + info->name[0]--; | + if (result < 0) { | + return -EINVAL; | + } | result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp); | if (result < 0) { | return -EINVAL; This works just fine in 1.14.0, where we call .open only once (so the INFO and GO repeat calls into the same plugin handle), but in 1.14.1 it regressed into causing an assertion failure: we are now calling .open a second time on a connection that is already opened: $ nbdkit -rfv null & $ hacked-qemu-io -f raw -r nbd://localhost -c quit ... nbdkit: null[1]: debug: null: open readonly=1 nbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed. Worse, on the mainline development, we have recently made it possible for plugins to actively report different information for different export names; for example, a plugin may choose to report different answers for .can_write on export A than for export B; but if we share cached handles, then an NBD_OPT_INFO on one export prevents correct answers for NBD_OPT_GO on the second export name. (The HACK envvar in my qemu modifications can be used to demonstrate cross-name requests, which are even less likely in a real client). The solution is to call .close after NBD_OPT_INFO, coupled with enough glue logic to reset cached connection handles back to the state expected by .open. This in turn means factoring out another backend_* function, but also gives us an opportunity to change backend_set_handle to no longer accept NULL. The assertion failure is, to some extent, a possible denial of service attack (one client can force nbdkit to exit by merely sending OPT_INFO before OPT_GO, preventing the next client from connecting), although this is mitigated by using TLS to weed out untrusted clients. Still, the fact that we introduced a potential DoS attack while trying to fix a traffic amplification security bug is not very nice. Sadly, as there are no known clients that easily trigger this mode of operation (OPT_INFO before OPT_GO), there is no easy way to cover this via a testsuite addition. I may end up hacking something into libnbd. Fixes: c05686f957 Signed-off-by: Eric Blake <eblake@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: negotiate_handshake_newstyle_options (struct connection *conn) { struct new_option new_option; size_t nr_options; uint64_t version; uint32_t option; uint32_t optlen; char data[MAX_OPTION_LENGTH+1]; struct new_handshake_finish handshake_finish; const char *optname; for (nr_options = 0; nr_options < MAX_NR_OPTIONS; ++nr_options) { if (conn_recv_full (conn, &new_option, sizeof new_option, "reading option: conn->recv: %m") == -1) return -1; version = be64toh (new_option.version); if (version != NEW_VERSION) { nbdkit_error ("unknown option version %" PRIx64 ", expecting %" PRIx64, version, NEW_VERSION); return -1; } /* There is a maximum option length we will accept, regardless * of the option type. */ optlen = be32toh (new_option.optlen); if (optlen > MAX_OPTION_LENGTH) { nbdkit_error ("client option data too long (%" PRIu32 ")", optlen); return -1; } option = be32toh (new_option.option); optname = name_of_nbd_opt (option); /* In --tls=require / FORCEDTLS mode the only options allowed * before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS. */ if (tls == 2 && !conn->using_tls && !(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) { if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_TLS_REQD)) return -1; continue; } switch (option) { case NBD_OPT_EXPORT_NAME: if (conn_recv_full (conn, data, optlen, "read: %s: %m", name_of_nbd_opt (option)) == -1) return -1; /* Apart from printing it, ignore the export name. */ data[optlen] = '\0'; debug ("newstyle negotiation: %s: " "client requested export '%s' (ignored)", name_of_nbd_opt (option), data); /* We have to finish the handshake by sending handshake_finish. */ if (finish_newstyle_options (conn) == -1) return -1; memset (&handshake_finish, 0, sizeof handshake_finish); handshake_finish.exportsize = htobe64 (conn->exportsize); handshake_finish.eflags = htobe16 (conn->eflags); if (conn->send (conn, &handshake_finish, (conn->cflags & NBD_FLAG_NO_ZEROES) ? offsetof (struct new_handshake_finish, zeroes) : sizeof handshake_finish) == -1) { nbdkit_error ("write: %s: %m", optname); return -1; } break; case NBD_OPT_ABORT: if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; debug ("client sent %s to abort the connection", name_of_nbd_opt (option)); return -1; case NBD_OPT_LIST: if (optlen != 0) { if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; if (conn_recv_full (conn, data, optlen, "read: %s: %m", name_of_nbd_opt (option)) == -1) return -1; continue; } /* Send back the exportname. */ debug ("newstyle negotiation: %s: advertising export '%s'", name_of_nbd_opt (option), exportname); if (send_newstyle_option_reply_exportname (conn, option, NBD_REP_SERVER, exportname) == -1) return -1; if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; break; case NBD_OPT_STARTTLS: if (optlen != 0) { if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; if (conn_recv_full (conn, data, optlen, "read: %s: %m", name_of_nbd_opt (option)) == -1) return -1; continue; } if (tls == 0) { /* --tls=off (NOTLS mode). */ #ifdef HAVE_GNUTLS #define NO_TLS_REPLY NBD_REP_ERR_POLICY #else #define NO_TLS_REPLY NBD_REP_ERR_UNSUP #endif if (send_newstyle_option_reply (conn, option, NO_TLS_REPLY) == -1) return -1; } else /* --tls=on or --tls=require */ { /* We can't upgrade to TLS twice on the same connection. */ if (conn->using_tls) { if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; continue; } /* We have to send the (unencrypted) reply before starting * the handshake. */ if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; /* Upgrade the connection to TLS. Also performs access control. */ if (crypto_negotiate_tls (conn, conn->sockin, conn->sockout) == -1) return -1; conn->using_tls = true; debug ("using TLS on this connection"); } break; case NBD_OPT_INFO: case NBD_OPT_GO: if (conn_recv_full (conn, data, optlen, "read: %s: %m", optname) == -1) return -1; if (optlen < 6) { /* 32 bit export length + 16 bit nr info */ debug ("newstyle negotiation: %s option length < 6", optname); if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; continue; } { uint32_t exportnamelen; uint16_t nrinfos; uint16_t info; size_t i; CLEANUP_FREE char *requested_exportname = NULL; /* Validate the name length and number of INFO requests. */ memcpy (&exportnamelen, &data[0], 4); exportnamelen = be32toh (exportnamelen); if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) { debug ("newstyle negotiation: %s: export name too long", optname); if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; continue; } memcpy (&nrinfos, &data[exportnamelen+4], 2); nrinfos = be16toh (nrinfos); if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) { debug ("newstyle negotiation: %s: " "number of information requests incorrect", optname); if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; continue; } /* As with NBD_OPT_EXPORT_NAME we print the export name and then * ignore it. */ requested_exportname = malloc (exportnamelen+1); if (requested_exportname == NULL) { nbdkit_error ("malloc: %m"); return -1; } memcpy (requested_exportname, &data[4], exportnamelen); requested_exportname[exportnamelen] = '\0'; debug ("newstyle negotiation: %s: " "client requested export '%s' (ignored)", optname, requested_exportname); /* The spec is confusing, but it is required that we send back * NBD_INFO_EXPORT, even if the client did not request it! * qemu client in particular does not request this, but will * fail if we don't send it. */ if (finish_newstyle_options (conn) == -1) return -1; if (send_newstyle_option_reply_info_export (conn, option, NBD_REP_INFO, NBD_INFO_EXPORT) == -1) return -1; /* For now we ignore all other info requests (but we must * ignore NBD_INFO_EXPORT if it was requested, because we * replied already above). Therefore this loop doesn't do * much at the moment. */ for (i = 0; i < nrinfos; ++i) { memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2); info = be16toh (info); switch (info) { case NBD_INFO_EXPORT: /* ignore - reply sent above */ break; default: debug ("newstyle negotiation: %s: " "ignoring NBD_INFO_* request %u (%s)", optname, (unsigned) info, name_of_nbd_info (info)); break; } } } /* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK * or ERROR packet. */ if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; break; case NBD_OPT_STRUCTURED_REPLY: if (optlen != 0) { if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; if (conn_recv_full (conn, data, optlen, "read: %s: %m", name_of_nbd_opt (option)) == -1) return -1; continue; } debug ("newstyle negotiation: %s: client requested structured replies", name_of_nbd_opt (option)); if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; conn->structured_replies = true; break; case NBD_OPT_LIST_META_CONTEXT: case NBD_OPT_SET_META_CONTEXT: { uint32_t opt_index; uint32_t exportnamelen; uint32_t nr_queries; uint32_t querylen; const char *what; if (conn_recv_full (conn, data, optlen, "read: %s: %m", optname) == -1) return -1; if (!conn->structured_replies) { if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; continue; } /* Minimum length of the option payload is: * 32 bit export name length followed by empty export name * + 32 bit number of queries followed by no queries * = 8 bytes. */ what = "optlen < 8"; if (optlen < 8) { opt_meta_invalid_option_len: debug ("newstyle negotiation: %s: invalid option length: %s", optname, what); if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_INVALID) == -1) return -1; continue; } /* Discard the export name. */ memcpy (&exportnamelen, &data[0], 4); exportnamelen = be32toh (exportnamelen); opt_index = 4 + exportnamelen; /* Read the number of queries. */ what = "reading number of queries"; if (opt_index+4 > optlen) goto opt_meta_invalid_option_len; memcpy (&nr_queries, &data[opt_index], 4); nr_queries = be32toh (nr_queries); opt_index += 4; /* for LIST: nr_queries == 0 means return all meta contexts * for SET: nr_queries == 0 means reset all contexts */ debug ("newstyle negotiation: %s: %s count: %d", optname, option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set", nr_queries); if (nr_queries == 0) { if (option == NBD_OPT_SET_META_CONTEXT) conn->meta_context_base_allocation = false; else /* LIST */ { if (send_newstyle_option_reply_meta_context (conn, option, NBD_REP_META_CONTEXT, 0, "base:allocation") == -1) return -1; } if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; } else { /* Read and answer each query. */ while (nr_queries > 0) { what = "reading query string length"; if (opt_index+4 > optlen) goto opt_meta_invalid_option_len; memcpy (&querylen, &data[opt_index], 4); querylen = be32toh (querylen); opt_index += 4; what = "reading query string"; if (opt_index + querylen > optlen) goto opt_meta_invalid_option_len; debug ("newstyle negotiation: %s: %s %.*s", optname, option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set", (int) querylen, &data[opt_index]); /* For LIST, "base:" returns all supported contexts in the * base namespace. We only support "base:allocation". */ if (option == NBD_OPT_LIST_META_CONTEXT && querylen == 5 && strncmp (&data[opt_index], "base:", 5) == 0) { if (send_newstyle_option_reply_meta_context (conn, option, NBD_REP_META_CONTEXT, 0, "base:allocation") == -1) return -1; } /* "base:allocation" requested by name. */ else if (querylen == 15 && strncmp (&data[opt_index], "base:allocation", 15) == 0) { if (send_newstyle_option_reply_meta_context (conn, option, NBD_REP_META_CONTEXT, option == NBD_OPT_SET_META_CONTEXT ? base_allocation_id : 0, "base:allocation") == -1) return -1; if (option == NBD_OPT_SET_META_CONTEXT) conn->meta_context_base_allocation = true; } /* Every other query must be ignored. */ opt_index += querylen; nr_queries--; } if (send_newstyle_option_reply (conn, option, NBD_REP_ACK) == -1) return -1; } debug ("newstyle negotiation: %s: reply complete", optname); } break; default: /* Unknown option. */ if (send_newstyle_option_reply (conn, option, NBD_REP_ERR_UNSUP) == -1) return -1; if (conn_recv_full (conn, data, optlen, "reading unknown option data: conn->recv: %m") == -1) return -1; } /* Note, since it's not very clear from the protocol doc, that the * client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and * that ends option negotiation. */ if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO) break; } if (nr_options >= MAX_NR_OPTIONS) { nbdkit_error ("client exceeded maximum number of options (%d)", MAX_NR_OPTIONS); return -1; } /* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS * by the time we finish option negotiation. If not, give up. */ if (tls == 2 && !conn->using_tls) { nbdkit_error ("non-TLS client tried to connect in --tls=require mode"); return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-406'], 'message': 'server: Fix regression for NBD_OPT_INFO before NBD_OPT_GO Most known NBD clients do not bother with NBD_OPT_INFO (except for clients like 'qemu-nbd --list' that don't ever intend to connect), but go straight to NBD_OPT_GO. However, it's not too hard to hack up qemu to add in an extra client step (whether info on the same name, or more interestingly, info on a different name), as a patch against qemu commit 6f214b30445: | diff --git i/nbd/client.c w/nbd/client.c | index f6733962b49b..425292ac5ea9 100644 | --- i/nbd/client.c | +++ w/nbd/client.c | @@ -1038,6 +1038,14 @@ int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc, | * TLS). If it is not available, fall back to | * NBD_OPT_LIST for nicer error messages about a missing | * export, then use NBD_OPT_EXPORT_NAME. */ | + if (getenv ("HACK")) | + info->name[0]++; | + result = nbd_opt_info_or_go(ioc, NBD_OPT_INFO, info, errp); | + if (getenv ("HACK")) | + info->name[0]--; | + if (result < 0) { | + return -EINVAL; | + } | result = nbd_opt_info_or_go(ioc, NBD_OPT_GO, info, errp); | if (result < 0) { | return -EINVAL; This works just fine in 1.14.0, where we call .open only once (so the INFO and GO repeat calls into the same plugin handle), but in 1.14.1 it regressed into causing an assertion failure: we are now calling .open a second time on a connection that is already opened: $ nbdkit -rfv null & $ hacked-qemu-io -f raw -r nbd://localhost -c quit ... nbdkit: null[1]: debug: null: open readonly=1 nbdkit: backend.c:179: backend_open: Assertion `h->handle == NULL' failed. Worse, on the mainline development, we have recently made it possible for plugins to actively report different information for different export names; for example, a plugin may choose to report different answers for .can_write on export A than for export B; but if we share cached handles, then an NBD_OPT_INFO on one export prevents correct answers for NBD_OPT_GO on the second export name. (The HACK envvar in my qemu modifications can be used to demonstrate cross-name requests, which are even less likely in a real client). The solution is to call .close after NBD_OPT_INFO, coupled with enough glue logic to reset cached connection handles back to the state expected by .open. This in turn means factoring out another backend_* function, but also gives us an opportunity to change backend_set_handle to no longer accept NULL. The assertion failure is, to some extent, a possible denial of service attack (one client can force nbdkit to exit by merely sending OPT_INFO before OPT_GO, preventing the next client from connecting), although this is mitigated by using TLS to weed out untrusted clients. Still, the fact that we introduced a potential DoS attack while trying to fix a traffic amplification security bug is not very nice. Sadly, as there are no known clients that easily trigger this mode of operation (OPT_INFO before OPT_GO), there is no easy way to cover this via a testsuite addition. I may end up hacking something into libnbd. Fixes: c05686f957 Signed-off-by: Eric Blake <eblake@redhat.com> (cherry picked from commit a6b88b195a959b17524d1c8353fd425d4891dc5f) Conflicts: server/backend.c server/connections.c server/filters.c server/internal.h server/plugins.c No backend.c in the stable branch, and less things to reset, so instead ode that logic into filter_close. Signed-off-by: Eric Blake <eblake@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: v9fs_vfs_getattr(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int flags) { struct dentry *dentry = path->dentry; struct v9fs_session_info *v9ses; struct p9_fid *fid; struct p9_wstat *st; p9_debug(P9_DEBUG_VFS, "dentry: %p\n", dentry); v9ses = v9fs_dentry2v9ses(dentry); if (v9ses->cache == CACHE_LOOSE || v9ses->cache == CACHE_FSCACHE) { generic_fillattr(d_inode(dentry), stat); return 0; } fid = v9fs_fid_lookup(dentry); if (IS_ERR(fid)) return PTR_ERR(fid); st = p9_client_stat(fid); if (IS_ERR(st)) return PTR_ERR(st); v9fs_stat2inode(st, d_inode(dentry), dentry->d_sb); generic_fillattr(d_inode(dentry), stat); p9stat_free(st); kfree(st); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit Use inode->i_lock to protect i_size_write(), else i_size_read() in generic_fillattr() may loop infinitely in read_seqcount_begin() when multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl() simultaneously under 32-bit SMP environment, and a soft lockup will be triggered as show below: watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217] Modules linked in: CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4 Hardware name: Generic DT based system PC is at generic_fillattr+0x104/0x108 LR is at 0xec497f00 pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013 sp : ec497e20 ip : ed608030 fp : ec497e3c r10: 00000000 r9 : ec497f00 r8 : ed608030 r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780 r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030 Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none Control: 10c5387d Table: ac48006a DAC: 00000051 CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4 Hardware name: Generic DT based system Backtrace: [<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24) [<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc) [<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20) [<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8) [<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380) [<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0) [<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64) [<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c) [<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc) [<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48) [<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240) [<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44) [<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4) [<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88) [<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98) [<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4) [<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c) [<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48) [<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec) [<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78) [<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28) [dominique.martinet@cea.fr: updated comment to not refer to a function in another subsystem] Link: http://lkml.kernel.org/r/20190124063514.8571-2-houtao1@huawei.com Cc: stable@vger.kernel.org Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.") Reported-by: Xing Gaopeng <xingaopeng@huawei.com> Signed-off-by: Hou Tao <houtao1@huawei.com> Signed-off-by: Dominique Martinet <dominique.martinet@cea.fr>'</s>
<s>[INST] Given the following code containing errors, provide 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 arc_emac_tx(struct sk_buff *skb, struct net_device *ndev) { struct arc_emac_priv *priv = netdev_priv(ndev); unsigned int len, *txbd_curr = &priv->txbd_curr; struct net_device_stats *stats = &ndev->stats; __le32 *info = &priv->txbd[*txbd_curr].info; dma_addr_t addr; if (skb_padto(skb, ETH_ZLEN)) return NETDEV_TX_OK; len = max_t(unsigned int, ETH_ZLEN, skb->len); if (unlikely(!arc_emac_tx_avail(priv))) { netif_stop_queue(ndev); netdev_err(ndev, "BUG! Tx Ring full when queue awake!\n"); return NETDEV_TX_BUSY; } addr = dma_map_single(&ndev->dev, (void *)skb->data, len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(&ndev->dev, addr))) { stats->tx_dropped++; stats->tx_errors++; dev_kfree_skb(skb); return NETDEV_TX_OK; } dma_unmap_addr_set(&priv->tx_buff[*txbd_curr], addr, addr); dma_unmap_len_set(&priv->tx_buff[*txbd_curr], len, len); priv->tx_buff[*txbd_curr].skb = skb; priv->txbd[*txbd_curr].data = cpu_to_le32(addr); /* Make sure pointer to data buffer is set */ wmb(); skb_tx_timestamp(skb); *info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len); /* Increment index to point to the next BD */ *txbd_curr = (*txbd_curr + 1) % TX_BD_NUM; /* Ensure that tx_clean() sees the new txbd_curr before * checking the queue status. This prevents an unneeded wake * of the queue in tx_clean(). */ smp_mb(); if (!arc_emac_tx_avail(priv)) { netif_stop_queue(ndev); /* Refresh tx_dirty */ smp_mb(); if (arc_emac_tx_avail(priv)) netif_start_queue(ndev); } arc_reg_set(priv, R_STATUS, TXPL_MASK); return NETDEV_TX_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'net: arc_emac: fix koops caused by sk_buff free There is a race between arc_emac_tx() and arc_emac_tx_clean(). sk_buff got freed by arc_emac_tx_clean() while arc_emac_tx() submitting sk_buff. In order to free sk_buff arc_emac_tx_clean() checks: if ((info & FOR_EMAC) || !txbd->data) break; ... dev_kfree_skb_irq(skb); If condition false, arc_emac_tx_clean() free sk_buff. In order to submit txbd, arc_emac_tx() do: priv->tx_buff[*txbd_curr].skb = skb; ... priv->txbd[*txbd_curr].data = cpu_to_le32(addr); ... ... <== arc_emac_tx_clean() check condition here ... <== (info & FOR_EMAC) is false ... <== !txbd->data is false ... *info = cpu_to_le32(FOR_EMAC | FIRST_OR_LAST_MASK | len); In order to reproduce the situation, run device: # iperf -s run on host: # iperf -t 600 -c <device-ip-addr> [ 28.396284] ------------[ cut here ]------------ [ 28.400912] kernel BUG at .../net/core/skbuff.c:1355! [ 28.414019] Internal error: Oops - BUG: 0 [#1] SMP ARM [ 28.419150] Modules linked in: [ 28.422219] CPU: 0 PID: 0 Comm: swapper/0 Tainted: G B 4.4.0+ #120 [ 28.429516] Hardware name: Rockchip (Device Tree) [ 28.434216] task: c0665070 ti: c0660000 task.ti: c0660000 [ 28.439622] PC is at skb_put+0x10/0x54 [ 28.443381] LR is at arc_emac_poll+0x260/0x474 [ 28.447821] pc : [<c03af580>] lr : [<c028fec4>] psr: a0070113 [ 28.447821] sp : c0661e58 ip : eea68502 fp : ef377000 [ 28.459280] r10: 0000012c r9 : f08b2000 r8 : eeb57100 [ 28.464498] r7 : 00000000 r6 : ef376594 r5 : 00000077 r4 : ef376000 [ 28.471015] r3 : 0030488b r2 : ef13e880 r1 : 000005ee r0 : eeb57100 [ 28.477534] Flags: NzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none [ 28.484658] Control: 10c5387d Table: 8eaf004a DAC: 00000051 [ 28.490396] Process swapper/0 (pid: 0, stack limit = 0xc0660210) [ 28.496393] Stack: (0xc0661e58 to 0xc0662000) [ 28.500745] 1e40: 00000002 00000000 [ 28.508913] 1e60: 00000000 ef376520 00000028 f08b23b8 00000000 ef376520 ef7b6900 c028fc64 [ 28.517082] 1e80: 2f158000 c0661ea8 c0661eb0 0000012c c065e900 c03bdeac ffff95e9 c0662100 [ 28.525250] 1ea0: c0663924 00000028 c0661ea8 c0661ea8 c0661eb0 c0661eb0 0000001e c0660000 [ 28.533417] 1ec0: 40000003 00000008 c0695a00 0000000a c066208c 00000100 c0661ee0 c0027410 [ 28.541584] 1ee0: ef0fb700 2f158000 00200000 ffff95e8 00000004 c0662100 c0662080 00000003 [ 28.549751] 1f00: 00000000 00000000 00000000 c065b45c 0000001e ef005000 c0647a30 00000000 [ 28.557919] 1f20: 00000000 c0027798 00000000 c005cf40 f0802100 c0662ffc c0661f60 f0803100 [ 28.566088] 1f40: c0661fb8 c00093bc c000ffb4 60070013 ffffffff c0661f94 c0661fb8 c00137d4 [ 28.574267] 1f60: 00000001 00000000 00000000 c001ffa0 00000000 c0660000 00000000 c065a364 [ 28.582441] 1f80: c0661fb8 c0647a30 00000000 00000000 00000000 c0661fb0 c000ffb0 c000ffb4 [ 28.590608] 1fa0: 60070013 ffffffff 00000051 00000000 00000000 c005496c c0662400 c061bc40 [ 28.598776] 1fc0: ffffffff ffffffff 00000000 c061b680 00000000 c0647a30 00000000 c0695294 [ 28.606943] 1fe0: c0662488 c0647a2c c066619c 6000406a 413fc090 6000807c 00000000 00000000 [ 28.615127] [<c03af580>] (skb_put) from [<ef376520>] (0xef376520) [ 28.621218] Code: e5902054 e590c090 e3520000 0a000000 (e7f001f2) [ 28.627307] ---[ end trace 4824734e2243fdb6 ]--- [ 34.377068] Internal error: Oops: 17 [#1] SMP ARM [ 34.382854] Modules linked in: [ 34.385947] CPU: 0 PID: 3 Comm: ksoftirqd/0 Not tainted 4.4.0+ #120 [ 34.392219] Hardware name: Rockchip (Device Tree) [ 34.396937] task: ef02d040 ti: ef05c000 task.ti: ef05c000 [ 34.402376] PC is at __dev_kfree_skb_irq+0x4/0x80 [ 34.407121] LR is at arc_emac_poll+0x130/0x474 [ 34.411583] pc : [<c03bb640>] lr : [<c028fd94>] psr: 60030013 [ 34.411583] sp : ef05de68 ip : 0008e83c fp : ef377000 [ 34.423062] r10: c001bec4 r9 : 00000000 r8 : f08b24c8 [ 34.428296] r7 : f08b2400 r6 : 00000075 r5 : 00000019 r4 : ef376000 [ 34.434827] r3 : 00060000 r2 : 00000042 r1 : 00000001 r0 : 00000000 [ 34.441365] Flags: nZCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none [ 34.448507] Control: 10c5387d Table: 8f25c04a DAC: 00000051 [ 34.454262] Process ksoftirqd/0 (pid: 3, stack limit = 0xef05c210) [ 34.460449] Stack: (0xef05de68 to 0xef05e000) [ 34.464827] de60: ef376000 c028fd94 00000000 c0669480 c0669480 ef376520 [ 34.473022] de80: 00000028 00000001 00002ae4 ef376520 ef7b6900 c028fc64 2f158000 ef05dec0 [ 34.481215] dea0: ef05dec8 0000012c c065e900 c03bdeac ffff983f c0662100 c0663924 00000028 [ 34.489409] dec0: ef05dec0 ef05dec0 ef05dec8 ef05dec8 ef7b6000 ef05c000 40000003 00000008 [ 34.497600] dee0: c0695a00 0000000a c066208c 00000100 ef05def8 c0027410 ef7b6000 40000000 [ 34.505795] df00: 04208040 ffff983e 00000004 c0662100 c0662080 00000003 ef05c000 ef027340 [ 34.513985] df20: ef05c000 c0666c2c 00000000 00000001 00000002 00000000 00000000 c0027568 [ 34.522176] df40: ef027340 c003ef48 ef027300 00000000 ef027340 c003edd4 00000000 00000000 [ 34.530367] df60: 00000000 c003c37c ffffff7f 00000001 00000000 ef027340 00000000 00030003 [ 34.538559] df80: ef05df80 ef05df80 00000000 00000000 ef05df90 ef05df90 ef05dfac ef027300 [ 34.546750] dfa0: c003c2a4 00000000 00000000 c000f578 00000000 00000000 00000000 00000000 [ 34.554939] dfc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 [ 34.563129] dfe0: 00000000 00000000 00000000 00000000 00000013 00000000 ffffffff dfff7fff [ 34.571360] [<c03bb640>] (__dev_kfree_skb_irq) from [<c028fd94>] (arc_emac_poll+0x130/0x474) [ 34.579840] [<c028fd94>] (arc_emac_poll) from [<c03bdeac>] (net_rx_action+0xdc/0x28c) [ 34.587712] [<c03bdeac>] (net_rx_action) from [<c0027410>] (__do_softirq+0xcc/0x1f8) [ 34.595482] [<c0027410>] (__do_softirq) from [<c0027568>] (run_ksoftirqd+0x2c/0x50) [ 34.603168] [<c0027568>] (run_ksoftirqd) from [<c003ef48>] (smpboot_thread_fn+0x174/0x18c) [ 34.611466] [<c003ef48>] (smpboot_thread_fn) from [<c003c37c>] (kthread+0xd8/0xec) [ 34.619075] [<c003c37c>] (kthread) from [<c000f578>] (ret_from_fork+0x14/0x3c) [ 34.626317] Code: e8bd8010 e3a00000 e12fff1e e92d4010 (e59030a4) [ 34.632572] ---[ end trace cca5a3d86a82249a ]--- Signed-off-by: Alexander Kochetkov <al.kochet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: base_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto, kern); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &base_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = MISDN_OPEN; mISDN_sock_link(&base_sockets, sk); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'mISDN: enforce CAP_NET_RAW for raw sockets When creating a raw AF_ISDN socket, CAP_NET_RAW needs to be checked first. Signed-off-by: Ori Nimron <orinimron123@gmail.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int hclge_shaper_para_calc(u32 ir, u8 shaper_level, u8 *ir_b, u8 *ir_u, u8 *ir_s) { #define DIVISOR_CLK (1000 * 8) #define DIVISOR_IR_B_126 (126 * DIVISOR_CLK) const u16 tick_array[HCLGE_SHAPER_LVL_CNT] = { 6 * 256, /* Prioriy level */ 6 * 32, /* Prioriy group level */ 6 * 8, /* Port level */ 6 * 256 /* Qset level */ }; u8 ir_u_calc = 0; u8 ir_s_calc = 0; u32 ir_calc; u32 tick; /* Calc tick */ if (shaper_level >= HCLGE_SHAPER_LVL_CNT) return -EINVAL; tick = tick_array[shaper_level]; /** * Calc the speed if ir_b = 126, ir_u = 0 and ir_s = 0 * the formula is changed to: * 126 * 1 * 8 * ir_calc = ---------------- * 1000 * tick * 1 */ ir_calc = (DIVISOR_IR_B_126 + (tick >> 1) - 1) / tick; if (ir_calc == ir) { *ir_b = 126; *ir_u = 0; *ir_s = 0; return 0; } else if (ir_calc > ir) { /* Increasing the denominator to select ir_s value */ while (ir_calc > ir) { ir_s_calc++; ir_calc = DIVISOR_IR_B_126 / (tick * (1 << ir_s_calc)); } if (ir_calc == ir) *ir_b = 126; else *ir_b = (ir * tick * (1 << ir_s_calc) + (DIVISOR_CLK >> 1)) / DIVISOR_CLK; } else { /* Increasing the numerator to select ir_u value */ u32 numerator; while (ir_calc < ir) { ir_u_calc++; numerator = DIVISOR_IR_B_126 * (1 << ir_u_calc); ir_calc = (numerator + (tick >> 1)) / tick; } if (ir_calc == ir) { *ir_b = 126; } else { u32 denominator = (DIVISOR_CLK * (1 << --ir_u_calc)); *ir_b = (ir * tick + (denominator >> 1)) / denominator; } } *ir_u = ir_u_calc; *ir_s = ir_s_calc; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'net: hns3: add some error checking in hclge_tm module When hdev->tx_sch_mode is HCLGE_FLAG_VNET_BASE_SCH_MODE, the hclge_tm_schd_mode_vnet_base_cfg calls hclge_tm_pri_schd_mode_cfg with vport->vport_id as pri_id, which is used as index for hdev->tm_info.tc_info, it will cause out of bound access issue if vport_id is equal to or larger than HNAE3_MAX_TC. Also hardware only support maximum speed of HCLGE_ETHER_MAX_RATE. So this patch adds two checks for above cases. Fixes: 848440544b41 ("net: hns3: Add support of TX Scheduler & Shaper to HNS3 driver") Signed-off-by: Yunsheng Lin <linyunsheng@huawei.com> Signed-off-by: Peng Li <lipeng321@huawei.com> Signed-off-by: Huazhong Tan <tanhuazhong@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int restore_fp(struct task_struct *tsk) { if (tsk->thread.load_fp || tm_active_with_fp(tsk)) { load_fp_state(&current->thread.fp_state); current->thread.load_fp++; return 1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts When in userspace and MSR FP=0 the hardware FP state is unrelated to the current process. This is extended for transactions where if tbegin is run with FP=0, the hardware checkpoint FP state will also be unrelated to the current process. Due to this, we need to ensure this hardware checkpoint is updated with the correct state before we enable FP for this process. Unfortunately we get this wrong when returning to a process from a hardware interrupt. A process that starts a transaction with FP=0 can take an interrupt. When the kernel returns back to that process, we change to FP=1 but with hardware checkpoint FP state not updated. If this transaction is then rolled back, the FP registers now contain the wrong state. The process looks like this: Userspace: Kernel Start userspace with MSR FP=0 TM=1 < ----- ... tbegin bne Hardware interrupt ---- > <do_IRQ...> .... ret_from_except restore_math() /* sees FP=0 */ restore_fp() tm_active_with_fp() /* sees FP=1 (Incorrect) */ load_fp_state() FP = 0 -> 1 < ----- Return to userspace with MSR TM=1 FP=1 with junk in the FP TM checkpoint TM rollback reads FP junk When returning from the hardware exception, tm_active_with_fp() is incorrectly making restore_fp() call load_fp_state() which is setting FP=1. The fix is to remove tm_active_with_fp(). tm_active_with_fp() is attempting to handle the case where FP state has been changed inside a transaction. In this case the checkpointed and transactional FP state is different and hence we must restore the FP state (ie. we can't do lazy FP restore inside a transaction that's used FP). It's safe to remove tm_active_with_fp() as this case is handled by restore_tm_state(). restore_tm_state() detects if FP has been using inside a transaction and will set load_fp and call restore_math() to ensure the FP state (checkpoint and transaction) is restored. This is a data integrity problem for the current process as the FP registers are corrupted. It's also a security problem as the FP registers from one process may be leaked to another. Similarly for VMX. A simple testcase to replicate this will be posted to tools/testing/selftests/powerpc/tm/tm-poison.c This fixes CVE-2019-15031. Fixes: a7771176b439 ("powerpc: Don't enable FP/Altivec if not checkpointed") Cc: stable@vger.kernel.org # 4.15+ Signed-off-by: Gustavo Romero <gromero@linux.ibm.com> Signed-off-by: Michael Neuling <mikey@neuling.org> Signed-off-by: Michael Ellerman <mpe@ellerman.id.au> Link: https://lore.kernel.org/r/20190904045529.23002-2-gromero@linux.vnet.ibm.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: icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep) { const struct icmp6_router_renum *rr6; const char *cp; const struct rr_pco_match *match; const struct rr_pco_use *use; char hbuf[NI_MAXHOST]; int n; if (ep < bp) return; rr6 = (const struct icmp6_router_renum *)bp; cp = (const char *)(rr6 + 1); ND_TCHECK(rr6->rr_reserved); switch (rr6->rr_code) { case ICMP6_ROUTER_RENUMBERING_COMMAND: ND_PRINT((ndo,"router renum: command")); break; case ICMP6_ROUTER_RENUMBERING_RESULT: ND_PRINT((ndo,"router renum: result")); break; case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET: ND_PRINT((ndo,"router renum: sequence number reset")); break; default: ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code)); break; } ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum))); if (ndo->ndo_vflag) { #define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "") ND_PRINT((ndo,"[")); /*]*/ if (rr6->rr_flags) { ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"), F(ICMP6_RR_FLAGS_REQRESULT, "R"), F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"), F(ICMP6_RR_FLAGS_SPECSITE, "S"), F(ICMP6_RR_FLAGS_PREVDONE, "P"))); } ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum)); ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay))); if (rr6->rr_reserved) ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved))); /*[*/ ND_PRINT((ndo,"]")); #undef F } if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) { match = (const struct rr_pco_match *)cp; cp = (const char *)(match + 1); ND_TCHECK(match->rpm_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"match(")); /*)*/ switch (match->rpm_code) { case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break; case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break; case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break; default: ND_PRINT((ndo,"#%u", match->rpm_code)); break; } if (ndo->ndo_vflag) { ND_PRINT((ndo,",ord=%u", match->rpm_ordinal)); ND_PRINT((ndo,",min=%u", match->rpm_minlen)); ND_PRINT((ndo,",max=%u", match->rpm_maxlen)); } if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen)); else ND_PRINT((ndo,",?/%u", match->rpm_matchlen)); /*(*/ ND_PRINT((ndo,")")); n = match->rpm_len - 3; if (n % 4) goto trunc; n /= 4; while (n-- > 0) { use = (const struct rr_pco_use *)cp; cp = (const char *)(use + 1); ND_TCHECK(use->rpu_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"use(")); /*)*/ if (use->rpu_flags) { #define F(x, y) ((use->rpu_flags) & (x) ? (y) : "") ND_PRINT((ndo,"%s%s,", F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"), F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P"))); #undef F } if (ndo->ndo_vflag) { ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask)); ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags)); if (~use->rpu_vltime == 0) ND_PRINT((ndo,"vltime=infty,")); else ND_PRINT((ndo,"vltime=%u,", EXTRACT_32BITS(&use->rpu_vltime))); if (~use->rpu_pltime == 0) ND_PRINT((ndo,"pltime=infty,")); else ND_PRINT((ndo,"pltime=%u,", EXTRACT_32BITS(&use->rpu_pltime))); } if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen, use->rpu_keeplen)); else ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen, use->rpu_keeplen)); /*(*/ ND_PRINT((ndo,")")); } } return; trunc: ND_PRINT((ndo,"[|icmp6]")); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14469/ISAKMP: Add a missing bounds check In ikev1_n_print() check bounds before trying to fetch the replay detection status. This fixes a buffer over-read discovered by Bhargava Shastry. Add a test using the capture file 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: ldp_pdu_print(netdissect_options *ndo, register const u_char *pptr) { const struct ldp_common_header *ldp_com_header; const struct ldp_msg_header *ldp_msg_header; const u_char *tptr,*msg_tptr; u_short tlen; u_short pdu_len,msg_len,msg_type,msg_tlen; int hexdump,processed; ldp_com_header = (const struct ldp_common_header *)pptr; ND_TCHECK(*ldp_com_header); /* * Sanity checking of the header. */ if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) { ND_PRINT((ndo, "%sLDP version %u packet not supported", (ndo->ndo_vflag < 1) ? "" : "\n\t", EXTRACT_16BITS(&ldp_com_header->version))); return 0; } pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length); if (pdu_len < sizeof(const struct ldp_common_header)-4) { /* length too short */ ND_PRINT((ndo, "%sLDP, pdu-length: %u (too short, < %u)", (ndo->ndo_vflag < 1) ? "" : "\n\t", pdu_len, (u_int)(sizeof(const struct ldp_common_header)-4))); return 0; } /* print the LSR-ID, label-space & length */ ND_PRINT((ndo, "%sLDP, Label-Space-ID: %s:%u, pdu-length: %u", (ndo->ndo_vflag < 1) ? "" : "\n\t", ipaddr_string(ndo, &ldp_com_header->lsr_id), EXTRACT_16BITS(&ldp_com_header->label_space), pdu_len)); /* bail out if non-verbose */ if (ndo->ndo_vflag < 1) return 0; /* ok they seem to want to know everything - lets fully decode it */ tptr = pptr + sizeof(const struct ldp_common_header); tlen = pdu_len - (sizeof(const struct ldp_common_header)-4); /* Type & Length fields not included */ while(tlen>0) { /* did we capture enough for fully decoding the msg header ? */ ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header)); ldp_msg_header = (const struct ldp_msg_header *)tptr; msg_len=EXTRACT_16BITS(ldp_msg_header->length); msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type)); if (msg_len < sizeof(struct ldp_msg_header)-4) { /* length too short */ /* FIXME vendor private / experimental check */ ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u (too short, < %u)", tok2str(ldp_msg_values, "Unknown", msg_type), msg_type, msg_len, (u_int)(sizeof(struct ldp_msg_header)-4))); return 0; } /* FIXME vendor private / experimental check */ ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]", tok2str(ldp_msg_values, "Unknown", msg_type), msg_type, msg_len, EXTRACT_32BITS(&ldp_msg_header->id), LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? "continue processing" : "ignore")); msg_tptr=tptr+sizeof(struct ldp_msg_header); msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */ /* did we capture enough for fully decoding the message ? */ ND_TCHECK2(*tptr, msg_len); hexdump=FALSE; switch(msg_type) { case LDP_MSG_NOTIF: case LDP_MSG_HELLO: case LDP_MSG_INIT: case LDP_MSG_KEEPALIVE: case LDP_MSG_ADDRESS: case LDP_MSG_LABEL_MAPPING: case LDP_MSG_ADDRESS_WITHDRAW: case LDP_MSG_LABEL_WITHDRAW: while(msg_tlen >= 4) { processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen); if (processed == 0) break; msg_tlen-=processed; msg_tptr+=processed; } break; /* * FIXME those are the defined messages that lack a decoder * you are welcome to contribute code ;-) */ case LDP_MSG_LABEL_REQUEST: case LDP_MSG_LABEL_RELEASE: case LDP_MSG_LABEL_ABORT_REQUEST: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, msg_tptr, "\n\t ", msg_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1 || hexdump==TRUE) print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), "\n\t ", msg_len); tptr += msg_len+4; tlen -= msg_len+4; } return pdu_len+4; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14461/LDP: Fix a bounds check In ldp_tlv_print(), the FT Session TLV length must be 12, not 8 (RFC3479) This fixes a buffer over-read discovered by Konrad Rieck and Bhargava Shastry. Add a test using the capture file supplied by the reporter(s). Moreover: Add and use tstr[]. Add a comment.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: print_trans(netdissect_options *ndo, const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf) { u_int bcc; const char *f1, *f2, *f3, *f4; const u_char *data, *param; const u_char *w = words + 1; int datalen, paramlen; if (request) { ND_TCHECK2(w[12 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); datalen = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n"; f2 = "|Name=[S]\n"; f3 = "|Param "; f4 = "|Data "; } else { ND_TCHECK2(w[7 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); datalen = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n"; f2 = "|Unknown "; f3 = "|Param "; f4 = "|Data "; } smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf), unicodestr); ND_TCHECK2(*data1, 2); bcc = EXTRACT_LE_16BITS(data1); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr); if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) { print_browse(ndo, param, paramlen, data, datalen); return; } if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) { print_ipc(ndo, param, paramlen, data, datalen); return; } if (paramlen) smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr); if (datalen) smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) SMB: Add two missing bounds checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; // XXX - make sure it's *not* a URL; we don't support opening // remote devices here. // Open the selected device // This is a fake open, since we do that only to get the needed parameters, then we close the device again if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; // Now, I can send a RPCAP open reply message if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ // We're done with the pcap_t. pcap_close(fp); // Send the reply. if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-918'], 'message': 'In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs.'</s>
<s>[INST] Given the following code containing errors, provide 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 pf_detect(void) { struct pf_unit *pf = units; int k, unit; printk("%s: %s version %s, major %d, cluster %d, nice %d\n", name, name, PF_VERSION, major, cluster, nice); par_drv = pi_register_driver(name); if (!par_drv) { pr_err("failed to register %s driver\n", name); return -1; } k = 0; if (pf_drive_count == 0) { if (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF, verbose, pf->name)) { if (!pf_probe(pf) && pf->disk) { pf->present = 1; k++; } else pi_release(pf->pi); } } else for (unit = 0; unit < PF_UNITS; unit++, pf++) { int *conf = *drives[unit]; if (!conf[D_PRT]) continue; if (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD], conf[D_UNI], conf[D_PRO], conf[D_DLY], pf_scratch, PI_PF, verbose, pf->name)) { if (pf->disk && !pf_probe(pf)) { pf->present = 1; k++; } else pi_release(pf->pi); } } if (k) return 0; printk("%s: No ATAPI disk detected\n", name); for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { blk_cleanup_queue(pf->disk->queue); pf->disk->queue = NULL; blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); } pi_unregister_driver(par_drv); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'paride/pf: Fix potential NULL pointer dereference Syzkaller report this: pf: pf version 1.04, major 47, cluster 64, nice 0 pf: No ATAPI disk detected kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pf_init+0x7af/0x1000 [pf] Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34 RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788 RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59 R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000 R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020 FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1e50000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp c ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp td glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace 7a818cf5f210d79e ]--- If alloc_disk fails in pf_init_units, pf->disk will be NULL, however in pf_detect and pf_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _gcry_ecc_gost_sign (gcry_mpi_t input, ECC_secret_key *skey, gcry_mpi_t r, gcry_mpi_t s) { gpg_err_code_t rc = 0; gcry_mpi_t k, dr, sum, ke, x, e; mpi_point_struct I; gcry_mpi_t hash; const void *abuf; unsigned int abits, qbits; mpi_ec_t ctx; if (DBG_CIPHER) log_mpidump ("gost sign hash ", input ); qbits = mpi_get_nbits (skey->E.n); /* Convert the INPUT into an MPI if needed. */ if (mpi_is_opaque (input)) { abuf = mpi_get_opaque (input, &abits); rc = _gcry_mpi_scan (&hash, GCRYMPI_FMT_USG, abuf, (abits+7)/8, NULL); if (rc) return rc; if (abits > qbits) mpi_rshift (hash, hash, abits - qbits); } else hash = input; k = NULL; dr = mpi_alloc (0); sum = mpi_alloc (0); ke = mpi_alloc (0); e = mpi_alloc (0); x = mpi_alloc (0); point_init (&I); ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0, skey->E.p, skey->E.a, skey->E.b); mpi_mod (e, input, skey->E.n); /* e = hash mod n */ if (!mpi_cmp_ui (e, 0)) mpi_set_ui (e, 1); /* Two loops to avoid R or S are zero. This is more of a joke than a real demand because the probability of them being zero is less than any hardware failure. Some specs however require it. */ do { do { mpi_free (k); k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM); _gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx); if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx)) { if (DBG_CIPHER) log_debug ("ecc sign: Failed to get affine coordinates\n"); rc = GPG_ERR_BAD_SIGNATURE; goto leave; } mpi_mod (r, x, skey->E.n); /* r = x mod n */ } while (!mpi_cmp_ui (r, 0)); mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */ mpi_mulm (ke, k, e, skey->E.n); /* ke = k*e mod n */ mpi_addm (s, ke, dr, skey->E.n); /* sum = (k*e+ d*r) mod n */ } while (!mpi_cmp_ui (s, 0)); if (DBG_CIPHER) { log_mpidump ("gost sign result r ", r); log_mpidump ("gost sign result s ", s); } leave: _gcry_mpi_ec_free (ctx); point_free (&I); mpi_free (x); mpi_free (e); mpi_free (ke); mpi_free (sum); mpi_free (dr); mpi_free (k); if (hash != input) mpi_free (hash); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-203'], 'message': 'dsa,ecdsa: Fix use of nonce, use larger one. * cipher/dsa-common.c (_gcry_dsa_modify_k): New. * cipher/pubkey-internal.h (_gcry_dsa_modify_k): New. * cipher/dsa.c (sign): Use _gcry_dsa_modify_k. * cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Likewise. * cipher/ecc-gost.c (_gcry_ecc_gost_sign): Likewise. CVE-id: CVE-2019-13627 GnuPG-bug-id: 4626 Signed-off-by: NIIBE Yutaka <gniibe@fsij.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: idn2_strerror_name (int rc) { switch (rc) { case IDN2_OK: return ERR2STR (IDN2_OK); case IDN2_MALLOC: return ERR2STR (IDN2_MALLOC); case IDN2_NO_CODESET: return ERR2STR (IDN2_NO_NODESET); case IDN2_ICONV_FAIL: return ERR2STR (IDN2_ICONV_FAIL); case IDN2_ENCODING_ERROR: return ERR2STR (IDN2_ENCODING_ERROR); case IDN2_NFC: return ERR2STR (IDN2_NFC); case IDN2_PUNYCODE_BAD_INPUT: return ERR2STR (IDN2_PUNYCODE_BAD_INPUT); case IDN2_PUNYCODE_BIG_OUTPUT: return ERR2STR (IDN2_PUNYCODE_BIG_OUTPUT); case IDN2_PUNYCODE_OVERFLOW: return ERR2STR (IDN2_PUNYCODE_OVERFLOW); case IDN2_TOO_BIG_DOMAIN: return ERR2STR (IDN2_TOO_BIG_DOMAIN); case IDN2_TOO_BIG_LABEL: return ERR2STR (IDN2_TOO_BIG_LABEL); case IDN2_INVALID_ALABEL: return ERR2STR (IDN2_INVALID_ALABEL); case IDN2_UALABEL_MISMATCH: return ERR2STR (IDN2_UALABEL_MISMATCH); case IDN2_INVALID_FLAGS: return ERR2STR (IDN2_INVALID_FLAGS); case IDN2_NOT_NFC: return ERR2STR (IDN2_NOT_NFC); case IDN2_2HYPHEN: return ERR2STR (IDN2_2HYPHEN); case IDN2_HYPHEN_STARTEND: return ERR2STR (IDN2_HYPHEN_STARTEND); case IDN2_LEADING_COMBINING: return ERR2STR (IDN2_LEADING_COMBINING); case IDN2_DISALLOWED: return ERR2STR (IDN2_DISALLOWED); case IDN2_CONTEXTJ: return ERR2STR (IDN2_CONTEXTJ); case IDN2_CONTEXTJ_NO_RULE: return ERR2STR (IDN2_CONTEXTJ_NO_RULE); case IDN2_CONTEXTO: return ERR2STR (IDN2_CONTEXTO); case IDN2_CONTEXTO_NO_RULE: return ERR2STR (IDN2_CONTEXTO_NO_RULE); case IDN2_UNASSIGNED: return ERR2STR (IDN2_UNASSIGNED); case IDN2_BIDI: return ERR2STR (IDN2_BIDI); case IDN2_DOT_IN_LABEL: return ERR2STR (IDN2_DOT_IN_LABEL); case IDN2_INVALID_TRANSITIONAL: return ERR2STR (IDN2_INVALID_TRANSITIONAL); case IDN2_INVALID_NONTRANSITIONAL: return ERR2STR (IDN2_INVALID_NONTRANSITIONAL); default: return "IDN2_UNKNOWN"; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default This adds another check to avoid unexpected results. It was a longstanding FIXME. Thanks to Jonathan Birch of Microsoft Corporation, Florian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS) for investigation, discussion and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 vrend_renderer_transfer_iov(const struct vrend_transfer_info *info, int transfer_mode) { struct vrend_resource *res; struct vrend_context *ctx; struct iovec *iov; int num_iovs; if (!info->box) return EINVAL; ctx = vrend_lookup_renderer_ctx(info->ctx_id); if (!ctx) return EINVAL; if (info->ctx_id == 0) res = vrend_resource_lookup(info->handle, 0); else res = vrend_renderer_ctx_res_lookup(ctx, info->handle); if (!res) { if (info->ctx_id) report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, info->handle); return EINVAL; } iov = info->iovec; num_iovs = info->iovec_cnt; if (res->iov && (!iov || num_iovs == 0)) { iov = res->iov; num_iovs = res->num_iovs; } if (!iov) { if (info->ctx_id) report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, info->handle); return EINVAL; } #ifdef ENABLE_GBM_ALLOCATION if (res->gbm_bo) return virgl_gbm_transfer(res->gbm_bo, transfer_mode, iov, num_iovs, info); #endif if (!check_transfer_bounds(res, info)) return EINVAL; if (!check_iov_bounds(res, info, iov, num_iovs)) return EINVAL; if (info->context0) { vrend_renderer_force_ctx_0(); ctx = NULL; } switch (transfer_mode) { case VIRGL_TRANSFER_TO_HOST: return vrend_renderer_transfer_write_iov(ctx, res, iov, num_iovs, info); case VIRGL_TRANSFER_FROM_HOST: return vrend_renderer_transfer_send_iov(res, iov, num_iovs, info); default: assert(0); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'vrend: check transfer bounds for negative values too and report error Closes #138 Signed-off-by: Gert Wollny <gert.wollny@collabora.com> Reviewed-by: Emil Velikov <emil.velikov@collabora.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: char * unescape(char * dest, const char * src) { while (*src) { if (*src == '\\') { ++src; switch (*src) { case 'n': *dest = '\n'; break; case 'r': *dest = '\r'; break; case 't': *dest = '\t'; break; case 'f': *dest = '\f'; break; case 'v': *dest = '\v'; break; default: *dest = *src; } } else { *dest = *src; } ++src; ++dest; } *dest = '\0'; return dest; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix various bugs found by OSS-Fuze.'</s>
<s>[INST] Given the following code containing errors, provide 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 MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=MagickMin(quantum/number_coordinates,BezierQuantum); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': '...'</s>
<s>[INST] Given the following code containing errors, provide 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 Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: { if (header.bits_per_pixel != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case StaticColor: case PseudoColor: { if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) || (header.ncolors == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case TrueColor: case DirectColor: { if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) && (header.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: { if (header.pixmap_depth != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case XYPixmap: case ZPixmap: { if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.bitmap_pad) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_unit) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.byte_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_bit_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.ncolors > 65535) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors, sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1553'</s>
<s>[INST] Given the following code containing errors, provide 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_reference(struct quota_handle *h, unsigned int blk) { if (blk >= h->qh_info.u.v2_mdqi.dqi_qtree.dqi_blocks) log_err("Illegal reference (%u >= %u) in %s quota file. " "Quota file is probably corrupted.\n" "Please run e2fsck (8) to fix it.", blk, h->qh_info.u.v2_mdqi.dqi_qtree.dqi_blocks, quota_type2name(h->qh_type)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'libsupport: add checks to prevent buffer overrun bugs in quota code A maliciously corrupted file systems can trigger buffer overruns in the quota code used by e2fsck. To fix this, add sanity checks to the quota header fields as well as to block number references in the quota tree. Addresses: CVE-2019-5094 Addresses: TALOS-2019-0887 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: fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; const OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_WORD_BOUND; tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option) && ! IS_WORD_BOUND_ALL_RANGE(env->option); break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_NOT_WORD_BOUND; tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option) && ! IS_WORD_BOUND_ALL_RANGE(env->option); break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_WORD_BEGIN; tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option); break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_WORD_END; tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option); break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc); if (num < -1) return ONIGERR_TOO_SHORT_DIGITS; else if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case 'o': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) { PINC; num = scan_unsigned_octal_number(&p, end, 11, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { OnigCodePoint c = PPEEK; if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || 0xff < num) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { r = fetch_named_backref_token(c, tok, &p, end, env); if (r < 0) return r; } else { PUNFETCH; onig_syntax_warn(env, "invalid back reference"); } } break; #endif #if defined(USE_SUBEXP_CALL) || defined(USE_NAMED_GROUP) case 'g': # ifdef USE_NAMED_GROUP if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_BRACE_BACKREF)) { PFETCH(c); if (c == '{') { r = fetch_named_backref_token(c, tok, &p, end, env); if (r < 0) return r; } else PUNFETCH; } # endif # ifdef USE_SUBEXP_CALL if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum = -1, rel = 0; UChar* name_end; OnigCodePoint cnext; cnext = PPEEK; if (cnext == '0') { PINC; if (PPEEK_IS(get_name_end_code_point(c))) { /* \g<0>, \g'0' */ PINC; name_end = p; gnum = 0; } } else if (cnext == '+') { PINC; rel = 1; } prev = p; if (gnum < 0) { r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; } tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; tok->u.call.rel = rel; } else { onig_syntax_warn(env, "invalid subexp call"); PUNFETCH; } } # endif break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } else { onig_syntax_warn(env, "invalid Unicode Property \\%c", c); } break; case 'R': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_R_LINEBREAK)) { tok->type = TK_LINEBREAK; } break; case 'X': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_X_EXTENDED_GRAPHEME_CLUSTER)) { tok->type = TK_EXTENDED_GRAPHEME_CLUSTER; } break; case 'K': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP)) { tok->type = TK_KEEP; } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if ((OnigCodePoint )tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp, end); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } #ifdef USE_PERL_SUBEXP_CALL /* (?&name), (?n), (?R), (?0), (?+n), (?-n) */ c = PPEEK; if ((c == '&' || c == 'R' || ONIGENC_IS_CODE_DIGIT(enc, c)) && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) { /* (?&name), (?n), (?R), (?0) */ int gnum; UChar *name; UChar *name_end; if (c == 'R' || c == '0') { PINC; /* skip 'R' / '0' */ if (!PPEEK_IS(')')) return ONIGERR_INVALID_GROUP_NAME; PINC; /* skip ')' */ name_end = name = p; gnum = 0; } else { int numref = 1; if (c == '&') { /* (?&name) */ PINC; numref = 0; /* don't allow number name */ } name = p; r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, numref); if (r < 0) return r; } tok->type = TK_CALL; tok->u.call.name = name; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; tok->u.call.rel = 0; break; } else if ((c == '-' || c == '+') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) { /* (?+n), (?-n) */ int gnum; UChar *name; UChar *name_end; OnigCodePoint cnext; PFETCH_READY; PINC; /* skip '-' / '+' */ cnext = PPEEK; if (ONIGENC_IS_CODE_DIGIT(enc, cnext)) { if (c == '-') PUNFETCH; name = p; r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = name; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; tok->u.call.rel = 1; break; } } #endif /* USE_PERL_SUBEXP_CALL */ #ifdef USE_CAPITAL_P_NAMED_GROUP if (PPEEK_IS('P') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_CAPITAL_P_NAMED_GROUP)) { int gnum; UChar *name; UChar *name_end; PFETCH_READY; PINC; /* skip 'P' */ if (PEND) return ONIGERR_UNDEFINED_GROUP_OPTION; PFETCH(c); if (c == '=') { /* (?P=name): backref */ r = fetch_named_backref_token((OnigCodePoint )'(', tok, &p, end, env); if (r < 0) return r; break; } else if (c == '>') { /* (?P>name): subexp call */ name = p; r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 0); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = name; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; tok->u.call.rel = 0; break; } } #endif /* USE_CAPITAL_P_NAMED_GROUP */ PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.anchor.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix SEGV in onig_error_code_to_str() (Fix #132) When onig_new(ONIG_SYNTAX_PERL) fails with ONIGERR_INVALID_GROUP_NAME, onig_error_code_to_str() crashes. onig_scan_env_set_error_string() should have been used when returning ONIGERR_INVALID_GROUP_NAME.'</s>
<s>[INST] Given the following code containing errors, provide 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(ConnectionHandlerTest, ListenerFilterTimeout) { InSequence s; TestListener* test_listener = addListener(1, true, false, "test_listener"); Network::MockListener* listener = new Network::MockListener(); Network::ListenerCallbacks* listener_callbacks; EXPECT_CALL(dispatcher_, createListener_(_, _, _)) .WillOnce( Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* { listener_callbacks = &cb; return listener; })); EXPECT_CALL(test_listener->socket_, localAddress()); handler_->addListener(*test_listener); Network::MockListenerFilter* test_filter = new Network::MockListenerFilter(); EXPECT_CALL(factory_, createListenerFilterChain(_)) .WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool { manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter}); return true; })); EXPECT_CALL(*test_filter, onAccept(_)) .WillOnce(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus { return Network::FilterStatus::StopIteration; })); Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>(); Network::IoSocketHandleImpl io_handle{42}; EXPECT_CALL(*accepted_socket, ioHandle()).WillRepeatedly(ReturnRef(io_handle)); Event::MockTimer* timeout = new Event::MockTimer(&dispatcher_); EXPECT_CALL(*timeout, enableTimer(std::chrono::milliseconds(15000), _)); listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket}); Stats::Gauge& downstream_pre_cx_active = stats_store_.gauge("downstream_pre_cx_active", Stats::Gauge::ImportMode::Accumulate); EXPECT_EQ(1UL, downstream_pre_cx_active.value()); EXPECT_CALL(*timeout, disableTimer()); timeout->invokeCallback(); dispatcher_.clearDeferredDeleteList(); EXPECT_EQ(0UL, downstream_pre_cx_active.value()); EXPECT_EQ(1UL, stats_store_.counter("downstream_pre_cx_timeout").value()); // Make sure we didn't continue to try create connection. EXPECT_EQ(0UL, stats_store_.counter("no_filter_chain_match").value()); EXPECT_CALL(*listener, onDestroy()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922) Signed-off-by: Yuchen Dai <silentdai@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 bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, "bin.demangle"); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3); const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, "bin"); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("["); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs exports\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Exports]\n"); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs symbols\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Symbols]\n"); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n"); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { // TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { // char *comment = fi->comment ? strdup (fi->comment) : NULL; r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf ("%s.%s", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf ("[Warning] Can't find flag (%s)\n", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); // str = r_str_replace (str, "\"", "\\\"", 1); r_cons_printf ("%s{\"name\":\"%s\"," "\"demname\":\"%s\"," "\"flagname\":\"%s\"," "\"ordinal\":%d," "\"bind\":\"%s\"," "\"size\":%d," "\"type\":\"%s\"," "\"vaddr\":%"PFMT64d"," "\"paddr\":%"PFMT64d"}", ((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""), str, sn.demname? sn.demname: "", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("0x%08"PFMT64x" %d %s\n", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("%s\n", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, "imp.", 4)) { if (lastfs != 'i') { r_cons_printf ("fs imports\n"); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? "exports": "symbols"; r_cons_printf ("fs %s\n", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n", r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, "pe")) { char *module = strdup (r_symbol_name); char *p = strstr (module, ".dll_"); if (p && strstr (module, "imp.")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf ("k bin/pe/%s/%d=%s.%s\n", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf ("k bin/pe/%s/%d=%s\n", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: "NONE"; const char *type = symbol->type? symbol->type: "NONE"; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); // const char *fwd = r_str_get (symbol->forwarder); r_cons_printf ("%03u", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf (" ----------"); } else { r_cons_printf (" 0x%08"PFMT64x, symbol->paddr); } r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n", addr, bind, type, symbol->size, *name? " ": "", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf ("{}"); } //handle thumb and arm for entry point since they are not present in symbols if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("]"); } r_spaces_pop (&r->anal->meta_spaces); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'More fixes for the CVE-2019-14745'</s>
<s>[INST] Given the following code containing errors, provide 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 decomp(unsigned char *srcBuf, unsigned char **jpegBuf, unsigned long *jpegSize, unsigned char *dstBuf, int w, int h, int subsamp, int jpegQual, char *fileName, int tilew, int tileh) { char tempStr[1024], sizeStr[24] = "\0", qualStr[13] = "\0", *ptr; FILE *file = NULL; tjhandle handle = NULL; int row, col, iter = 0, dstBufAlloc = 0, retval = 0; double elapsed, elapsedDecode; int ps = tjPixelSize[pf]; int scaledw = TJSCALED(w, sf); int scaledh = TJSCALED(h, sf); int pitch = scaledw * ps; int ntilesw = (w + tilew - 1) / tilew, ntilesh = (h + tileh - 1) / tileh; unsigned char *dstPtr, *dstPtr2, *yuvBuf = NULL; if (jpegQual > 0) { snprintf(qualStr, 13, "_Q%d", jpegQual); qualStr[12] = 0; } if ((handle = tjInitDecompress()) == NULL) THROW_TJ("executing tjInitDecompress()"); if (dstBuf == NULL) { if ((dstBuf = (unsigned char *)malloc(pitch * scaledh)) == NULL) THROW_UNIX("allocating destination buffer"); dstBufAlloc = 1; } /* Set the destination buffer to gray so we know whether the decompressor attempted to write to it */ memset(dstBuf, 127, pitch * scaledh); if (doYUV) { int width = doTile ? tilew : scaledw; int height = doTile ? tileh : scaledh; int yuvSize = tjBufSizeYUV2(width, yuvPad, height, subsamp); if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL) THROW_UNIX("allocating YUV buffer"); memset(yuvBuf, 127, yuvSize); } /* Benchmark */ iter = -1; elapsed = elapsedDecode = 0.; while (1) { int tile = 0; double start = getTime(); for (row = 0, dstPtr = dstBuf; row < ntilesh; row++, dstPtr += pitch * tileh) { for (col = 0, dstPtr2 = dstPtr; col < ntilesw; col++, tile++, dstPtr2 += ps * tilew) { int width = doTile ? min(tilew, w - col * tilew) : scaledw; int height = doTile ? min(tileh, h - row * tileh) : scaledh; if (doYUV) { double startDecode; if (tjDecompressToYUV2(handle, jpegBuf[tile], jpegSize[tile], yuvBuf, width, yuvPad, height, flags) == -1) THROW_TJ("executing tjDecompressToYUV2()"); startDecode = getTime(); if (tjDecodeYUV(handle, yuvBuf, yuvPad, subsamp, dstPtr2, width, pitch, height, pf, flags) == -1) THROW_TJ("executing tjDecodeYUV()"); if (iter >= 0) elapsedDecode += getTime() - startDecode; } else if (tjDecompress2(handle, jpegBuf[tile], jpegSize[tile], dstPtr2, width, pitch, height, pf, flags) == -1) THROW_TJ("executing tjDecompress2()"); } } elapsed += getTime() - start; if (iter >= 0) { iter++; if (elapsed >= benchTime) break; } else if (elapsed >= warmup) { iter = 0; elapsed = elapsedDecode = 0.; } } if (doYUV) elapsed -= elapsedDecode; if (tjDestroy(handle) == -1) THROW_TJ("executing tjDestroy()"); handle = NULL; if (quiet) { printf("%-6s%s", sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4, tempStr, 1024), quiet == 2 ? "\n" : " "); if (doYUV) printf("%s\n", sigfig((double)(w * h) / 1000000. * (double)iter / elapsedDecode, 4, tempStr, 1024)); else if (quiet != 2) printf("\n"); } else { printf("%s --> Frame rate: %f fps\n", doYUV ? "Decomp to YUV" : "Decompress ", (double)iter / elapsed); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsed); if (doYUV) { printf("YUV Decode --> Frame rate: %f fps\n", (double)iter / elapsedDecode); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsedDecode); } } if (!doWrite) goto bailout; if (sf.num != 1 || sf.denom != 1) snprintf(sizeStr, 24, "%d_%d", sf.num, sf.denom); else if (tilew != w || tileh != h) snprintf(sizeStr, 24, "%dx%d", tilew, tileh); else snprintf(sizeStr, 24, "full"); if (decompOnly) snprintf(tempStr, 1024, "%s_%s.%s", fileName, sizeStr, ext); else snprintf(tempStr, 1024, "%s_%s%s_%s.%s", fileName, subName[subsamp], qualStr, sizeStr, ext); if (tjSaveImage(tempStr, dstBuf, scaledw, 0, scaledh, pf, flags) == -1) THROW_TJG("saving bitmap"); ptr = strrchr(tempStr, '.'); snprintf(ptr, 1024 - (ptr - tempStr), "-err.%s", ext); if (srcBuf && sf.num == 1 && sf.denom == 1) { if (!quiet) printf("Compression error written to %s.\n", tempStr); if (subsamp == TJ_GRAYSCALE) { int index, index2; for (row = 0, index = 0; row < h; row++, index += pitch) { for (col = 0, index2 = index; col < w; col++, index2 += ps) { int rindex = index2 + tjRedOffset[pf]; int gindex = index2 + tjGreenOffset[pf]; int bindex = index2 + tjBlueOffset[pf]; int y = (int)((double)srcBuf[rindex] * 0.299 + (double)srcBuf[gindex] * 0.587 + (double)srcBuf[bindex] * 0.114 + 0.5); if (y > 255) y = 255; if (y < 0) y = 0; dstBuf[rindex] = abs(dstBuf[rindex] - y); dstBuf[gindex] = abs(dstBuf[gindex] - y); dstBuf[bindex] = abs(dstBuf[bindex] - y); } } } else { for (row = 0; row < h; row++) for (col = 0; col < w * ps; col++) dstBuf[pitch * row + col] = abs(dstBuf[pitch * row + col] - srcBuf[pitch * row + col]); } if (tjSaveImage(tempStr, dstBuf, w, 0, h, pf, flags) == -1) THROW_TJG("saving bitmap"); } bailout: if (file) fclose(file); if (handle) tjDestroy(handle); if (dstBuf && dstBufAlloc) free(dstBuf); if (yuvBuf) free(yuvBuf); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: soup_ntlm_parse_challenge (const char *challenge, char **nonce, char **default_domain, gboolean *ntlmv2_session) { gsize clen; NTLMString domain; guchar *chall; guint32 flags; chall = g_base64_decode (challenge, &clen); if (clen < NTLM_CHALLENGE_DOMAIN_STRING_OFFSET || clen < NTLM_CHALLENGE_NONCE_OFFSET + NTLM_CHALLENGE_NONCE_LENGTH) { g_free (chall); return FALSE; } memcpy (&flags, chall + NTLM_CHALLENGE_FLAGS_OFFSET, sizeof(flags)); flags = GUINT_FROM_LE (flags); *ntlmv2_session = (flags & NTLM_FLAGS_NEGOTIATE_NTLMV2) ? TRUE : FALSE; if (default_domain) { memcpy (&domain, chall + NTLM_CHALLENGE_DOMAIN_STRING_OFFSET, sizeof (domain)); domain.length = GUINT16_FROM_LE (domain.length); domain.offset = GUINT16_FROM_LE (domain.offset); if (clen < domain.length + domain.offset) { g_free (chall); return FALSE; } *default_domain = g_convert ((char *)chall + domain.offset, domain.length, "UTF-8", "UCS-2LE", NULL, NULL, NULL); } if (nonce) { *nonce = g_memdup (chall + NTLM_CHALLENGE_NONCE_OFFSET, NTLM_CHALLENGE_NONCE_LENGTH); } g_free (chall); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'NTLMv2 responses 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: psutil_pids(PyObject *self, PyObject *args) { kinfo_proc *proclist = NULL; kinfo_proc *orig_address = NULL; size_t num_processes; size_t idx; PyObject *py_retlist = PyList_New(0); PyObject *py_pid = NULL; if (py_retlist == NULL) return NULL; // TODO: RuntimeError is inappropriate here; we could return the // original error instead. if (psutil_get_proc_list(&proclist, &num_processes) != 0) { if (errno != 0) { PyErr_SetFromErrno(PyExc_OSError); } else { PyErr_SetString(PyExc_RuntimeError, "failed to retrieve process list"); } goto error; } if (num_processes > 0) { orig_address = proclist; // save so we can free it after we're done for (idx = 0; idx < num_processes; idx++) { #ifdef PSUTIL_FREEBSD py_pid = Py_BuildValue("i", proclist->ki_pid); #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD) py_pid = Py_BuildValue("i", proclist->p_pid); #endif if (!py_pid) goto error; if (PyList_Append(py_retlist, py_pid)) goto error; Py_DECREF(py_pid); proclist++; } free(orig_address); } return py_retlist; error: Py_XDECREF(py_pid); Py_DECREF(py_retlist); if (orig_address != NULL) free(orig_address); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible double-free.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: psutil_disk_io_counters(PyObject *self, PyObject *args) { CFDictionaryRef parent_dict; CFDictionaryRef props_dict; CFDictionaryRef stats_dict; io_registry_entry_t parent; io_registry_entry_t disk; io_iterator_t disk_list; PyObject *py_disk_info = NULL; PyObject *py_retdict = PyDict_New(); if (py_retdict == NULL) return NULL; // Get list of disks if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOMediaClass), &disk_list) != kIOReturnSuccess) { PyErr_SetString( PyExc_RuntimeError, "unable to get the list of disks."); goto error; } // Iterate over disks while ((disk = IOIteratorNext(disk_list)) != 0) { py_disk_info = NULL; parent_dict = NULL; props_dict = NULL; stats_dict = NULL; if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent) != kIOReturnSuccess) { PyErr_SetString(PyExc_RuntimeError, "unable to get the disk's parent."); IOObjectRelease(disk); goto error; } if (IOObjectConformsTo(parent, "IOBlockStorageDriver")) { if (IORegistryEntryCreateCFProperties( disk, (CFMutableDictionaryRef *) &parent_dict, kCFAllocatorDefault, kNilOptions ) != kIOReturnSuccess) { PyErr_SetString(PyExc_RuntimeError, "unable to get the parent's properties."); IOObjectRelease(disk); IOObjectRelease(parent); goto error; } if (IORegistryEntryCreateCFProperties( parent, (CFMutableDictionaryRef *) &props_dict, kCFAllocatorDefault, kNilOptions ) != kIOReturnSuccess) { PyErr_SetString(PyExc_RuntimeError, "unable to get the disk properties."); CFRelease(props_dict); IOObjectRelease(disk); IOObjectRelease(parent); goto error; } const int kMaxDiskNameSize = 64; CFStringRef disk_name_ref = (CFStringRef)CFDictionaryGetValue( parent_dict, CFSTR(kIOBSDNameKey)); char disk_name[kMaxDiskNameSize]; CFStringGetCString(disk_name_ref, disk_name, kMaxDiskNameSize, CFStringGetSystemEncoding()); stats_dict = (CFDictionaryRef)CFDictionaryGetValue( props_dict, CFSTR(kIOBlockStorageDriverStatisticsKey)); if (stats_dict == NULL) { PyErr_SetString(PyExc_RuntimeError, "Unable to get disk stats."); goto error; } CFNumberRef number; int64_t reads = 0; int64_t writes = 0; int64_t read_bytes = 0; int64_t write_bytes = 0; int64_t read_time = 0; int64_t write_time = 0; // Get disk reads/writes if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsReadsKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &reads); } if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsWritesKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &writes); } // Get disk bytes read/written if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &read_bytes); } if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &write_bytes); } // Get disk time spent reading/writing (nanoseconds) if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &read_time); } if ((number = (CFNumberRef)CFDictionaryGetValue( stats_dict, CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey)))) { CFNumberGetValue(number, kCFNumberSInt64Type, &write_time); } // Read/Write time on macOS comes back in nanoseconds and in psutil // we've standardized on milliseconds so do the conversion. py_disk_info = Py_BuildValue( "(KKKKKK)", reads, writes, read_bytes, write_bytes, read_time / 1000 / 1000, write_time / 1000 / 1000); if (!py_disk_info) goto error; if (PyDict_SetItemString(py_retdict, disk_name, py_disk_info)) goto error; Py_DECREF(py_disk_info); CFRelease(parent_dict); IOObjectRelease(parent); CFRelease(props_dict); IOObjectRelease(disk); } } IOObjectRelease (disk_list); return py_retdict; error: Py_XDECREF(py_disk_info); Py_DECREF(py_retdict); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible double-free.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: psutil_proc_memory_maps(PyObject *self, PyObject *args) { int pid; int fd = -1; char path[1000]; char perms[10]; const char *name; struct stat st; pstatus_t status; prxmap_t *xmap = NULL, *p; off_t size; size_t nread; int nmap; uintptr_t pr_addr_sz; uintptr_t stk_base_sz, brk_base_sz; const char *procfs_path; PyObject *py_tuple = NULL; PyObject *py_path = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) goto error; sprintf(path, "%s/%i/status", procfs_path, pid); if (! psutil_file_to_struct(path, (void *)&status, sizeof(status))) goto error; sprintf(path, "%s/%i/xmap", procfs_path, pid); if (stat(path, &st) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } size = st.st_size; fd = open(path, O_RDONLY); if (fd == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } xmap = (prxmap_t *)malloc(size); if (xmap == NULL) { PyErr_NoMemory(); goto error; } nread = pread(fd, xmap, size, 0); nmap = nread / sizeof(prxmap_t); p = xmap; while (nmap) { nmap -= 1; if (p == NULL) { p += 1; continue; } perms[0] = '\0'; pr_addr_sz = p->pr_vaddr + p->pr_size; // perms sprintf(perms, "%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-', p->pr_mflags & MA_WRITE ? 'w' : '-', p->pr_mflags & MA_EXEC ? 'x' : '-', p->pr_mflags & MA_SHARED ? 's' : '-'); // name if (strlen(p->pr_mapname) > 0) { name = p->pr_mapname; } else { if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) { name = "[shmid]"; } else { stk_base_sz = status.pr_stkbase + status.pr_stksize; brk_base_sz = status.pr_brkbase + status.pr_brksize; if ((pr_addr_sz > status.pr_stkbase) && (p->pr_vaddr < stk_base_sz)) { name = "[stack]"; } else if ((p->pr_mflags & MA_ANON) && \ (pr_addr_sz > status.pr_brkbase) && \ (p->pr_vaddr < brk_base_sz)) { name = "[heap]"; } else { name = "[anon]"; } } } py_path = PyUnicode_DecodeFSDefault(name); if (! py_path) goto error; py_tuple = Py_BuildValue( "kksOkkk", (unsigned long)p->pr_vaddr, (unsigned long)pr_addr_sz, perms, py_path, (unsigned long)p->pr_rss * p->pr_pagesize, (unsigned long)p->pr_anon * p->pr_pagesize, (unsigned long)p->pr_locked * p->pr_pagesize); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_path); Py_DECREF(py_tuple); // increment pointer p += 1; } close(fd); free(xmap); return py_retlist; error: if (fd != -1) close(fd); Py_XDECREF(py_tuple); Py_XDECREF(py_path); Py_DECREF(py_retlist); if (xmap != NULL) free(xmap); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible double-free.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: psutil_users(PyObject *self, PyObject *args) { PyObject *py_retlist = PyList_New(0); PyObject *py_username = NULL; PyObject *py_tty = NULL; PyObject *py_hostname = NULL; PyObject *py_tuple = NULL; if (py_retlist == NULL) return NULL; #if (defined(__FreeBSD_version) && (__FreeBSD_version < 900000)) || PSUTIL_OPENBSD struct utmp ut; FILE *fp; fp = fopen(_PATH_UTMP, "r"); if (fp == NULL) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, _PATH_UTMP); goto error; } while (fread(&ut, sizeof(ut), 1, fp) == 1) { if (*ut.ut_name == '\0') continue; py_username = PyUnicode_DecodeFSDefault(ut.ut_name); if (! py_username) goto error; py_tty = PyUnicode_DecodeFSDefault(ut.ut_line); if (! py_tty) goto error; py_hostname = PyUnicode_DecodeFSDefault(ut.ut_host); if (! py_hostname) goto error; py_tuple = Py_BuildValue( "(OOOfi)", py_username, // username py_tty, // tty py_hostname, // hostname (float)ut.ut_time, // start time #ifdef PSUTIL_OPENBSD -1 // process id (set to None later) #else ut.ut_pid // process id #endif ); if (!py_tuple) { fclose(fp); goto error; } if (PyList_Append(py_retlist, py_tuple)) { fclose(fp); goto error; } Py_DECREF(py_username); Py_DECREF(py_tty); Py_DECREF(py_hostname); Py_DECREF(py_tuple); } fclose(fp); #else struct utmpx *utx; setutxent(); while ((utx = getutxent()) != NULL) { if (utx->ut_type != USER_PROCESS) continue; py_username = PyUnicode_DecodeFSDefault(utx->ut_user); if (! py_username) goto error; py_tty = PyUnicode_DecodeFSDefault(utx->ut_line); if (! py_tty) goto error; py_hostname = PyUnicode_DecodeFSDefault(utx->ut_host); if (! py_hostname) goto error; py_tuple = Py_BuildValue( "(OOOfi)", py_username, // username py_tty, // tty py_hostname, // hostname (float)utx->ut_tv.tv_sec, // start time #ifdef PSUTIL_OPENBSD -1 // process id (set to None later) #else utx->ut_pid // process id #endif ); if (!py_tuple) { endutxent(); goto error; } if (PyList_Append(py_retlist, py_tuple)) { endutxent(); goto error; } Py_DECREF(py_username); Py_DECREF(py_tty); Py_DECREF(py_hostname); Py_DECREF(py_tuple); } endutxent(); #endif return py_retlist; error: Py_XDECREF(py_username); Py_XDECREF(py_tty); Py_XDECREF(py_hostname); Py_XDECREF(py_tuple); Py_DECREF(py_retlist); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible double-free.'</s>
<s>[INST] Given the following code containing errors, provide 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 lsi_execute_script(LSIState *s) { PCIDevice *pci_dev = PCI_DEVICE(s); uint32_t insn; uint32_t addr, addr_high; int opcode; int insn_processed = 0; s->istat1 |= LSI_ISTAT1_SRUN; again: insn_processed++; insn = read_dword(s, s->dsp); if (!insn) { /* If we receive an empty opcode increment the DSP by 4 bytes instead of 8 and execute the next opcode at that location */ s->dsp += 4; goto again; } addr = read_dword(s, s->dsp + 4); addr_high = 0; trace_lsi_execute_script(s->dsp, insn, addr); s->dsps = addr; s->dcmd = insn >> 24; s->dsp += 8; switch (insn >> 30) { case 0: /* Block move. */ if (s->sist1 & LSI_SIST1_STO) { trace_lsi_execute_script_blockmove_delayed(); lsi_stop_script(s); break; } s->dbc = insn & 0xffffff; s->rbc = s->dbc; /* ??? Set ESA. */ s->ia = s->dsp - 8; if (insn & (1 << 29)) { /* Indirect addressing. */ addr = read_dword(s, addr); } else if (insn & (1 << 28)) { uint32_t buf[2]; int32_t offset; /* Table indirect addressing. */ /* 32-bit Table indirect */ offset = sextract32(addr, 0, 24); pci_dma_read(pci_dev, s->dsa + offset, buf, 8); /* byte count is stored in bits 0:23 only */ s->dbc = cpu_to_le32(buf[0]) & 0xffffff; s->rbc = s->dbc; addr = cpu_to_le32(buf[1]); /* 40-bit DMA, upper addr bits [39:32] stored in first DWORD of * table, bits [31:24] */ if (lsi_dma_40bit(s)) addr_high = cpu_to_le32(buf[0]) >> 24; else if (lsi_dma_ti64bit(s)) { int selector = (cpu_to_le32(buf[0]) >> 24) & 0x1f; switch (selector) { case 0 ... 0x0f: /* offset index into scratch registers since * TI64 mode can use registers C to R */ addr_high = s->scratch[2 + selector]; break; case 0x10: addr_high = s->mmrs; break; case 0x11: addr_high = s->mmws; break; case 0x12: addr_high = s->sfs; break; case 0x13: addr_high = s->drs; break; case 0x14: addr_high = s->sbms; break; case 0x15: addr_high = s->dbms; break; default: qemu_log_mask(LOG_GUEST_ERROR, "lsi_scsi: Illegal selector specified (0x%x > 0x15) " "for 64-bit DMA block move", selector); break; } } } else if (lsi_dma_64bit(s)) { /* fetch a 3rd dword if 64-bit direct move is enabled and only if we're not doing table indirect or indirect addressing */ s->dbms = read_dword(s, s->dsp); s->dsp += 4; s->ia = s->dsp - 12; } if ((s->sstat1 & PHASE_MASK) != ((insn >> 24) & 7)) { trace_lsi_execute_script_blockmove_badphase( scsi_phase_name(s->sstat1), scsi_phase_name(insn >> 24)); lsi_script_scsi_interrupt(s, LSI_SIST0_MA, 0); break; } s->dnad = addr; s->dnad64 = addr_high; switch (s->sstat1 & 0x7) { case PHASE_DO: s->waiting = LSI_DMA_SCRIPTS; lsi_do_dma(s, 1); if (s->waiting) s->waiting = LSI_DMA_IN_PROGRESS; break; case PHASE_DI: s->waiting = LSI_DMA_SCRIPTS; lsi_do_dma(s, 0); if (s->waiting) s->waiting = LSI_DMA_IN_PROGRESS; break; case PHASE_CMD: lsi_do_command(s); break; case PHASE_ST: lsi_do_status(s); break; case PHASE_MO: lsi_do_msgout(s); break; case PHASE_MI: lsi_do_msgin(s); break; default: qemu_log_mask(LOG_UNIMP, "lsi_scsi: Unimplemented phase %s\n", scsi_phase_name(s->sstat1)); } s->dfifo = s->dbc & 0xff; s->ctest5 = (s->ctest5 & 0xfc) | ((s->dbc >> 8) & 3); s->sbc = s->dbc; s->rbc -= s->dbc; s->ua = addr + s->dbc; break; case 1: /* IO or Read/Write instruction. */ opcode = (insn >> 27) & 7; if (opcode < 5) { uint32_t id; if (insn & (1 << 25)) { id = read_dword(s, s->dsa + sextract32(insn, 0, 24)); } else { id = insn; } id = (id >> 16) & 0xf; if (insn & (1 << 26)) { addr = s->dsp + sextract32(addr, 0, 24); } s->dnad = addr; switch (opcode) { case 0: /* Select */ s->sdid = id; if (s->scntl1 & LSI_SCNTL1_CON) { trace_lsi_execute_script_io_alreadyreselected(); s->dsp = s->dnad; break; } s->sstat0 |= LSI_SSTAT0_WOA; s->scntl1 &= ~LSI_SCNTL1_IARB; if (!scsi_device_find(&s->bus, 0, id, 0)) { lsi_bad_selection(s, id); break; } trace_lsi_execute_script_io_selected(id, insn & (1 << 3) ? " ATN" : ""); /* ??? Linux drivers compain when this is set. Maybe it only applies in low-level mode (unimplemented). lsi_script_scsi_interrupt(s, LSI_SIST0_CMP, 0); */ s->select_tag = id << 8; s->scntl1 |= LSI_SCNTL1_CON; if (insn & (1 << 3)) { s->socl |= LSI_SOCL_ATN; s->sbcl |= LSI_SBCL_ATN; } s->sbcl |= LSI_SBCL_BSY; lsi_set_phase(s, PHASE_MO); s->waiting = LSI_NOWAIT; break; case 1: /* Disconnect */ trace_lsi_execute_script_io_disconnect(); s->scntl1 &= ~LSI_SCNTL1_CON; /* FIXME: this is not entirely correct; the target need not ask * for reselection until it has to send data, while here we force a * reselection as soon as the bus is free. The correct flow would * reselect before lsi_transfer_data and disconnect as soon as * DMA ends. */ if (!s->current) { lsi_request *p = get_pending_req(s); if (p) { lsi_reselect(s, p); } } break; case 2: /* Wait Reselect */ if (s->istat0 & LSI_ISTAT0_SIGP) { s->dsp = s->dnad; } else if (!lsi_irq_on_rsl(s)) { lsi_wait_reselect(s); } break; case 3: /* Set */ trace_lsi_execute_script_io_set( insn & (1 << 3) ? " ATN" : "", insn & (1 << 6) ? " ACK" : "", insn & (1 << 9) ? " TM" : "", insn & (1 << 10) ? " CC" : ""); if (insn & (1 << 3)) { s->socl |= LSI_SOCL_ATN; s->sbcl |= LSI_SBCL_ATN; lsi_set_phase(s, PHASE_MO); } if (insn & (1 << 6)) { s->sbcl |= LSI_SBCL_ACK; } if (insn & (1 << 9)) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: Target mode not implemented\n"); } if (insn & (1 << 10)) s->carry = 1; break; case 4: /* Clear */ trace_lsi_execute_script_io_clear( insn & (1 << 3) ? " ATN" : "", insn & (1 << 6) ? " ACK" : "", insn & (1 << 9) ? " TM" : "", insn & (1 << 10) ? " CC" : ""); if (insn & (1 << 3)) { s->socl &= ~LSI_SOCL_ATN; s->sbcl &= ~LSI_SBCL_ATN; } if (insn & (1 << 6)) { s->sbcl &= ~LSI_SBCL_ACK; } if (insn & (1 << 10)) s->carry = 0; break; } } else { uint8_t op0; uint8_t op1; uint8_t data8; int reg; int operator; static const char *opcode_names[3] = {"Write", "Read", "Read-Modify-Write"}; static const char *operator_names[8] = {"MOV", "SHL", "OR", "XOR", "AND", "SHR", "ADD", "ADC"}; reg = ((insn >> 16) & 0x7f) | (insn & 0x80); data8 = (insn >> 8) & 0xff; opcode = (insn >> 27) & 7; operator = (insn >> 24) & 7; trace_lsi_execute_script_io_opcode( opcode_names[opcode - 5], reg, operator_names[operator], data8, s->sfbr, (insn & (1 << 23)) ? " SFBR" : ""); op0 = op1 = 0; switch (opcode) { case 5: /* From SFBR */ op0 = s->sfbr; op1 = data8; break; case 6: /* To SFBR */ if (operator) op0 = lsi_reg_readb(s, reg); op1 = data8; break; case 7: /* Read-modify-write */ if (operator) op0 = lsi_reg_readb(s, reg); if (insn & (1 << 23)) { op1 = s->sfbr; } else { op1 = data8; } break; } switch (operator) { case 0: /* move */ op0 = op1; break; case 1: /* Shift left */ op1 = op0 >> 7; op0 = (op0 << 1) | s->carry; s->carry = op1; break; case 2: /* OR */ op0 |= op1; break; case 3: /* XOR */ op0 ^= op1; break; case 4: /* AND */ op0 &= op1; break; case 5: /* SHR */ op1 = op0 & 1; op0 = (op0 >> 1) | (s->carry << 7); s->carry = op1; break; case 6: /* ADD */ op0 += op1; s->carry = op0 < op1; break; case 7: /* ADC */ op0 += op1 + s->carry; if (s->carry) s->carry = op0 <= op1; else s->carry = op0 < op1; break; } switch (opcode) { case 5: /* From SFBR */ case 7: /* Read-modify-write */ lsi_reg_writeb(s, reg, op0); break; case 6: /* To SFBR */ s->sfbr = op0; break; } } break; case 2: /* Transfer Control. */ { int cond; int jmp; if ((insn & 0x002e0000) == 0) { trace_lsi_execute_script_tc_nop(); break; } if (s->sist1 & LSI_SIST1_STO) { trace_lsi_execute_script_tc_delayedselect_timeout(); lsi_stop_script(s); break; } cond = jmp = (insn & (1 << 19)) != 0; if (cond == jmp && (insn & (1 << 21))) { trace_lsi_execute_script_tc_compc(s->carry == jmp); cond = s->carry != 0; } if (cond == jmp && (insn & (1 << 17))) { trace_lsi_execute_script_tc_compp(scsi_phase_name(s->sstat1), jmp ? '=' : '!', scsi_phase_name(insn >> 24)); cond = (s->sstat1 & PHASE_MASK) == ((insn >> 24) & 7); } if (cond == jmp && (insn & (1 << 18))) { uint8_t mask; mask = (~insn >> 8) & 0xff; trace_lsi_execute_script_tc_compd( s->sfbr, mask, jmp ? '=' : '!', insn & mask); cond = (s->sfbr & mask) == (insn & mask); } if (cond == jmp) { if (insn & (1 << 23)) { /* Relative address. */ addr = s->dsp + sextract32(addr, 0, 24); } switch ((insn >> 27) & 7) { case 0: /* Jump */ trace_lsi_execute_script_tc_jump(addr); s->adder = addr; s->dsp = addr; break; case 1: /* Call */ trace_lsi_execute_script_tc_call(addr); s->temp = s->dsp; s->dsp = addr; break; case 2: /* Return */ trace_lsi_execute_script_tc_return(s->temp); s->dsp = s->temp; break; case 3: /* Interrupt */ trace_lsi_execute_script_tc_interrupt(s->dsps); if ((insn & (1 << 20)) != 0) { s->istat0 |= LSI_ISTAT0_INTF; lsi_update_irq(s); } else { lsi_script_dma_interrupt(s, LSI_DSTAT_SIR); } break; default: trace_lsi_execute_script_tc_illegal(); lsi_script_dma_interrupt(s, LSI_DSTAT_IID); break; } } else { trace_lsi_execute_script_tc_cc_failed(); } } break; case 3: if ((insn & (1 << 29)) == 0) { /* Memory move. */ uint32_t dest; /* ??? The docs imply the destination address is loaded into the TEMP register. However the Linux drivers rely on the value being presrved. */ dest = read_dword(s, s->dsp); s->dsp += 4; lsi_memcpy(s, dest, addr, insn & 0xffffff); } else { uint8_t data[7]; int reg; int n; int i; if (insn & (1 << 28)) { addr = s->dsa + sextract32(addr, 0, 24); } n = (insn & 7); reg = (insn >> 16) & 0xff; if (insn & (1 << 24)) { pci_dma_read(pci_dev, addr, data, n); trace_lsi_execute_script_mm_load(reg, n, addr, *(int *)data); for (i = 0; i < n; i++) { lsi_reg_writeb(s, reg + i, data[i]); } } else { trace_lsi_execute_script_mm_store(reg, n, addr); for (i = 0; i < n; i++) { data[i] = lsi_reg_readb(s, reg + i); } pci_dma_write(pci_dev, addr, data, n); } } } if (insn_processed > 10000 && s->waiting == LSI_NOWAIT) { /* Some windows drivers make the device spin waiting for a memory location to change. If we have been executed a lot of code then assume this is the case and force an unexpected device disconnect. This is apparently sufficient to beat the drivers into submission. */ if (!(s->sien0 & LSI_SIST0_UDC)) { qemu_log_mask(LOG_GUEST_ERROR, "lsi_scsi: inf. loop with UDC masked"); } lsi_script_scsi_interrupt(s, LSI_SIST0_UDC, 0); lsi_disconnect(s); } else if (s->istat1 & LSI_ISTAT1_SRUN && s->waiting == LSI_NOWAIT) { if (s->dcntl & LSI_DCNTL_SSM) { lsi_script_dma_interrupt(s, LSI_DSTAT_SSI); } else { goto again; } } trace_lsi_execute_script_stop(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'scsi: lsi: exit infinite loop while executing script (CVE-2019-12068) When executing script in lsi_execute_script(), the LSI scsi adapter emulator advances 's->dsp' index to read next opcode. This can lead to an infinite loop if the next opcode is empty. Move the existing loop exit after 10k iterations so that it covers no-op opcodes as well. Reported-by: Bugs SysSec <bugs-syssec@rub.de> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int acp_hw_init(void *handle) { int r, i; uint64_t acp_base; u32 val = 0; u32 count = 0; struct device *dev; struct i2s_platform_data *i2s_pdata; struct amdgpu_device *adev = (struct amdgpu_device *)handle; const struct amdgpu_ip_block *ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_ACP); if (!ip_block) return -EINVAL; r = amd_acp_hw_init(adev->acp.cgs_device, ip_block->version->major, ip_block->version->minor); /* -ENODEV means board uses AZ rather than ACP */ if (r == -ENODEV) { amdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true); return 0; } else if (r) { return r; } if (adev->rmmio_size == 0 || adev->rmmio_size < 0x5289) return -EINVAL; acp_base = adev->rmmio_base; adev->acp.acp_genpd = kzalloc(sizeof(struct acp_pm_domain), GFP_KERNEL); if (adev->acp.acp_genpd == NULL) return -ENOMEM; adev->acp.acp_genpd->gpd.name = "ACP_AUDIO"; adev->acp.acp_genpd->gpd.power_off = acp_poweroff; adev->acp.acp_genpd->gpd.power_on = acp_poweron; adev->acp.acp_genpd->adev = adev; pm_genpd_init(&adev->acp.acp_genpd->gpd, NULL, false); adev->acp.acp_cell = kcalloc(ACP_DEVS, sizeof(struct mfd_cell), GFP_KERNEL); if (adev->acp.acp_cell == NULL) return -ENOMEM; adev->acp.acp_res = kcalloc(5, sizeof(struct resource), GFP_KERNEL); if (adev->acp.acp_res == NULL) { kfree(adev->acp.acp_cell); return -ENOMEM; } i2s_pdata = kcalloc(3, sizeof(struct i2s_platform_data), GFP_KERNEL); if (i2s_pdata == NULL) { kfree(adev->acp.acp_res); kfree(adev->acp.acp_cell); return -ENOMEM; } switch (adev->asic_type) { case CHIP_STONEY: i2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET | DW_I2S_QUIRK_16BIT_IDX_OVERRIDE; break; default: i2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET; } i2s_pdata[0].cap = DWC_I2S_PLAY; i2s_pdata[0].snd_rates = SNDRV_PCM_RATE_8000_96000; i2s_pdata[0].i2s_reg_comp1 = ACP_I2S_COMP1_PLAY_REG_OFFSET; i2s_pdata[0].i2s_reg_comp2 = ACP_I2S_COMP2_PLAY_REG_OFFSET; switch (adev->asic_type) { case CHIP_STONEY: i2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET | DW_I2S_QUIRK_COMP_PARAM1 | DW_I2S_QUIRK_16BIT_IDX_OVERRIDE; break; default: i2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET | DW_I2S_QUIRK_COMP_PARAM1; } i2s_pdata[1].cap = DWC_I2S_RECORD; i2s_pdata[1].snd_rates = SNDRV_PCM_RATE_8000_96000; i2s_pdata[1].i2s_reg_comp1 = ACP_I2S_COMP1_CAP_REG_OFFSET; i2s_pdata[1].i2s_reg_comp2 = ACP_I2S_COMP2_CAP_REG_OFFSET; i2s_pdata[2].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET; switch (adev->asic_type) { case CHIP_STONEY: i2s_pdata[2].quirks |= DW_I2S_QUIRK_16BIT_IDX_OVERRIDE; break; default: break; } i2s_pdata[2].cap = DWC_I2S_PLAY | DWC_I2S_RECORD; i2s_pdata[2].snd_rates = SNDRV_PCM_RATE_8000_96000; i2s_pdata[2].i2s_reg_comp1 = ACP_BT_COMP1_REG_OFFSET; i2s_pdata[2].i2s_reg_comp2 = ACP_BT_COMP2_REG_OFFSET; adev->acp.acp_res[0].name = "acp2x_dma"; adev->acp.acp_res[0].flags = IORESOURCE_MEM; adev->acp.acp_res[0].start = acp_base; adev->acp.acp_res[0].end = acp_base + ACP_DMA_REGS_END; adev->acp.acp_res[1].name = "acp2x_dw_i2s_play"; adev->acp.acp_res[1].flags = IORESOURCE_MEM; adev->acp.acp_res[1].start = acp_base + ACP_I2S_PLAY_REGS_START; adev->acp.acp_res[1].end = acp_base + ACP_I2S_PLAY_REGS_END; adev->acp.acp_res[2].name = "acp2x_dw_i2s_cap"; adev->acp.acp_res[2].flags = IORESOURCE_MEM; adev->acp.acp_res[2].start = acp_base + ACP_I2S_CAP_REGS_START; adev->acp.acp_res[2].end = acp_base + ACP_I2S_CAP_REGS_END; adev->acp.acp_res[3].name = "acp2x_dw_bt_i2s_play_cap"; adev->acp.acp_res[3].flags = IORESOURCE_MEM; adev->acp.acp_res[3].start = acp_base + ACP_BT_PLAY_REGS_START; adev->acp.acp_res[3].end = acp_base + ACP_BT_PLAY_REGS_END; adev->acp.acp_res[4].name = "acp2x_dma_irq"; adev->acp.acp_res[4].flags = IORESOURCE_IRQ; adev->acp.acp_res[4].start = amdgpu_irq_create_mapping(adev, 162); adev->acp.acp_res[4].end = adev->acp.acp_res[4].start; adev->acp.acp_cell[0].name = "acp_audio_dma"; adev->acp.acp_cell[0].num_resources = 5; adev->acp.acp_cell[0].resources = &adev->acp.acp_res[0]; adev->acp.acp_cell[0].platform_data = &adev->asic_type; adev->acp.acp_cell[0].pdata_size = sizeof(adev->asic_type); adev->acp.acp_cell[1].name = "designware-i2s"; adev->acp.acp_cell[1].num_resources = 1; adev->acp.acp_cell[1].resources = &adev->acp.acp_res[1]; adev->acp.acp_cell[1].platform_data = &i2s_pdata[0]; adev->acp.acp_cell[1].pdata_size = sizeof(struct i2s_platform_data); adev->acp.acp_cell[2].name = "designware-i2s"; adev->acp.acp_cell[2].num_resources = 1; adev->acp.acp_cell[2].resources = &adev->acp.acp_res[2]; adev->acp.acp_cell[2].platform_data = &i2s_pdata[1]; adev->acp.acp_cell[2].pdata_size = sizeof(struct i2s_platform_data); adev->acp.acp_cell[3].name = "designware-i2s"; adev->acp.acp_cell[3].num_resources = 1; adev->acp.acp_cell[3].resources = &adev->acp.acp_res[3]; adev->acp.acp_cell[3].platform_data = &i2s_pdata[2]; adev->acp.acp_cell[3].pdata_size = sizeof(struct i2s_platform_data); r = mfd_add_hotplug_devices(adev->acp.parent, adev->acp.acp_cell, ACP_DEVS); if (r) return r; for (i = 0; i < ACP_DEVS ; i++) { dev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i); r = pm_genpd_add_device(&adev->acp.acp_genpd->gpd, dev); if (r) { dev_err(dev, "Failed to add dev to genpd\n"); return r; } } /* Assert Soft reset of ACP */ val = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET); val |= ACP_SOFT_RESET__SoftResetAud_MASK; cgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val); count = ACP_SOFT_RESET_DONE_TIME_OUT_VALUE; while (true) { val = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET); if (ACP_SOFT_RESET__SoftResetAudDone_MASK == (val & ACP_SOFT_RESET__SoftResetAudDone_MASK)) break; if (--count == 0) { dev_err(&adev->pdev->dev, "Failed to reset ACP\n"); return -ETIMEDOUT; } udelay(100); } /* Enable clock to ACP and wait until the clock is enabled */ val = cgs_read_register(adev->acp.cgs_device, mmACP_CONTROL); val = val | ACP_CONTROL__ClkEn_MASK; cgs_write_register(adev->acp.cgs_device, mmACP_CONTROL, val); count = ACP_CLOCK_EN_TIME_OUT_VALUE; while (true) { val = cgs_read_register(adev->acp.cgs_device, mmACP_STATUS); if (val & (u32) 0x1) break; if (--count == 0) { dev_err(&adev->pdev->dev, "Failed to reset ACP\n"); return -ETIMEDOUT; } udelay(100); } /* Deassert the SOFT RESET flags */ val = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET); val &= ~ACP_SOFT_RESET__SoftResetAud_MASK; cgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amdgpu: fix multiple memory leaks in acp_hw_init In acp_hw_init there are some allocations that needs to be released in case of failure: 1- adev->acp.acp_genpd should be released if any allocation attemp for adev->acp.acp_cell, adev->acp.acp_res or i2s_pdata fails. 2- all of those allocations should be released if mfd_add_hotplug_devices or pm_genpd_add_device fail. 3- Release is needed in case of time out values expire. Reviewed-by: Christian König <christian.koenig@amd.com> Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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 sdma_init(struct hfi1_devdata *dd, u8 port) { unsigned this_idx; struct sdma_engine *sde; struct rhashtable *tmp_sdma_rht; u16 descq_cnt; void *curr_head; struct hfi1_pportdata *ppd = dd->pport + port; u32 per_sdma_credits; uint idle_cnt = sdma_idle_cnt; size_t num_engines = chip_sdma_engines(dd); int ret = -ENOMEM; if (!HFI1_CAP_IS_KSET(SDMA)) { HFI1_CAP_CLEAR(SDMA_AHG); return 0; } if (mod_num_sdma && /* can't exceed chip support */ mod_num_sdma <= chip_sdma_engines(dd) && /* count must be >= vls */ mod_num_sdma >= num_vls) num_engines = mod_num_sdma; dd_dev_info(dd, "SDMA mod_num_sdma: %u\n", mod_num_sdma); dd_dev_info(dd, "SDMA chip_sdma_engines: %u\n", chip_sdma_engines(dd)); dd_dev_info(dd, "SDMA chip_sdma_mem_size: %u\n", chip_sdma_mem_size(dd)); per_sdma_credits = chip_sdma_mem_size(dd) / (num_engines * SDMA_BLOCK_SIZE); /* set up freeze waitqueue */ init_waitqueue_head(&dd->sdma_unfreeze_wq); atomic_set(&dd->sdma_unfreeze_count, 0); descq_cnt = sdma_get_descq_cnt(); dd_dev_info(dd, "SDMA engines %zu descq_cnt %u\n", num_engines, descq_cnt); /* alloc memory for array of send engines */ dd->per_sdma = kcalloc_node(num_engines, sizeof(*dd->per_sdma), GFP_KERNEL, dd->node); if (!dd->per_sdma) return ret; idle_cnt = ns_to_cclock(dd, idle_cnt); if (idle_cnt) dd->default_desc1 = SDMA_DESC1_HEAD_TO_HOST_FLAG; else dd->default_desc1 = SDMA_DESC1_INT_REQ_FLAG; if (!sdma_desct_intr) sdma_desct_intr = SDMA_DESC_INTR; /* Allocate memory for SendDMA descriptor FIFOs */ for (this_idx = 0; this_idx < num_engines; ++this_idx) { sde = &dd->per_sdma[this_idx]; sde->dd = dd; sde->ppd = ppd; sde->this_idx = this_idx; sde->descq_cnt = descq_cnt; sde->desc_avail = sdma_descq_freecnt(sde); sde->sdma_shift = ilog2(descq_cnt); sde->sdma_mask = (1 << sde->sdma_shift) - 1; /* Create a mask specifically for each interrupt source */ sde->int_mask = (u64)1 << (0 * TXE_NUM_SDMA_ENGINES + this_idx); sde->progress_mask = (u64)1 << (1 * TXE_NUM_SDMA_ENGINES + this_idx); sde->idle_mask = (u64)1 << (2 * TXE_NUM_SDMA_ENGINES + this_idx); /* Create a combined mask to cover all 3 interrupt sources */ sde->imask = sde->int_mask | sde->progress_mask | sde->idle_mask; spin_lock_init(&sde->tail_lock); seqlock_init(&sde->head_lock); spin_lock_init(&sde->senddmactrl_lock); spin_lock_init(&sde->flushlist_lock); seqlock_init(&sde->waitlock); /* insure there is always a zero bit */ sde->ahg_bits = 0xfffffffe00000000ULL; sdma_set_state(sde, sdma_state_s00_hw_down); /* set up reference counting */ kref_init(&sde->state.kref); init_completion(&sde->state.comp); INIT_LIST_HEAD(&sde->flushlist); INIT_LIST_HEAD(&sde->dmawait); sde->tail_csr = get_kctxt_csr_addr(dd, this_idx, SD(TAIL)); tasklet_init(&sde->sdma_hw_clean_up_task, sdma_hw_clean_up_task, (unsigned long)sde); tasklet_init(&sde->sdma_sw_clean_up_task, sdma_sw_clean_up_task, (unsigned long)sde); INIT_WORK(&sde->err_halt_worker, sdma_err_halt_wait); INIT_WORK(&sde->flush_worker, sdma_field_flush); sde->progress_check_head = 0; timer_setup(&sde->err_progress_check_timer, sdma_err_progress_check, 0); sde->descq = dma_alloc_coherent(&dd->pcidev->dev, descq_cnt * sizeof(u64[2]), &sde->descq_phys, GFP_KERNEL); if (!sde->descq) goto bail; sde->tx_ring = kvzalloc_node(array_size(descq_cnt, sizeof(struct sdma_txreq *)), GFP_KERNEL, dd->node); if (!sde->tx_ring) goto bail; } dd->sdma_heads_size = L1_CACHE_BYTES * num_engines; /* Allocate memory for DMA of head registers to memory */ dd->sdma_heads_dma = dma_alloc_coherent(&dd->pcidev->dev, dd->sdma_heads_size, &dd->sdma_heads_phys, GFP_KERNEL); if (!dd->sdma_heads_dma) { dd_dev_err(dd, "failed to allocate SendDMA head memory\n"); goto bail; } /* Allocate memory for pad */ dd->sdma_pad_dma = dma_alloc_coherent(&dd->pcidev->dev, sizeof(u32), &dd->sdma_pad_phys, GFP_KERNEL); if (!dd->sdma_pad_dma) { dd_dev_err(dd, "failed to allocate SendDMA pad memory\n"); goto bail; } /* assign each engine to different cacheline and init registers */ curr_head = (void *)dd->sdma_heads_dma; for (this_idx = 0; this_idx < num_engines; ++this_idx) { unsigned long phys_offset; sde = &dd->per_sdma[this_idx]; sde->head_dma = curr_head; curr_head += L1_CACHE_BYTES; phys_offset = (unsigned long)sde->head_dma - (unsigned long)dd->sdma_heads_dma; sde->head_phys = dd->sdma_heads_phys + phys_offset; init_sdma_regs(sde, per_sdma_credits, idle_cnt); } dd->flags |= HFI1_HAS_SEND_DMA; dd->flags |= idle_cnt ? HFI1_HAS_SDMA_TIMEOUT : 0; dd->num_sdma = num_engines; ret = sdma_map_init(dd, port, ppd->vls_operational, NULL); if (ret < 0) goto bail; tmp_sdma_rht = kzalloc(sizeof(*tmp_sdma_rht), GFP_KERNEL); if (!tmp_sdma_rht) { ret = -ENOMEM; goto bail; } ret = rhashtable_init(tmp_sdma_rht, &sdma_rht_params); if (ret < 0) goto bail; dd->sdma_rht = tmp_sdma_rht; dd_dev_info(dd, "SDMA num_sdma: %u\n", dd->num_sdma); return 0; bail: sdma_clean(dd, num_engines); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'RDMA/hfi1: Prevent memory leak in sdma_init In sdma_init if rhashtable_init fails the allocated memory for tmp_sdma_rht should be released. Fixes: 5a52a7acf7e2 ("IB/hfi1: NULL pointer dereference when freeing rhashtable") Link: https://lore.kernel.org/r/20190925144543.10141-1-navid.emamdoost@gmail.com Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Acked-by: Dennis Dalessandro <dennis.dalessandro@intel.com> Signed-off-by: Jason Gunthorpe <jgg@mellanox.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 mwifiex_pcie_init_evt_ring(struct mwifiex_adapter *adapter) { struct pcie_service_card *card = adapter->card; struct mwifiex_evt_buf_desc *desc; struct sk_buff *skb; dma_addr_t buf_pa; int i; for (i = 0; i < MWIFIEX_MAX_EVT_BD; i++) { /* Allocate skb here so that firmware can DMA data from it */ skb = dev_alloc_skb(MAX_EVENT_SIZE); if (!skb) { mwifiex_dbg(adapter, ERROR, "Unable to allocate skb for EVENT buf.\n"); kfree(card->evtbd_ring_vbase); return -ENOMEM; } skb_put(skb, MAX_EVENT_SIZE); if (mwifiex_map_pci_memory(adapter, skb, MAX_EVENT_SIZE, PCI_DMA_FROMDEVICE)) return -1; buf_pa = MWIFIEX_SKB_DMA_ADDR(skb); mwifiex_dbg(adapter, EVENT, "info: EVT ring: skb=%p len=%d data=%p buf_pa=%#x:%x\n", skb, skb->len, skb->data, (u32)buf_pa, (u32)((u64)buf_pa >> 32)); card->evt_buf_list[i] = skb; card->evtbd_ring[i] = (void *)(card->evtbd_ring_vbase + (sizeof(*desc) * i)); desc = card->evtbd_ring[i]; desc->paddr = buf_pa; desc->len = (u16)skb->len; desc->flags = 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-200', 'CWE-401'], 'message': 'mwifiex: pcie: Fix memory leak in mwifiex_pcie_init_evt_ring In mwifiex_pcie_init_evt_ring, a new skb is allocated which should be released if mwifiex_map_pci_memory() fails. The release for skb and card->evtbd_ring_vbase is added. Fixes: 0732484b47b5 ("mwifiex: separate ring initialization and ring creation routines") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Acked-by: Ganapathi Bhat <gbhat@marvell.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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 struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices, u64 devid, const u8 *uuid) { struct btrfs_device *dev; list_for_each_entry(dev, &fs_devices->devices, dev_list) { if (dev->devid == devid && (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) { return dev; } } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@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 long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_dev_info_args *di_args; struct btrfs_device *dev; int ret = 0; char *s_uuid = NULL; di_args = memdup_user(arg, sizeof(*di_args)); if (IS_ERR(di_args)) return PTR_ERR(di_args); if (!btrfs_is_empty_uuid(di_args->uuid)) s_uuid = di_args->uuid; rcu_read_lock(); dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid, NULL); if (!dev) { ret = -ENODEV; goto out; } di_args->devid = dev->devid; di_args->bytes_used = btrfs_device_get_bytes_used(dev); di_args->total_bytes = btrfs_device_get_total_bytes(dev); memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid)); if (dev->name) { strncpy(di_args->path, rcu_str_deref(dev->name), sizeof(di_args->path) - 1); di_args->path[sizeof(di_args->path) - 1] = 0; } else { di_args->path[0] = '\0'; } out: rcu_read_unlock(); if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args))) ret = -EFAULT; kfree(di_args); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@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: struct resource_pool *dcn10_create_resource_pool( const struct dc_init_data *init_data, struct dc *dc) { struct dcn10_resource_pool *pool = kzalloc(sizeof(struct dcn10_resource_pool), GFP_KERNEL); if (!pool) return NULL; if (construct(init_data->num_virtual_links, dc, pool)) return &pool->base; BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amd/display: prevent memory leak In dcn*_create_resource_pool the allocated memory should be released if construct pool fails. Reviewed-by: Harry Wentland <harry.wentland@amd.com> Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct clock_source *dce100_clock_source_create( struct dc_context *ctx, struct dc_bios *bios, enum clock_source_id id, const struct dce110_clk_src_regs *regs, bool dp_clk_src) { struct dce110_clk_src *clk_src = kzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL); if (!clk_src) return NULL; if (dce110_clk_src_construct(clk_src, ctx, bios, id, regs, &cs_shift, &cs_mask)) { clk_src->base.dp_clk_src = dp_clk_src; return &clk_src->base; } BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak In dcn*_clock_source_create when dcn20_clk_src_construct fails allocated clk_src needs release. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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 sof_dfsentry_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { #if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_IPC_FLOOD_TEST) struct snd_sof_dfsentry *dfse = file->private_data; struct snd_sof_dev *sdev = dfse->sdev; unsigned long ipc_duration_ms = 0; bool flood_duration_test = false; unsigned long ipc_count = 0; struct dentry *dentry; int err; #endif size_t size; char *string; int ret; string = kzalloc(count, GFP_KERNEL); if (!string) return -ENOMEM; size = simple_write_to_buffer(string, count, ppos, buffer, count); ret = size; #if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_IPC_FLOOD_TEST) /* * write op is only supported for ipc_flood_count or * ipc_flood_duration_ms debugfs entries atm. * ipc_flood_count floods the DSP with the number of IPC's specified. * ipc_duration_ms test floods the DSP for the time specified * in the debugfs entry. */ dentry = file->f_path.dentry; if (strcmp(dentry->d_name.name, "ipc_flood_count") && strcmp(dentry->d_name.name, "ipc_flood_duration_ms")) return -EINVAL; if (!strcmp(dentry->d_name.name, "ipc_flood_duration_ms")) flood_duration_test = true; /* test completion criterion */ if (flood_duration_test) ret = kstrtoul(string, 0, &ipc_duration_ms); else ret = kstrtoul(string, 0, &ipc_count); if (ret < 0) goto out; /* limit max duration/ipc count for flood test */ if (flood_duration_test) { if (!ipc_duration_ms) { ret = size; goto out; } /* find the minimum. min() is not used to avoid warnings */ if (ipc_duration_ms > MAX_IPC_FLOOD_DURATION_MS) ipc_duration_ms = MAX_IPC_FLOOD_DURATION_MS; } else { if (!ipc_count) { ret = size; goto out; } /* find the minimum. min() is not used to avoid warnings */ if (ipc_count > MAX_IPC_FLOOD_COUNT) ipc_count = MAX_IPC_FLOOD_COUNT; } ret = pm_runtime_get_sync(sdev->dev); if (ret < 0) { dev_err_ratelimited(sdev->dev, "error: debugfs write failed to resume %d\n", ret); pm_runtime_put_noidle(sdev->dev); goto out; } /* flood test */ ret = sof_debug_ipc_flood_test(sdev, dfse, flood_duration_test, ipc_duration_ms, ipc_count); pm_runtime_mark_last_busy(sdev->dev); err = pm_runtime_put_autosuspend(sdev->dev); if (err < 0) dev_err_ratelimited(sdev->dev, "error: debugfs write failed to idle %d\n", err); /* return size if test is successful */ if (ret >= 0) ret = size; out: #endif kfree(string); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ASoC: SOF: Fix memory leak in sof_dfsentry_write In the implementation of sof_dfsentry_write() memory allocated for string is leaked in case of an error. Go to error handling path if the d_name.name is not valid. Fixes: 091c12e1f50c ("ASoC: SOF: debug: add new debugfs entries for IPC flood test") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Link: https://lore.kernel.org/r/20191027194856.4056-1-navid.emamdoost@gmail.com Signed-off-by: Mark Brown <broonie@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: create_face_from_contents (FontLoadJob *job, gchar **contents, GError **error) { FT_Error ft_error; FT_Face retval; ft_error = FT_New_Memory_Face (job->library, (const FT_Byte *) job->face_contents, (FT_Long) job->face_length, job->face_index, &retval); if (ft_error != 0) { g_autofree gchar *uri = g_file_get_uri (job->file); g_set_error (error, G_IO_ERROR, 0, "Unable to read the font face file '%s'", uri); return NULL; } *contents = g_steal_pointer (&job->face_contents); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fallback to basename when no family name (CVE-2019-19308) Instead of possibly returning an empty string, which will cause issues later on. We store the GFile that was loaded to create the FT_Face into its generic client data structure, and load the basename from it when we don't have a family name. https://gitlab.gnome.org/GNOME/gnome-font-viewer/issues/17'</s>
<s>[INST] Given the following code containing errors, provide 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 zpff_init(struct hid_device *hid) { struct zpff_device *zpff; struct hid_report *report; struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct input_dev *dev = hidinput->input; int i, error; for (i = 0; i < 4; i++) { report = hid_validate_values(hid, HID_OUTPUT_REPORT, 0, i, 1); if (!report) return -ENODEV; } zpff = kzalloc(sizeof(struct zpff_device), GFP_KERNEL); if (!zpff) return -ENOMEM; set_bit(FF_RUMBLE, dev->ffbit); error = input_ff_create_memless(dev, zpff, zpff_play); if (error) { kfree(zpff); return error; } zpff->report = report; zpff->report->field[0]->value[0] = 0x00; zpff->report->field[1]->value[0] = 0x02; zpff->report->field[2]->value[0] = 0x00; zpff->report->field[3]->value[0] = 0x00; hid_hw_request(hid, zpff->report, HID_REQ_SET_REPORT); hid_info(hid, "force feedback for Zeroplus based devices by Anssi Hannula <anssi.hannula@gmail.com>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 drff_init(struct hid_device *hid) { struct drff_device *drff; struct hid_report *report; struct hid_input *hidinput = list_first_entry(&hid->inputs, struct hid_input, list); struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list; struct input_dev *dev = hidinput->input; int error; if (list_empty(report_list)) { hid_err(hid, "no output reports found\n"); return -ENODEV; } report = list_first_entry(report_list, struct hid_report, list); if (report->maxfield < 1) { hid_err(hid, "no fields in the report\n"); return -ENODEV; } if (report->field[0]->report_count < 7) { hid_err(hid, "not enough values in the field\n"); return -ENODEV; } drff = kzalloc(sizeof(struct drff_device), GFP_KERNEL); if (!drff) return -ENOMEM; set_bit(FF_RUMBLE, dev->ffbit); error = input_ff_create_memless(dev, drff, drff_play); if (error) { kfree(drff); return error; } drff->report = report; drff->report->field[0]->value[0] = 0xf3; drff->report->field[0]->value[1] = 0x00; drff->report->field[0]->value[2] = 0x00; drff->report->field[0]->value[3] = 0x00; drff->report->field[0]->value[4] = 0x00; drff->report->field[0]->value[5] = 0x00; drff->report->field[0]->value[6] = 0x00; hid_hw_request(hid, drff->report, HID_REQ_SET_REPORT); hid_info(hid, "Force Feedback for DragonRise Inc. " "game controllers by Richard Walmsley <richwalm@gmail.com>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 fts3DoAutoincrmerge( Fts3Table *p, /* FTS3 table handle */ const char *zParam /* Nul-terminated string containing boolean */ ){ int rc = SQLITE_OK; sqlite3_stmt *pStmt = 0; p->nAutoincrmerge = fts3Getint(&zParam); if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){ p->nAutoincrmerge = 8; } if( !p->bHasStat ){ assert( p->bFts4==0 ); sqlite3Fts3CreateStatTable(&rc, p); if( rc ) return rc; } rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ) return rc; sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'More improvements to shadow table corruption detection in FTS3. FossilOrigin-Name: 51525f9c3235967bc00a090e84c70a6400698c897aa4742e817121c725b8c99d'</s>
<s>[INST] Given the following code containing errors, provide 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 fts3SegWriterAdd( Fts3Table *p, /* Virtual table handle */ SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ int isCopyTerm, /* True if buffer zTerm must be copied */ const char *zTerm, /* Pointer to buffer containing term */ int nTerm, /* Size of term in bytes */ const char *aDoclist, /* Pointer to buffer containing doclist */ int nDoclist /* Size of doclist in bytes */ ){ int nPrefix; /* Size of term prefix in bytes */ int nSuffix; /* Size of term suffix in bytes */ int nReq; /* Number of bytes required on leaf page */ int nData; SegmentWriter *pWriter = *ppWriter; if( !pWriter ){ int rc; sqlite3_stmt *pStmt; /* Allocate the SegmentWriter structure */ pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); if( !pWriter ) return SQLITE_NOMEM; memset(pWriter, 0, sizeof(SegmentWriter)); *ppWriter = pWriter; /* Allocate a buffer in which to accumulate data */ pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); if( !pWriter->aData ) return SQLITE_NOMEM; pWriter->nSize = p->nNodeSize; /* Find the next free blockid in the %_segments table */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; if( SQLITE_ROW==sqlite3_step(pStmt) ){ pWriter->iFree = sqlite3_column_int64(pStmt, 0); pWriter->iFirst = pWriter->iFree; } rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ) return rc; } nData = pWriter->nData; nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when ** compared with BINARY collation. This indicates corruption. */ if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; /* Figure out how many bytes are required by this new entry */ nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ nSuffix + /* Term suffix */ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ if( nData>0 && nData+nReq>p->nNodeSize ){ int rc; /* The current leaf node is full. Write it out to the database. */ rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); if( rc!=SQLITE_OK ) return rc; p->nLeafAdd++; /* Add the current term to the interior node tree. The term added to ** the interior tree must: ** ** a) be greater than the largest term on the leaf node just written ** to the database (still available in pWriter->zTerm), and ** ** b) be less than or equal to the term about to be added to the new ** leaf node (zTerm/nTerm). ** ** In other words, it must be the prefix of zTerm 1 byte longer than ** the common prefix (if any) of zTerm and pWriter->zTerm. */ assert( nPrefix<nTerm ); rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1); if( rc!=SQLITE_OK ) return rc; nData = 0; pWriter->nTerm = 0; nPrefix = 0; nSuffix = nTerm; nReq = 1 + /* varint containing prefix size */ sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ nTerm + /* Term suffix */ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ } /* Increase the total number of bytes written to account for the new entry. */ pWriter->nLeafData += nReq; /* If the buffer currently allocated is too small for this entry, realloc ** the buffer to make it large enough. */ if( nReq>pWriter->nSize ){ char *aNew = sqlite3_realloc(pWriter->aData, nReq); if( !aNew ) return SQLITE_NOMEM; pWriter->aData = aNew; pWriter->nSize = nReq; } assert( nData+nReq<=pWriter->nSize ); /* Append the prefix-compressed term and doclist to the buffer. */ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); nData += nSuffix; nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); memcpy(&pWriter->aData[nData], aDoclist, nDoclist); pWriter->nData = nData + nDoclist; /* Save the current term so that it can be used to prefix-compress the next. ** If the isCopyTerm parameter is true, then the buffer pointed to by ** zTerm is transient, so take a copy of the term data. Otherwise, just ** store a copy of the pointer. */ if( isCopyTerm ){ if( nTerm>pWriter->nMalloc ){ char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } pWriter->nMalloc = nTerm*2; pWriter->zMalloc = zNew; pWriter->zTerm = zNew; } assert( pWriter->zTerm==pWriter->zMalloc ); memcpy(pWriter->zTerm, zTerm, nTerm); }else{ pWriter->zTerm = (char *)zTerm; } pWriter->nTerm = nTerm; return SQLITE_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Improved detection of corrupt shadow tables in FTS3. Enable the debugging special-inserts for FTS3 for both SQLITE_DEBUG and SQLITE_TEST. FossilOrigin-Name: 04b2873be5aedeb1c4325cf36c4b5d180f929a641caf1e3829c03778adb29c8e'</s>
<s>[INST] Given the following code containing errors, provide 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 renameTableSelectCb(Walker *pWalker, Select *pSelect){ int i; RenameCtx *p = pWalker->u.pRename; SrcList *pSrc = pSelect->pSrc; if( pSrc==0 ){ assert( pWalker->pParse->db->mallocFailed ); return WRC_Abort; } for(i=0; i<pSrc->nSrc; i++){ struct SrcList_item *pItem = &pSrc->a[i]; if( pItem->pTab==p->pTab ){ renameTokenFind(pWalker->pParse, p, pItem->zName); } } renameWalkWith(pWalker, pSelect); return WRC_Continue; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself. FossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5'</s>
<s>[INST] Given the following code containing errors, provide 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 iowarrior_disconnect(struct usb_interface *interface) { struct iowarrior *dev; int minor; dev = usb_get_intfdata(interface); mutex_lock(&iowarrior_open_disc_lock); usb_set_intfdata(interface, NULL); /* prevent device read, write and ioctl */ dev->present = 0; minor = dev->minor; mutex_unlock(&iowarrior_open_disc_lock); /* give back our minor - this will call close() locks need to be dropped at this point*/ usb_deregister_dev(interface, &iowarrior_class); mutex_lock(&dev->mutex); /* prevent device read, write and ioctl */ mutex_unlock(&dev->mutex); if (dev->opened) { /* There is a process that holds a filedescriptor to the device , so we only shutdown read-/write-ops going on. Deleting the device is postponed until close() was called. */ usb_kill_urb(dev->int_in_urb); wake_up_interruptible(&dev->read_wait); wake_up_interruptible(&dev->write_wait); } else { /* no process is using the device, cleanup now */ iowarrior_delete(dev); } dev_info(&interface->dev, "I/O-Warror #%d now disconnected\n", minor - IOWARRIOR_MINOR_BASE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'USB: iowarrior: fix use-after-free on disconnect A recent fix addressing a deadlock on disconnect introduced a new bug by moving the present flag out of the critical section protected by the driver-data mutex. This could lead to a racing release() freeing the driver data before disconnect() is done with it. Due to insufficient locking a related use-after-free could be triggered also before the above mentioned commit. Specifically, the driver needs to hold the driver-data mutex also while checking the opened flag at disconnect(). Fixes: c468a8aa790e ("usb: iowarrior: fix deadlock on disconnect") Fixes: 946b960d13c1 ("USB: add driver for iowarrior devices.") Cc: stable <stable@vger.kernel.org> # 2.6.21 Reported-by: syzbot+0761012cebf7bdb38137@syzkaller.appspotmail.com Signed-off-by: Johan Hovold <johan@kernel.org> Link: https://lore.kernel.org/r/20191009104846.5925-2-johan@kernel.org 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: int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver) { int retval; int minor_base = class_driver->minor_base; int minor; char name[20]; #ifdef CONFIG_USB_DYNAMIC_MINORS /* * We don't care what the device tries to start at, we want to start * at zero to pack the devices into the smallest available space with * no holes in the minor range. */ minor_base = 0; #endif if (class_driver->fops == NULL) return -EINVAL; if (intf->minor >= 0) return -EADDRINUSE; mutex_lock(&init_usb_class_mutex); retval = init_usb_class(); mutex_unlock(&init_usb_class_mutex); if (retval) return retval; dev_dbg(&intf->dev, "looking for a minor, starting at %d\n", minor_base); down_write(&minor_rwsem); for (minor = minor_base; minor < MAX_USB_MINORS; ++minor) { if (usb_minors[minor]) continue; usb_minors[minor] = class_driver->fops; intf->minor = minor; break; } up_write(&minor_rwsem); if (intf->minor < 0) return -EXFULL; /* create a usb class device for this usb interface */ snprintf(name, sizeof(name), class_driver->name, minor - minor_base); intf->usb_dev = device_create(usb_class->class, &intf->dev, MKDEV(USB_MAJOR, minor), class_driver, "%s", kbasename(name)); if (IS_ERR(intf->usb_dev)) { down_write(&minor_rwsem); usb_minors[minor] = NULL; intf->minor = -1; up_write(&minor_rwsem); retval = PTR_ERR(intf->usb_dev); } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'USB: core: Fix races in character device registration and deregistraion The syzbot fuzzer has found two (!) races in the USB character device registration and deregistration routines. This patch fixes the races. The first race results from the fact that usb_deregister_dev() sets usb_minors[intf->minor] to NULL before calling device_destroy() on the class device. This leaves a window during which another thread can allocate the same minor number but will encounter a duplicate name error when it tries to register its own class device. A typical error message in the system log would look like: sysfs: cannot create duplicate filename '/class/usbmisc/ldusb0' The patch fixes this race by destroying the class device first. The second race is in usb_register_dev(). When that routine runs, it first allocates a minor number, then drops minor_rwsem, and then creates the class device. If the device creation fails, the minor number is deallocated and the whole routine returns an error. But during the time while minor_rwsem was dropped, there is a window in which the minor number is allocated and so another thread can successfully open the device file. Typically this results in use-after-free errors or invalid accesses when the other thread closes its open file reference, because the kernel then tries to release resources that were already deallocated when usb_register_dev() failed. The patch fixes this race by keeping minor_rwsem locked throughout the entire routine. Reported-and-tested-by: syzbot+30cf45ebfe0b0c4847a1@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Link: https://lore.kernel.org/r/Pine.LNX.4.44L0.1908121607590.1659-100000@iolanthe.rowland.org 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: int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data, amqp_frame_t *decoded_frame) { size_t bytes_consumed; void *raw_frame; /* Returning frame_type of zero indicates either insufficient input, or a complete, ignored frame was read. */ decoded_frame->frame_type = 0; if (received_data.len == 0) { return AMQP_STATUS_OK; } if (state->state == CONNECTION_STATE_IDLE) { state->state = CONNECTION_STATE_HEADER; } bytes_consumed = consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } raw_frame = state->inbound_buffer.bytes; switch (state->state) { case CONNECTION_STATE_INITIAL: /* check for a protocol header from the server */ if (memcmp(raw_frame, "AMQP", 4) == 0) { decoded_frame->frame_type = AMQP_PSEUDOFRAME_PROTOCOL_HEADER; decoded_frame->channel = 0; decoded_frame->payload.protocol_header.transport_high = amqp_d8(amqp_offset(raw_frame, 4)); decoded_frame->payload.protocol_header.transport_low = amqp_d8(amqp_offset(raw_frame, 5)); decoded_frame->payload.protocol_header.protocol_version_major = amqp_d8(amqp_offset(raw_frame, 6)); decoded_frame->payload.protocol_header.protocol_version_minor = amqp_d8(amqp_offset(raw_frame, 7)); return_to_idle(state); return (int)bytes_consumed; } /* it's not a protocol header; fall through to process it as a regular frame header */ case CONNECTION_STATE_HEADER: { amqp_channel_t channel; amqp_pool_t *channel_pool; /* frame length is 3 bytes in */ channel = amqp_d16(amqp_offset(raw_frame, 1)); state->target_size = amqp_d32(amqp_offset(raw_frame, 3)) + HEADER_SIZE + FOOTER_SIZE; if ((size_t)state->frame_max < state->target_size) { return AMQP_STATUS_BAD_AMQP_DATA; } channel_pool = amqp_get_or_create_channel_pool(state, channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } amqp_pool_alloc_bytes(channel_pool, state->target_size, &state->inbound_buffer); if (NULL == state->inbound_buffer.bytes) { return AMQP_STATUS_NO_MEMORY; } memcpy(state->inbound_buffer.bytes, state->header_buffer, HEADER_SIZE); raw_frame = state->inbound_buffer.bytes; state->state = CONNECTION_STATE_BODY; bytes_consumed += consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } } /* fall through to process body */ case CONNECTION_STATE_BODY: { amqp_bytes_t encoded; int res; amqp_pool_t *channel_pool; /* Check frame end marker (footer) */ if (amqp_d8(amqp_offset(raw_frame, state->target_size - 1)) != AMQP_FRAME_END) { return AMQP_STATUS_BAD_AMQP_DATA; } decoded_frame->frame_type = amqp_d8(amqp_offset(raw_frame, 0)); decoded_frame->channel = amqp_d16(amqp_offset(raw_frame, 1)); channel_pool = amqp_get_or_create_channel_pool(state, decoded_frame->channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } switch (decoded_frame->frame_type) { case AMQP_FRAME_METHOD: decoded_frame->payload.method.id = amqp_d32(amqp_offset(raw_frame, HEADER_SIZE)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 4); encoded.len = state->target_size - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_decode_method(decoded_frame->payload.method.id, channel_pool, encoded, &decoded_frame->payload.method.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_HEADER: decoded_frame->payload.properties.class_id = amqp_d16(amqp_offset(raw_frame, HEADER_SIZE)); /* unused 2-byte weight field goes here */ decoded_frame->payload.properties.body_size = amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 12); encoded.len = state->target_size - HEADER_SIZE - 12 - FOOTER_SIZE; decoded_frame->payload.properties.raw = encoded; res = amqp_decode_properties( decoded_frame->payload.properties.class_id, channel_pool, encoded, &decoded_frame->payload.properties.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_BODY: decoded_frame->payload.body_fragment.len = state->target_size - HEADER_SIZE - FOOTER_SIZE; decoded_frame->payload.body_fragment.bytes = amqp_offset(raw_frame, HEADER_SIZE); break; case AMQP_FRAME_HEARTBEAT: break; default: /* Ignore the frame */ decoded_frame->frame_type = 0; break; } return_to_idle(state); return (int)bytes_consumed; } default: amqp_abort("Internal error: invalid amqp_connection_state_t->state %d", state->state); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190', 'CWE-787'], 'message': 'lib: check frame_size is >= INT32_MAX When parsing a frame header, validate that the frame_size is less than or equal to INT32_MAX. Given frame_max is limited between 0 and INT32_MAX in amqp_login and friends, this does not change the API. This prevents a potential buffer overflow when a malicious client sends a frame_size that is close to UINT32_MAX, in which causes an overflow when computing state->target_size resulting in a small value there. A buffer is then allocated with the small amount, then memcopy copies the frame_size writing to memory beyond the end of the buffer.'</s>
<s>[INST] Given the following code containing errors, provide 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 sqlite3WindowRewrite(Parse *pParse, Select *p){ int rc = SQLITE_OK; if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){ Vdbe *v = sqlite3GetVdbe(pParse); sqlite3 *db = pParse->db; Select *pSub = 0; /* The subquery */ SrcList *pSrc = p->pSrc; Expr *pWhere = p->pWhere; ExprList *pGroupBy = p->pGroupBy; Expr *pHaving = p->pHaving; ExprList *pSort = 0; ExprList *pSublist = 0; /* Expression list for sub-query */ Window *pMWin = p->pWin; /* Master window object */ Window *pWin; /* Window object iterator */ Table *pTab; pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ){ return SQLITE_NOMEM; } p->pSrc = 0; p->pWhere = 0; p->pGroupBy = 0; p->pHaving = 0; p->selFlags &= ~SF_Aggregate; p->selFlags |= SF_WinRewrite; /* Create the ORDER BY clause for the sub-select. This is the concatenation ** of the window PARTITION and ORDER BY clauses. Then, if this makes it ** redundant, remove the ORDER BY from the parent SELECT. */ pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0); pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1); if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){ int nSave = pSort->nExpr; pSort->nExpr = p->pOrderBy->nExpr; if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){ sqlite3ExprListDelete(db, p->pOrderBy); p->pOrderBy = 0; } pSort->nExpr = nSave; } /* Assign a cursor number for the ephemeral table used to buffer rows. ** The OpenEphemeral instruction is coded later, after it is known how ** many columns the table will have. */ pMWin->iEphCsr = pParse->nTab++; pParse->nTab += 3; selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist); selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist); pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0); /* Append the PARTITION BY and ORDER BY expressions to the to the ** sub-select expression list. They are required to figure out where ** boundaries for partitions and sets of peer rows lie. */ pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0); pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0); /* Append the arguments passed to each window function to the ** sub-select expression list. Also allocate two registers for each ** window function - one for the accumulator, another for interim ** results. */ for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ ExprList *pArgs = pWin->pOwner->x.pList; if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){ selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist); pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); pWin->bExprArgs = 1; }else{ pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); pSublist = exprListAppendList(pParse, pSublist, pArgs, 0); } if( pWin->pFilter ){ Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0); pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter); } pWin->regAccum = ++pParse->nMem; pWin->regResult = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); } /* If there is no ORDER BY or PARTITION BY clause, and the window ** function accepts zero arguments, and there are no other columns ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible ** that pSublist is still NULL here. Add a constant expression here to ** keep everything legal in this case. */ if( pSublist==0 ){ pSublist = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_INTEGER, "0") ); } pSub = sqlite3SelectNew( pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0 ); p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); if( p->pSrc ){ Table *pTab2; p->pSrc->a[0].pSelect = pSub; sqlite3SrcListAssignCursors(pParse, p->pSrc); pSub->selFlags |= SF_Expanded; pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE); if( pTab2==0 ){ rc = SQLITE_NOMEM; }else{ memcpy(pTab, pTab2, sizeof(Table)); pTab->tabFlags |= TF_Ephemeral; p->pSrc->a[0].pTab = pTab; pTab = pTab2; } sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr); sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr); sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr); sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr); }else{ sqlite3SelectDelete(db, pSub); } if( db->mallocFailed ) rc = SQLITE_NOMEM; sqlite3DbFree(db, pTab); } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755'], 'message': 'When an error occurs while rewriting the parser tree for window functions in the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set, and make sure that this shuts down any subsequent code generation that might depend on the transformations that were implemented. This fixes a problem discovered by the Yongheng and Rui fuzzer. FossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f'</s>
<s>[INST] Given the following code containing errors, provide 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 vpx_rb_read_bit(struct vpx_read_bit_buffer *rb) { const size_t off = rb->bit_offset; const size_t p = off >> 3; const int q = 7 - (int)(off & 0x7); if (rb->bit_buffer + p < rb->bit_buffer_end) { const int bit = (rb->bit_buffer[p] >> q) & 1; rb->bit_offset = off + 1; return bit; } else { rb->error_handler(rb->error_handler_data); return 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vp9: fix OOB read in decoder_peek_si_internal Profile 1 or 3 bitstreams may require 11 bytes for the header in the intra-only case. Additionally add a check on the bit reader's error handler callback to ensure it's non-NULL before calling to avoid future regressions. This has existed since at least (pre-1.4.0): 09bf1d61c Changes hdr for profiles > 1 for intraonly frames BUG=webm:1543 Change-Id: I23901e6e3a219170e8ea9efecc42af0be2e5c378'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: std::string GetTempFileName() { #if !defined _MSC_VER && !defined __MINGW32__ std::string temp_file_name_template_str = std::string(std::getenv("TEST_TMPDIR") ? std::getenv("TEST_TMPDIR") : ".") + "/libwebm_temp.XXXXXX"; char* temp_file_name_template = new char[temp_file_name_template_str.length() + 1]; memset(temp_file_name_template, 0, temp_file_name_template_str.length() + 1); temp_file_name_template_str.copy(temp_file_name_template, temp_file_name_template_str.length(), 0); int fd = mkstemp(temp_file_name_template); std::string temp_file_name = (fd != -1) ? std::string(temp_file_name_template) : std::string(); delete[] temp_file_name_template; if (fd != -1) { close(fd); } return temp_file_name; #else char tmp_file_name[_MAX_PATH]; #if defined _MSC_VER || defined MINGW_HAS_SECURE_API errno_t err = tmpnam_s(tmp_file_name); #else char* fname_pointer = tmpnam(tmp_file_name); errno_t err = (fname_pointer == &tmp_file_name[0]) ? 0 : -1; #endif if (err == 0) { return std::string(tmp_file_name); } return std::string(); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exif_data_load_data_entry (ExifData *data, ExifEntry *entry, const unsigned char *d, unsigned int size, unsigned int offset) { unsigned int s, doff; entry->tag = exif_get_short (d + offset + 0, data->priv->order); entry->format = exif_get_short (d + offset + 2, data->priv->order); entry->components = exif_get_long (d + offset + 4, data->priv->order); /* FIXME: should use exif_tag_get_name_in_ifd here but entry->parent * has not been set yet */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading entry 0x%x ('%s')...", entry->tag, exif_tag_get_name (entry->tag)); /* {0,1,2,4,8} x { 0x00000000 .. 0xffffffff } * -> { 0x000000000 .. 0x7fffffff8 } */ s = exif_format_get_size(entry->format) * entry->components; if ((s < entry->components) || (s == 0)){ return 0; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ if (s > 4) doff = exif_get_long (d + offset + 8, data->priv->order); else doff = offset + 8; /* Sanity checks */ if ((doff + s < doff) || (doff + s < s) || (doff + s > size)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Tag data past end of buffer (%u > %u)", doff+s, size); return 0; } entry->data = exif_data_alloc (data, s); if (entry->data) { entry->size = s; memcpy (entry->data, d + doff, s); } else { EXIF_LOG_NO_MEMORY(data->priv->log, "ExifData", s); return 0; } /* If this is the MakerNote, remember the offset */ if (entry->tag == EXIF_TAG_MAKER_NOTE) { if (!entry->data) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found with empty data"); } else if (entry->size > 6) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found (%02x %02x %02x %02x " "%02x %02x %02x...).", entry->data[0], entry->data[1], entry->data[2], entry->data[3], entry->data[4], entry->data[5], entry->data[6]); } data->priv->offset_mnote = doff; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'fix CVE-2019-9278 avoid the use of unsafe integer overflow checking constructs (unsigned integer operations cannot overflow, so "u1 + u2 > u1" can be optimized away) check for the actual sizes, which should also handle the overflows document other places google patched, but do not seem relevant due to other restrictions fixes https://github.com/libexif/libexif/issues/26'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if (strcmp(im->mode, "1") == 0 && state->xsize > state->bytes * 8) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Catch PCX P mode buffer overrun'</s>
<s>[INST] Given the following code containing errors, provide 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 ieee80211_add_station(struct wiphy *wiphy, struct net_device *dev, const u8 *mac, struct station_parameters *params) { struct ieee80211_local *local = wiphy_priv(wiphy); struct sta_info *sta; struct ieee80211_sub_if_data *sdata; int err; int layer2_update; if (params->vlan) { sdata = IEEE80211_DEV_TO_SUB_IF(params->vlan); if (sdata->vif.type != NL80211_IFTYPE_AP_VLAN && sdata->vif.type != NL80211_IFTYPE_AP) return -EINVAL; } else sdata = IEEE80211_DEV_TO_SUB_IF(dev); if (ether_addr_equal(mac, sdata->vif.addr)) return -EINVAL; if (is_multicast_ether_addr(mac)) return -EINVAL; if (params->sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER) && sdata->vif.type == NL80211_IFTYPE_STATION && !sdata->u.mgd.associated) return -EINVAL; sta = sta_info_alloc(sdata, mac, GFP_KERNEL); if (!sta) return -ENOMEM; if (params->sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER)) sta->sta.tdls = true; err = sta_apply_parameters(local, sta, params); if (err) { sta_info_free(local, sta); return err; } /* * for TDLS and for unassociated station, rate control should be * initialized only when rates are known and station is marked * authorized/associated */ if (!test_sta_flag(sta, WLAN_STA_TDLS_PEER) && test_sta_flag(sta, WLAN_STA_ASSOC)) rate_control_rate_init(sta); layer2_update = sdata->vif.type == NL80211_IFTYPE_AP_VLAN || sdata->vif.type == NL80211_IFTYPE_AP; err = sta_info_insert_rcu(sta); if (err) { rcu_read_unlock(); return err; } if (layer2_update) cfg80211_send_layer2_update(sta->sdata->dev, sta->sta.addr); rcu_read_unlock(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'mac80211: Do not send Layer 2 Update frame before authorization The Layer 2 Update frame is used to update bridges when a station roams to another AP even if that STA does not transmit any frames after the reassociation. This behavior was described in IEEE Std 802.11F-2003 as something that would happen based on MLME-ASSOCIATE.indication, i.e., before completing 4-way handshake. However, this IEEE trial-use recommended practice document was published before RSN (IEEE Std 802.11i-2004) and as such, did not consider RSN use cases. Furthermore, IEEE Std 802.11F-2003 was withdrawn in 2006 and as such, has not been maintained amd should not be used anymore. Sending out the Layer 2 Update frame immediately after association is fine for open networks (and also when using SAE, FT protocol, or FILS authentication when the station is actually authenticated by the time association completes). However, it is not appropriate for cases where RSN is used with PSK or EAP authentication since the station is actually fully authenticated only once the 4-way handshake completes after authentication and attackers might be able to use the unauthenticated triggering of Layer 2 Update frame transmission to disrupt bridge behavior. Fix this by postponing transmission of the Layer 2 Update frame from station entry addition to the point when the station entry is marked authorized. Similarly, send out the VLAN binding update only if the STA entry has already been authorized. Signed-off-by: Jouni Malinen <jouni@codeaurora.org> Reviewed-by: Johannes Berg <johannes@sipsolutions.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: static int fill_dir_block(ext2_filsys fs, blk64_t *block_nr, e2_blkcnt_t blockcnt, blk64_t ref_block EXT2FS_ATTR((unused)), int ref_offset EXT2FS_ATTR((unused)), void *priv_data) { struct fill_dir_struct *fd = (struct fill_dir_struct *) priv_data; struct hash_entry *new_array, *ent; struct ext2_dir_entry *dirent; char *dir; unsigned int offset, dir_offset, rec_len, name_len; int hash_alg, hash_flags; if (blockcnt < 0) return 0; offset = blockcnt * fs->blocksize; if (offset + fs->blocksize > fd->inode->i_size) { fd->err = EXT2_ET_DIR_CORRUPTED; return BLOCK_ABORT; } dir = (fd->buf+offset); if (*block_nr == 0) { memset(dir, 0, fs->blocksize); dirent = (struct ext2_dir_entry *) dir; (void) ext2fs_set_rec_len(fs, fs->blocksize, dirent); } else { int flags = fs->flags; fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; fd->err = ext2fs_read_dir_block4(fs, *block_nr, dir, 0, fd->dir); fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); if (fd->err) return BLOCK_ABORT; } hash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL; hash_alg = fs->super->s_def_hash_version; if ((hash_alg <= EXT2_HASH_TEA) && (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH)) hash_alg += 3; /* While the directory block is "hot", index it. */ dir_offset = 0; while (dir_offset < fs->blocksize) { dirent = (struct ext2_dir_entry *) (dir + dir_offset); (void) ext2fs_get_rec_len(fs, dirent, &rec_len); name_len = ext2fs_dirent_name_len(dirent); if (((dir_offset + rec_len) > fs->blocksize) || (rec_len < 8) || ((rec_len % 4) != 0) || (name_len + 8 > rec_len)) { fd->err = EXT2_ET_DIR_CORRUPTED; return BLOCK_ABORT; } dir_offset += rec_len; if (dirent->inode == 0) continue; if (!fd->compress && (name_len == 1) && (dirent->name[0] == '.')) continue; if (!fd->compress && (name_len == 2) && (dirent->name[0] == '.') && (dirent->name[1] == '.')) { fd->parent = dirent->inode; continue; } if (fd->num_array >= fd->max_array) { new_array = realloc(fd->harray, sizeof(struct hash_entry) * (fd->max_array+500)); if (!new_array) { fd->err = ENOMEM; return BLOCK_ABORT; } fd->harray = new_array; fd->max_array += 500; } ent = fd->harray + fd->num_array++; ent->dir = dirent; fd->dir_size += EXT2_DIR_REC_LEN(name_len); ent->ino = dirent->inode; if (fd->compress) ent->hash = ent->minor_hash = 0; else { fd->err = ext2fs_dirhash2(hash_alg, dirent->name, name_len, fs->encoding, hash_flags, fs->super->s_hash_seed, &ent->hash, &ent->minor_hash); if (fd->err) return BLOCK_ABORT; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'e2fsck: abort if there is a corrupted directory block when rehashing In e2fsck pass 3a, when we are rehashing directories, at least in theory, all of the directories should have had corruptions with respect to directory entry structure fixed. However, it's possible (for example, if the user declined a fix) that we can reach this stage of processing with a corrupted directory entries. So check for that case and don't try to process a corrupted directory block so we don't run into trouble in mutate_name() if there is a zero-length file name. Addresses: TALOS-2019-0973 Addresses: CVE-2019-5188 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: inline int check(int itemSize, int nItems=1) { if (ptr + itemSize * nItems > end) { if (ptr + itemSize > end) return overrun(itemSize, nItems); nItems = (end - ptr) / itemSize; } return nItems; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide 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 copyBytes(InStream* is, int length) { while (length > 0) { int n = check(1, length); is->readBytes(ptr, n); ptr += n; length -= n; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: size_t recv_body(char* buf, size_t max) override { auto& message = parser.get(); auto& body_remaining = message.body(); body_remaining.data = buf; body_remaining.size = max; while (body_remaining.size && !parser.is_done()) { boost::system::error_code ec; http::async_read_some(stream, buffer, parser, yield[ec]); if (ec == http::error::partial_message || ec == http::error::need_buffer) { break; } if (ec) { ldout(cct, 4) << "failed to read body: " << ec.message() << dendl; throw rgw::io::Exception(ec.value(), std::system_category()); } } return max - body_remaining.size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'rgw: improve beast Avoid leaking connections that had partially-consumed client data on unexpected disconnect. Resolves CVE-2020-1700 (moderate impact flaw). Fixes: https://tracker.ceph.com/issues/42531 Signed-off-by: Or Friedmann <ofriedma@redhat.com> Signed-off-by: Matt Benjamin <mbenjamin@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 do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) { u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); unsigned long flags; u64 expires; /* confirm we're still not at a refresh boundary */ raw_spin_lock_irqsave(&cfs_b->lock, flags); cfs_b->slack_started = false; if (cfs_b->distribute_running) { raw_spin_unlock_irqrestore(&cfs_b->lock, flags); return; } if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) { raw_spin_unlock_irqrestore(&cfs_b->lock, flags); return; } if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) runtime = cfs_b->runtime; expires = cfs_b->runtime_expires; if (runtime) cfs_b->distribute_running = 1; raw_spin_unlock_irqrestore(&cfs_b->lock, flags); if (!runtime) return; runtime = distribute_cfs_runtime(cfs_b, runtime, expires); raw_spin_lock_irqsave(&cfs_b->lock, flags); if (expires == cfs_b->runtime_expires) lsub_positive(&cfs_b->runtime, runtime); cfs_b->distribute_running = 0; raw_spin_unlock_irqrestore(&cfs_b->lock, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices It has been observed, that highly-threaded, non-cpu-bound applications running under cpu.cfs_quota_us constraints can hit a high percentage of periods throttled while simultaneously not consuming the allocated amount of quota. This use case is typical of user-interactive non-cpu bound applications, such as those running in kubernetes or mesos when run on multiple cpu cores. This has been root caused to cpu-local run queue being allocated per cpu bandwidth slices, and then not fully using that slice within the period. At which point the slice and quota expires. This expiration of unused slice results in applications not being able to utilize the quota for which they are allocated. The non-expiration of per-cpu slices was recently fixed by 'commit 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition")'. Prior to that it appears that this had been broken since at least 'commit 51f2176d74ac ("sched/fair: Fix unlocked reads of some cfs_b->quota/period")' which was introduced in v3.16-rc1 in 2014. That added the following conditional which resulted in slices never being expired. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) { /* extend local deadline, drift is bounded above by 2 ticks */ cfs_rq->runtime_expires += TICK_NSEC; Because this was broken for nearly 5 years, and has recently been fixed and is now being noticed by many users running kubernetes (https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion that the mechanisms around expiring runtime should be removed altogether. This allows quota already allocated to per-cpu run-queues to live longer than the period boundary. This allows threads on runqueues that do not use much CPU to continue to use their remaining slice over a longer period of time than cpu.cfs_period_us. However, this helps prevent the above condition of hitting throttling while also not fully utilizing your cpu quota. This theoretically allows a machine to use slightly more than its allotted quota in some periods. This overflow would be bounded by the remaining quota left on each per-cpu runqueueu. This is typically no more than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will change nothing, as they should theoretically fully utilize all of their quota in each period. For user-interactive tasks as described above this provides a much better user/application experience as their cpu utilization will more closely match the amount they requested when they hit throttling. This means that cpu limits no longer strictly apply per period for non-cpu bound applications, but that they are still accurate over longer timeframes. This greatly improves performance of high-thread-count, non-cpu bound applications with low cfs_quota_us allocation on high-core-count machines. In the case of an artificial testcase (10ms/100ms of quota on 80 CPU machine), this commit resulted in almost 30x performance improvement, while still maintaining correct cpu quota restrictions. That testcase is available at https://github.com/indeedeng/fibtest. Fixes: 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition") Signed-off-by: Dave Chiluk <chiluk+linux@indeed.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Reviewed-by: Phil Auld <pauld@redhat.com> Reviewed-by: Ben Segall <bsegall@google.com> Cc: Ingo Molnar <mingo@redhat.com> Cc: John Hammond <jhammond@indeed.com> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Kyle Anderson <kwa@yelp.com> Cc: Gabriel Munos <gmunoz@netflix.com> Cc: Peter Oskolkov <posk@posk.io> Cc: Cong Wang <xiyou.wangcong@gmail.com> Cc: Brendan Gregg <bgregg@netflix.com> Link: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.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: lyd_new(struct lyd_node *parent, const struct lys_module *module, const char *name) { const struct lys_node *snode = NULL, *siblings; if ((!parent && !module) || !name) { LOGARG; return NULL; } siblings = lyd_new_find_schema(parent, module, 0); if (!siblings) { LOGARG; return NULL; } if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_CONTAINER | LYS_LIST | LYS_NOTIF | LYS_RPC | LYS_ACTION, &snode) || !snode) { LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".", name, lys_node_module(siblings)->name, siblings->name); return NULL; } return _lyd_new(parent, snode, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide 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 yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-119'], 'message': 'yang parser BUGFIX allocate more patterns than currently needed Fixes #740'</s>
<s>[INST] Given the following code containing errors, provide 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 __init cpia2_init(void) { LOG("%s v%s\n", ABOUT, CPIA_VERSION); check_parameters(); cpia2_usb_init(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'media: cpia2: Fix use-after-free in cpia2_exit Syzkaller report this: BUG: KASAN: use-after-free in sysfs_remove_file_ns+0x5f/0x70 fs/sysfs/file.c:468 Read of size 8 at addr ffff8881f59a6b70 by task syz-executor.0/8363 CPU: 0 PID: 8363 Comm: syz-executor.0 Not tainted 5.0.0-rc8+ #3 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 print_address_description+0x65/0x270 mm/kasan/report.c:187 kasan_report+0x149/0x18d mm/kasan/report.c:317 sysfs_remove_file_ns+0x5f/0x70 fs/sysfs/file.c:468 sysfs_remove_file include/linux/sysfs.h:519 [inline] driver_remove_file+0x40/0x50 drivers/base/driver.c:122 usb_remove_newid_files drivers/usb/core/driver.c:212 [inline] usb_deregister+0x12a/0x3b0 drivers/usb/core/driver.c:1005 cpia2_exit+0xa/0x16 [cpia2] __do_sys_delete_module kernel/module.c:1018 [inline] __se_sys_delete_module kernel/module.c:961 [inline] __x64_sys_delete_module+0x3dc/0x5e0 kernel/module.c:961 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f86f3754c58 EFLAGS: 00000246 ORIG_RAX: 00000000000000b0 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000020000300 RBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f86f37556bc R13: 00000000004bcca9 R14: 00000000006f6b48 R15: 00000000ffffffff Allocated by task 8363: set_track mm/kasan/common.c:85 [inline] __kasan_kmalloc.constprop.3+0xa0/0xd0 mm/kasan/common.c:495 kmalloc include/linux/slab.h:545 [inline] kzalloc include/linux/slab.h:740 [inline] bus_add_driver+0xc0/0x610 drivers/base/bus.c:651 driver_register+0x1bb/0x3f0 drivers/base/driver.c:170 usb_register_driver+0x267/0x520 drivers/usb/core/driver.c:965 0xffffffffc1b4817c do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe Freed by task 8363: set_track mm/kasan/common.c:85 [inline] __kasan_slab_free+0x130/0x180 mm/kasan/common.c:457 slab_free_hook mm/slub.c:1430 [inline] slab_free_freelist_hook mm/slub.c:1457 [inline] slab_free mm/slub.c:3005 [inline] kfree+0xe1/0x270 mm/slub.c:3957 kobject_cleanup lib/kobject.c:662 [inline] kobject_release lib/kobject.c:691 [inline] kref_put include/linux/kref.h:67 [inline] kobject_put+0x146/0x240 lib/kobject.c:708 bus_remove_driver+0x10e/0x220 drivers/base/bus.c:732 driver_unregister+0x6c/0xa0 drivers/base/driver.c:197 usb_register_driver+0x341/0x520 drivers/usb/core/driver.c:980 0xffffffffc1b4817c do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe The buggy address belongs to the object at ffff8881f59a6b40 which belongs to the cache kmalloc-256 of size 256 The buggy address is located 48 bytes inside of 256-byte region [ffff8881f59a6b40, ffff8881f59a6c40) The buggy address belongs to the page: page:ffffea0007d66980 count:1 mapcount:0 mapping:ffff8881f6c02e00 index:0x0 flags: 0x2fffc0000000200(slab) raw: 02fffc0000000200 dead000000000100 dead000000000200 ffff8881f6c02e00 raw: 0000000000000000 00000000800c000c 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8881f59a6a00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ffff8881f59a6a80: 00 00 00 00 00 00 00 00 00 00 fc fc fc fc fc fc >ffff8881f59a6b00: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb ^ ffff8881f59a6b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8881f59a6c00: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc cpia2_init does not check return value of cpia2_init, if it failed in usb_register_driver, there is already cleanup using driver_unregister. No need call cpia2_usb_cleanup on module exit. Reported-by: Hulk Robot <hulkci@huawei.com> Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+samsung@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: int i915_gem_context_open(struct drm_i915_private *i915, struct drm_file *file) { struct drm_i915_file_private *file_priv = file->driver_priv; struct i915_gem_context *ctx; int err; idr_init(&file_priv->context_idr); mutex_lock(&i915->drm.struct_mutex); ctx = i915_gem_create_context(i915); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err; } err = gem_context_register(ctx, file_priv); if (err) goto err_ctx; GEM_BUG_ON(ctx->user_handle != DEFAULT_CONTEXT_HANDLE); GEM_BUG_ON(i915_gem_context_is_kernel(ctx)); mutex_unlock(&i915->drm.struct_mutex); return 0; err_ctx: context_close(ctx); err: mutex_unlock(&i915->drm.struct_mutex); idr_destroy(&file_priv->context_idr); return PTR_ERR(ctx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'drm/i915: Introduce a mutex for file_priv->context_idr Define a mutex for the exclusive use of interacting with the per-file context-idr, that was previously guarded by struct_mutex. This allows us to reduce the coverage of struct_mutex, with a view to removing the last bits coordinating GEM context later. (In the short term, we avoid taking struct_mutex while using the extended constructor functions, preventing some nasty recursion.) v2: s/context_lock/context_idr_lock/ Signed-off-by: Chris Wilson <chris@chris-wilson.co.uk> Cc: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Reviewed-by: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Link: https://patchwork.freedesktop.org/patch/msgid/20190321140711.11190-2-chris@chris-wilson.co.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 void sfq_perturbation(struct timer_list *t) { struct sfq_sched_data *q = from_timer(q, t, perturb_timer); struct Qdisc *sch = q->sch; spinlock_t *root_lock = qdisc_lock(qdisc_root_sleeping(sch)); spin_lock(root_lock); q->perturbation = prandom_u32(); if (!q->filter_list && q->tail) sfq_rehash(sch); spin_unlock(root_lock); if (q->perturb_period) mod_timer(&q->perturb_timer, jiffies + q->perturb_period); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void sfb_init_perturbation(u32 slot, struct sfb_sched_data *q) { q->bins[slot].perturbation = prandom_u32(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.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: char* parseKey( char* ptr, FileNode& map_node, FileNode& value_placeholder ) { char c; char *endptr = ptr - 1, *saveptr; if( *ptr == '-' ) CV_PARSE_ERROR_CPP( "Key may not start with \'-\'" ); do c = *++endptr; while( cv_isprint(c) && c != ':' ); if( c != ':' ) CV_PARSE_ERROR_CPP( "Missing \':\'" ); saveptr = endptr + 1; do c = *--endptr; while( c == ' ' ); ++endptr; if( endptr == ptr ) CV_PARSE_ERROR_CPP( "An empty key" ); value_placeholder = fs->addNode(map_node, std::string(ptr, endptr - ptr), FileNode::NONE); ptr = saveptr; return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char* parseTag( char* ptr, std::string& tag_name, std::string& type_name, int& tag_type ) { if( *ptr == '\0' ) CV_PARSE_ERROR_CPP( "Unexpected end of the stream" ); if( *ptr != '<' ) CV_PARSE_ERROR_CPP( "Tag should start with \'<\'" ); ptr++; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); if( cv_isalnum(*ptr) || *ptr == '_' ) tag_type = CV_XML_OPENING_TAG; else if( *ptr == '/' ) { tag_type = CV_XML_CLOSING_TAG; ptr++; } else if( *ptr == '?' ) { tag_type = CV_XML_HEADER_TAG; ptr++; } else if( *ptr == '!' ) { tag_type = CV_XML_DIRECTIVE_TAG; assert( ptr[1] != '-' || ptr[2] != '-' ); ptr++; } else CV_PARSE_ERROR_CPP( "Unknown tag type" ); tag_name.clear(); type_name.clear(); for(;;) { char c, *endptr; if( !cv_isalpha(*ptr) && *ptr != '_' ) CV_PARSE_ERROR_CPP( "Name should start with a letter or underscore" ); endptr = ptr - 1; do c = *++endptr; while( cv_isalnum(c) || c == '_' || c == '-' ); std::string attrname(ptr, (size_t)(endptr - ptr)); ptr = endptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); if( tag_name.empty() ) tag_name = attrname; else { if( tag_type == CV_XML_CLOSING_TAG ) CV_PARSE_ERROR_CPP( "Closing tag should not contain any attributes" ); if( *ptr != '=' ) { ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG ); if( *ptr != '=' ) CV_PARSE_ERROR_CPP( "Attribute name should be followed by \'=\'" ); } c = *++ptr; if( c != '\"' && c != '\'' ) { ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG ); if( *ptr != '\"' && *ptr != '\'' ) CV_PARSE_ERROR_CPP( "Attribute value should be put into single or double quotes" ); } char quote = *ptr++; endptr = ptr; for(;;) { c = *endptr++; if( c == quote ) break; if( c == '\0' ) CV_PARSE_ERROR_CPP( "Unexpected end of line" ); } if( attrname == "type_id" ) { CV_Assert( type_name.empty() ); type_name = std::string(ptr, (size_t)(endptr - 1 - ptr)); } ptr = endptr; } c = *ptr; bool have_space = cv_isspace(c) || c == '\0'; if( c != '>' ) { ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG ); c = *ptr; } if( c == '>' ) { if( tag_type == CV_XML_HEADER_TAG ) CV_PARSE_ERROR_CPP( "Invalid closing tag for <?xml ..." ); ptr++; break; } else if( c == '?' && tag_type == CV_XML_HEADER_TAG ) { if( ptr[1] != '>' ) // FIXIT ptr[1] - out of bounds read without check CV_PARSE_ERROR_CPP( "Invalid closing tag for <?xml ..." ); ptr += 2; break; } else if( c == '/' && ptr[1] == '>' && tag_type == CV_XML_OPENING_TAG ) // FIXIT ptr[1] - out of bounds read without check { tag_type = CV_XML_EMPTY_TAG; ptr += 2; break; } if( !have_space ) CV_PARSE_ERROR_CPP( "There should be space between attributes" ); } return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipmi_fru_print(struct ipmi_intf * intf, struct sdr_record_fru_locator * fru) { char desc[17]; uint8_t bridged_request = 0; uint32_t save_addr; uint32_t save_channel; int rc = 0; if (!fru) return __ipmi_fru_print(intf, 0); /* Logical FRU Device * dev_type == 0x10 * modifier * 0x00 = IPMI FRU Inventory * 0x01 = DIMM Memory ID * 0x02 = IPMI FRU Inventory * 0x03 = System Processor FRU * 0xff = unspecified * * EEPROM 24C01 or equivalent * dev_type >= 0x08 && dev_type <= 0x0f * modifier * 0x00 = unspecified * 0x01 = DIMM Memory ID * 0x02 = IPMI FRU Inventory * 0x03 = System Processor Cartridge */ if (fru->dev_type != 0x10 && (fru->dev_type_modifier != 0x02 || fru->dev_type < 0x08 || fru->dev_type > 0x0f)) return -1; if (fru->dev_slave_addr == IPMI_BMC_SLAVE_ADDR && fru->device_id == 0) return 0; memset(desc, 0, sizeof(desc)); memcpy(desc, fru->id_string, fru->id_code & 0x01f); desc[fru->id_code & 0x01f] = 0; printf("FRU Device Description : %s (ID %d)\n", desc, fru->device_id); switch (fru->dev_type_modifier) { case 0x00: case 0x02: if (BRIDGE_TO_SENSOR(intf, fru->dev_slave_addr, fru->channel_num)) { bridged_request = 1; save_addr = intf->target_addr; intf->target_addr = fru->dev_slave_addr; save_channel = intf->target_channel; intf->target_channel = fru->channel_num; } /* print FRU */ rc = __ipmi_fru_print(intf, fru->device_id); if (bridged_request) { intf->target_addr = save_addr; intf->target_channel = save_channel; } break; case 0x01: rc = ipmi_spd_print_fru(intf, fru->device_id); break; default: if (verbose) printf(" Unsupported device 0x%02x " "type 0x%02x with modifier 0x%02x\n", fru->device_id, fru->dev_type, fru->dev_type_modifier); else printf(" Unsupported device\n"); } printf("\n"); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'fru, sdr: Fix id_string buffer overflows Final part of the fixes for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp 9 variants of stack buffer overflow when parsing `id_string` field of SDR records returned from `CMD_GET_SDR` command. SDR record structs have an `id_code` field, and an `id_string` `char` array. The length of `id_string` is calculated as `(id_code & 0x1f) + 1`, which can be larger than expected 16 characters (if `id_code = 0xff`, then length will be `(0xff & 0x1f) + 1 = 32`). In numerous places, this can cause stack buffer overflow when copying into fixed buffer of size `17` bytes from this calculated length.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddress) { ObjectAddress address; ObjectAddress refAddr; Relation rel; address = get_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object, &rel, AccessExclusiveLock, false); /* * If a relation was involved, it would have been opened and locked. We * don't need the relation here, but we'll retain the lock until commit. */ if (rel) table_close(rel, NoLock); refAddr = get_object_address(OBJECT_EXTENSION, (Node *) stmt->extname, &rel, AccessExclusiveLock, false); Assert(rel == NULL); if (refAddress) *refAddress = refAddr; recordDependencyOn(&address, &refAddr, DEPENDENCY_AUTO_EXTENSION); return address; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'Fix priv checks for ALTER <object> DEPENDS ON EXTENSION Marking an object as dependant on an extension did not have any privilege check whatsoever; this allowed any user to mark objects as droppable by anyone able to DROP EXTENSION, which could be used to cause system-wide havoc. Disallow by checking that the calling user owns the mentioned object. (No constraints are placed on the extension.) Security: CVE-2020-1720 Reported-by: Tom Lane Discussion: 31605.1566429043@sss.pgh.pa.us'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: choose_windows(s) const char *s; { register int i; for (i = 0; winchoices[i].procs; i++) { if ('+' == winchoices[i].procs->name[0]) continue; if ('-' == winchoices[i].procs->name[0]) continue; if (!strcmpi(s, winchoices[i].procs->name)) { windowprocs = *winchoices[i].procs; if (last_winchoice && last_winchoice->ini_routine) (*last_winchoice->ini_routine)(WININIT_UNDO); if (winchoices[i].ini_routine) (*winchoices[i].ini_routine)(WININIT); last_winchoice = &winchoices[i]; return; } } if (!windowprocs.win_raw_print) windowprocs.win_raw_print = def_raw_print; if (!windowprocs.win_wait_synch) /* early config file error processing routines call this */ windowprocs.win_wait_synch = def_wait_synch; if (!winchoices[0].procs) { raw_printf("No window types?"); nh_terminate(EXIT_FAILURE); } if (!winchoices[1].procs) { config_error_add( "Window type %s not recognized. The only choice is: %s", s, winchoices[0].procs->name); } else { char buf[BUFSZ]; boolean first = TRUE; buf[0] = '\0'; for (i = 0; winchoices[i].procs; i++) { if ('+' == winchoices[i].procs->name[0]) continue; if ('-' == winchoices[i].procs->name[0]) continue; Sprintf(eos(buf), "%s%s", first ? "" : ", ", winchoices[i].procs->name); first = FALSE; } config_error_add("Window type %s not recognized. Choices are: %s", s, buf); } if (windowprocs.win_raw_print == def_raw_print || WINDOWPORT("safe-startup")) nh_terminate(EXIT_SUCCESS); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-269'], 'message': 'command line triggered buffer overruns Prevent extremely long command line arguments from overflowing local buffers in raw_printf or config_error_add. The increased buffer sizes they recently got to deal with long configuration file values aren't sufficient to handle command line induced overflows. choose_windows(core): copy and truncate the window_type argument in case it gets passed to config_error_add(). process_options(unix): report bad values with "%.60s" so that vsprintf will implicitly truncate when formatted by raw_printf().'</s>
<s>[INST] Given the following code containing errors, provide 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 MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info, Image *image,Image *inject_image) { Image *group4_image; ImageInfo *write_info; MagickBooleanType status; size_t length; unsigned char *group4; status=MagickTrue; write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent); group4_image=CloneImage(inject_image,0,0,MagickTrue,&image->exception); if (group4_image == (Image *) NULL) return(MagickFalse); group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, &image->exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) return(MagickFalse); write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1542'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: regset_search_body_position_lead(OnigRegSet* set, const UChar* str, const UChar* end, const UChar* start, const UChar* range, /* match start range */ const UChar* orig_range, /* data range */ OnigOptionType option, MatchArg* msas, int* rmatch_pos) { int r, n, i; UChar *s, *prev; UChar *low, *high, *low_prev; UChar* sch_range; regex_t* reg; OnigEncoding enc; SearchRange* sr; n = set->n; enc = set->enc; s = (UChar* )start; if (s > str) prev = onigenc_get_prev_char_head(enc, str, s); else prev = (UChar* )NULL; sr = (SearchRange* )xmalloc(sizeof(*sr) * n); CHECK_NULL_RETURN_MEMERR(sr); for (i = 0; i < n; i++) { reg = set->rs[i].reg; sr[i].state = SRS_DEAD; if (reg->optimize != OPTIMIZE_NONE) { if (reg->dist_max != INFINITE_LEN) { if ((ptrdiff_t )(end - range) > (ptrdiff_t )reg->dist_max) sch_range = (UChar* )range + reg->dist_max; else sch_range = (UChar* )end; if (forward_search(reg, str, end, s, sch_range, &low, &high, &low_prev)) { sr[i].state = SRS_LOW_HIGH; sr[i].low = low; sr[i].high = high; sr[i].low_prev = low_prev; sr[i].sch_range = sch_range; } } else { sch_range = (UChar* )end; if (forward_search(reg, str, end, s, sch_range, &low, &high, (UChar** )NULL)) { goto total_active; } } } else { total_active: sr[i].state = SRS_ALL_RANGE; sr[i].low = s; sr[i].high = (UChar* )range; sr[i].low_prev = prev; } } #define ACTIVATE_ALL_LOW_HIGH_SEARCH_THRESHOLD_LEN 500 if (set->all_low_high != 0 && range - start > ACTIVATE_ALL_LOW_HIGH_SEARCH_THRESHOLD_LEN) { do { int try_count = 0; for (i = 0; i < n; i++) { if (sr[i].state == SRS_DEAD) continue; if (s < sr[i].low) continue; if (s >= sr[i].high) { if (forward_search(set->rs[i].reg, str, end, s, sr[i].sch_range, &low, &high, &low_prev) != 0) { sr[i].low = low; sr[i].high = high; sr[i].low_prev = low_prev; if (s < low) continue; } else { sr[i].state = SRS_DEAD; continue; } } reg = set->rs[i].reg; REGSET_MATCH_AND_RETURN_CHECK(orig_range); try_count++; } /* for (i) */ if (s >= range) break; if (try_count == 0) { low = (UChar* )range; for (i = 0; i < n; i++) { if (sr[i].state == SRS_LOW_HIGH && low > sr[i].low) { low = sr[i].low; low_prev = sr[i].low_prev; } } if (low == range) break; s = low; prev = low_prev; } else { prev = s; s += enclen(enc, s); } } while (1); } else { int prev_is_newline = 1; do { for (i = 0; i < n; i++) { if (sr[i].state == SRS_DEAD) continue; if (sr[i].state == SRS_LOW_HIGH) { if (s < sr[i].low) continue; if (s >= sr[i].high) { if (forward_search(set->rs[i].reg, str, end, s, sr[i].sch_range, &low, &high, &low_prev) != 0) { sr[i].low = low; sr[i].high = high; /* sr[i].low_prev = low_prev; */ if (s < low) continue; } else { sr[i].state = SRS_DEAD; continue; } } } reg = set->rs[i].reg; if ((reg->anchor & ANCR_ANYCHAR_INF) == 0 || prev_is_newline != 0) { REGSET_MATCH_AND_RETURN_CHECK(orig_range); } } if (s >= range) break; if (set->anychar_inf != 0) prev_is_newline = ONIGENC_IS_MBC_NEWLINE(set->enc, s, end); prev = s; s += enclen(enc, s); } while (1); } xfree(sr); return ONIG_MISMATCH; finish: xfree(sr); return r; match: xfree(sr); *rmatch_pos = (int )(s - str); return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'</s>
<s>[INST] Given the following code containing errors, provide 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 UnicodeStringTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char *par) { if (exec) logln("TestSuite UnicodeStringTest: "); TESTCASE_AUTO_BEGIN; TESTCASE_AUTO_CREATE_CLASS(StringCaseTest); TESTCASE_AUTO(TestBasicManipulation); TESTCASE_AUTO(TestCompare); TESTCASE_AUTO(TestExtract); TESTCASE_AUTO(TestRemoveReplace); TESTCASE_AUTO(TestSearching); TESTCASE_AUTO(TestSpacePadding); TESTCASE_AUTO(TestPrefixAndSuffix); TESTCASE_AUTO(TestFindAndReplace); TESTCASE_AUTO(TestBogus); TESTCASE_AUTO(TestReverse); TESTCASE_AUTO(TestMiscellaneous); TESTCASE_AUTO(TestStackAllocation); TESTCASE_AUTO(TestUnescape); TESTCASE_AUTO(TestCountChar32); TESTCASE_AUTO(TestStringEnumeration); TESTCASE_AUTO(TestNameSpace); TESTCASE_AUTO(TestUTF32); TESTCASE_AUTO(TestUTF8); TESTCASE_AUTO(TestReadOnlyAlias); TESTCASE_AUTO(TestAppendable); TESTCASE_AUTO(TestUnicodeStringImplementsAppendable); TESTCASE_AUTO(TestSizeofUnicodeString); TESTCASE_AUTO(TestStartsWithAndEndsWithNulTerminated); TESTCASE_AUTO(TestMoveSwap); TESTCASE_AUTO(TestUInt16Pointers); TESTCASE_AUTO(TestWCharPointers); TESTCASE_AUTO(TestNullPointers); TESTCASE_AUTO(TestUnicodeStringInsertAppendToSelf); TESTCASE_AUTO_END; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'ICU-20958 Prevent SEGV_MAPERR in append See #971'</s>
<s>[INST] Given the following code containing errors, provide 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 tight_fill_palette(VncState *vs, int x, int y, size_t count, uint32_t *bg, uint32_t *fg, VncPalette *palette) { int max; max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor; if (max < 2 && count >= tight_conf[vs->tight.compression].mono_min_rect_size) { max = 2; } if (max >= 256) { max = 256; } switch (vs->client_pf.bytes_per_pixel) { case 4: return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette); case 2: return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette); default: max = 2; return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_mono_rect(VncState *vs, int x, int y, int w, int h, uint32_t bg, uint32_t fg) { ssize_t bytes; int stream = 1; int level = tight_conf[vs->tight.compression].mono_zlib_level; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { int ret; int bpp = vs->client_pf.bytes_per_pixel * 8; VncPalette *palette = palette_new(2, bpp); palette_put(palette, bg); palette_put(palette, fg); ret = send_png_rect(vs, x, y, w, h, palette); palette_destroy(palette); return ret; } #endif bytes = DIV_ROUND_UP(w, 8) * h; vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4); vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE); vnc_write_u8(vs, 1); switch (vs->client_pf.bytes_per_pixel) { case 4: { uint32_t buf[2] = {bg, fg}; size_t ret = sizeof (buf); if (vs->tight.pixel24) { tight_pack24(vs, (unsigned char*)buf, 2, &ret); } vnc_write(vs, buf, ret); tight_encode_mono_rect32(vs->tight.tight.buffer, w, h, bg, fg); break; } case 2: vnc_write(vs, &bg, 2); vnc_write(vs, &fg, 2); tight_encode_mono_rect16(vs->tight.tight.buffer, w, h, bg, fg); break; default: vnc_write_u8(vs, bg); vnc_write_u8(vs, fg); tight_encode_mono_rect8(vs->tight.tight.buffer, w, h, bg, fg); break; } vs->tight.tight.offset = bytes; bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY); return (bytes >= 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings) { int i; unsigned int enc = 0; vs->features = 0; vs->vnc_encoding = 0; vs->tight.compression = 9; vs->tight.quality = -1; /* Lossless by default */ vs->absolute = -1; /* * Start from the end because the encodings are sent in order of preference. * This way the preferred encoding (first encoding defined in the array) * will be set at the end of the loop. */ for (i = n_encodings - 1; i >= 0; i--) { enc = encodings[i]; switch (enc) { case VNC_ENCODING_RAW: vs->vnc_encoding = enc; break; case VNC_ENCODING_COPYRECT: vs->features |= VNC_FEATURE_COPYRECT_MASK; break; case VNC_ENCODING_HEXTILE: vs->features |= VNC_FEATURE_HEXTILE_MASK; vs->vnc_encoding = enc; break; case VNC_ENCODING_TIGHT: vs->features |= VNC_FEATURE_TIGHT_MASK; vs->vnc_encoding = enc; break; #ifdef CONFIG_VNC_PNG case VNC_ENCODING_TIGHT_PNG: vs->features |= VNC_FEATURE_TIGHT_PNG_MASK; vs->vnc_encoding = enc; break; #endif case VNC_ENCODING_ZLIB: vs->features |= VNC_FEATURE_ZLIB_MASK; vs->vnc_encoding = enc; break; case VNC_ENCODING_ZRLE: vs->features |= VNC_FEATURE_ZRLE_MASK; vs->vnc_encoding = enc; break; case VNC_ENCODING_ZYWRLE: vs->features |= VNC_FEATURE_ZYWRLE_MASK; vs->vnc_encoding = enc; break; case VNC_ENCODING_DESKTOPRESIZE: vs->features |= VNC_FEATURE_RESIZE_MASK; break; case VNC_ENCODING_POINTER_TYPE_CHANGE: vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK; break; case VNC_ENCODING_RICH_CURSOR: vs->features |= VNC_FEATURE_RICH_CURSOR_MASK; if (vs->vd->cursor) { vnc_cursor_define(vs); } break; case VNC_ENCODING_EXT_KEY_EVENT: send_ext_key_event_ack(vs); break; case VNC_ENCODING_AUDIO: send_ext_audio_ack(vs); break; case VNC_ENCODING_WMVi: vs->features |= VNC_FEATURE_WMVI_MASK; break; case VNC_ENCODING_LED_STATE: vs->features |= VNC_FEATURE_LED_STATE_MASK; break; case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9: vs->tight.compression = (enc & 0x0F); break; case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9: if (vs->vd->lossy) { vs->tight.quality = (enc & 0x0F); } break; default: VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc); break; } } vnc_desktop_resize(vs); check_pointer_type_change(&vs->mouse_mode_notifier, NULL); vnc_led_state_change(vs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tight_init_stream(VncState *vs, int stream_id, int level, int strategy) { z_streamp zstream = &vs->tight.stream[stream_id]; if (zstream->opaque == NULL) { int err; VNC_DEBUG("VNC: TIGHT: initializing zlib stream %d\n", stream_id); VNC_DEBUG("VNC: TIGHT: opaque = %p | vs = %p\n", zstream->opaque, vs); zstream->zalloc = vnc_zlib_zalloc; zstream->zfree = vnc_zlib_zfree; err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS, MAX_MEM_LEVEL, strategy); if (err != Z_OK) { fprintf(stderr, "VNC: error initializing zlib\n"); return -1; } vs->tight.levels[stream_id] = level; zstream->opaque = vs; } if (vs->tight.levels[stream_id] != level) { if (deflateParams(zstream, level, strategy) != Z_OK) { return -1; } vs->tight.levels[stream_id] = level; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_arg(struct compiling *c, const node *n) { identifier name; expr_ty annotation = NULL; node *ch; arg_ty ret; assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef); ch = CHILD(n, 0); name = NEW_IDENTIFIER(ch); if (!name) return NULL; if (forbidden_name(c, name, ch, 0)) return NULL; if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) { annotation = ast_for_expr(c, CHILD(n, 2)); if (!annotation) return NULL; } ret = arg(name, annotation, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!ret) return NULL; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize) /*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/ { PyObject *source_copy; const char *str; int compile_mode = -1; int is_ast; PyCompilerFlags cf; int start[] = {Py_file_input, Py_eval_input, Py_single_input}; PyObject *result; cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8; if (flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) { PyErr_SetString(PyExc_ValueError, "compile(): unrecognised flags"); goto error; } /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ if (optimize < -1 || optimize > 2) { PyErr_SetString(PyExc_ValueError, "compile(): invalid optimize value"); goto error; } if (!dont_inherit) { PyEval_MergeCompilerFlags(&cf); } if (strcmp(mode, "exec") == 0) compile_mode = 0; else if (strcmp(mode, "eval") == 0) compile_mode = 1; else if (strcmp(mode, "single") == 0) compile_mode = 2; else { PyErr_SetString(PyExc_ValueError, "compile() mode must be 'exec', 'eval' or 'single'"); goto error; } is_ast = PyAST_Check(source); if (is_ast == -1) goto error; if (is_ast) { if (flags & PyCF_ONLY_AST) { Py_INCREF(source); result = source; } else { PyArena *arena; mod_ty mod; arena = PyArena_New(); if (arena == NULL) goto error; mod = PyAST_obj2mod(source, arena, compile_mode); if (mod == NULL) { PyArena_Free(arena); goto error; } if (!PyAST_Validate(mod)) { PyArena_Free(arena); goto error; } result = (PyObject*)PyAST_CompileObject(mod, filename, &cf, optimize, arena); PyArena_Free(arena); } goto finally; } str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy); if (str == NULL) goto error; result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize); Py_XDECREF(source_copy); goto finally; error: result = NULL; finally: Py_DECREF(filename); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_for_stmt(struct compiling *c, const node *n0, bool is_async) { const node * const n = is_async ? CHILD(n0, 1) : n0; asdl_seq *_target, *seq = NULL, *suite_seq; expr_ty expression; expr_ty target, first; const node *node_target; int end_lineno, end_col_offset; /* for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] */ REQ(n, for_stmt); if (NCH(n) == 9) { seq = ast_for_suite(c, CHILD(n, 8)); if (!seq) return NULL; } node_target = CHILD(n, 1); _target = ast_for_exprlist(c, node_target, Store); if (!_target) return NULL; /* Check the # of children rather than the length of _target, since for x, in ... has 1 element in _target, but still requires a Tuple. */ first = (expr_ty)asdl_seq_GET(_target, 0); if (NCH(node_target) == 1) target = first; else target = Tuple(_target, Store, first->lineno, first->col_offset, node_target->n_end_lineno, node_target->n_end_col_offset, c->c_arena); expression = ast_for_testlist(c, CHILD(n, 3)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 5)); if (!suite_seq) return NULL; if (seq != NULL) { get_last_end_pos(seq, &end_lineno, &end_col_offset); } else { get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); } if (is_async) return AsyncFor(target, expression, suite_seq, seq, LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena); else return For(target, expression, suite_seq, seq, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_import_stmt(struct compiling *c, const node *n) { /* import_stmt: import_name | import_from import_name: 'import' dotted_as_names import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+) 'import' ('*' | '(' import_as_names ')' | import_as_names) */ int lineno; int col_offset; int i; asdl_seq *aliases; REQ(n, import_stmt); lineno = LINENO(n); col_offset = n->n_col_offset; n = CHILD(n, 0); if (TYPE(n) == import_name) { n = CHILD(n, 1); REQ(n, dotted_as_names); aliases = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!aliases) return NULL; for (i = 0; i < NCH(n); i += 2) { alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, i / 2, import_alias); } // Even though n is modified above, the end position is not changed return Import(aliases, lineno, col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (TYPE(n) == import_from) { int n_children; int idx, ndots = 0; const node *n_copy = n; alias_ty mod = NULL; identifier modname = NULL; /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { if (TYPE(CHILD(n, idx)) == dotted_name) { mod = alias_for_import_name(c, CHILD(n, idx), 0); if (!mod) return NULL; idx++; break; } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) { /* three consecutive dots are tokenized as one ELLIPSIS */ ndots += 3; continue; } else if (TYPE(CHILD(n, idx)) != DOT) { break; } ndots++; } idx++; /* skip over the 'import' keyword */ switch (TYPE(CHILD(n, idx))) { case STAR: /* from ... import * */ n = CHILD(n, idx); n_children = 1; break; case LPAR: /* from ... import (x, y, z) */ n = CHILD(n, idx + 1); n_children = NCH(n); break; case import_as_names: /* from ... import x, y, z */ n = CHILD(n, idx); n_children = NCH(n); if (n_children % 2 == 0) { ast_error(c, n, "trailing comma not allowed without" " surrounding parentheses"); return NULL; } break; default: ast_error(c, n, "Unexpected node-type in from-import"); return NULL; } aliases = _Py_asdl_seq_new((n_children + 1) / 2, c->c_arena); if (!aliases) return NULL; /* handle "from ... import *" special b/c there's no children */ if (TYPE(n) == STAR) { alias_ty import_alias = alias_for_import_name(c, n, 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, 0, import_alias); } else { for (i = 0; i < NCH(n); i += 2) { alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, i / 2, import_alias); } } if (mod != NULL) modname = mod->name; return ImportFrom(modname, aliases, ndots, lineno, col_offset, n_copy->n_end_lineno, n_copy->n_end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unknown import statement: starts with command '%s'", STR(CHILD(n, 0))); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>