text
stringlengths
486
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int install_permanent_handler(int num_cpus, uintptr_t smbase, size_t smsize, size_t save_state_size) { /* There are num_cpus concurrent stacks and num_cpus concurrent save * state areas. Lastly, set the stack size to 1KiB. */ struct smm_loader_params smm_params = { .per_cpu_stack_size = CONFIG_SMM_MODULE_STACK_SIZE, .num_concurrent_stacks = num_cpus, .per_cpu_save_state_size = save_state_size, .num_concurrent_save_states = num_cpus, }; /* Allow callback to override parameters. */ if (mp_state.ops.adjust_smm_params != NULL) mp_state.ops.adjust_smm_params(&smm_params, 1); printk(BIOS_DEBUG, "Installing SMM handler to 0x%08lx\n", smbase); if (smm_load_module((void *)smbase, smsize, &smm_params)) return -1; adjust_smm_apic_id_map(&smm_params); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'cpu/x86/smm: Introduce SMM module loader version 2 Xeon-SP Skylake Scalable Processor can have 36 CPU threads (18 cores). Current coreboot SMM is unable to handle more than ~32 CPU threads. This patch introduces a version 2 of the SMM module loader which addresses this problem. Having two versions of the SMM module loader prevents any issues to current projects. Future Xeon-SP products will be using this version of the SMM loader. Subsequent patches will enable board specific functionality for Xeon-SP. The reason for moving to version 2 is the state save area begins to encroach upon the SMI handling code when more than 32 CPU threads are in the system. This can cause system hangs, reboots, etc. The second change is related to staggered entry points with simple near jumps. In the current loader, near jumps will not work because the CPU is jumping within the same code segment. In version 2, "far" address jumps are necessary therefore protected mode must be enabled first. The SMM layout and how the CPUs are staggered are documented in the code. By making the modifications above, this allows the smm module loader to expand easily as more CPU threads are added. TEST=build for Tiogapass platform under OCP mainboard. Enable the following in Kconfig. select CPU_INTEL_COMMON_SMM select SOC_INTEL_COMMON_BLOCK_SMM select SMM_TSEG select HAVE_SMI_HANDLER select ACPI_INTEL_HARDWARE_SLEEP_VALUES Debug console will show all 36 cores relocated. Further tested by generating SMI's to port 0xb2 using XDP/ITP HW debugger and ensured all cores entering and exiting SMM properly. In addition, booted to Linux 5.4 kernel and observed no issues during mp init. Change-Id: I00a23a5f2a46110536c344254868390dbb71854c Signed-off-by: Rocky Phagura <rphagura@fb.com> Reviewed-on: https://review.coreboot.org/c/coreboot/+/43684 Tested-by: build bot (Jenkins) <no-reply@coreboot.org> Reviewed-by: Angel Pons <th3fanbus@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; // H.264 uses edge emulation for out of frame motion vectors, for this // it requires a temporary area large enough to hold a 21x21 block, // increasing witdth ensure that the temporary area is large enough, // the next rounded up width is 32 *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/utils: correct align value for interplay Fixes out of array access Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg 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: init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj) { switch (mrb_type(obj)) { case MRB_TT_CLASS: case MRB_TT_MODULE: copy_class(mrb, dest, obj); mrb_iv_copy(mrb, dest, obj); mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__")); break; case MRB_TT_OBJECT: case MRB_TT_SCLASS: case MRB_TT_HASH: case MRB_TT_DATA: case MRB_TT_EXCEPTION: mrb_iv_copy(mrb, dest, obj); break; case MRB_TT_ISTRUCT: mrb_istruct_copy(dest, obj); break; default: break; } mrb_funcall(mrb, dest, "initialize_copy", 1, obj); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-824'], 'message': 'Should not call `initialize_copy` for `TT_ICLASS`; fix #4027 Since `TT_ICLASS` is a internal object that should never be revealed to Ruby world.'</s>
<s>[INST] Given the following code containing errors, provide 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::wstring CreateUniqueTempDirectory() { // We need to put downloaded updates into a directory of their own, because // if we put it in $TMP, some DLLs could be there and interfere with the // installer. // // This code creates a new randomized directory name and tries to create it; // this process is repeated if the directory already exists. wchar_t tmpdir[MAX_PATH+1]; if ( GetTempPath(MAX_PATH+1, tmpdir) == 0 ) throw Win32Exception("Cannot create temporary directory"); for ( ;; ) { std::wstring dir(tmpdir); dir += L"Update-"; UUID uuid; UuidCreate(&uuid); RPC_WSTR uuidStr; RPC_STATUS status = UuidToString(&uuid, &uuidStr); dir += reinterpret_cast<wchar_t*>(uuidStr); RpcStringFree(&uuidStr); if ( CreateDirectory(dir.c_str(), NULL) ) return dir; else if ( GetLastError() != ERROR_ALREADY_EXISTS ) throw Win32Exception("Cannot create temporary directory"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-426', 'CWE-401'], 'message': 'Verify UpdateTempDir isn't maliciously modified Don't just delete the stored updates temporary directory on launch, but validate the registry key to ensure it is in an expected location and follows WinSparkle's naming convention. This is to prevent malicious users from modifying this registry key and forcing the host app to delete arbitrary directories (a user being able to delete the key would be able to delete the directory themselves, so it's not a serious issue, but it nevertheless is bad behavior and shouldn't be possible).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: extern "C" void *malloc_wrapper(size_t size, void *caller) { void *ptr = NULL; #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); #endif #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); alloc_info_t *alloc_info = (alloc_info_t *)SUPER_MALLOC(size + sizeof(alloc_info_t)); if (alloc_info != NULL) { alloc_info->size = size; alloc_info->signature = MBED_HEAP_STATS_SIGNATURE; ptr = (void *)(alloc_info + 1); heap_stats.current_size += size; heap_stats.total_size += size; heap_stats.alloc_cnt += 1; if (heap_stats.current_size > heap_stats.max_size) { heap_stats.max_size = heap_stats.current_size; } heap_stats.overhead_size += MALLOC_HEAP_TOTAL_SIZE(MALLOC_HEADER_PTR(alloc_info)) - size; } else { heap_stats.alloc_fail_cnt += 1; } malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED ptr = SUPER_MALLOC(size); #endif // #ifdef MBED_HEAP_STATS_ENABLED #ifdef MBED_MEM_TRACING_ENABLED mbed_mem_trace_malloc(ptr, size, caller); mbed_mem_trace_unlock(); #endif // #ifdef MBED_MEM_TRACING_ENABLED return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Add integer overflow check to the malloc wrappers Add a check that the combined size of the buffer to allocate and alloc_info_t does not exceed the maximum integer value representable by size_t.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: escapes(cp, tp) const char *cp; char *tp; { while (*cp) { int cval = 0, meta = 0; if (*cp == '\\' && cp[1] && index("mM", cp[1]) && cp[2]) { meta = 1; cp += 2; } if (*cp == '\\' && cp[1] && index("0123456789xXoO", cp[1]) && cp[2]) { NEARDATA const char hex[] = "00112233445566778899aAbBcCdDeEfF"; const char *dp; int dcount = 0; cp++; if (*cp == 'x' || *cp == 'X') for (++cp; *cp && (dp = index(hex, *cp)) && (dcount++ < 2); cp++) cval = (cval * 16) + ((int)(dp - hex) / 2); else if (*cp == 'o' || *cp == 'O') for (++cp; *cp && (index("01234567",*cp)) && (dcount++ < 3); cp++) cval = (cval * 8) + (*cp - '0'); else for (; *cp && (index("0123456789",*cp)) && (dcount++ < 3); cp++) cval = (cval * 10) + (*cp - '0'); } else if (*cp == '\\' && cp[1]) { /* C-style character escapes */ switch (*++cp) { case '\\': cval = '\\'; break; case 'n': cval = '\n'; break; case 't': cval = '\t'; break; case 'b': cval = '\b'; break; case 'r': cval = '\r'; break; default: cval = *cp; } cp++; } else if (*cp == '^' && cp[1]) { /* expand control-character syntax */ cval = (*++cp & 0x1f); cp++; } else cval = *cp++; if (meta) cval |= 0x80; *tp++ = cval; } *tp = '\0'; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'escapes() revamp Partial rewrite of escapes(), mostly changing its if-then-else logic so that end-of-string can be checked once instead for each case. The previous version had a bug if the input string ended with backslash and one decimal digit (due to being lumped together with the handling for trailing \X or \O).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor* inputs; const Tensor* labels_indices; const Tensor* labels_values; const Tensor* seq_len; OP_REQUIRES_OK(ctx, ctx->input("inputs", &inputs)); OP_REQUIRES_OK(ctx, ctx->input("labels_indices", &labels_indices)); OP_REQUIRES_OK(ctx, ctx->input("labels_values", &labels_values)); OP_REQUIRES_OK(ctx, ctx->input("sequence_length", &seq_len)); OP_REQUIRES(ctx, inputs->shape().dims() == 3, errors::InvalidArgument("inputs is not a 3-Tensor")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(seq_len->shape()), errors::InvalidArgument("sequence_length is not a vector")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(labels_indices->shape()), errors::InvalidArgument("labels_indices is not a matrix")); OP_REQUIRES(ctx, labels_indices->dim_size(1) > 1, errors::InvalidArgument( "labels_indices second dimension must be >= 1. Received ", labels_indices->dim_size(1))); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(labels_values->shape()), errors::InvalidArgument("labels_values is not a vector")); const TensorShape& inputs_shape = inputs->shape(); const int64 max_time = inputs_shape.dim_size(0); const int64 batch_size = inputs_shape.dim_size(1); const int64 num_classes_raw = inputs_shape.dim_size(2); OP_REQUIRES( ctx, FastBoundsCheck(num_classes_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("num_classes cannot exceed max int")); const int num_classes = static_cast<const int>(num_classes_raw); OP_REQUIRES( ctx, batch_size == seq_len->dim_size(0), errors::InvalidArgument("len(sequence_length) != batch_size. ", "len(sequence_length): ", seq_len->dim_size(0), " batch_size: ", batch_size)); auto seq_len_t = seq_len->vec<int32>(); OP_REQUIRES(ctx, labels_indices->dim_size(0) == labels_values->dim_size(0), errors::InvalidArgument( "labels_indices and labels_values must contain the " "same number of rows, but saw shapes: ", labels_indices->shape().DebugString(), " vs. ", labels_values->shape().DebugString())); OP_REQUIRES(ctx, batch_size != 0, errors::InvalidArgument("batch_size must not be 0")); // Figure out the maximum label length to use as sparse tensor dimension. auto labels_indices_t = labels_indices->matrix<int64>(); int64 max_label_len = 0; for (int i = 0; i < labels_indices->dim_size(0); i++) { max_label_len = std::max(max_label_len, labels_indices_t(i, 1) + 1); } TensorShape labels_shape({batch_size, max_label_len}); std::vector<int64> order{0, 1}; sparse::SparseTensor labels_sp; OP_REQUIRES_OK( ctx, sparse::SparseTensor::Create(*labels_indices, *labels_values, labels_shape, order, &labels_sp)); Status labels_sp_valid = labels_sp.IndicesValid(); OP_REQUIRES(ctx, labels_sp_valid.ok(), errors::InvalidArgument("label SparseTensor is not valid: ", labels_sp_valid.error_message())); typename ctc::CTCLossCalculator<T>::LabelSequences labels_t(batch_size); for (const auto& g : labels_sp.group({0})) { // iterate by batch const int64 batch_indices = g.group()[0]; OP_REQUIRES(ctx, FastBoundsCheck(batch_indices, batch_size), errors::InvalidArgument("labels batch index must be between ", 0, " and ", batch_size, " but saw: ", batch_indices)); auto values = g.values<int32>(); std::vector<int>* b_values = &labels_t[batch_indices]; b_values->resize(values.size()); for (int i = 0; i < values.size(); ++i) (*b_values)[i] = values(i); } OP_REQUIRES(ctx, static_cast<size_t>(batch_size) == labels_t.size(), errors::InvalidArgument("len(labels) != batch_size. ", "len(labels): ", labels_t.size(), " batch_size: ", batch_size)); for (int64 b = 0; b < batch_size; ++b) { OP_REQUIRES( ctx, seq_len_t(b) <= max_time, errors::InvalidArgument("sequence_length(", b, ") <= ", max_time)); } Tensor* loss = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output("loss", seq_len->shape(), &loss)); auto loss_t = loss->vec<T>(); Tensor* gradient; OP_REQUIRES_OK(ctx, ctx->allocate_output("gradient", inputs_shape, &gradient)); auto gradient_t = gradient->tensor<T, 3>(); auto inputs_t = inputs->tensor<T, 3>(); std::vector<OutputMap> gradient_list_t; std::vector<InputMap> input_list_t; for (std::size_t t = 0; t < max_time; ++t) { input_list_t.emplace_back(inputs_t.data() + t * batch_size * num_classes, batch_size, num_classes); gradient_list_t.emplace_back( gradient_t.data() + t * batch_size * num_classes, batch_size, num_classes); } gradient_t.setZero(); // Assumption: the blank index is num_classes - 1 ctc::CTCLossCalculator<T> ctc_loss_calculator(num_classes - 1, 0); DeviceBase::CpuWorkerThreads workers = *ctx->device()->tensorflow_cpu_worker_threads(); OP_REQUIRES_OK(ctx, ctc_loss_calculator.CalculateLoss( seq_len_t, labels_t, input_list_t, preprocess_collapse_repeated_, ctc_merge_repeated_, ignore_longer_outputs_than_inputs_, &loss_t, &gradient_list_t, &workers)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-665'], 'message': 'Fix nullptr deref in `tf.raw_ops.CTCLoss`. PiperOrigin-RevId: 372266334 Change-Id: Ic52c3e9f13a38f54482d670907eda1688450862b'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr) { InitializeCriticalSection(mutex); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Make pthread_mutex static initialisation work on Windows. This takes the dynamic initialisation code added to CRYPTO_lock() in e5081719 and applies it to the Window's pthread_mutex implementation. This allows for PTHREAD_MUTEX_INITIALIZER to be used on Windows. bcook has agreed to place this code in the public domain (as per the rest of the code in pthread.h).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int db_interception(struct vcpu_svm *svm) { struct kvm_run *kvm_run = svm->vcpu.run; if (!(svm->vcpu.guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) && !svm->nmi_singlestep) { kvm_queue_exception(&svm->vcpu, DB_VECTOR); return 1; } if (svm->nmi_singlestep) { svm->nmi_singlestep = false; if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) svm->vmcb->save.rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF); update_db_bp_intercept(&svm->vcpu); } if (svm->vcpu.guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) { kvm_run->exit_reason = KVM_EXIT_DEBUG; kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip; kvm_run->debug.arch.exception = DB_VECTOR; return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-399'], 'message': 'KVM: svm: unconditionally intercept #DB This is needed to avoid the possibility that the guest triggers an infinite stream of #DB exceptions (CVE-2015-8104). VMX is not affected: because it does not save DR6 in the VMCS, it already intercepts #DB unconditionally. Reported-by: Jan Beulich <jbeulich@suse.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: static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; if (s->has_alpha) avctx->pix_fmt = AV_PIX_FMT_YUVA420P; } s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <rsbultje@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status GetMatchingPaths(FileSystem* fs, Env* env, const string& pattern, std::vector<string>* results) { results->clear(); if (pattern.empty()) { return Status::OK(); } string fixed_prefix = pattern.substr(0, pattern.find_first_of("*?[\\")); string eval_pattern = pattern; string dir(io::Dirname(fixed_prefix)); // If dir is empty then we need to fix up fixed_prefix and eval_pattern to // include . as the top level directory. if (dir.empty()) { dir = "."; fixed_prefix = io::JoinPath(dir, fixed_prefix); eval_pattern = io::JoinPath(dir, eval_pattern); } bool is_directory = pattern[pattern.size() - 1] == '/'; #ifdef PLATFORM_WINDOWS is_directory = is_directory || pattern[pattern.size() - 1] == '\\'; #endif std::vector<string> dirs; if (!is_directory) { dirs.emplace_back(eval_pattern); } StringPiece tmp_dir(io::Dirname(eval_pattern)); while (tmp_dir.size() > dir.size()) { dirs.emplace_back(string(tmp_dir)); tmp_dir = io::Dirname(tmp_dir); } dirs.emplace_back(dir); std::reverse(dirs.begin(), dirs.end()); // Setup a parallel BFS to explore everything under dir. std::deque<std::pair<string, int>> dir_q; std::deque<std::pair<string, int>> next_dir_q; dir_q.emplace_back(std::make_pair(dirs[0], 0)); Status ret; // Status to return. mutex results_mutex; condition_variable results_cond; mutex next_que_mutex; condition_variable next_que_cond; while (!dir_q.empty()) { next_dir_q.clear(); std::vector<Status> new_rets(dir_q.size()); auto handle_level = [fs, &results, &dir_q, &next_dir_q, &new_rets, &is_directory, &dirs, &results_mutex, &results_cond, &next_que_mutex, &next_que_cond](int i) { string current_dir = dir_q.at(i).first; int dir_index = dir_q.at(i).second; dir_index++; std::vector<string> children; Status s = fs->GetChildren(current_dir, &children); // In case PERMISSION_DENIED is encountered, we bail here. if (s.code() == tensorflow::error::PERMISSION_DENIED) { return; } new_rets[i] = s; if (children.empty()) return; // children_dir_status holds is_dir status for children. It can have three // possible values: OK for true; FAILED_PRECONDITION for false; CANCELLED // if we don't calculate IsDirectory (we might do that because there isn't // any point in exploring that child path). std::vector<Status> children_dir_status; // This IsDirectory call can be expensive for some FS. Parallelizing it. children_dir_status.resize(children.size()); auto handle_children = [fs, &current_dir, &children, &dirs, dir_index, is_directory, &children_dir_status](int j) { const string child_path = io::JoinPath(current_dir, children[j]); if (!fs->Match(child_path, dirs[dir_index])) { children_dir_status[j] = Status(tensorflow::error::CANCELLED, "Operation not needed"); } else if (dir_index != dirs.size() - 1) { children_dir_status[j] = fs->IsDirectory(child_path); } else { children_dir_status[j] = is_directory ? fs->IsDirectory(child_path) : Status::OK(); } }; ForEach(0, children.size(), handle_children); for (size_t j = 0; j < children.size(); ++j) { const string child_path = io::JoinPath(current_dir, children[j]); // If the IsDirectory call was cancelled we bail. if (children_dir_status[j].code() == tensorflow::error::CANCELLED) { continue; } if (children_dir_status[j].ok()) { if (dir_index != dirs.size() - 1) { mutex_lock lk(next_que_mutex); next_dir_q.emplace_back(std::make_pair(child_path, dir_index)); next_que_cond.notify_one(); } else { mutex_lock lk(results_mutex); results->emplace_back(child_path); results_cond.notify_one(); } } } }; ForEach(0, dir_q.size(), handle_level); ret.Update(new_rets[dir_q.size() - 1]); std::swap(dir_q, next_dir_q); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Completely rewrite `GetMatchingPaths`. The current parallel implementation is too complex (lambda inside lambda, two levels of parallelism) and has a read outside of bounds issue. The new implementation cleans up artifacts from the previous implementations that were left in the code as it evolves. We add multiple helper functions, and document invariants and preconditions as well as every major step. This way, we fix the security issue and a potential new one which was not caught before PiperOrigin-RevId: 346146220 Change-Id: Iec0f44673f43349797bf9944dffe9b2f779137d8'</s>
<s>[INST] Given the following code containing errors, provide 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 TransposeShapeFn(InferenceContext* c) { ShapeHandle input = c->input(0); ShapeHandle perm_shape = c->input(1); const Tensor* perm = c->input_tensor(1); DimensionHandle perm_elems = c->NumElements(perm_shape); // If we don't have rank information on the input or value information on // perm we can't return any shape information, otherwise we have enough // information to at least find the rank of the output. if (!c->RankKnown(input) && !c->ValueKnown(perm_elems) && perm == nullptr) { c->set_output(0, c->UnknownShape()); return Status::OK(); } // Find our value of the rank. int64_t rank; if (c->RankKnown(input)) { rank = c->Rank(input); } else if (c->ValueKnown(perm_elems)) { rank = c->Value(perm_elems); } else { rank = perm->NumElements(); } if (!c->RankKnown(input) && rank < 2) { // A permutation array containing a single element is ambiguous. It could // indicate either a scalar or a 1-dimensional array, both of which the // transpose op returns unchanged. c->set_output(0, input); return Status::OK(); } std::vector<DimensionHandle> dims; dims.resize(rank); TF_RETURN_IF_ERROR(c->WithRank(input, rank, &input)); // Ensure that perm is a vector and has rank elements. TF_RETURN_IF_ERROR(c->WithRank(perm_shape, 1, &perm_shape)); TF_RETURN_IF_ERROR(c->WithValue(perm_elems, rank, &perm_elems)); // If we know the rank of the input and the value of perm, we can return // all shape information, otherwise we can only return rank information, // but no information for the dimensions. if (perm != nullptr) { std::vector<int64_t> data; if (perm->dtype() == DT_INT32) { data = AsInt64<int32>(perm, rank); } else { data = AsInt64<int64_t>(perm, rank); } for (int32_t i = 0; i < rank; ++i) { int64_t in_idx = data[i]; if (in_idx >= rank) { return errors::InvalidArgument("perm dim ", in_idx, " is out of range of input rank ", rank); } dims[i] = c->Dim(input, in_idx); } } else { for (int i = 0; i < rank; ++i) { dims[i] = c->UnknownDim(); } } c->set_output(0, c->MakeShape(dims)); return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Make Transpose's shape inference function validate that negative `perm` values are within the tensor's rank. PiperOrigin-RevId: 403252853 Change-Id: Ia6b31b45b237312668bb31c2c3b3c7bbce2d2610'</s>
<s>[INST] Given the following code containing errors, provide 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 Crypto::get_random_values(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "crypto.getRandomValues", 1)) return false; if (!args[0].isObject() || !is_int_typed_array(&args[0].toObject())) { JS_ReportErrorUTF8(cx, "crypto.getRandomValues: input must be an integer-typed TypedArray"); return false; } JS::RootedObject typed_array(cx, &args[0].toObject()); size_t byte_length = JS_GetArrayBufferViewByteLength(typed_array); if (byte_length > MAX_BYTE_LENGTH) { JS_ReportErrorUTF8(cx, "crypto.getRandomValues: input byteLength must be at most %u, " "but is %zu", MAX_BYTE_LENGTH, byte_length); return false; } JS::AutoCheckCannotGC noGC(cx); bool is_shared; void *buffer = JS_GetArrayBufferViewData(typed_array, &is_shared, noGC); arc4random_buf(buffer, byte_length); args.rval().setObject(*typed_array); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'use rangom_get instead of arc4random as arc4random does not work correctly with wizer wizer causes the seed in arc4random to be the same between executions which is not random'</s>
<s>[INST] Given the following code containing errors, provide 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 audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs) { GF_MPEGAudioSampleEntryBox *ptr; char *data; u8 a, b, c, d; u32 i, size, v, nb_alnum; GF_Err e; u64 pos, start; ptr = (GF_MPEGAudioSampleEntryBox *)s; start = gf_bs_get_position(bs); gf_bs_seek(bs, start + 8); v = gf_bs_read_u16(bs); if (v) ptr->is_qtff = 1; //try to disambiguate QTFF v1 and MP4 v1 audio sample entries ... if (v==1) { //go to end of ISOM audio sample entry, skip 4 byte (box size field), read 4 bytes (box type) and check if this looks like a box gf_bs_seek(bs, start + 8 + 20 + 4); a = gf_bs_read_u8(bs); b = gf_bs_read_u8(bs); c = gf_bs_read_u8(bs); d = gf_bs_read_u8(bs); nb_alnum = 0; if (isalnum(a)) nb_alnum++; if (isalnum(b)) nb_alnum++; if (isalnum(c)) nb_alnum++; if (isalnum(d)) nb_alnum++; if (nb_alnum>2) ptr->is_qtff = 0; } gf_bs_seek(bs, start); e = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs); if (e) return e; pos = gf_bs_get_position(bs); size = (u32) s->size; //when cookie is set on bs, always convert qtff-style mp4a to isobmff-style //since the conversion is done in addBox and we don't have the bitstream there (arg...), flag the box if (gf_bs_get_cookie(bs)) { ptr->is_qtff |= 1<<16; } e = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox); if (!e) return GF_OK; if (size<8) return GF_ISOM_INVALID_FILE; /*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/ gf_bs_seek(bs, pos); data = (char*)gf_malloc(sizeof(char) * size); gf_bs_read_data(bs, data, size); for (i=0; i<size-8; i++) { if (GF_4CC((u32)data[i+4], (u8)data[i+5], (u8)data[i+6], (u8)data[i+7]) == GF_ISOM_BOX_TYPE_ESDS) { GF_BitStream *mybs = gf_bs_new(data + i, size - i, GF_BITSTREAM_READ); if (ptr->esd) { gf_isom_box_del((GF_Box *)ptr->esd); ptr->esd=NULL; } e = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs); if (e==GF_OK) { gf_isom_box_add_for_dump_mode((GF_Box*)ptr, (GF_Box*)ptr->esd); } else if (ptr->esd) { gf_isom_box_del((GF_Box *)ptr->esd); ptr->esd=NULL; } gf_bs_del(mybs); break; } } gf_free(data); return e; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'fix UAF in audio_sample_entry_Read (#1440)'</s>
<s>[INST] Given the following code containing errors, provide 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 stop() { #ifdef CROW_ENABLE_SSL if (ssl_used_) { if (ssl_server_) { ssl_server_->stop(); } } else #endif { std::vector<crow::websocket::connection*> websockets_to_close = websockets_; for (auto websocket : websockets_to_close) { CROW_LOG_INFO << "Quitting Websocket: " << websocket; websocket->close("Server Application Terminated"); } if (server_) { server_->stop(); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent HTTP pipelining which Crow doesn't support.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int _server_handle_vCont(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) { char *action = NULL; if (send_ack (g) < 0) { return -1; } g->data[g->data_len] = '\0'; if (g->data[5] == '?') { // Query about everything we support return send_msg (g, "vCont;c;s"); } if (!(action = strtok (g->data, ";"))) { return send_msg (g, "E01"); } while (action = strtok (NULL, ";")) { eprintf ("action: %s\n", action); switch (action[0]) { case 's': // TODO handle thread selections if (cmd_cb (core_ptr, "ds", NULL, 0) < 0) { send_msg (g, "E01"); return -1; } return send_msg (g, "OK"); case 'c': // TODO handle thread selections if (cmd_cb (core_ptr, "dc", NULL, 0) < 0) { send_msg (g, "E01"); return -1; } return send_msg (g, "OK"); default: // TODO support others return send_msg (g, "E01"); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Fix ext2 buffer overflow in r2_sbu_grub_memmove'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ut64 MACH0_(get_baddr)(struct MACH0_(obj_t)* bin) { int i; if (bin->hdr.filetype != MH_EXECUTE && bin->hdr.filetype != MH_DYLINKER) return 0; for (i = 0; i < bin->nsegs; ++i) if (bin->segs[i].fileoff == 0 && bin->segs[i].filesize != 0) return bin->segs[i].vmaddr; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix null deref and uaf in mach0 parser'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf, int saltLen, int bits, void* heap) { int ret = 0; int hLen, i, o, maskLen, hiBits; byte* m; byte* s; #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) byte salt[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ]; #else byte* salt = NULL; #endif #else byte salt[WC_MAX_DIGEST_SIZE]; #endif #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) if (pkcsBlockLen > RSA_MAX_SIZE/8) { return MEMORY_E; } #endif hLen = wc_HashGetDigestSize(hType); if (hLen < 0) return hLen; if ((int)inputLen != hLen) { return BAD_FUNC_ARG; } hiBits = (bits - 1) & 0x7; if (hiBits == 0) { /* Per RFC8017, set the leftmost 8emLen - emBits bits of the leftmost octet in DB to zero. */ *(pkcsBlock++) = 0; pkcsBlockLen--; } if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) { saltLen = RSA_PSS_SALT_MAX_SZ; } #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if (saltLen > hLen) { return PSS_SALTLEN_E; } #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) { return PSS_SALTLEN_E; } #else else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { saltLen = (int)pkcsBlockLen - hLen - 2; if (saltLen < 0) { return PSS_SALTLEN_E; } } else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) { return PSS_SALTLEN_E; } #endif if ((int)pkcsBlockLen - hLen < saltLen + 2) { return PSS_SALTLEN_E; } maskLen = pkcsBlockLen - 1 - hLen; #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) salt = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (salt == NULL) { return MEMORY_E; } #endif s = m = salt; XMEMSET(m, 0, RSA_PSS_PAD_SZ); m += RSA_PSS_PAD_SZ; XMEMCPY(m, input, inputLen); m += inputLen; o = (int)(m - s); if (saltLen > 0) { ret = wc_RNG_GenerateBlock(rng, m, saltLen); if (ret == 0) { m += saltLen; } } #else s = m = pkcsBlock; XMEMSET(m, 0, RSA_PSS_PAD_SZ); m += RSA_PSS_PAD_SZ; XMEMCPY(m, input, inputLen); m += inputLen; o = 0; if (saltLen > 0) { ret = wc_RNG_GenerateBlock(rng, salt, saltLen); if (ret == 0) { XMEMCPY(m, salt, saltLen); m += saltLen; } } #endif if (ret == 0) { /* Put Hash at end of pkcsBlock - 1 */ ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen); } if (ret == 0) { /* Set the last eight bits or trailer field to the octet 0xbc */ pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM; ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap); } if (ret == 0) { /* Clear the first high bit when "8emLen - emBits" is non-zero. where emBits = n modBits - 1 */ if (hiBits) pkcsBlock[0] &= (1 << hiBits) - 1; m = pkcsBlock + maskLen - saltLen - 1; *(m++) ^= 0x01; for (i = 0; i < saltLen; i++) { m[i] ^= salt[o + i]; } } #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) if (salt != NULL) { XFREE(salt, heap, DYNAMIC_TYPE_RSA_BUFFER); } #endif #endif return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310', 'CWE-787'], 'message': 'RSA-PSS: Handle edge case with encoding message to hash When the key is small relative to the digest (1024-bit key, 64-byte hash, 61-byte salt length), the internal message to hash is larger than the output size. Allocate a buffer for the message when this happens.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PizCompressor::uncompress (const char *inPtr, int inSize, IMATH_NAMESPACE::Box2i range, const char *&outPtr) { // // This is the cunompress function which is used by both the tiled and // scanline decompression routines. // // // Special case - empty input buffer // if (inSize == 0) { outPtr = _outBuffer; return 0; } // // Determine the layout of the compressed pixel data // int minX = range.min.x; int maxX = range.max.x; int minY = range.min.y; int maxY = range.max.y; if (maxY > _maxY) maxY = _maxY; if (maxX > _maxX) maxX = _maxX; unsigned short *tmpBufferEnd = _tmpBuffer; int i = 0; for (ChannelList::ConstIterator c = _channels.begin(); c != _channels.end(); ++c, ++i) { ChannelData &cd = _channelData[i]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = numSamples (c.channel().xSampling, minX, maxX); cd.ny = numSamples (c.channel().ySampling, minY, maxY); cd.ys = c.channel().ySampling; cd.size = pixelTypeSize (c.channel().type) / pixelTypeSize (HALF); tmpBufferEnd += cd.nx * cd.ny * cd.size; } // // Read range compression data // unsigned short minNonZero; unsigned short maxNonZero; AutoArray <unsigned char, BITMAP_SIZE> bitmap; memset (bitmap, 0, sizeof (unsigned char) * BITMAP_SIZE); Xdr::read <CharPtrIO> (inPtr, minNonZero); Xdr::read <CharPtrIO> (inPtr, maxNonZero); if (maxNonZero >= BITMAP_SIZE) { throw InputExc ("Error in header for PIZ-compressed data " "(invalid bitmap size)."); } if (minNonZero <= maxNonZero) { Xdr::read <CharPtrIO> (inPtr, (char *) &bitmap[0] + minNonZero, maxNonZero - minNonZero + 1); } AutoArray <unsigned short, USHORT_RANGE> lut; unsigned short maxValue = reverseLutFromBitmap (bitmap, lut); // // Huffman decoding // int length; Xdr::read <CharPtrIO> (inPtr, length); hufUncompress (inPtr, length, _tmpBuffer, tmpBufferEnd - _tmpBuffer); // // Wavelet decoding // for (int i = 0; i < _numChans; ++i) { ChannelData &cd = _channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode (cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut (lut, _tmpBuffer, tmpBufferEnd - _tmpBuffer); // // Rearrange the pixel data into the format expected by the caller. // char *outEnd = _outBuffer; if (_format == XDR) { // // Machine-independent (Xdr) data format // for (int y = minY; y <= maxY; ++y) { for (int i = 0; i < _numChans; ++i) { ChannelData &cd = _channelData[i]; if (modp (y, cd.ys) != 0) continue; for (int x = cd.nx * cd.size; x > 0; --x) { Xdr::write <CharPtrIO> (outEnd, *cd.end); ++cd.end; } } } } else { // // Native, machine-dependent data format // for (int y = minY; y <= maxY; ++y) { for (int i = 0; i < _numChans; ++i) { ChannelData &cd = _channelData[i]; if (modp (y, cd.ys) != 0) continue; int n = cd.nx * cd.size; memcpy (outEnd, cd.end, n * sizeof (unsigned short)); outEnd += n * sizeof (unsigned short); cd.end += n; } } } #if defined (DEBUG) for (int i = 1; i < _numChans; ++i) assert (_channelData[i-1].end == _channelData[i].start); assert (_channelData[_numChans-1].end == tmpBufferEnd); #endif outPtr = _outBuffer; return outEnd - _outBuffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'Add additional input validation in an attempt to resolve issue #232'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int oe_iov_pack( const struct oe_iovec* iov, int iovcnt, void** buf_out, size_t* buf_size_out) { int ret = -1; struct oe_iovec* buf = NULL; size_t buf_size = 0; size_t data_size = 0; if (buf_out) *buf_out = NULL; if (buf_size_out) *buf_size_out = 0; /* Reject invalid parameters. */ if (iovcnt < 0 || (iovcnt > 0 && !iov) || !buf_out || !buf_size_out) goto done; /* Handle zero-sized iovcnt up front. */ if (iovcnt == 0) { if (iov) { if (!(buf = oe_calloc(1, sizeof(uint64_t)))) goto done; buf_size = sizeof(uint64_t); } *buf_out = buf; *buf_size_out = buf_size; buf = NULL; ret = 0; goto done; } /* Calculate the total number of data bytes. */ for (int i = 0; i < iovcnt; i++) data_size += iov[i].iov_len; /* Calculate the total size of the resulting buffer. */ buf_size = (sizeof(struct oe_iovec) * (size_t)iovcnt) + data_size; /* Allocate the output buffer. */ if (!(buf = oe_calloc(1, buf_size))) goto done; /* Initialize the array elements. */ { uint8_t* p = (uint8_t*)&buf[iovcnt]; size_t n = data_size; int i; for (i = 0; i < iovcnt; i++) { const size_t iov_len = iov[i].iov_len; const void* iov_base = iov[i].iov_base; if (iov_len) { buf[i].iov_len = iov_len; buf[i].iov_base = (void*)(p - (uint8_t*)buf); if (!iov_base) goto done; if (oe_memcpy_s(p, n, iov_base, iov_len) != OE_OK) goto done; p += iov_len; n -= iov_len; } } /* Fail if the data was not exhausted. */ if (n != 0) goto done; } *buf_out = buf; *buf_size_out = buf_size; buf = NULL; ret = 0; done: if (buf) oe_free(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m Signed-off-by: Ming-Wei Shih <mishih@microsoft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t _epoll_writev( oe_fd_t* desc, const struct oe_iovec* iov, int iovcnt) { ssize_t ret = -1; epoll_t* file = _cast_epoll(desc); void* buf = NULL; size_t buf_size = 0; if (!file || (iovcnt && !iov) || iovcnt < 0 || iovcnt > OE_IOV_MAX) OE_RAISE_ERRNO(OE_EINVAL); /* Flatten the IO vector into contiguous heap memory. */ if (oe_iov_pack(iov, iovcnt, &buf, &buf_size) != 0) OE_RAISE_ERRNO(OE_ENOMEM); /* Call the host. */ if (oe_syscall_writev_ocall(&ret, file->host_fd, buf, iovcnt, buf_size) != OE_OK) { OE_RAISE_ERRNO(OE_EINVAL); } done: if (buf) oe_free(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m Signed-off-by: Ming-Wei Shih <mishih@microsoft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t _hostfs_read(oe_fd_t* desc, void* buf, size_t count) { ssize_t ret = -1; file_t* file = _cast_file(desc); if (!file) OE_RAISE_ERRNO(OE_EINVAL); /* Call the host to perform the read(). */ if (oe_syscall_read_ocall(&ret, file->host_fd, buf, count) != OE_OK) OE_RAISE_ERRNO(OE_EINVAL); done: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m Signed-off-by: Ming-Wei Shih <mishih@microsoft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (str_len > INT_MAX) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72674 - check both curl_escape and curl_unescape'</s>
<s>[INST] Given the following code containing errors, provide 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 *skcipher_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_skcipher(name, type, mask); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: stable@vger.kernel.org Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Tested-by: Dmitry Vyukov <dvyukov@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int udp_v6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; struct udphdr *uh; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi6 *fl6 = &inet->cork.fl.u.ip6; int err = 0; int is_udplite = IS_UDPLITE(sk); __wsum csum = 0; /* Grab the skbuff where UDP header space exists. */ if ((skb = skb_peek(&sk->sk_write_queue)) == NULL) goto out; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = fl6->fl6_sport; uh->dest = fl6->fl6_dport; uh->len = htons(up->len); uh->check = 0; if (is_udplite) csum = udplite_csum_outgoing(sk, skb); else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, up->len); goto send; } else csum = udp_csum_outgoing(sk, skb); /* add protocol-dependent pseudo-header */ uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr, up->len, fl6->flowi6_proto, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip6_push_pending_frames(sk); if (err) { if (err == -ENOBUFS && !inet6_sk(sk)->recverr) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); out: up->len = 0; up->pending = 0; return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-703'], 'message': 'ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data We accidentally call down to ip6_push_pending_frames when uncorking pending AF_INET data on a ipv6 socket. This results in the following splat (from Dave Jones): skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL> ------------[ cut here ]------------ kernel BUG at net/core/skbuff.c:126! invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth +netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37 task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000 RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65 RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282 RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006 RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520 RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800 R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800 FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600 Stack: ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4 ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6 ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0 Call Trace: [<ffffffff8159a9aa>] skb_push+0x3a/0x40 [<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0 [<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140 [<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0 [<ffffffff81694660>] ? udplite_getfrag+0x20/0x20 [<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0 [<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0 [<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40 [<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20 [<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0 [<ffffffff816f5d54>] tracesys+0xdd/0xe2 Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 RIP [<ffffffff816e759c>] skb_panic+0x63/0x65 RSP <ffff8801e6431de8> This patch adds a check if the pending data is of address family AF_INET and directly calls udp_push_ending_frames from udp_v6_push_pending_frames if that is the case. This bug was found by Dave Jones with trinity. (Also move the initialization of fl6 below the AF_INET check, even if not strictly necessary.) Cc: Dave Jones <davej@redhat.com> Cc: YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ext4_xattr_create_cache(char *name) { return mb_cache_create(name, HASH_BUCKET_BITS); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ion_handle_put(struct ion_handle *handle) { struct ion_client *client = handle->client; int ret; mutex_lock(&client->lock); ret = kref_put(&handle->ref, ion_handle_destroy); mutex_unlock(&client->lock); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'staging/android/ion : fix a race condition in the ion driver There is a use-after-free problem in the ion driver. This is caused by a race condition in the ion_ioctl() function. A handle has ref count of 1 and two tasks on different cpus calls ION_IOC_FREE simultaneously. cpu 0 cpu 1 ------------------------------------------------------- ion_handle_get_by_id() (ref == 2) ion_handle_get_by_id() (ref == 3) ion_free() (ref == 2) ion_handle_put() (ref == 1) ion_free() (ref == 0 so ion_handle_destroy() is called and the handle is freed.) ion_handle_put() is called and it decreases the slub's next free pointer The problem is detected as an unaligned access in the spin lock functions since it uses load exclusive instruction. In some cases it corrupts the slub's free pointer which causes a mis-aligned access to the next free pointer.(kmalloc returns a pointer like ffffc0745b4580aa). And it causes lots of other hard-to-debug problems. This symptom is caused since the first member in the ion_handle structure is the reference count and the ion driver decrements the reference after it has been freed. To fix this problem client->lock mutex is extended to protect all the codes that uses the handle. Signed-off-by: Eun Taik Lee <eun.taik.lee@samsung.com> Reviewed-by: Laura Abbott <labbott@redhat.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ndisc_router_discovery(struct sk_buff *skb) { struct ra_msg *ra_msg = (struct ra_msg *)skb_transport_header(skb); struct neighbour *neigh = NULL; struct inet6_dev *in6_dev; struct rt6_info *rt = NULL; int lifetime; struct ndisc_options ndopts; int optlen; unsigned int pref = 0; __u8 *opt = (__u8 *)(ra_msg + 1); optlen = (skb_tail_pointer(skb) - skb_transport_header(skb)) - sizeof(struct ra_msg); ND_PRINTK(2, info, "RA: %s, dev: %s\n", __func__, skb->dev->name); if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "RA: source address is not link-local\n"); return; } if (optlen < 0) { ND_PRINTK(2, warn, "RA: packet too short\n"); return; } #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_HOST) { ND_PRINTK(2, warn, "RA: from host or unauthorized router\n"); return; } #endif /* * set the RA_RECV flag in the interface */ in6_dev = __in6_dev_get(skb->dev); if (in6_dev == NULL) { ND_PRINTK(0, err, "RA: can't find inet6 device for %s\n", skb->dev->name); return; } if (!ndisc_parse_options(opt, optlen, &ndopts)) { ND_PRINTK(2, warn, "RA: invalid ND options\n"); return; } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, did not accept ra for dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific parameters from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT, dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #endif if (in6_dev->if_flags & IF_RS_SENT) { /* * flag that an RA was received after an RS was sent * out on this interface. */ in6_dev->if_flags |= IF_RA_RCVD; } /* * Remember the managed/otherconf flags from most recently * received RA message (RFC 2462) -- yoshfuji */ in6_dev->if_flags = (in6_dev->if_flags & ~(IF_RA_MANAGED | IF_RA_OTHERCONF)) | (ra_msg->icmph.icmp6_addrconf_managed ? IF_RA_MANAGED : 0) | (ra_msg->icmph.icmp6_addrconf_other ? IF_RA_OTHERCONF : 0); if (!in6_dev->cnf.accept_ra_defrtr) { ND_PRINTK(2, info, "RA: %s, defrtr is false for dev: %s\n", __func__, skb->dev->name); goto skip_defrtr; } /* Do not accept RA with source-addr found on local machine unless * accept_ra_from_local is set to true. */ if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: default router ignored\n", skb->dev->name); goto skip_defrtr; } lifetime = ntohs(ra_msg->icmph.icmp6_rt_lifetime); #ifdef CONFIG_IPV6_ROUTER_PREF pref = ra_msg->icmph.icmp6_router_pref; /* 10b is handled as if it were 00b (medium) */ if (pref == ICMPV6_ROUTER_PREF_INVALID || !in6_dev->cnf.accept_ra_rtr_pref) pref = ICMPV6_ROUTER_PREF_MEDIUM; #endif rt = rt6_get_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev); if (rt) { neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (!neigh) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } } if (rt && lifetime == 0) { ip6_del_rt(rt); rt = NULL; } ND_PRINTK(3, info, "RA: rt: %p lifetime: %d, for dev: %s\n", rt, lifetime, skb->dev->name); if (rt == NULL && lifetime) { ND_PRINTK(3, info, "RA: adding default router\n"); rt = rt6_add_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev, pref); if (rt == NULL) { ND_PRINTK(0, err, "RA: %s failed to add default route\n", __func__); return; } neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (neigh == NULL) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } neigh->flags |= NTF_ROUTER; } else if (rt) { rt->rt6i_flags = (rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref); } if (rt) rt6_set_expires(rt, jiffies + (HZ * lifetime)); if (ra_msg->icmph.icmp6_hop_limit) { in6_dev->cnf.hop_limit = ra_msg->icmph.icmp6_hop_limit; if (rt) dst_metric_set(&rt->dst, RTAX_HOPLIMIT, ra_msg->icmph.icmp6_hop_limit); } skip_defrtr: /* * Update Reachable Time and Retrans Timer */ if (in6_dev->nd_parms) { unsigned long rtime = ntohl(ra_msg->retrans_timer); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/HZ) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; NEIGH_VAR_SET(in6_dev->nd_parms, RETRANS_TIME, rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } rtime = ntohl(ra_msg->reachable_time); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/(3*HZ)) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; if (rtime != NEIGH_VAR(in6_dev->nd_parms, BASE_REACHABLE_TIME)) { NEIGH_VAR_SET(in6_dev->nd_parms, BASE_REACHABLE_TIME, rtime); NEIGH_VAR_SET(in6_dev->nd_parms, GC_STALETIME, 3 * rtime); in6_dev->nd_parms->reachable_time = neigh_rand_reach_time(rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } } } skip_linkparms: /* * Process options. */ if (!neigh) neigh = __neigh_lookup(&nd_tbl, &ipv6_hdr(skb)->saddr, skb->dev, 1); if (neigh) { u8 *lladdr = NULL; if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) { ND_PRINTK(2, warn, "RA: invalid link-layer address length\n"); goto out; } } neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| NEIGH_UPDATE_F_ISROUTER); } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, accept_ra is false for dev: %s\n", __func__, skb->dev->name); goto out; } #ifdef CONFIG_IPV6_ROUTE_INFO if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: router info ignored.\n", skb->dev->name); goto skip_routeinfo; } if (in6_dev->cnf.accept_ra_rtr_pref && ndopts.nd_opts_ri) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_ri; p; p = ndisc_next_option(p, ndopts.nd_opts_ri_end)) { struct route_info *ri = (struct route_info *)p; #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT && ri->prefix_len == 0) continue; #endif if (ri->prefix_len == 0 && !in6_dev->cnf.accept_ra_defrtr) continue; if (ri->prefix_len > in6_dev->cnf.accept_ra_rt_info_max_plen) continue; rt6_route_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, &ipv6_hdr(skb)->saddr); } } skip_routeinfo: #endif #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific ndopts from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT (interior routes), dev: %s\n", __func__, skb->dev->name); goto out; } #endif if (in6_dev->cnf.accept_ra_pinfo && ndopts.nd_opts_pi) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_pi; p; p = ndisc_next_option(p, ndopts.nd_opts_pi_end)) { addrconf_prefix_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, ndopts.nd_opts_src_lladdr != NULL); } } if (ndopts.nd_opts_mtu && in6_dev->cnf.accept_ra_mtu) { __be32 n; u32 mtu; memcpy(&n, ((u8 *)(ndopts.nd_opts_mtu+1))+2, sizeof(mtu)); mtu = ntohl(n); if (mtu < IPV6_MIN_MTU || mtu > skb->dev->mtu) { ND_PRINTK(2, warn, "RA: invalid mtu: %d\n", mtu); } else if (in6_dev->cnf.mtu6 != mtu) { in6_dev->cnf.mtu6 = mtu; if (rt) dst_metric_set(&rt->dst, RTAX_MTU, mtu); rt6_mtu_change(skb->dev, mtu); } } if (ndopts.nd_useropts) { struct nd_opt_hdr *p; for (p = ndopts.nd_useropts; p; p = ndisc_next_useropt(p, ndopts.nd_useropts_end)) { ndisc_ra_useropt(skb, p); } } if (ndopts.nd_opts_tgt_lladdr || ndopts.nd_opts_rh) { ND_PRINTK(2, warn, "RA: invalid RA options\n"); } out: ip6_rt_put(rt); if (neigh) neigh_release(neigh); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'ipv6: Don't reduce hop limit for an interface A local route may have a lower hop_limit set than global routes do. RFC 3756, Section 4.2.7, "Parameter Spoofing" > 1. The attacker includes a Current Hop Limit of one or another small > number which the attacker knows will cause legitimate packets to > be dropped before they reach their destination. > As an example, one possible approach to mitigate this threat is to > ignore very small hop limits. The nodes could implement a > configurable minimum hop limit, and ignore attempts to set it below > said limit. Signed-off-by: D.S. Ljungmark <ljungmark@modio.se> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13005/NFS: Add two bounds checks before fetching data This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cmv_process_header(CmvContext *s, const uint8_t *buf, const uint8_t *buf_end) { int pal_start, pal_count, i, ret, fps; if(buf_end - buf < 16) { av_log(s->avctx, AV_LOG_WARNING, "truncated header\n"); return AVERROR_INVALIDDATA; } s->width = AV_RL16(&buf[4]); s->height = AV_RL16(&buf[6]); ret = ff_set_dimensions(s->avctx, s->width, s->height); if (ret < 0) return ret; fps = AV_RL16(&buf[10]); if (fps > 0) s->avctx->time_base = (AVRational){ 1, fps }; pal_start = AV_RL16(&buf[12]); pal_count = AV_RL16(&buf[14]); buf += 16; for (i=pal_start; i<pal_start+pal_count && i<AVPALETTE_COUNT && buf_end - buf >= 3; i++) { s->palette[i] = AV_RB24(buf); buf += 3; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'eacmv: clear references on frame dimensions change Fixes invalid reads. Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind CC:libav-stable@libav.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: extern "C" void *malloc_wrapper(size_t size, void *caller) { void *ptr = NULL; #if MBED_MEM_TRACING_ENABLED mbed_mem_trace_lock(); #endif #if MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); alloc_info_t *alloc_info = (alloc_info_t *)SUPER_MALLOC(size + sizeof(alloc_info_t)); if (alloc_info != NULL) { alloc_info->size = size; alloc_info->signature = MBED_HEAP_STATS_SIGNATURE; ptr = (void *)(alloc_info + 1); heap_stats.current_size += size; heap_stats.total_size += size; heap_stats.alloc_cnt += 1; if (heap_stats.current_size > heap_stats.max_size) { heap_stats.max_size = heap_stats.current_size; } heap_stats.overhead_size += get_malloc_block_total_size((void *)alloc_info) - size; } else { heap_stats.alloc_fail_cnt += 1; } malloc_stats_mutex->unlock(); #else // #if MBED_HEAP_STATS_ENABLED ptr = SUPER_MALLOC(size); #endif // #if MBED_HEAP_STATS_ENABLED #if MBED_MEM_TRACING_ENABLED mbed_mem_trace_malloc(ptr, size, caller); mbed_mem_trace_unlock(); #endif // #if MBED_MEM_TRACING_ENABLED return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Add integer overflow check to the malloc wrappers Add a check that the combined size of the buffer to allocate and alloc_info_t does not exceed the maximum integer value representable by size_t.'</s>
<s>[INST] Given the following code containing errors, provide 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 on_part_data( multipart_parser *parser, const char *at, size_t length) { multipart_parser_data_t *data = NULL; ogs_assert(parser); data = multipart_parser_get_data(parser); ogs_assert(data); if (at && length) { SWITCH(data->part[data->num_of_part].content_type) CASE(OGS_SBI_CONTENT_JSON_TYPE) CASE(OGS_SBI_CONTENT_5GNAS_TYPE) CASE(OGS_SBI_CONTENT_NGAP_TYPE) size_t offset = 0; if (data->part[data->num_of_part].content == NULL) { data->part[data->num_of_part].content_length = length; data->part[data->num_of_part].content = (char *)ogs_malloc(length + 1); ogs_assert(data->part[data->num_of_part].content); } else { offset = data->part[data->num_of_part].content_length; if ((data->part[data->num_of_part].content_length + length) > OGS_HUGE_LEN) { ogs_error("Overflow length [%d:%d]", (int)data->part[data->num_of_part].content_length, (int)length); ogs_assert_if_reached(); return 0; } data->part[data->num_of_part].content_length += length; data->part[data->num_of_part].content = (char *)ogs_realloc( data->part[data->num_of_part].content, data->part[data->num_of_part].content_length + 1); ogs_assert(data->part[data->num_of_part].content); } memcpy(data->part[data->num_of_part].content + offset, at, length); data->part[data->num_of_part].content[ data->part[data->num_of_part].content_length] = 0; break; DEFAULT ogs_log_hexdump(OGS_LOG_FATAL, (unsigned char *)at, length); ogs_error("Unknown content_type [%s]", data->part[data->num_of_part].content_type); END } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-787'], 'message': '[AMF] fix the memory problem (#1247) 1. memory corruption - Overflow num_of_part in SBI message 2. null pointer dereference - n2InfoContent->ngap_ie_type'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: makeOperatorDependencies(HeapTuple tuple, bool isUpdate) { Form_pg_operator oper = (Form_pg_operator) GETSTRUCT(tuple); ObjectAddress myself, referenced; myself.classId = OperatorRelationId; myself.objectId = oper->oid; myself.objectSubId = 0; /* * If we are updating the operator, delete any existing entries, except * for extension membership which should remain the same. */ if (isUpdate) { deleteDependencyRecordsFor(myself.classId, myself.objectId, true); deleteSharedDependencyRecordsFor(myself.classId, myself.objectId, 0); } /* Dependency on namespace */ if (OidIsValid(oper->oprnamespace)) { referenced.classId = NamespaceRelationId; referenced.objectId = oper->oprnamespace; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* Dependency on left type */ if (OidIsValid(oper->oprleft)) { referenced.classId = TypeRelationId; referenced.objectId = oper->oprleft; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* Dependency on right type */ if (OidIsValid(oper->oprright)) { referenced.classId = TypeRelationId; referenced.objectId = oper->oprright; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* Dependency on result type */ if (OidIsValid(oper->oprresult)) { referenced.classId = TypeRelationId; referenced.objectId = oper->oprresult; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* * NOTE: we do not consider the operator to depend on the associated * operators oprcom and oprnegate. We would not want to delete this * operator if those go away, but only reset the link fields; which is not * a function that the dependency code can presently handle. (Something * could perhaps be done with objectSubId though.) For now, it's okay to * let those links dangle if a referenced operator is removed. */ /* Dependency on implementation function */ if (OidIsValid(oper->oprcode)) { referenced.classId = ProcedureRelationId; referenced.objectId = oper->oprcode; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* Dependency on restriction selectivity function */ if (OidIsValid(oper->oprrest)) { referenced.classId = ProcedureRelationId; referenced.objectId = oper->oprrest; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* Dependency on join selectivity function */ if (OidIsValid(oper->oprjoin)) { referenced.classId = ProcedureRelationId; referenced.objectId = oper->oprjoin; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } /* Dependency on owner */ recordDependencyOnOwner(OperatorRelationId, oper->oid, oper->oprowner); /* Dependency on extension */ recordDependencyOnCurrentExtension(&myself, true); 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: bool SNC_io_parser<EW>:: read_vertex(Vertex_handle vh) { bool OK = true; int index; #ifdef CGAL_NEF_NATURAL_COORDINATE_INPUT typename K::RT hx, hy, hz, hw; #endif in >> index; OK = OK && test_string("{"); vh->sncp() = this->sncp(); in >> index; vh->svertices_begin() = (index >= 0 ? Edge_of[index] : this->svertices_end()); in >> index; vh->svertices_last() = index >= 0 ? Edge_of[index] : this->svertices_end(); OK = OK && test_string(","); in >> index; vh->shalfedges_begin() = index >= 0 ? SEdge_of[index] : this->shalfedges_end(); in >> index; vh->shalfedges_last() = index >= 0 ? SEdge_of[index] : this->shalfedges_end(); OK = OK && test_string(","); in >> index; vh->sfaces_begin() = index >= 0 ? SFace_of[index] : this->sfaces_end(); in >> index; vh->sfaces_last() = index >= 0 ? SFace_of[index] : this->sfaces_end(); OK = OK && test_string(","); in >> index; vh->shalfloop() = index >= 0 ? SLoop_of[index] : this->shalfloops_end(); OK = OK && test_string("|"); #ifdef CGAL_NEF_NATURAL_COORDINATE_INPUT in >> hx >> hy >> hz >> hw; vh->point() = Point_3(hx,hy,hz,hw); #else vh->point() = Geometry_io<typename K::Kernel_tag, Kernel>::template read_point<Kernel, K>(in); #endif OK = OK && test_string("}"); in >> vh->mark(); return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix Nef_3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Permissions::check_remote_datareader( const PermissionsHandle& remote_handle, const uint32_t domain_id, const ReaderProxyData& subscription_data, bool& relay_only, SecurityException& exception) { bool returned_value = false; const AccessPermissionsHandle& rah = AccessPermissionsHandle::narrow(remote_handle); relay_only = false; if (rah.nil()) { exception = _SecurityException_("Bad precondition"); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); return false; } const EndpointSecurityAttributes* attributes = nullptr; if ((attributes = is_topic_in_sec_attributes(subscription_data.topicName().c_str(), rah->governance_topic_rules_)) != nullptr) { if (!attributes->is_read_protected) { return true; } } else { exception = _SecurityException_( "Not found topic access rule for topic " + subscription_data.topicName().to_string()); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); return false; } for (auto rule : rah->grant.rules) { if (is_domain_in_set(domain_id, rule.domains)) { if (is_topic_in_criterias(subscription_data.topicName(), rule.subscribes)) { if (rule.allow) { returned_value = true; } else { exception = _SecurityException_(subscription_data.topicName().to_string() + std::string(" topic denied by deny rule.")); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); } break; } if (is_topic_in_criterias(subscription_data.topicName(), rule.relays)) { if (rule.allow) { relay_only = true; returned_value = true; } break; } } } if (!returned_value && strlen(exception.what()) == 0) { exception = _SecurityException_(subscription_data.topicName().to_string() + std::string(" topic not found in allow rule.")); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); } return returned_value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387) * Refs 5346. Blackbox test Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. one-way string compare Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. Do not add partition separator on last partition Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. Uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. Uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Access control unit testing It only covers Partition and Topic permissions Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs #3680. Fix partition check on Permissions plugin. Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Fix tests on mac Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Fix windows tests Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Avoid memory leak on test Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Proxy data mocks should not return temporary objects Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * refs 3680. uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> Co-authored-by: Miguel Company <MiguelCompany@eprosima.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Permissions::check_remote_datawriter( const PermissionsHandle& remote_handle, const uint32_t domain_id, const WriterProxyData& publication_data, SecurityException& exception) { bool returned_value = false; const AccessPermissionsHandle& rah = AccessPermissionsHandle::narrow(remote_handle); if (rah.nil()) { exception = _SecurityException_("Bad precondition"); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); return false; } const EndpointSecurityAttributes* attributes = nullptr; if ((attributes = is_topic_in_sec_attributes(publication_data.topicName().c_str(), rah->governance_topic_rules_)) != nullptr) { if (!attributes->is_write_protected) { return true; } } else { exception = _SecurityException_( "Not found topic access rule for topic " + publication_data.topicName().to_string()); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); return false; } for (auto rule : rah->grant.rules) { if (is_domain_in_set(domain_id, rule.domains)) { if (is_topic_in_criterias(publication_data.topicName().c_str(), rule.publishes)) { if (rule.allow) { returned_value = true; } else { exception = _SecurityException_(publication_data.topicName().to_string() + std::string(" topic denied by deny rule.")); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); } break; } } } if (!returned_value && strlen(exception.what()) == 0) { exception = _SecurityException_(publication_data.topicName().to_string() + std::string(" topic not found in allow rule.")); EMERGENCY_SECURITY_LOGGING("Permissions", exception.what()); } return returned_value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387) * Refs 5346. Blackbox test Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. one-way string compare Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. Do not add partition separator on last partition Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. Uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 5346. Uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Access control unit testing It only covers Partition and Topic permissions Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs #3680. Fix partition check on Permissions plugin. Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Fix tests on mac Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Fix windows tests Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Avoid memory leak on test Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * Refs 3680. Proxy data mocks should not return temporary objects Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> * refs 3680. uncrustify Signed-off-by: Iker Luengo <ikerluengo@eprosima.com> Co-authored-by: Miguel Company <MiguelCompany@eprosima.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cmd_info(void *data, const char *input) { RCore *core = (RCore *) data; bool newline = r_config_get_i (core->config, "scr.interactive"); RBinObject *o = r_bin_cur_object (core->bin); RCoreFile *cf = core->file; int i, va = core->io->va || core->io->debug; int mode = 0; //R_CORE_BIN_SIMPLE; int is_array = 0; Sdb *db; for (i = 0; input[i] && input[i] != ' '; i++) ; if (i > 0) { switch (input[i - 1]) { case '*': mode = R_CORE_BIN_RADARE; break; case 'j': mode = R_CORE_BIN_JSON; break; case 'q': mode = R_CORE_BIN_SIMPLE; break; } } if (mode == R_CORE_BIN_JSON) { if (strlen (input + 1) > 1) { is_array = 1; } } if (is_array) { r_cons_printf ("{"); } if (!*input) { cmd_info_bin (core, va, mode); } /* i* is an alias for iI* */ if (!strcmp (input, "*")) { input = "I*"; } RBinObject *obj = r_bin_cur_object (core->bin); while (*input) { switch (*input) { case 'b': // "ib" { ut64 baddr = r_config_get_i (core->config, "bin.baddr"); if (input[1] == ' ') { baddr = r_num_math (core->num, input + 1); } // XXX: this will reload the bin using the buffer. // An assumption is made that assumes there is an underlying // plugin that will be used to load the bin (e.g. malloc://) // TODO: Might be nice to reload a bin at a specified offset? r_core_bin_reload (core, NULL, baddr); r_core_block_read (core); newline = false; } break; case 'k': db = o? o->kv: NULL; //:eprintf ("db = %p\n", db); switch (input[1]) { case 'v': if (db) { char *o = sdb_querys (db, NULL, 0, input + 3); if (o && *o) { r_cons_print (o); } free (o); } break; case '*': r_core_bin_export_info_rad (core); break; case '.': case ' ': if (db) { char *o = sdb_querys (db, NULL, 0, input + 2); if (o && *o) { r_cons_print (o); } free (o); } break; case '\0': if (db) { char *o = sdb_querys (db, NULL, 0, "*"); if (o && *o) { r_cons_print (o); } free (o); } break; case '?': default: eprintf ("Usage: ik [sdb-query]\n"); eprintf ("Usage: ik* # load all header information\n"); } goto done; break; case 'o': { if (!cf) { eprintf ("Core file not open\n"); return 0; } const char *fn = input[1] == ' '? input + 2: cf->desc->name; ut64 baddr = r_config_get_i (core->config, "bin.baddr"); r_core_bin_load (core, fn, baddr); } break; #define RBININFO(n,x,y,z)\ if (is_array) {\ if (is_array == 1) { is_array++;\ } else { r_cons_printf (",");}\ r_cons_printf ("\"%s\":",n);\ }\ if (z) { playMsg (core, n, z);}\ r_core_bin_info (core, x, mode, va, NULL, y); case 'A': newline = false; if (input[1] == 'j') { r_cons_printf ("{"); r_bin_list_archs (core->bin, 'j'); r_cons_printf ("}\n"); } else { r_bin_list_archs (core->bin, 1); } break; case 'E': RBININFO ("exports", R_CORE_BIN_ACC_EXPORTS, NULL, 0); break; case 'Z': RBININFO ("size", R_CORE_BIN_ACC_SIZE, NULL, 0); break; case 'S': //we comes from ia or iS if ((input[1] == 'm' && input[2] == 'z') || !input[1]) { RBININFO ("sections", R_CORE_BIN_ACC_SECTIONS, NULL, 0); } else { //iS entropy,sha1 RBinObject *obj = r_bin_cur_object (core->bin); if (mode == R_CORE_BIN_RADARE || mode == R_CORE_BIN_JSON || mode == R_CORE_BIN_SIMPLE) { RBININFO ("sections", R_CORE_BIN_ACC_SECTIONS, input + 2, obj? r_list_length (obj->sections): 0); } else { RBININFO ("sections", R_CORE_BIN_ACC_SECTIONS, input + 1, obj? r_list_length (obj->sections): 0); } //we move input until get '\0' while (*(++input)) ; //input-- because we are inside a while that does input++ // oob read if not input-- input--; } break; case 'H': if (input[1] == 'H') { // "iHH" RBININFO ("header", R_CORE_BIN_ACC_HEADER, NULL, -1); break; } case 'h': RBININFO ("fields", R_CORE_BIN_ACC_FIELDS, NULL, 0); break; case 'l': RBININFO ("libs", R_CORE_BIN_ACC_LIBS, NULL, obj? r_list_length (obj->libs): 0); break; case 'L': { char *ptr = strchr (input, ' '); int json = input[1] == 'j'? 'j': 0; if (ptr && ptr[1]) { const char *plugin_name = ptr + 1; if (is_array) { r_cons_printf ("\"plugin\": "); } r_bin_list_plugin (core->bin, plugin_name, json); } else { r_bin_list (core->bin, json); } newline = false; goto done; } break; case 's': if (input[1] == '.') { ut64 addr = core->offset + (core->print->cur_enabled? core->print->cur: 0); RFlagItem *f = r_flag_get_at (core->flags, addr, false); if (f) { if (f->offset == addr || !f->offset) { r_cons_printf ("%s", f->name); } else { r_cons_printf ("%s+%d", f->name, (int) (addr - f->offset)); } } input++; break; } else { RBinObject *obj = r_bin_cur_object (core->bin); RBININFO ("symbols", R_CORE_BIN_ACC_SYMBOLS, NULL, obj? r_list_length (obj->symbols): 0); break; } case 'R': if (input[1] == '*') { mode = R_CORE_BIN_RADARE; } else if (input[1] == 'j') { mode = R_CORE_BIN_JSON; } RBININFO ("resources", R_CORE_BIN_ACC_RESOURCES, NULL, 0); break; case 'r': RBININFO ("relocs", R_CORE_BIN_ACC_RELOCS, NULL, 0); break; case 'd': RBININFO ("dwarf", R_CORE_BIN_ACC_DWARF, NULL, -1); break; case 'i': RBININFO ("imports",R_CORE_BIN_ACC_IMPORTS, NULL, obj? r_list_length (obj->imports): 0); break; case 'I': RBININFO ("info", R_CORE_BIN_ACC_INFO, NULL, 0); break; case 'e': RBININFO ("entries", R_CORE_BIN_ACC_ENTRIES, NULL, 0); break; case 'M': RBININFO ("main", R_CORE_BIN_ACC_MAIN, NULL, 0); break; case 'm': RBININFO ("memory", R_CORE_BIN_ACC_MEM, NULL, 0); break; case 'V': RBININFO ("versioninfo", R_CORE_BIN_ACC_VERSIONINFO, NULL, 0); break; case 'C': RBININFO ("signature", R_CORE_BIN_ACC_SIGNATURE, NULL, 0); break; case 'z': if (input[1] == 'z') { //izz switch (input[2]) { case '*': mode = R_CORE_BIN_RADARE; break; case 'j': mode = R_CORE_BIN_JSON; break; case 'q': //izzq if (input[3] == 'q') { //izzqq mode = R_CORE_BIN_SIMPLEST; input++; } else { mode = R_CORE_BIN_SIMPLE; } break; default: mode = R_CORE_BIN_PRINT; break; } input++; RBININFO ("strings", R_CORE_BIN_ACC_RAW_STRINGS, NULL, 0); } else { RBinObject *obj = r_bin_cur_object (core->bin); if (input[1] == 'q') { mode = (input[2] == 'q') ? R_CORE_BIN_SIMPLEST : R_CORE_BIN_SIMPLE; input++; } if (obj) { RBININFO ("strings", R_CORE_BIN_ACC_STRINGS, NULL, obj? r_list_length (obj->strings): 0); } } break; case 'c': // for r2 `ic` if (input[1] == '?') { eprintf ("Usage: ic[ljq*] [class-index or name]\n"); } else if (input[1] == ' ' || input[1] == 'q' || input[1] == 'j' || input[1] == 'l') { RBinClass *cls; RBinSymbol *sym; RListIter *iter, *iter2; RBinObject *obj = r_bin_cur_object (core->bin); if (obj) { if (input[2]) { int idx = -1; const char * cls_name = NULL; if (r_num_is_valid_input (core->num, input + 2)) { idx = r_num_math (core->num, input + 2); } else { const char * first_char = input + ((input[1] == ' ') ? 1 : 2); int not_space = strspn (first_char, " "); if (first_char[not_space]) { cls_name = first_char + not_space; } } int count = 0; r_list_foreach (obj->classes, iter, cls) { if ((idx >= 0 && idx != count++) || (cls_name && strcmp (cls_name, cls->name) != 0)){ continue; } switch (input[1]) { case '*': r_list_foreach (cls->methods, iter2, sym) { r_cons_printf ("f sym.%s @ 0x%"PFMT64x "\n", sym->name, sym->vaddr); } input++; break; case 'l': r_list_foreach (cls->methods, iter2, sym) { const char *comma = iter2->p? " ": ""; r_cons_printf ("%s0x%"PFMT64d, comma, sym->vaddr); } r_cons_newline (); input++; break; case 'j': input++; r_cons_printf ("\"class\":\"%s\"", cls->name); r_cons_printf (",\"methods\":["); r_list_foreach (cls->methods, iter2, sym) { const char *comma = iter2->p? ",": ""; if (sym->method_flags) { char *flags = r_core_bin_method_flags_str (sym, R_CORE_BIN_JSON); r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"vaddr\":%"PFMT64d "}", comma, sym->name, flags, sym->vaddr); R_FREE (flags); } else { r_cons_printf ("%s{\"name\":\"%s\",\"vaddr\":%"PFMT64d "}", comma, sym->name, sym->vaddr); } } r_cons_printf ("]"); break; default: r_cons_printf ("class %s\n", cls->name); r_list_foreach (cls->methods, iter2, sym) { char *flags = r_core_bin_method_flags_str (sym, 0); r_cons_printf ("0x%08"PFMT64x " method %s %s %s\n", sym->vaddr, cls->name, flags, sym->name); R_FREE (flags); } break; } goto done; } goto done; } else { playMsg (core, "classes", r_list_length (obj->classes)); if (input[1] == 'l' && obj) { // "icl" r_list_foreach (obj->classes, iter, cls) { r_list_foreach (cls->methods, iter2, sym) { const char *comma = iter2->p? " ": ""; r_cons_printf ("%s0x%"PFMT64d, comma, sym->vaddr); } if (!r_list_empty (cls->methods)) { r_cons_newline (); } } } else { RBININFO ("classes", R_CORE_BIN_ACC_CLASSES, NULL, r_list_length (obj->classes)); } } } } else { RBinObject *obj = r_bin_cur_object (core->bin); int len = obj? r_list_length (obj->classes): 0; RBININFO ("classes", R_CORE_BIN_ACC_CLASSES, NULL, len); } break; case 'D': if (input[1] != ' ' || !demangle (core, input + 2)) { eprintf ("|Usage: iD lang symbolname\n"); } return 0; case 'a': switch (mode) { case R_CORE_BIN_RADARE: cmd_info (core, "iIiecsSmz*"); break; case R_CORE_BIN_JSON: cmd_info (core, "iIiecsSmzj"); break; case R_CORE_BIN_SIMPLE: cmd_info (core, "iIiecsSmzq"); break; default: cmd_info (core, "IiEecsSmz"); break; } break; case '?': { const char *help_message[] = { "Usage: i", "", "Get info from opened file (see rabin2's manpage)", "Output mode:", "", "", "'*'", "", "Output in radare commands", "'j'", "", "Output in json", "'q'", "", "Simple quiet output", "Actions:", "", "", "i|ij", "", "Show info of current file (in JSON)", "iA", "", "List archs", "ia", "", "Show all info (imports, exports, sections..)", "ib", "", "Reload the current buffer for setting of the bin (use once only)", "ic", "", "List classes, methods and fields", "iC", "", "Show signature info (entitlements, ...)", "id", "", "Debug information (source lines)", "iD", " lang sym", "demangle symbolname for given language", "ie", "", "Entrypoint", "iE", "", "Exports (global symbols)", "ih", "", "Headers (alias for iH)", "iHH", "", "Verbose Headers in raw text", "ii", "", "Imports", "iI", "", "Binary info", "ik", " [query]", "Key-value database from RBinObject", "il", "", "Libraries", "iL ", "[plugin]", "List all RBin plugins loaded or plugin details", "im", "", "Show info about predefined memory allocation", "iM", "", "Show main address", "io", " [file]", "Load info from file (or last opened) use bin.baddr", "ir", "", "Relocs", "iR", "", "Resources", "is", "", "Symbols", "iS ", "[entropy,sha1]", "Sections (choose which hash algorithm to use)", "iV", "", "Display file version info", "iz|izj", "", "Strings in data sections (in JSON/Base64)", "izz", "", "Search for Strings in the whole binary", "iZ", "", "Guess size of binary program", NULL }; r_core_cmd_help (core, help_message); } goto done; case '*': mode = R_CORE_BIN_RADARE; goto done; case 'q': mode = R_CORE_BIN_SIMPLE; cmd_info_bin (core, va, mode); goto done; case 'j': mode = R_CORE_BIN_JSON; if (is_array > 1) { mode |= R_CORE_BIN_ARRAY; } cmd_info_bin (core, va, mode); goto done; default: cmd_info_bin (core, va, mode); break; } input++; if ((*input == 'j' || *input == 'q') && !input[1]) { break; } } done: if (is_array) { r_cons_printf ("}\n"); } if (newline) { r_cons_newline (); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #7727 - undefined pointers and out of band string access fixes'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteJPEGImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option, *sampling_factor, *value; ErrorManager error_manager; Image *volatile volatile_image; int colorspace, quality; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType status; MemoryInfo *memory_info; register JSAMPLE *q; register ssize_t i; ssize_t y; struct jpeg_compress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; unsigned short scale; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((LocaleCompare(image_info->magick,"JPS") == 0) && (image->next != (Image *) NULL)) image=AppendImages(image,MagickFalse,exception); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); volatile_image=image; jpeg_info.client_data=(void *) volatile_image; jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; error_manager.exception=exception; error_manager.image=volatile_image; memory_info=(MemoryInfo *) NULL; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_compress(&jpeg_info); (void) CloseBlob(volatile_image); return(MagickFalse); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_compress(&jpeg_info); JPEGDestinationManager(&jpeg_info,image); if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); jpeg_info.image_width=(unsigned int) image->columns; jpeg_info.image_height=(unsigned int) image->rows; jpeg_info.input_components=3; jpeg_info.data_precision=8; jpeg_info.in_color_space=JCS_RGB; switch (image->colorspace) { case CMYKColorspace: { jpeg_info.input_components=4; jpeg_info.in_color_space=JCS_CMYK; break; } case YCbCrColorspace: case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: { jpeg_info.in_color_space=JCS_YCbCr; break; } case GRAYColorspace: { if (image_info->type == TrueColorType) break; jpeg_info.input_components=1; jpeg_info.in_color_space=JCS_GRAYSCALE; break; } default: { (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image_info->type == TrueColorType) break; if (SetImageGray(image,exception) != MagickFalse) { jpeg_info.input_components=1; jpeg_info.in_color_space=JCS_GRAYSCALE; } break; } } jpeg_set_defaults(&jpeg_info); if (jpeg_info.in_color_space == JCS_CMYK) jpeg_set_colorspace(&jpeg_info,JCS_YCCK); if ((jpeg_info.data_precision != 12) && (image->depth <= 8)) jpeg_info.data_precision=8; else jpeg_info.data_precision=BITS_IN_JSAMPLE; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image resolution: %.20g,%.20g",image->resolution.x,image->resolution.y); if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { /* Set image resolution. */ jpeg_info.write_JFIF_header=TRUE; jpeg_info.X_density=(UINT16) image->resolution.x; jpeg_info.Y_density=(UINT16) image->resolution.y; /* Set image resolution units. */ if (image->units == PixelsPerInchResolution) jpeg_info.density_unit=(UINT8) 1; if (image->units == PixelsPerCentimeterResolution) jpeg_info.density_unit=(UINT8) 2; } jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:optimize-coding"); if (option != (const char *) NULL) jpeg_info.optimize_coding=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; else { MagickSizeType length; length=(MagickSizeType) jpeg_info.input_components*image->columns* image->rows*sizeof(JSAMPLE); if (length == (MagickSizeType) ((size_t) length)) { /* Perform optimization only if available memory resources permit it. */ status=AcquireMagickResource(MemoryResource,length); RelinquishMagickResource(MemoryResource,length); jpeg_info.optimize_coding=status == MagickFalse ? FALSE : TRUE; } } #if (JPEG_LIB_VERSION >= 61) && defined(C_PROGRESSIVE_SUPPORTED) if ((LocaleCompare(image_info->magick,"PJPEG") == 0) || (image_info->interlace != NoInterlace)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); jpeg_simple_progression(&jpeg_info); } else if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: non-progressive"); #else if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); #endif quality=92; if ((image_info->compression != LosslessJPEGCompression) && (image->quality <= 100)) { if (image->quality != UndefinedCompressionQuality) quality=(int) image->quality; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: %.20g", (double) image->quality); } else { #if !defined(C_LOSSLESS_SUPPORTED) quality=100; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: 100"); #else if (image->quality < 100) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, "LosslessToLossyJPEGConversion",image->filename); else { int point_transform, predictor; predictor=image->quality/100; /* range 1-7 */ point_transform=image->quality % 20; /* range 0-15 */ jpeg_simple_lossless(&jpeg_info,predictor,point_transform); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Compression: lossless"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Predictor: %d",predictor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Point Transform: %d",point_transform); } } #endif } option=GetImageOption(image_info,"jpeg:extent"); if (option != (const char *) NULL) { Image *jpeg_image; ImageInfo *extent_info; extent_info=CloneImageInfo(image_info); extent_info->blob=NULL; jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image != (Image *) NULL) { MagickSizeType extent; size_t maximum, minimum; /* Search for compression quality that does not exceed image extent. */ extent_info->quality=0; extent=(MagickSizeType) SiPrefixToDoubleInterval(option,100.0); (void) DeleteImageOption(extent_info,"jpeg:extent"); (void) DeleteImageArtifact(jpeg_image,"jpeg:extent"); maximum=image_info->quality; if (maximum < 2) maximum=101; for (minimum=2; minimum < maximum; ) { (void) AcquireUniqueFilename(jpeg_image->filename); jpeg_image->quality=minimum+(maximum-minimum+1)/2; status=WriteJPEGImage(extent_info,jpeg_image,exception); if (GetBlobSize(jpeg_image) <= extent) minimum=jpeg_image->quality+1; else maximum=jpeg_image->quality-1; (void) RelinquishUniqueFileResource(jpeg_image->filename); } quality=(int) minimum-1; jpeg_image=DestroyImage(jpeg_image); } extent_info=DestroyImageInfo(extent_info); } jpeg_set_quality(&jpeg_info,quality,TRUE); #if (JPEG_LIB_VERSION >= 70) option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) { GeometryInfo geometry_info; int flags; /* Set quality scaling for luminance and chrominance separately. */ flags=ParseGeometry(option,&geometry_info); if (((flags & RhoValue) != 0) && ((flags & SigmaValue) != 0)) { jpeg_info.q_scale_factor[0]=jpeg_quality_scaling((int) (geometry_info.rho+0.5)); jpeg_info.q_scale_factor[1]=jpeg_quality_scaling((int) (geometry_info.sigma+0.5)); jpeg_default_qtables(&jpeg_info,TRUE); } } #endif colorspace=jpeg_info.in_color_space; value=GetImageOption(image_info,"jpeg:colorspace"); if (value == (char *) NULL) value=GetImageProperty(image,"jpeg:colorspace",exception); if (value != (char *) NULL) colorspace=StringToInteger(value); sampling_factor=(const char *) NULL; if (colorspace == jpeg_info.in_color_space) { value=GetImageOption(image_info,"jpeg:sampling-factor"); if (value == (char *) NULL) value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } } value=GetImageOption(image_info,"jpeg:sampling-factor"); if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor == (const char *) NULL) { if (quality >= 90) for (i=0; i < MAX_COMPONENTS; i++) { jpeg_info.comp_info[i].h_samp_factor=1; jpeg_info.comp_info[i].v_samp_factor=1; } } else { char **factors; GeometryInfo geometry_info; MagickStatusType flags; /* Set sampling factor. */ i=0; factors=SamplingFactorToList(sampling_factor); if (factors != (char **) NULL) { for (i=0; i < MAX_COMPONENTS; i++) { if (factors[i] == (char *) NULL) break; flags=ParseGeometry(factors[i],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_info.comp_info[i].h_samp_factor=(int) geometry_info.rho; jpeg_info.comp_info[i].v_samp_factor=(int) geometry_info.sigma; factors[i]=(char *) RelinquishMagickMemory(factors[i]); } factors=(char **) RelinquishMagickMemory(factors); } for ( ; i < MAX_COMPONENTS; i++) { jpeg_info.comp_info[i].h_samp_factor=1; jpeg_info.comp_info[i].v_samp_factor=1; } } option=GetImageOption(image_info,"jpeg:q-table"); if (option != (const char *) NULL) { QuantizationTable *table; /* Custom quantization tables. */ table=GetQuantizationTable(option,"0",exception); if (table != (QuantizationTable *) NULL) { for (i=0; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=0; jpeg_add_quant_table(&jpeg_info,0,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } table=GetQuantizationTable(option,"1",exception); if (table != (QuantizationTable *) NULL) { for (i=1; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=1; jpeg_add_quant_table(&jpeg_info,1,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } table=GetQuantizationTable(option,"2",exception); if (table != (QuantizationTable *) NULL) { for (i=2; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=2; jpeg_add_quant_table(&jpeg_info,2,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } table=GetQuantizationTable(option,"3",exception); if (table != (QuantizationTable *) NULL) { for (i=3; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=3; jpeg_add_quant_table(&jpeg_info,3,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } } jpeg_start_compress(&jpeg_info,TRUE); if (image->debug != MagickFalse) { if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Storage class: DirectClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Depth: %.20g", (double) image->depth); if (image->colors != 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Number of colors: %.20g",(double) image->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Number of colors: unspecified"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "JPEG data precision: %d",(int) jpeg_info.data_precision); switch (image->colorspace) { case CMYKColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Storage class: DirectClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: CMYK"); break; } case YCbCrColorspace: case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: YCbCr"); break; } default: break; } switch (image->colorspace) { case CMYKColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: CMYK"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor, jpeg_info.comp_info[3].h_samp_factor, jpeg_info.comp_info[3].v_samp_factor); break; } case GRAYColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: GRAY"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d",jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor); break; } case sRGBColorspace: case RGBColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image colorspace is RGB"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor); break; } case YCbCrColorspace: case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: YCbCr"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d", image->colorspace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor, jpeg_info.comp_info[3].h_samp_factor, jpeg_info.comp_info[3].v_samp_factor); break; } } } /* Write JPEG profiles. */ value=GetImageProperty(image,"comment",exception); if (value != (char *) NULL) for (i=0; i < (ssize_t) strlen(value); i+=65533L) jpeg_write_marker(&jpeg_info,JPEG_COM,(unsigned char *) value+i, (unsigned int) MagickMin((size_t) strlen(value+i),65533L)); if (image->profiles != (void *) NULL) WriteProfile(&jpeg_info,image); /* Convert MIFF to JPEG raster pixels. */ memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.input_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_compress(&jpeg_info); if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(MagickFalse); } scanline[0]=(JSAMPROW) jpeg_pixels; scale=65535/(unsigned short) GetQuantumRange((size_t) jpeg_info.data_precision); if (scale == 0) scale=1; if (jpeg_info.data_precision <= 8) { if ((jpeg_info.in_color_space == JCS_RGB) || (jpeg_info.in_color_space == JCS_YCbCr)) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) ScaleQuantumToChar(GetPixelRed(image,p)); *q++=(JSAMPLE) ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=(JSAMPLE) ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else if (jpeg_info.in_color_space == JCS_GRAYSCALE) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( image,p))); p+=GetPixelChannels(image); } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { /* Convert DirectClass packets to contiguous CMYK scanlines. */ *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelCyan(image,p)))); *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelMagenta(image,p)))); *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelYellow(image,p)))); *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelBlack(image,p)))); p+=GetPixelChannels(image); } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (jpeg_info.in_color_space == JCS_GRAYSCALE) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, p)))/scale); p+=GetPixelChannels(image); } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else if ((jpeg_info.in_color_space == JCS_RGB) || (jpeg_info.in_color_space == JCS_YCbCr)) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelRed(image,p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelGreen(image,p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelBlue(image,p))/scale); p+=GetPixelChannels(image); } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { /* Convert DirectClass packets to contiguous CMYK scanlines. */ *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelRed( image,p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelGreen( image,p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelBlue( image,p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelBlack( image,p))/scale); p+=GetPixelChannels(image); } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (y == (ssize_t) image->rows) jpeg_finish_compress(&jpeg_info); /* Relinquish resources. */ jpeg_destroy_compress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Changed the JPEG writer to raise a warning when the exif profile exceeds 65533 bytes and truncate it.'</s>
<s>[INST] Given the following code containing errors, provide 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 vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'kvm:vmx: more complete state update on APICv on/off The function to update APICv on/off state (in particular, to deactivate it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust APICv-related fields among secondary processor-based VM-execution controls. As a result, Windows 2012 guests get stuck when SynIC-based auto-EOI interrupt intersected with e.g. an IPI in the guest. In addition, the MSR intercept bitmap isn't updated every time "virtualize x2APIC mode" is toggled. This path can only be triggered by a malicious guest, because Windows didn't use x2APIC but rather their own synthetic APIC access MSRs; however a guest running in a SynIC-enabled VM could switch to x2APIC and thus obtain direct access to host APIC MSRs (CVE-2016-4440). The patch fixes those omissions. Signed-off-by: Roman Kagan <rkagan@virtuozzo.com> Reported-by: Steve Rutherford <srutherford@google.com> Reported-by: Yang Zhang <yang.zhang.wz@gmail.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int userfaultfd_register(struct userfaultfd_ctx *ctx, unsigned long arg) { struct mm_struct *mm = ctx->mm; struct vm_area_struct *vma, *prev, *cur; int ret; struct uffdio_register uffdio_register; struct uffdio_register __user *user_uffdio_register; unsigned long vm_flags, new_flags; bool found; bool basic_ioctls; unsigned long start, end, vma_end; user_uffdio_register = (struct uffdio_register __user *) arg; ret = -EFAULT; if (copy_from_user(&uffdio_register, user_uffdio_register, sizeof(uffdio_register)-sizeof(__u64))) goto out; ret = -EINVAL; if (!uffdio_register.mode) goto out; if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING| UFFDIO_REGISTER_MODE_WP)) goto out; vm_flags = 0; if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING) vm_flags |= VM_UFFD_MISSING; if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) { vm_flags |= VM_UFFD_WP; /* * FIXME: remove the below error constraint by * implementing the wprotect tracking mode. */ ret = -EINVAL; goto out; } ret = validate_range(mm, uffdio_register.range.start, uffdio_register.range.len); if (ret) goto out; start = uffdio_register.range.start; end = start + uffdio_register.range.len; ret = -ENOMEM; if (!mmget_not_zero(mm)) goto out; down_write(&mm->mmap_sem); vma = find_vma_prev(mm, start, &prev); if (!vma) goto out_unlock; /* check that there's at least one vma in the range */ ret = -EINVAL; if (vma->vm_start >= end) goto out_unlock; /* * If the first vma contains huge pages, make sure start address * is aligned to huge page size. */ if (is_vm_hugetlb_page(vma)) { unsigned long vma_hpagesize = vma_kernel_pagesize(vma); if (start & (vma_hpagesize - 1)) goto out_unlock; } /* * Search for not compatible vmas. */ found = false; basic_ioctls = false; for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { cond_resched(); BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); /* check not compatible vmas */ ret = -EINVAL; if (!vma_can_userfault(cur)) goto out_unlock; /* * If this vma contains ending address, and huge pages * check alignment. */ if (is_vm_hugetlb_page(cur) && end <= cur->vm_end && end > cur->vm_start) { unsigned long vma_hpagesize = vma_kernel_pagesize(cur); ret = -EINVAL; if (end & (vma_hpagesize - 1)) goto out_unlock; } /* * Check that this vma isn't already owned by a * different userfaultfd. We can't allow more than one * userfaultfd to own a single vma simultaneously or we * wouldn't know which one to deliver the userfaults to. */ ret = -EBUSY; if (cur->vm_userfaultfd_ctx.ctx && cur->vm_userfaultfd_ctx.ctx != ctx) goto out_unlock; /* * Note vmas containing huge pages */ if (is_vm_hugetlb_page(cur)) basic_ioctls = true; found = true; } BUG_ON(!found); if (vma->vm_start < start) prev = vma; ret = 0; do { cond_resched(); BUG_ON(!vma_can_userfault(vma)); BUG_ON(vma->vm_userfaultfd_ctx.ctx && vma->vm_userfaultfd_ctx.ctx != ctx); /* * Nothing to do: this vma is already registered into this * userfaultfd and with the right tracking mode too. */ if (vma->vm_userfaultfd_ctx.ctx == ctx && (vma->vm_flags & vm_flags) == vm_flags) goto skip; if (vma->vm_start > start) start = vma->vm_start; vma_end = min(end, vma->vm_end); new_flags = (vma->vm_flags & ~vm_flags) | vm_flags; prev = vma_merge(mm, prev, start, vma_end, new_flags, vma->anon_vma, vma->vm_file, vma->vm_pgoff, vma_policy(vma), ((struct vm_userfaultfd_ctx){ ctx })); if (prev) { vma = prev; goto next; } if (vma->vm_start < start) { ret = split_vma(mm, vma, start, 1); if (ret) break; } if (vma->vm_end > end) { ret = split_vma(mm, vma, end, 0); if (ret) break; } next: /* * In the vma_merge() successful mprotect-like case 8: * the next vma was merged into the current one and * the current one has not been updated yet. */ vma->vm_flags = new_flags; vma->vm_userfaultfd_ctx.ctx = ctx; skip: prev = vma; start = vma->vm_end; vma = vma->vm_next; } while (vma && vma->vm_start < end); out_unlock: up_write(&mm->mmap_sem); mmput(mm); if (!ret) { /* * Now that we scanned all vmas we can already tell * userland which ioctls methods are guaranteed to * succeed on this range. */ if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC : UFFD_API_RANGE_IOCTLS, &user_uffdio_register->ioctls)) ret = -EFAULT; } out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862', 'CWE-863'], 'message': 'userfaultfd: shmem/hugetlbfs: only allow to register VM_MAYWRITE vmas After the VMA to register the uffd onto is found, check that it has VM_MAYWRITE set before allowing registration. This way we inherit all common code checks before allowing to fill file holes in shmem and hugetlbfs with UFFDIO_COPY. The userfaultfd memory model is not applicable for readonly files unless it's a MAP_PRIVATE. Link: http://lkml.kernel.org/r/20181126173452.26955-4-aarcange@redhat.com Fixes: ff62a3421044 ("hugetlb: implement memfd sealing") Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Reviewed-by: Mike Rapoport <rppt@linux.ibm.com> Reviewed-by: Hugh Dickins <hughd@google.com> Reported-by: Jann Horn <jannh@google.com> Fixes: 4c27fe4c4c84 ("userfaultfd: shmem: add shmem_mcopy_atomic_pte for userfaultfd support") Cc: <stable@vger.kernel.org> Cc: "Dr. David Alan Gilbert" <dgilbert@redhat.com> Cc: Mike Kravetz <mike.kravetz@oracle.com> Cc: Peter Xu <peterx@redhat.com> Cc: stable@vger.kernel.org Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13689/IKEv1: Fix addr+subnet length check. An IPv6 address plus subnet mask is 32 bytes, not 20 bytes. 16 bytes of IPv6 address, 16 bytes of subnet mask. 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).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline int ComputeOutSize(TfLitePadding padding, int image_size, int filter_size, int stride, int dilation_rate = 1) { int effective_filter_size = (filter_size - 1) * dilation_rate + 1; switch (padding) { case kTfLitePaddingSame: return (image_size + stride - 1) / stride; case kTfLitePaddingValid: return (image_size + stride - effective_filter_size) / stride; default: return 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Fix division by zero in TFLite padding. PiperOrigin-RevId: 370777494 Change-Id: Ic1331e4a1603b9e4c8aa183012a6c8237410aa0f'</s>
<s>[INST] Given the following code containing errors, provide 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 generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen) { return crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext *ctx) override { const Tensor *indices_t, *values_t, *shape_t, *dense_t; OP_REQUIRES_OK(ctx, ctx->input("sp_indices", &indices_t)); OP_REQUIRES_OK(ctx, ctx->input("sp_values", &values_t)); OP_REQUIRES_OK(ctx, ctx->input("sp_shape", &shape_t)); OP_REQUIRES_OK(ctx, ctx->input("dense", &dense_t)); // Validations. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()), errors::InvalidArgument( "Input sp_indices should be a matrix but received shape: ", indices_t->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values_t->shape()) && TensorShapeUtils::IsVector(shape_t->shape()), errors::InvalidArgument( "Inputs sp_values and sp_shape should be vectors " "but received shapes: ", values_t->shape().DebugString(), " and ", shape_t->shape().DebugString())); const auto indices_mat = indices_t->matrix<int64>(); const auto shape_vec = shape_t->vec<int64>(); const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec)); const auto rhs_dims = BCast::FromShape(dense_t->shape()); BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims. // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal // to dims in rhs (from right to left). auto VecGreaterEq = [](ArraySlice<int64> lhs, ArraySlice<int64> rhs) { if (lhs.size() < rhs.size()) return false; for (size_t i = 0; i < rhs.size(); ++i) { if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false; } return true; }; OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(), errors::InvalidArgument( "SparseDenseBinaryOpShared broadcasts dense to sparse " "only; got incompatible shapes: [", absl::StrJoin(lhs_dims, ","), "] vs. [", absl::StrJoin(rhs_dims, ","), "]")); Tensor *output_values = nullptr; Tensor dense_gathered; const int64 nnz = indices_t->dim_size(0); OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({nnz}), &output_values)); OP_REQUIRES_OK( ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape({nnz}), &dense_gathered)); // Pulls relevant entries from the dense side, with reshape and broadcasting // *of the dense side* taken into account. Use a TensorRef to avoid blowing // up memory. // // We can directly use the sparse indices to look up dense side, because // "b.y_reshape()" and "b.y_bcast()" are guaranteed to have rank "ndims". auto dense_gathered_flat = dense_gathered.flat<T>(); const int ndims = lhs_dims.size(); switch (ndims) { #define CASE(NDIM) \ case NDIM: { \ TensorRef<Eigen::Tensor<const T, NDIM, Eigen::RowMajor>> rhs_ref = \ dense_t->shaped<T, NDIM>(b.y_reshape()) \ .broadcast(BCast::ToIndexArray<NDIM>(b.y_bcast())); \ Eigen::array<Eigen::DenseIndex, NDIM> idx; \ bool indices_valid = true; \ for (int i = 0; i < nnz; ++i) { \ for (int d = 0; d < NDIM; ++d) { \ idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \ if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \ indices_valid = false; \ } \ } \ OP_REQUIRES( \ ctx, indices_valid, \ errors::InvalidArgument("Provided indices are out-of-bounds w.r.t. " \ "dense side with broadcasted shape")); \ dense_gathered_flat(i) = rhs_ref.coeff(idx); \ } \ break; \ } CASE(1); CASE(2); CASE(3); CASE(4); CASE(5); default: OP_REQUIRES( ctx, false, errors::InvalidArgument("Only tensors with ranks between 1 and 5 " "are currently supported. Tensor rank: ", ndims)); #undef CASE } output_values->flat<T>().device(ctx->eigen_device<Device>()) = values_t->flat<T>().binaryExpr(dense_gathered_flat, typename Functor::func()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Fix heap-buffer-overflow issue with `tf.raw_ops.SparseDenseCwiseMul`. PiperOrigin-RevId: 372054410 Change-Id: Ifcce0491e2e3816838c87e73be30a1e61b65174d'</s>
<s>[INST] Given the following code containing errors, provide 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 irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct sk_buff *skb; size_t copied; int err; IRDA_DEBUG(4, "%s()\n", __func__); skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) return err; skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n", __func__, copied, size); copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); skb_free_datagram(sk, skb); /* * Check if we have previously stopped IrTTP and we know * have more free space in our rx_queue. If so tell IrTTP * to start delivering frames again before our rx_queue gets * empty */ if (self->rx_flow == FLOW_STOP) { if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) { IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__); self->rx_flow = FLOW_START; irttp_flow_request(self->tsap, FLOW_START); } } return copied; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'irda: Fix missing msg_namelen update in irda_recvmsg_dgram() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about irda_recvmsg_dgram() not filling the msg_name in case it was set. Cc: Samuel Ortiz <samuel@sortiz.org> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { // Skip whitespace while (begin && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } else if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } else if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #12239 - crash in the x86.nz assembler ##asm (#12252)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: enum ImapAuthRes imap_auth_cram_md5(struct ImapData *idata, const char *method) { char ibuf[LONG_STRING * 2], obuf[LONG_STRING]; unsigned char hmac_response[MD5_DIGEST_LEN]; int len; int rc; if (!mutt_bit_isset(idata->capabilities, ACRAM_MD5)) return IMAP_AUTH_UNAVAIL; mutt_message(_("Authenticating (CRAM-MD5)...")); /* get auth info */ if (mutt_account_getlogin(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; imap_cmd_start(idata, "AUTHENTICATE CRAM-MD5"); /* From RFC2195: * The data encoded in the first ready response contains a presumptively * arbitrary string of random digits, a timestamp, and the fully-qualified * primary host name of the server. The syntax of the unencoded form must * correspond to that of an RFC822 'msg-id' [RFC822] as described in [POP3]. */ do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_RESPOND) { mutt_debug(1, "Invalid response from server: %s\n", ibuf); goto bail; } len = mutt_b64_decode(obuf, idata->buf + 2); if (len == -1) { mutt_debug(1, "Error decoding base64 response.\n"); goto bail; } obuf[len] = '\0'; mutt_debug(2, "CRAM challenge: %s\n", obuf); /* The client makes note of the data and then responds with a string * consisting of the user name, a space, and a 'digest'. The latter is * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the * key is a shared secret and the digested text is the timestamp (including * angle-brackets). * * Note: The user name shouldn't be quoted. Since the digest can't contain * spaces, there is no ambiguity. Some servers get this wrong, we'll work * around them when the bug report comes in. Until then, we'll remain * blissfully RFC-compliant. */ hmac_md5(idata->conn->account.pass, obuf, hmac_response); /* dubious optimisation I saw elsewhere: make the whole string in one call */ int off = snprintf(obuf, sizeof(obuf), "%s ", idata->conn->account.user); mutt_md5_toascii(hmac_response, obuf + off); mutt_debug(2, "CRAM response: %s\n", obuf); /* ibuf must be long enough to store the base64 encoding of obuf, * plus the additional debris */ mutt_b64_encode(ibuf, obuf, strlen(obuf), sizeof(ibuf) - 2); mutt_str_strcat(ibuf, sizeof(ibuf), "\r\n"); mutt_socket_send(idata->conn, ibuf); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_OK) { mutt_debug(1, "Error receiving server response.\n"); goto bail; } if (imap_code(idata->buf)) return IMAP_AUTH_SUCCESS; bail: mutt_error(_("CRAM-MD5 authentication failed.")); return IMAP_AUTH_FAILURE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t lbs_debugfs_write(struct file *f, const char __user *buf, size_t cnt, loff_t *ppos) { int r, i; char *pdata; char *p; char *p0; char *p1; char *p2; struct debug_data *d = f->private_data; pdata = kmalloc(cnt, GFP_KERNEL); if (pdata == NULL) return 0; if (copy_from_user(pdata, buf, cnt)) { lbs_deb_debugfs("Copy from user failed\n"); kfree(pdata); return 0; } p0 = pdata; for (i = 0; i < num_of_items; i++) { do { p = strstr(p0, d[i].name); if (p == NULL) break; p1 = strchr(p, '\n'); if (p1 == NULL) break; p0 = p1++; p2 = strchr(p, '='); if (!p2) break; p2++; r = simple_strtoul(p2, NULL, 0); if (d[i].size == 1) *((u8 *) d[i].addr) = (u8) r; else if (d[i].size == 2) *((u16 *) d[i].addr) = (u16) r; else if (d[i].size == 4) *((u32 *) d[i].addr) = (u32) r; else if (d[i].size == 8) *((u64 *) d[i].addr) = (u64) r; break; } while (1); } kfree(pdata); return (ssize_t)cnt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'libertas: potential oops in debugfs If we do a zero size allocation then it will oops. Also we can't be sure the user passes us a NUL terminated string so I've added a terminator. This code can only be triggered by root. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Acked-by: Dan Williams <dcbw@redhat.com> Signed-off-by: John W. Linville <linville@tuxdriver.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: parse_packet(const unsigned char *from, struct interface *ifp, const unsigned char *packet, int packetlen) { int i; const unsigned char *message; unsigned char type, len; int bodylen; struct neighbour *neigh; int have_router_id = 0, have_v4_prefix = 0, have_v6_prefix = 0, have_v4_nh = 0, have_v6_nh = 0; unsigned char router_id[8], v4_prefix[16], v6_prefix[16], v4_nh[16], v6_nh[16]; int have_hello_rtt = 0; /* Content of the RTT sub-TLV on IHU messages. */ unsigned int hello_send_us = 0, hello_rtt_receive_time = 0; babel_interface_nfo *babel_ifp = babel_get_if_nfo(ifp); if(babel_ifp->flags & BABEL_IF_TIMESTAMPS) { /* We want to track exactly when we received this packet. */ gettime(&babel_now); } if(!linklocal(from)) { flog_err(EC_BABEL_PACKET, "Received packet from non-local address %s.", format_address(from)); return; } if (babel_packet_examin (packet, packetlen)) { flog_err(EC_BABEL_PACKET, "Received malformed packet on %s from %s.", ifp->name, format_address(from)); return; } neigh = find_neighbour(from, ifp); if(neigh == NULL) { flog_err(EC_BABEL_PACKET, "Couldn't allocate neighbour."); return; } DO_NTOHS(bodylen, packet + 2); if(bodylen + 4 > packetlen) { flog_err(EC_BABEL_PACKET, "Received truncated packet (%d + 4 > %d).", bodylen, packetlen); bodylen = packetlen - 4; } i = 0; while(i < bodylen) { message = packet + 4 + i; type = message[0]; if(type == MESSAGE_PAD1) { debugf(BABEL_DEBUG_COMMON,"Received pad1 from %s on %s.", format_address(from), ifp->name); i++; continue; } len = message[1]; if(type == MESSAGE_PADN) { debugf(BABEL_DEBUG_COMMON,"Received pad%d from %s on %s.", len, format_address(from), ifp->name); } else if(type == MESSAGE_ACK_REQ) { unsigned short nonce, interval; DO_NTOHS(nonce, message + 4); DO_NTOHS(interval, message + 6); debugf(BABEL_DEBUG_COMMON,"Received ack-req (%04X %d) from %s on %s.", nonce, interval, format_address(from), ifp->name); send_ack(neigh, nonce, interval); } else if(type == MESSAGE_ACK) { debugf(BABEL_DEBUG_COMMON,"Received ack from %s on %s.", format_address(from), ifp->name); /* Nothing right now */ } else if(type == MESSAGE_HELLO) { unsigned short seqno, interval; int changed; unsigned int timestamp = 0; DO_NTOHS(seqno, message + 4); DO_NTOHS(interval, message + 6); debugf(BABEL_DEBUG_COMMON,"Received hello %d (%d) from %s on %s.", seqno, interval, format_address(from), ifp->name); changed = update_neighbour(neigh, seqno, interval); update_neighbour_metric(neigh, changed); if(interval > 0) /* Multiply by 3/2 to allow hellos to expire. */ schedule_neighbours_check(interval * 15, 0); /* Sub-TLV handling. */ if(len > 8) { if(parse_hello_subtlv(message + 8, len - 6, &timestamp) > 0) { neigh->hello_send_us = timestamp; neigh->hello_rtt_receive_time = babel_now; have_hello_rtt = 1; } } } else if(type == MESSAGE_IHU) { unsigned short txcost, interval; unsigned char address[16]; int rc; DO_NTOHS(txcost, message + 4); DO_NTOHS(interval, message + 6); rc = network_address(message[2], message + 8, len - 6, address); if(rc < 0) goto fail; debugf(BABEL_DEBUG_COMMON,"Received ihu %d (%d) from %s on %s for %s.", txcost, interval, format_address(from), ifp->name, format_address(address)); if(message[2] == 0 || is_interface_ll_address(ifp, address)) { int changed = txcost != neigh->txcost; neigh->txcost = txcost; neigh->ihu_time = babel_now; neigh->ihu_interval = interval; update_neighbour_metric(neigh, changed); if(interval > 0) /* Multiply by 3/2 to allow neighbours to expire. */ schedule_neighbours_check(interval * 45, 0); /* RTT sub-TLV. */ if(len > 10 + rc) parse_ihu_subtlv(message + 8 + rc, len - 6 - rc, &hello_send_us, &hello_rtt_receive_time); } } else if(type == MESSAGE_ROUTER_ID) { memcpy(router_id, message + 4, 8); have_router_id = 1; debugf(BABEL_DEBUG_COMMON,"Received router-id %s from %s on %s.", format_eui64(router_id), format_address(from), ifp->name); } else if(type == MESSAGE_NH) { unsigned char nh[16]; int rc; rc = network_address(message[2], message + 4, len - 2, nh); if(rc < 0) { have_v4_nh = 0; have_v6_nh = 0; goto fail; } debugf(BABEL_DEBUG_COMMON,"Received nh %s (%d) from %s on %s.", format_address(nh), message[2], format_address(from), ifp->name); if(message[2] == 1) { memcpy(v4_nh, nh, 16); have_v4_nh = 1; } else { memcpy(v6_nh, nh, 16); have_v6_nh = 1; } } else if(type == MESSAGE_UPDATE) { unsigned char prefix[16], *nh; unsigned char plen; unsigned char channels[DIVERSITY_HOPS]; unsigned short interval, seqno, metric; int rc, parsed_len; DO_NTOHS(interval, message + 6); DO_NTOHS(seqno, message + 8); DO_NTOHS(metric, message + 10); if(message[5] == 0 || (message[2] == 1 ? have_v4_prefix : have_v6_prefix)) rc = network_prefix(message[2], message[4], message[5], message + 12, message[2] == 1 ? v4_prefix : v6_prefix, len - 10, prefix); else rc = -1; if(rc < 0) { if(message[3] & 0x80) have_v4_prefix = have_v6_prefix = 0; goto fail; } parsed_len = 10 + rc; plen = message[4] + (message[2] == 1 ? 96 : 0); if(message[3] & 0x80) { if(message[2] == 1) { memcpy(v4_prefix, prefix, 16); have_v4_prefix = 1; } else { memcpy(v6_prefix, prefix, 16); have_v6_prefix = 1; } } if(message[3] & 0x40) { if(message[2] == 1) { memset(router_id, 0, 4); memcpy(router_id + 4, prefix + 12, 4); } else { memcpy(router_id, prefix + 8, 8); } have_router_id = 1; } if(!have_router_id && message[2] != 0) { flog_err(EC_BABEL_PACKET, "Received prefix with no router id."); goto fail; } debugf(BABEL_DEBUG_COMMON,"Received update%s%s for %s from %s on %s.", (message[3] & 0x80) ? "/prefix" : "", (message[3] & 0x40) ? "/id" : "", format_prefix(prefix, plen), format_address(from), ifp->name); if(message[2] == 0) { if(metric < 0xFFFF) { flog_err(EC_BABEL_PACKET, "Received wildcard update with finite metric."); goto done; } retract_neighbour_routes(neigh); goto done; } else if(message[2] == 1) { if(!have_v4_nh) goto fail; nh = v4_nh; } else if(have_v6_nh) { nh = v6_nh; } else { nh = neigh->address; } if(message[2] == 1) { if(!babel_get_if_nfo(ifp)->ipv4) goto done; } if((babel_get_if_nfo(ifp)->flags & BABEL_IF_FARAWAY)) { channels[0] = 0; } else { /* This will be overwritten by parse_update_subtlv below. */ if(metric < 256) { /* Assume non-interfering (wired) link. */ channels[0] = 0; } else { /* Assume interfering. */ channels[0] = BABEL_IF_CHANNEL_INTERFERING; channels[1] = 0; } if(parsed_len < len) parse_update_subtlv(message + 2 + parsed_len, len - parsed_len, channels); } update_route(router_id, prefix, plen, seqno, metric, interval, neigh, nh, channels, channels_len(channels)); } else if(type == MESSAGE_REQUEST) { unsigned char prefix[16], plen; int rc; rc = network_prefix(message[2], message[3], 0, message + 4, NULL, len - 2, prefix); if(rc < 0) goto fail; plen = message[3] + (message[2] == 1 ? 96 : 0); debugf(BABEL_DEBUG_COMMON,"Received request for %s from %s on %s.", message[2] == 0 ? "any" : format_prefix(prefix, plen), format_address(from), ifp->name); if(message[2] == 0) { struct babel_interface *neigh_ifp =babel_get_if_nfo(neigh->ifp); /* If a neighbour is requesting a full route dump from us, we might as well send it an IHU. */ send_ihu(neigh, NULL); /* Since nodes send wildcard requests on boot, booting a large number of nodes at the same time may cause an update storm. Ignore a wildcard request that happens shortly after we sent a full update. */ if(neigh_ifp->last_update_time < (time_t)(babel_now.tv_sec - MAX(neigh_ifp->hello_interval / 100, 1))) send_update(neigh->ifp, 0, NULL, 0); } else { send_update(neigh->ifp, 0, prefix, plen); } } else if(type == MESSAGE_MH_REQUEST) { unsigned char prefix[16], plen; unsigned short seqno; int rc; DO_NTOHS(seqno, message + 4); rc = network_prefix(message[2], message[3], 0, message + 16, NULL, len - 14, prefix); if(rc < 0) goto fail; plen = message[3] + (message[2] == 1 ? 96 : 0); debugf(BABEL_DEBUG_COMMON,"Received request (%d) for %s from %s on %s (%s, %d).", message[6], format_prefix(prefix, plen), format_address(from), ifp->name, format_eui64(message + 8), seqno); handle_request(neigh, prefix, plen, message[6], seqno, message + 8); } else { debugf(BABEL_DEBUG_COMMON,"Received unknown packet type %d from %s on %s.", type, format_address(from), ifp->name); } done: i += len + 2; continue; fail: flog_err(EC_BABEL_PACKET, "Couldn't parse packet (%d, %d) from %s on %s.", message[0], message[1], format_address(from), ifp->name); goto done; } /* We can calculate the RTT to this neighbour. */ if(have_hello_rtt && hello_send_us && hello_rtt_receive_time) { int remote_waiting_us, local_waiting_us; unsigned int rtt, smoothed_rtt; unsigned int old_rttcost; int changed = 0; remote_waiting_us = neigh->hello_send_us - hello_rtt_receive_time; local_waiting_us = time_us(neigh->hello_rtt_receive_time) - hello_send_us; /* Sanity checks (validity window of 10 minutes). */ if(remote_waiting_us < 0 || local_waiting_us < 0 || remote_waiting_us > 600000000 || local_waiting_us > 600000000) return; rtt = MAX(0, local_waiting_us - remote_waiting_us); debugf(BABEL_DEBUG_COMMON, "RTT to %s on %s sample result: %d us.", format_address(from), ifp->name, rtt); old_rttcost = neighbour_rttcost(neigh); if (valid_rtt(neigh)) { /* Running exponential average. */ smoothed_rtt = (babel_ifp->rtt_decay * rtt + (256 - babel_ifp->rtt_decay) * neigh->rtt); /* Rounding (up or down) to get closer to the sample. */ neigh->rtt = (neigh->rtt >= rtt) ? smoothed_rtt / 256 : (smoothed_rtt + 255) / 256; } else { /* We prefer to be conservative with new neighbours (higher RTT) */ assert(rtt <= 0x7FFFFFFF); neigh->rtt = 2*rtt; } changed = (neighbour_rttcost(neigh) == old_rttcost ? 0 : 1); update_neighbour_metric(neigh, changed); neigh->rtt_time = babel_now; } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'babeld: fix #10487 by adding a check on packet length The body length of a packet should satisfy the condition: packetlen >= bodylen + 4. Otherwise, heap overflows may happen. Signed-off-by: whichbug <whichbug@github.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: Status SpaceToBatchOpCompute(OpKernelContext* context, const Tensor& orig_input_tensor, const Tensor& orig_block_shape, const Tensor& orig_paddings) { const int input_dims = orig_input_tensor.dims(); if (!TensorShapeUtils::IsVector(orig_block_shape.shape())) { return errors::InvalidArgument("block_shape rank should be 1 instead of ", orig_block_shape.dims()); } const int block_dims = orig_block_shape.dim_size(0); if (orig_input_tensor.dims() < 1 + block_dims) { return errors::InvalidArgument("input rank should be >= ", 1 + block_dims, " instead of ", orig_input_tensor.dims()); } if (!(TensorShapeUtils::IsMatrix(orig_paddings.shape()) && block_dims == orig_paddings.dim_size(0) && 2 == orig_paddings.dim_size(1))) { return errors::InvalidArgument("paddings should have shape [", block_dims, ", 2] instead of ", orig_paddings.shape().DebugString()); } // To avoid out-of-bounds access in the case that the block_shape and/or // paddings tensors are concurrently modified, we must copy the values. gtl::InlinedVector<int64_t, 4> block_shape; gtl::InlinedVector<int64_t, 8> paddings; internal::spacetobatch::SubtleMustCopyFlat(orig_block_shape, &block_shape); internal::spacetobatch::SubtleMustCopyFlat(orig_paddings, &paddings); // Determine the length of the prefix of block dims that can be combined // into the batch dimension due to having no padding and block_shape=1. int removed_prefix_block_dims = 0; for (; removed_prefix_block_dims < block_dims; ++removed_prefix_block_dims) { const int dim = removed_prefix_block_dims; if (paddings[2 * dim] != 0 || paddings[2 * dim + 1] != 0 || block_shape[dim] != 1) { break; } } // Determine the length of the suffix of block dims that can be combined // into the depth dimension due to having no padding and block_shape=1. int removed_suffix_block_dims = 0; for (; removed_suffix_block_dims < block_dims - removed_prefix_block_dims; ++removed_suffix_block_dims) { const int dim = block_dims - 1 - removed_suffix_block_dims; if (paddings[dim * 2] != 0 || paddings[dim * 2 + 1] != 0 || block_shape[dim] != 1) { break; } } // Compute the product of the block_shape values. int64_t block_shape_product = 1; for (int block_dim = 0; block_dim < block_dims; ++block_dim) { block_shape_product *= block_shape[block_dim]; } if (block_shape_product <= 0) { return errors::InvalidArgument( "Product of block sizes must be positive, got ", block_shape_product); } const int internal_block_dims = block_dims - removed_prefix_block_dims - removed_suffix_block_dims; if (internal_block_dims > kMaxSpaceToBatchBlockDims) { return errors::InvalidArgument( "Maximum number of non-combined block dimensions is ", internal_block_dims, " but must not exceed ", kMaxSpaceToBatchBlockDims); } if (internal_block_dims == 0) { context->set_output(0, orig_input_tensor); return Status::OK(); } // For the purpose of computing the result, the input will be treated as // having this shape, of rank 2 + internal_block_dims. TensorShape internal_input_shape; // For the purpose of computing the result, the output will be treated as // having this shape, of rank 2 + internal_block_dims. TensorShape internal_output_shape; // The actual output shape exposed to callers. TensorShape external_output_shape; external_output_shape.AddDim(orig_input_tensor.dim_size(0) * block_shape_product); int64_t input_batch_size = orig_input_tensor.dim_size(0); for (int block_dim = 0; block_dim < removed_prefix_block_dims; ++block_dim) { const int64_t size = orig_input_tensor.dim_size(block_dim + 1); input_batch_size *= size; external_output_shape.AddDim(size); } internal_input_shape.AddDim(input_batch_size); internal_output_shape.AddDim(input_batch_size * block_shape_product); for (int block_dim = removed_prefix_block_dims; block_dim < block_dims - removed_suffix_block_dims; ++block_dim) { const int64_t pad_start = paddings[2 * block_dim], pad_end = paddings[2 * block_dim + 1]; if (pad_start < 0 || pad_end < 0) { return errors::InvalidArgument("Paddings must be non-negative"); } const int64_t input_size = orig_input_tensor.dim_size(block_dim + 1); const int64_t block_shape_value = block_shape[block_dim]; const int64_t padded_size = input_size + pad_start + pad_end; if (padded_size % block_shape_value != 0) { return errors::InvalidArgument("padded_shape[", block_dim, "]=", padded_size, " is not divisible by block_shape[", block_dim, "]=", block_shape_value); } internal_input_shape.AddDim(input_size); const int64_t output_size = padded_size / block_shape_value; internal_output_shape.AddDim(output_size); external_output_shape.AddDim(output_size); } int64_t depth = 1; for (int dim = block_dims - removed_suffix_block_dims + 1; dim < input_dims; ++dim) { const int64_t size = orig_input_tensor.dim_size(dim); external_output_shape.AddDim(size); depth *= size; } internal_input_shape.AddDim(depth); internal_output_shape.AddDim(depth); // Allocate output tensor. Tensor* output_tensor = nullptr; TF_RETURN_IF_ERROR( context->allocate_output(0, external_output_shape, &output_tensor)); const int64_t* internal_paddings = &paddings[2 * removed_prefix_block_dims]; const int64_t* internal_block_shape = &block_shape[removed_prefix_block_dims]; switch (internal_block_dims) { #define TF_SPACETOBATCH_BLOCK_DIMS_CASE(NUM_BLOCK_DIMS) \ case NUM_BLOCK_DIMS: { \ TF_RETURN_IF_ERROR( \ functor::SpaceToBatchFunctor<Device, T, NUM_BLOCK_DIMS, false>()( \ context->eigen_device<Device>(), \ orig_input_tensor.shaped<T, NUM_BLOCK_DIMS + 2>( \ internal_input_shape.dim_sizes()), \ internal_block_shape, internal_paddings, \ output_tensor->shaped<T, NUM_BLOCK_DIMS + 2>( \ internal_output_shape.dim_sizes()))); \ } break; \ /**/ TF_SPACETOBATCH_FOR_EACH_NUM_BLOCK_DIMS(TF_SPACETOBATCH_BLOCK_DIMS_CASE) #undef TF_SPACETOBATCH_BLOCK_DIMS_CASE } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix security vulnerability with SpaceToBatchNDOp. PiperOrigin-RevId: 445527615'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns) { struct mnt_namespace *new_ns; struct ucounts *ucounts; int ret; ucounts = inc_mnt_namespaces(user_ns); if (!ucounts) return ERR_PTR(-ENOSPC); new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL); if (!new_ns) { dec_mnt_namespaces(ucounts); return ERR_PTR(-ENOMEM); } ret = ns_alloc_inum(&new_ns->ns); if (ret) { kfree(new_ns); dec_mnt_namespaces(ucounts); return ERR_PTR(ret); } new_ns->ns.ops = &mntns_operations; new_ns->seq = atomic64_add_return(1, &mnt_ns_seq); atomic_set(&new_ns->count, 1); new_ns->root = NULL; INIT_LIST_HEAD(&new_ns->list); init_waitqueue_head(&new_ns->poll); new_ns->event = 0; new_ns->user_ns = get_user_ns(user_ns); new_ns->ucounts = ucounts; return new_ns; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'mnt: Add a per mount namespace limit on the number of mounts CAI Qian <caiqian@redhat.com> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <raven@themaw.net> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <caiqian@redhat.com> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tty_open(struct inode *inode, struct file *filp) { struct tty_struct *tty = NULL; int noctty, retval; struct tty_driver *driver; int index; dev_t device = inode->i_rdev; unsigned saved_flags = filp->f_flags; nonseekable_open(inode, filp); retry_open: noctty = filp->f_flags & O_NOCTTY; index = -1; retval = 0; mutex_lock(&tty_mutex); tty_lock(); if (device == MKDEV(TTYAUX_MAJOR, 0)) { tty = get_current_tty(); if (!tty) { tty_unlock(); mutex_unlock(&tty_mutex); return -ENXIO; } driver = tty_driver_kref_get(tty->driver); index = tty->index; filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */ /* noctty = 1; */ /* FIXME: Should we take a driver reference ? */ tty_kref_put(tty); goto got_driver; } #ifdef CONFIG_VT if (device == MKDEV(TTY_MAJOR, 0)) { extern struct tty_driver *console_driver; driver = tty_driver_kref_get(console_driver); index = fg_console; noctty = 1; goto got_driver; } #endif if (device == MKDEV(TTYAUX_MAJOR, 1)) { struct tty_driver *console_driver = console_device(&index); if (console_driver) { driver = tty_driver_kref_get(console_driver); if (driver) { /* Don't let /dev/console block */ filp->f_flags |= O_NONBLOCK; noctty = 1; goto got_driver; } } tty_unlock(); mutex_unlock(&tty_mutex); return -ENODEV; } driver = get_tty_driver(device, &index); if (!driver) { tty_unlock(); mutex_unlock(&tty_mutex); return -ENODEV; } got_driver: if (!tty) { /* check whether we're reopening an existing tty */ tty = tty_driver_lookup_tty(driver, inode, index); if (IS_ERR(tty)) { tty_unlock(); mutex_unlock(&tty_mutex); return PTR_ERR(tty); } } if (tty) { retval = tty_reopen(tty); if (retval) tty = ERR_PTR(retval); } else tty = tty_init_dev(driver, index, 0); mutex_unlock(&tty_mutex); tty_driver_kref_put(driver); if (IS_ERR(tty)) { tty_unlock(); return PTR_ERR(tty); } retval = tty_add_file(tty, filp); if (retval) { tty_unlock(); tty_release(inode, filp); return retval; } check_tty_count(tty, "tty_open"); if (tty->driver->type == TTY_DRIVER_TYPE_PTY && tty->driver->subtype == PTY_TYPE_MASTER) noctty = 1; #ifdef TTY_DEBUG_HANGUP printk(KERN_DEBUG "opening %s...", tty->name); #endif if (tty->ops->open) retval = tty->ops->open(tty, filp); else retval = -ENODEV; filp->f_flags = saved_flags; if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN)) retval = -EBUSY; if (retval) { #ifdef TTY_DEBUG_HANGUP printk(KERN_DEBUG "error %d in opening %s...", retval, tty->name); #endif tty_unlock(); /* need to call tty_release without BTM */ tty_release(inode, filp); if (retval != -ERESTARTSYS) return retval; if (signal_pending(current)) return retval; schedule(); /* * Need to reset f_op in case a hangup happened. */ tty_lock(); if (filp->f_op == &hung_up_tty_fops) filp->f_op = &tty_fops; tty_unlock(); goto retry_open; } tty_unlock(); mutex_lock(&tty_mutex); tty_lock(); spin_lock_irq(&current->sighand->siglock); if (!noctty && current->signal->leader && !current->signal->tty && tty->session == NULL) __proc_set_tty(current, tty); spin_unlock_irq(&current->sighand->siglock); tty_unlock(); mutex_unlock(&tty_mutex); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'TTY: drop driver reference in tty_open fail path When tty_driver_lookup_tty fails in tty_open, we forget to drop a reference to the tty driver. This was added by commit 4a2b5fddd5 (Move tty lookup/reopen to caller). Fix that by adding tty_driver_kref_put to the fail path. I will refactor the code later. This is for the ease of backporting to stable. Introduced-in: v2.6.28-rc2 Signed-off-by: Jiri Slaby <jslaby@suse.cz> Cc: stable <stable@vger.kernel.org> Cc: Alan Cox <alan@lxorguk.ukuu.org.uk> Acked-by: Sukadev Bhattiprolu <sukadev@linux.vnet.ibm.com> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <hawkes@google.com> Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ok_png_decode2(ok_png_decoder *decoder) { ok_png *png = decoder->png; uint8_t png_header[8]; if (!ok_read(decoder, png_header, sizeof(png_header))) { return; } uint8_t png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; if (memcmp(png_header, png_signature, 8) != 0) { ok_png_error(decoder->png, OK_PNG_ERROR_INVALID, "Invalid signature (not a PNG file)"); return; } // When info_only is true, we only care about the IHDR chunk and whether or not // the tRNS chunk exists. bool info_only = (decoder->decode_flags & OK_PNG_INFO_ONLY) != 0; bool hdr_found = false; bool end_found = false; while (!end_found) { uint8_t chunk_header[8]; uint8_t chunk_footer[4]; if (!ok_read(decoder, chunk_header, sizeof(chunk_header))) { return; } const uint32_t chunk_length = readBE32(chunk_header); const uint32_t chunk_type = readBE32(chunk_header + 4); bool success = false; if (!hdr_found && chunk_type != OK_PNG_CHUNK_CGBI && chunk_type != OK_PNG_CHUNK_IHDR) { ok_png_error(png, OK_PNG_ERROR_INVALID, "IHDR chunk must appear first"); return; } if (chunk_type == OK_PNG_CHUNK_IHDR) { hdr_found = true; success = ok_png_read_header(decoder, chunk_length); if (success && info_only) { // If the png has alpha, then we have all the info we need. // Otherwise, continue scanning to see if the tRNS chunk exists. if (png->has_alpha) { return; } } } else if (chunk_type == OK_PNG_CHUNK_CGBI) { success = ok_seek(decoder, (long)chunk_length); decoder->is_ios_format = true; } else if (chunk_type == OK_PNG_CHUNK_PLTE && !info_only) { success = ok_png_read_palette(decoder, chunk_length); } else if (chunk_type == OK_PNG_CHUNK_TRNS) { if (info_only) { // No need to parse this chunk, we have all the info we need. png->has_alpha = true; return; } else { success = ok_png_read_transparency(decoder, chunk_length); } } else if (chunk_type == OK_PNG_CHUNK_IDAT) { if (info_only) { // Both IHDR and tRNS must come before IDAT, so we have all the info we need. return; } success = ok_png_read_data(decoder, chunk_length); } else if (chunk_type == OK_PNG_CHUNK_IEND) { success = ok_seek(decoder, (long)chunk_length); end_found = true; } else { // Ignore this chunk success = ok_seek(decoder, (long)chunk_length); } if (!success) { return; } // Read the footer (CRC) and ignore it if (!ok_read(decoder, chunk_footer, sizeof(chunk_footer))) { return; } } // Sanity check if (!decoder->decoding_completed) { ok_png_error(png, OK_PNG_ERROR_INVALID, "Missing imaga data"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'ok_png: Disallow multiple IHDR chunks (#15)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInput); const TfLiteTensor* axis = GetInput(context, node, kAxis); TfLiteTensor* output = GetOutput(context, node, 0); output->type = input->type; if (IsConstantTensor(axis)) { int axis_value; TF_LITE_ENSURE_OK(context, GetAxisValueFromTensor(context, *axis, &axis_value)); return ExpandTensorDim(context, *input, axis_value, output); } SetTensorToDynamic(output); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = input->dims->data[0]; output_size->data[1] = input->dims->data[1]; output_size->data[2] = input->dims->data[2]; output_size->data[3] = input->dims->data[3]; return context->ResizeTensor(context, output, output_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* axis_tensor = GetInput(context, node, kAxisTensor); int axis = GetTensorData<int32_t>(axis_tensor)[0]; const int rank = NumDimensions(input); if (axis < 0) { axis += rank; } TF_LITE_ENSURE(context, axis >= 0 && axis < rank); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); switch (output->type) { case kTfLiteFloat32: { reference_ops::Reverse<float>( axis, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); break; } case kTfLiteUInt8: { reference_ops::Reverse<uint8_t>( axis, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); break; } case kTfLiteInt16: { reference_ops::Reverse<int16_t>( axis, GetTensorShape(input), GetTensorData<int16_t>(input), GetTensorShape(output), GetTensorData<int16_t>(output)); break; } case kTfLiteInt32: { reference_ops::Reverse<int32_t>( axis, GetTensorShape(input), GetTensorData<int32_t>(input), GetTensorShape(output), GetTensorData<int32_t>(output)); break; } case kTfLiteInt64: { reference_ops::Reverse<int64_t>( axis, GetTensorShape(input), GetTensorData<int64_t>(input), GetTensorShape(output), GetTensorData<int64_t>(output)); break; } case kTfLiteBool: { reference_ops::Reverse<bool>( axis, GetTensorShape(input), GetTensorData<bool>(input), GetTensorShape(output), GetTensorData<bool>(output)); break; } default: { context->ReportError(context, "Type '%s' is not supported by reverse.", TfLiteTypeGetName(output->type)); return kTfLiteError; } } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* top_k = GetInput(context, node, kInputTopK); // INT32 number of top results is supported. TF_LITE_ENSURE_TYPES_EQ(context, top_k->type, kTfLiteInt32); // Check that the tensor contains only one value. TF_LITE_ENSURE_EQ(context, NumElements(top_k), 1); const int32 k = *GetTensorData<int32_t>(top_k); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const int num_dimensions = NumDimensions(input); // Check that input has one or more dimensions. TF_LITE_ENSURE_MSG(context, input->dims->size >= 1, "TopK k input must have 1 or more dimensions."); // Check that k is less or equal the internal dimension. TF_LITE_ENSURE_MSG(context, k <= input->dims->data[num_dimensions - 1], "TopK k is higher than the internal dimension."); TfLiteIntArray* output_indexes_shape = TfLiteIntArrayCreate(num_dimensions); TfLiteIntArray* output_values_shape = TfLiteIntArrayCreate(num_dimensions); for (int i = 0; i < num_dimensions - 1; ++i) { output_indexes_shape->data[i] = input->dims->data[i]; output_values_shape->data[i] = input->dims->data[i]; } output_indexes_shape->data[num_dimensions - 1] = k; output_values_shape->data[num_dimensions - 1] = k; TfLiteTensor* output_indexes = GetOutput(context, node, kOutputIndexes); TfLiteTensor* output_values = GetOutput(context, node, kOutputValues); // Force output types. output_indexes->type = kTfLiteInt32; output_values->type = input->type; auto resize_tensor = [context](TfLiteTensor* tensor, TfLiteIntArray* new_size, TfLiteIntArray* delete_on_error) { TfLiteStatus status = context->ResizeTensor(context, tensor, new_size); if (status != kTfLiteOk) { if (delete_on_error != nullptr) { TfLiteIntArrayFree(delete_on_error); } } return status; }; TF_LITE_ENSURE_OK(context, resize_tensor(output_indexes, output_indexes_shape, output_values_shape)); TF_LITE_ENSURE_OK(context, resize_tensor(output_values, output_values_shape, nullptr)); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const int num_elements = NumElements(input); TF_LITE_ENSURE_EQ(context, num_elements, NumElements(output)); switch (input->type) { case kTfLiteInt64: return copyToTensor(context, input->data.i64, output, num_elements); case kTfLiteInt32: return copyToTensor(context, input->data.i32, output, num_elements); case kTfLiteUInt8: return copyToTensor(context, input->data.uint8, output, num_elements); case kTfLiteFloat32: return copyToTensor(context, GetTensorData<float>(input), output, num_elements); case kTfLiteBool: return copyToTensor(context, input->data.b, output, num_elements); case kTfLiteComplex64: return copyToTensor( context, reinterpret_cast<std::complex<float>*>(input->data.c64), output, num_elements); default: // Unsupported type. TF_LITE_UNSUPPORTED_TYPE(context, input->type, "Cast"); } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* cond_tensor = GetInput(context, node, kInputConditionTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, cond_tensor, output)); } TfLiteIntArray* dims = cond_tensor->dims; if (dims->size == 0) { // Scalar tensors are not supported. TF_LITE_KERNEL_LOG(context, "Where op requires condition w/ rank > 0"); return kTfLiteError; } reference_ops::SelectTrueCoords(GetTensorShape(cond_tensor), GetTensorData<bool>(cond_tensor), GetTensorData<int64_t>(output)); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus SigmoidEval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); switch (input->type) { case kTfLiteFloat32: { if (kernel_type == kReference) { reference_ops::Logistic( GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } else { optimized_ops::Logistic( GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } break; } case kTfLiteInt16: { LogisticParams params; if (kernel_type == kReference || (data->input_multiplier > 0)) { const int size = MatchingFlatSize(GetTensorShape(input), GetTensorShape(output)); reference_integer_ops::Logistic(data->input_multiplier, size, GetTensorData<int16_t>(input), GetTensorData<int16_t>(output)); } else { optimized_ops::Logistic( params, GetTensorShape(input), GetTensorData<int16_t>(input), GetTensorShape(output), GetTensorData<int16_t>(output)); } break; } case kTfLiteUInt8: { if (kernel_type == kFixedPointOptimized) { LogisticParams params; params.input_zero_point = input->params.zero_point; params.input_range_radius = data->input_range_radius; params.input_multiplier = data->input_multiplier; params.input_left_shift = data->input_left_shift; optimized_ops::Logistic16bitPrecision( params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } else { EvalUsingLookupTable(data, input, output); } break; } case kTfLiteInt8: { if (kernel_type == kFixedPointOptimized) { LogisticParams params; params.input_zero_point = input->params.zero_point; params.input_range_radius = data->input_range_radius; params.input_multiplier = data->input_multiplier; params.input_left_shift = data->input_left_shift; optimized_ops::Logistic16bitPrecision( params, GetTensorShape(input), GetTensorData<int8_t>(input), GetTensorShape(output), GetTensorData<int8_t>(output)); } else { EvalUsingLookupTable(data, input, output); } break; } default: TF_LITE_KERNEL_LOG(context, "Only float32, uint8, int16 and int8 are supported " "currently, got %s.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* diag = GetInput(context, node, kDiagonalTensor); FillDiagHelper(input, diag, output); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0); OpData* op_data = reinterpret_cast<OpData*>(node->user_data); OpContext op_context(context, node); TF_LITE_ENSURE(context, op_context.input->type == kTfLiteUInt8 || op_context.input->type == kTfLiteInt8 || op_context.input->type == kTfLiteInt16 || op_context.input->type == kTfLiteFloat16); TF_LITE_ENSURE(context, op_context.ref->type == kTfLiteFloat32); op_data->max_diff = op_data->tolerance * op_context.input->params.scale; switch (op_context.input->type) { case kTfLiteUInt8: case kTfLiteInt8: op_data->max_diff *= (1 << 8); break; case kTfLiteInt16: op_data->max_diff *= (1 << 16); break; default: break; } // Allocate tensor to store the dequantized inputs. if (op_data->cache_tensor_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK( context, context->AddTensors(context, 1, &op_data->cache_tensor_id)); } TfLiteIntArrayFree(node->temporaries); node->temporaries = TfLiteIntArrayCreate(1); node->temporaries->data[0] = op_data->cache_tensor_id; TfLiteTensor* dequantized = GetTemporary(context, node, /*index=*/0); dequantized->type = op_context.ref->type; dequantized->allocation_type = kTfLiteDynamic; TF_LITE_ENSURE_OK(context, context->ResizeTensor( context, dequantized, TfLiteIntArrayCopy(op_context.input->dims))); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus LogSoftmaxEval(TfLiteContext* context, TfLiteNode* node) { const LogSoftmaxOpData* data = reinterpret_cast<LogSoftmaxOpData*>(node->user_data); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); switch (input->type) { case kTfLiteFloat32: { SoftmaxParams op_params; if (kernel_type == kGenericOptimized) { optimized_ops::LogSoftmax( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } else { reference_ops::LogSoftmax( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } return kTfLiteOk; } case kTfLiteUInt8: { SoftmaxParams op_params = data->params; if (kernel_type == kGenericOptimized) { optimized_ops::LogSoftmax( op_params, input->params.scale, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } else { reference_ops::LogSoftmax( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } return kTfLiteOk; } case kTfLiteInt8: { const auto input_shape = GetTensorShape(input); const auto output_shape = GetTensorShape(output); const int trailing_dim = input_shape.DimensionsCount() - 1; const int outer_size = MatchingFlatSizeSkipDim(input_shape, trailing_dim, output_shape); const int depth = MatchingDim(input_shape, trailing_dim, output_shape, trailing_dim); reference_integer_ops::LogSoftmax( data->input_multiplier, data->input_left_shift, data->reverse_scaling_divisor, data->reverse_scaling_right_shift, data->diff_min, outer_size, depth, GetTensorData<int8_t>(input), GetTensorData<int8_t>(output)); return kTfLiteOk; } default: TF_LITE_KERNEL_LOG( context, "Only float32, uint8 and int8 are supported currently, got %s.", TfLiteTypeGetName(input->type)); return kTfLiteError; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLitePackParams* data = reinterpret_cast<TfLitePackParams*>(node->builtin_data); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); switch (output->type) { case kTfLiteFloat32: { return PackImpl<float>(context, node, output, data->values_count, data->axis); } case kTfLiteUInt8: { return PackImpl<uint8_t>(context, node, output, data->values_count, data->axis); } case kTfLiteInt8: { return PackImpl<int8_t>(context, node, output, data->values_count, data->axis); } case kTfLiteInt16: { return PackImpl<int16_t>(context, node, output, data->values_count, data->axis); } case kTfLiteInt32: { return PackImpl<int32_t>(context, node, output, data->values_count, data->axis); } case kTfLiteInt64: { return PackImpl<int64_t>(context, node, output, data->values_count, data->axis); } default: { context->ReportError(context, "Type '%s' is not supported by pack.", TfLiteTypeGetName(output->type)); return kTfLiteError; } } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static TfLiteStatus AllocateTemporaryTensorsIfRequired(TfLiteContext* context, TfLiteNode* node, bool is_hybrid, bool is_per_channel, KernelType kernel_type) { auto* params = reinterpret_cast<TfLiteConvParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE(context, node->inputs->size >= 2); const TfLiteTensor* input = GetInput(context, node, 0); const TfLiteTensor* filter = GetInput(context, node, 1); // If we're using the optimized multithreaded EigenTensor implementation of // convolution, it expects the filter weights to be transposed compared to // the normal TF Lite buffer format. Typical TF Lite weights are // [filter_count, filter_height, filter_width, input_depth], but for the float // implementation we need them as [filter_height, filter_width, input_depth, // filter_count]. We get to that format by transposing, and create a temporary // buffer to store the results. // This path is only used for float processing, so only create the buffer if // we're running with that data type. data->need_hwcn_weights = input->type == kTfLiteFloat32 && data->supports_multithreaded_kernel; // We don't always need to allocate im2col. It is only used in some versions // of the optimized Conv. This test just mimics something that happens inside // optimized_ops.h, in order to avoid a DCHECK(!im2col_data). data->need_im2col = IsIm2ColRequired(input, params, filter, data, is_hybrid, kernel_type); int temporaries_count = 0; if (data->need_im2col) { data->im2col_index = temporaries_count; if (data->im2col_id == kTensorNotAllocated) { context->AddTensors(context, 1, &data->im2col_id); } ++temporaries_count; } if (data->need_hwcn_weights) { data->hwcn_weights_index = temporaries_count; if (data->hwcn_weights_id == kTensorNotAllocated) { context->AddTensors(context, 1, &data->hwcn_weights_id); } ++temporaries_count; } if (is_hybrid) { // Allocate tensor to store the on-the-fly quantized inputs. data->input_quantized_index = temporaries_count; if (data->input_quantized_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK( context, context->AddTensors(context, 1, &data->input_quantized_id)); } ++temporaries_count; // Allocate tensor to store the quantization params computed during // on-the-fly input quantization. data->scaling_factors_index = temporaries_count; if (data->scaling_factors_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK( context, context->AddTensors(context, 1, &data->scaling_factors_id)); } ++temporaries_count; // Allocate tensor to store the accumulators for the matrix multiply. data->accum_scratch_index = temporaries_count; if (data->accum_scratch_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK( context, context->AddTensors(context, 1, &data->accum_scratch_id)); } ++temporaries_count; if (is_per_channel) { data->input_offset_index = temporaries_count; if (data->input_offset_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK( context, context->AddTensors(context, 1, &data->input_offset_id)); } ++temporaries_count; data->row_sums_index = temporaries_count; if (data->row_sums_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK(context, context->AddTensors(context, 1, &data->row_sums_id)); } ++temporaries_count; } } TfLiteIntArrayFree(node->temporaries); node->temporaries = TfLiteIntArrayCreate(temporaries_count); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE(context, node->inputs->size == kInputNum); TF_LITE_ENSURE(context, node->outputs->size == kOutputNum); const TfLiteTensor* input = GetInput(context, node, kInputData); const TfLiteTensor* prev_activation = GetInput(context, node, kInputPrevActivation); const TfLiteTensor* weights = GetInput(context, node, kInputWeights); const TfLiteTensor* bias = GetInput(context, node, kInputBiases); const TfLiteTensor* prev_state = GetInput(context, node, kInputPrevState); TF_LITE_ENSURE_EQ(context, input->dims->size, 2); const int num_batches = input->dims->data[0]; const int input_depth = input->dims->data[1]; TF_LITE_ENSURE_EQ(context, prev_activation->dims->size, 2); TF_LITE_ENSURE_EQ(context, prev_activation->dims->data[0], num_batches); const int activation_depth = prev_activation->dims->data[1]; const int total_depth = input_depth + activation_depth; TF_LITE_ENSURE_EQ(context, weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, weights->dims->data[0], 4 * activation_depth); TF_LITE_ENSURE_EQ(context, weights->dims->data[1], total_depth); TF_LITE_ENSURE_EQ(context, bias->dims->size, 1); TF_LITE_ENSURE_EQ(context, bias->dims->data[0], 4 * activation_depth); TF_LITE_ENSURE_EQ(context, prev_state->dims->size, 2); TF_LITE_ENSURE_EQ(context, prev_state->dims->data[0], num_batches); TF_LITE_ENSURE_EQ(context, prev_state->dims->data[1], activation_depth); TfLiteTensor* activation_out = GetOutput(context, node, kOutputActivation); TfLiteTensor* state_out = GetOutput(context, node, kOutputState); TfLiteTensor* concat_temp = GetOutput(context, node, kOutputConcatTemp); TfLiteTensor* activation_temp = GetOutput(context, node, kOutputActivationTemp); TF_LITE_ENSURE_OK(context, context->ResizeTensor( context, activation_out, TfLiteIntArrayCopy(prev_activation->dims))); TF_LITE_ENSURE_OK( context, context->ResizeTensor(context, state_out, TfLiteIntArrayCopy(prev_state->dims))); TfLiteIntArray* concat_temp_size = TfLiteIntArrayCreate(2); concat_temp_size->data[0] = num_batches; concat_temp_size->data[1] = total_depth; TF_LITE_ENSURE_OK( context, context->ResizeTensor(context, concat_temp, concat_temp_size)); TfLiteIntArray* activation_temp_size = TfLiteIntArrayCreate(2); activation_temp_size->data[0] = num_batches; activation_temp_size->data[1] = 4 * activation_depth; TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, activation_temp, activation_temp_size)); // Set the state tensors as persistent. for (auto index : {kInputPrevActivation, kInputPrevState}) { TfLiteTensor* tensor = &context->tensors[node->inputs->data[index]]; tensor->allocation_type = kTfLiteArenaRwPersistent; } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { // Check for supported activation types. auto* params = reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data); const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const bool is_quantized = ((filter->type == kTfLiteUInt8) || (filter->type == kTfLiteInt8)); const bool is_hybrid = is_quantized && (input->type == kTfLiteFloat32); const bool is_pie = kernel_type == kLegacyPie; // Pie and hybrid path supports all kinds of fused activations, otherwise only // clipping activations are supported. if (!is_pie && !is_hybrid) { TF_LITE_ENSURE(context, params->activation == kTfLiteActNone || params->activation == kTfLiteActRelu || params->activation == kTfLiteActReluN1To1 || params->activation == kTfLiteActRelu6); } return PrepareImpl(context, node); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = input->type; return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus PrepareImpl(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); // Check we have all the inputs and outputs we need. TF_LITE_ENSURE(context, node->inputs->size == 2 || node->inputs->size == 3); // Shuffled formats need a workspace to store the shuffled input activations. const int expected_outputs_count = params->weights_format == kTfLiteFullyConnectedWeightsFormatDefault ? 1 : 2; TF_LITE_ENSURE_EQ(context, node->outputs->size, expected_outputs_count); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor); const TfLiteTensor* bias = (node->inputs->size == 3) ? GetOptionalInputTensor(context, node, kBiasTensor) : nullptr; TfLiteTensor* output = GetOutput(context, node, kOutputTensor); // Check proper datatype match among all Input Tensors TF_LITE_ENSURE_STATUS( CheckTypes(context, input, filter, bias, output, params)); // Check all the parameters of tensor match within themselves and match the // input configuration. int input_size = 1; for (int i = 0; i < input->dims->size; i++) { input_size *= input->dims->data[i]; } TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 2); const int batch_size = input_size / filter->dims->data[1]; const int num_units = filter->dims->data[0]; if (bias) { TF_LITE_ENSURE_EQ(context, NumElements(bias), SizeOfDimension(filter, 0)); } // Note that quantized inference requires that all tensors have their // parameters set. This is usually done during quantized training. if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8 || input->type == kTfLiteInt16) { double real_multiplier = 0.0; TF_LITE_ENSURE_STATUS(GetQuantizedConvolutionMultipler( context, input, filter, bias, output, &real_multiplier)); int exponent; QuantizeMultiplier(real_multiplier, &data->output_multiplier, &exponent); data->output_shift = exponent; TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized( context, params->activation, output, &data->output_activation_min, &data->output_activation_max)); } if (input->type == kTfLiteInt16 && output->type == kTfLiteInt16) { TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); } // If we have to perform on-the-fly quantization (with quantized weights and // float inputs) first we need to quantize the inputs. Allocate a temporary // buffer to store the intermediate quantized values. // Additionally, we allocate a temporary buffer to store the accumulated // quantized values prior to multiplication by the scaling factor. if (input->type == kTfLiteFloat32 && (filter->type == kTfLiteUInt8 || filter->type == kTfLiteInt8)) { TfLiteIntArrayFree(node->temporaries); data->compute_row_sums = true; node->temporaries = TfLiteIntArrayCreate(5); node->temporaries->data[0] = data->scratch_tensor_index; TfLiteTensor* input_quantized = GetTemporary(context, node, /*index=*/0); input_quantized->type = filter->type; input_quantized->allocation_type = kTfLiteArenaRw; TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims); TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized, input_quantized_size)); node->temporaries->data[1] = data->scratch_tensor_index + 1; TfLiteTensor* scaling_factors = GetTemporary(context, node, /*index=*/1); scaling_factors->type = kTfLiteFloat32; scaling_factors->allocation_type = kTfLiteArenaRw; int scaling_dims[1] = {batch_size}; if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) { TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1); scaling_factors_size->data[0] = batch_size; TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors, scaling_factors_size)); } node->temporaries->data[2] = data->scratch_tensor_index + 2; TfLiteTensor* accum_scratch = GetTemporary(context, node, /*index=*/2); accum_scratch->type = kTfLiteInt32; accum_scratch->allocation_type = kTfLiteArenaRw; int accum_scratch_dims[2] = {num_units, batch_size}; if (!TfLiteIntArrayEqualsArray(accum_scratch->dims, 2, accum_scratch_dims)) { TfLiteIntArray* accum_size = TfLiteIntArrayCreate(2); accum_size->data[0] = num_units; accum_size->data[1] = batch_size; TF_LITE_ENSURE_OK( context, context->ResizeTensor(context, accum_scratch, accum_size)); } node->temporaries->data[3] = data->scratch_tensor_index + 3; TfLiteTensor* input_offsets = GetTemporary(context, node, /*index=*/3); input_offsets->type = kTfLiteInt32; input_offsets->allocation_type = kTfLiteArenaRw; if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) { TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1); input_offsets_size->data[0] = batch_size; TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets, input_offsets_size)); } node->temporaries->data[4] = data->scratch_tensor_index + 4; TfLiteTensor* row_sums = GetTemporary(context, node, /*index=*/4); row_sums->type = kTfLiteInt32; row_sums->allocation_type = kTfLiteArenaRwPersistent; int row_sums_dims[1] = {num_units}; if (!TfLiteIntArrayEqualsArray(row_sums->dims, 1, row_sums_dims)) { TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(1); row_sums_size->data[0] = row_sums_dims[0]; TF_LITE_ENSURE_OK( context, context->ResizeTensor(context, row_sums, row_sums_size)); } } // Resize output. TfLiteIntArray* output_size_array = nullptr; if (params->keep_num_dims) { // When number of dimensions are kept the filter operates along the last // dimensions. In other words, for an input tensor with shape // [batch_size, ..., n_inputs] and a filter of shape [n_inputs, n_units] // this Op produces an output of shape [batch_size, ..., n_units]. TF_LITE_ENSURE_EQ(context, input->dims->data[input->dims->size - 1], SizeOfDimension(filter, 1)); output_size_array = TfLiteIntArrayCopy(input->dims); output_size_array->data[output_size_array->size - 1] = num_units; } else { // Otherwise, the output is (potentially flattened to) a 2-D matrix. output_size_array = TfLiteIntArrayCreate(2); output_size_array->data[0] = batch_size; output_size_array->data[1] = num_units; } TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output, output_size_array)); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 4); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* indices = GetInput(context, node, kIndicesTensor); const TfLiteTensor* output_shape = GetInput(context, node, kOutputShapeTensor); const TfLiteTensor* values = GetInput(context, node, kValueInputTensor); const TfLiteTensor* default_value = GetInput(context, node, kDefaultValueTensor); // TODO(renjieliu): Handle validate_indices. // Indices can be 0-D, 1-D or 2-D. TF_LITE_ASSERT(NumDimensions(indices) >= 0); TF_LITE_ENSURE(context, NumDimensions(indices) < 3); TF_LITE_ASSERT(NumDimensions(output_shape) >= 0); TF_LITE_ENSURE_EQ(context, NumDimensions(output_shape), 1); // Values can be 0-D or 1-D. TF_LITE_ASSERT(NumDimensions(values) >= 0); TF_LITE_ENSURE(context, NumDimensions(values) < 2); TF_LITE_ENSURE_EQ(context, NumElements(default_value), 1); TF_LITE_ENSURE( context, indices->type == kTfLiteInt32 || indices->type == kTfLiteInt64); TF_LITE_ENSURE(context, output_shape->type == kTfLiteInt32 || output_shape->type == kTfLiteInt64); TF_LITE_ENSURE(context, values->type == kTfLiteInt32 || values->type == kTfLiteInt64 || values->type == kTfLiteInt8 || values->type == kTfLiteUInt8 || values->type == kTfLiteFloat32); TF_LITE_ENSURE_TYPES_EQ(context, values->type, default_value->type); // Ensure dimensions match. TF_LITE_ENSURE_OK( context, CheckDimensionsMatch(context, indices, output_shape, values)); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = values->type; TF_LITE_ENSURE_EQ(context, NumDimensions(output_shape), 1); if (!IsConstantTensor(output_shape)) { SetTensorToDynamic(output); return kTfLiteOk; } return ResizeOutputShape(context, output_shape, output); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TfLitePackParams* data = reinterpret_cast<TfLitePackParams*>(node->builtin_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), data->values_count); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input0 = GetInput(context, node, 0); const int dimension_size = NumDimensions(input0) + 1; if (data->axis < 0) { data->axis += dimension_size; } TF_LITE_ENSURE(context, NumDimensions(input0) >= data->axis); TF_LITE_ENSURE(context, data->axis >= 0); if (input0->type != kTfLiteInt32 && input0->type != kTfLiteFloat32 && input0->type != kTfLiteUInt8 && input0->type != kTfLiteInt8 && input0->type != kTfLiteInt16 && input0->type != kTfLiteInt64) { context->ReportError(context, "Type '%s' is not supported by pack.", TfLiteTypeGetName(input0->type)); return kTfLiteError; } // Make sure all inputs have the same shape and type. for (int i = 1; i < data->values_count; ++i) { const TfLiteTensor* input = GetInput(context, node, i); TF_LITE_ENSURE(context, HaveSameShapes(input0, input)); TF_LITE_ENSURE_TYPES_EQ(context, input0->type, input->type); } // Resize output. rank R will become rank R + 1 const TfLiteIntArray* input_shape = input0->dims; TfLiteIntArray* output_shape = TfLiteIntArrayCreate(dimension_size); int i = 0; for (int index = 0; index < dimension_size; ++index) { if (index == data->axis) { output_shape->data[index] = data->values_count; } else { output_shape->data[index] = input_shape->data[i++]; } } TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input0->type); // Guarantee input/output quantization params match as we do not support // packing quantized tensors. for (int i = 0; i < data->values_count; i++) { const TfLiteTensor* input = GetInput(context, node, i); TF_LITE_ENSURE_EQ(context, input->params.zero_point, output->params.zero_point); TF_LITE_ENSURE_EQ(context, input->params.scale, output->params.scale); } return context->ResizeTensor(context, output, output_shape); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus CheckInputTensorDimensions(TfLiteContext* context, TfLiteNode* node, int n_input, int n_output, int n_cell, bool use_layer_norm, bool is_integer) { const auto* params = static_cast<TfLiteLSTMParams*>(node->builtin_data); // Making sure clipping parameters have valid values. // == 0 means no clipping // > 0 means clipping TF_LITE_ENSURE(context, params->cell_clip >= 0); TF_LITE_ENSURE(context, params->proj_clip >= 0); const TfLiteTensor* input_to_forget_weights = GetInput(context, node, kInputToForgetWeightsTensor); TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[0], n_cell); TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[1], n_input); TF_LITE_ENSURE(context, (input_to_forget_weights->type == kTfLiteFloat32) || (input_to_forget_weights->type == kTfLiteUInt8) || (input_to_forget_weights->type == kTfLiteInt8)); const TfLiteTensor* input_to_input_weights = GetOptionalInputTensor(context, node, kInputToInputWeightsTensor); const bool use_cifg = (input_to_input_weights == nullptr); if (!use_cifg) { TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[0], n_cell); TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[1], n_input); TF_LITE_ENSURE_TYPES_EQ(context, input_to_input_weights->type, input_to_forget_weights->type); } const TfLiteTensor* input_to_cell_weights = GetInput(context, node, kInputToCellWeightsTensor); TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[0], n_cell); TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[1], n_input); TF_LITE_ENSURE_TYPES_EQ(context, input_to_cell_weights->type, input_to_forget_weights->type); const TfLiteTensor* recurrent_to_input_weights = GetOptionalInputTensor(context, node, kRecurrentToInputWeightsTensor); if (recurrent_to_input_weights != nullptr) { TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[0], n_cell); TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[1], n_output); TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_input_weights->type, input_to_forget_weights->type); } const TfLiteTensor* recurrent_to_forget_weights = GetInput(context, node, kRecurrentToForgetWeightsTensor); TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[0], n_cell); TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[1], n_output); TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_forget_weights->type, input_to_forget_weights->type); const TfLiteTensor* recurrent_to_cell_weights = GetInput(context, node, kRecurrentToCellWeightsTensor); TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[0], n_cell); TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[1], n_output); TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_cell_weights->type, input_to_forget_weights->type); // We make sure the input-gate's parameters are either both present (regular // LSTM) or not at all (CIFG-LSTM). const bool cifg_weights_all_or_none = ((input_to_input_weights != nullptr) && (recurrent_to_input_weights != nullptr)) || ((input_to_input_weights == nullptr) && (recurrent_to_input_weights == nullptr)); TF_LITE_ENSURE(context, cifg_weights_all_or_none == true); const TfLiteTensor* cell_to_input_weights = GetOptionalInputTensor(context, node, kCellToInputWeightsTensor); if (cell_to_input_weights) { TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->size, 1); TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->data[0], n_cell); TF_LITE_ENSURE_TYPES_EQ( context, cell_to_input_weights->type, is_integer ? kTfLiteInt16 : input_to_forget_weights->type); } const TfLiteTensor* cell_to_forget_weights = GetOptionalInputTensor(context, node, kCellToForgetWeightsTensor); if (cell_to_forget_weights) { TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->size, 1); TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->data[0], n_cell); TF_LITE_ENSURE_TYPES_EQ( context, cell_to_forget_weights->type, is_integer ? kTfLiteInt16 : input_to_forget_weights->type); } const TfLiteTensor* cell_to_output_weights = GetOptionalInputTensor(context, node, kCellToOutputWeightsTensor); if (cell_to_output_weights) { TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->size, 1); TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->data[0], n_cell); TF_LITE_ENSURE_TYPES_EQ( context, cell_to_output_weights->type, is_integer ? kTfLiteInt16 : input_to_forget_weights->type); } // Making sure the peephole weights are there all or none. const bool peephole_weights_all_or_none = ((cell_to_input_weights != nullptr || use_cifg) && (cell_to_forget_weights != nullptr) && (cell_to_output_weights != nullptr)) || ((cell_to_input_weights == nullptr) && (cell_to_forget_weights == nullptr) && (cell_to_output_weights == nullptr)); TF_LITE_ENSURE(context, peephole_weights_all_or_none == true); // Make sure the input gate bias is present only when not a CIFG-LSTM. const TfLiteTensor* input_gate_bias = GetOptionalInputTensor(context, node, kInputGateBiasTensor); if (use_cifg) { TF_LITE_ENSURE_EQ(context, input_gate_bias, nullptr); } else { TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->size, 1); TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, input_gate_bias->type, kTfLiteInt32); } else { TF_LITE_ENSURE_TYPES_EQ(context, input_gate_bias->type, kTfLiteFloat32); } } const TfLiteTensor* forget_gate_bias = GetInput(context, node, kForgetGateBiasTensor); TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->size, 1); TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, forget_gate_bias->type, kTfLiteInt32); } else { TF_LITE_ENSURE_TYPES_EQ(context, forget_gate_bias->type, kTfLiteFloat32); } const TfLiteTensor* cell_gate_bias = GetInput(context, node, kCellGateBiasTensor); TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->size, 1); TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, cell_gate_bias->type, kTfLiteInt32); } else { TF_LITE_ENSURE_TYPES_EQ(context, cell_gate_bias->type, kTfLiteFloat32); } const TfLiteTensor* output_gate_bias = GetInput(context, node, kOutputGateBiasTensor); TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->size, 1); TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, output_gate_bias->type, kTfLiteInt32); } else { TF_LITE_ENSURE_TYPES_EQ(context, output_gate_bias->type, kTfLiteFloat32); } const TfLiteTensor* projection_weights = GetOptionalInputTensor(context, node, kProjectionWeightsTensor); if (projection_weights != nullptr) { TF_LITE_ENSURE_EQ(context, projection_weights->dims->size, 2); TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[0], n_output); TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[1], n_cell); TF_LITE_ENSURE_TYPES_EQ(context, projection_weights->type, input_to_forget_weights->type); } const TfLiteTensor* projection_bias = GetOptionalInputTensor(context, node, kProjectionBiasTensor); if (projection_bias != nullptr) { TF_LITE_ENSURE_EQ(context, projection_bias->dims->size, 1); TF_LITE_ENSURE_EQ(context, projection_bias->dims->data[0], n_output); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, projection_bias->type, kTfLiteInt32); } else { TF_LITE_ENSURE_TYPES_EQ(context, projection_bias->type, kTfLiteFloat32); } } // Making sure the projection tensors are consistent: // 1) If projection weight is not present, then projection bias should not be // present. // 2) If projection weight is present, then projection bias is optional. // TODO(ghodrat): make sure this is correct. const bool projection_tensors_consistent = ((projection_weights != nullptr) || (projection_bias == nullptr)); TF_LITE_ENSURE(context, projection_tensors_consistent == true); if (use_layer_norm) { const TfLiteTensor* input_layer_norm_coefficients = GetOptionalInputTensor( context, node, kInputLayerNormCoefficientsTensor); if (use_cifg) { TF_LITE_ENSURE_EQ(context, input_layer_norm_coefficients, nullptr); } else { TF_LITE_ENSURE(context, input_layer_norm_coefficients != nullptr); TF_LITE_ENSURE_EQ(context, input_layer_norm_coefficients->dims->size, 1); TF_LITE_ENSURE_EQ(context, input_layer_norm_coefficients->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, input_layer_norm_coefficients->type, kTfLiteInt16); } else { TF_LITE_ENSURE_TYPES_EQ(context, input_layer_norm_coefficients->type, kTfLiteFloat32); } } const TfLiteTensor* forget_layer_norm_coefficients = GetOptionalInputTensor( context, node, kForgetLayerNormCoefficientsTensor); TF_LITE_ENSURE(context, forget_layer_norm_coefficients != nullptr); TF_LITE_ENSURE_EQ(context, forget_layer_norm_coefficients->dims->size, 1); TF_LITE_ENSURE_EQ(context, forget_layer_norm_coefficients->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, forget_layer_norm_coefficients->type, kTfLiteInt16); } else { TF_LITE_ENSURE_TYPES_EQ(context, forget_layer_norm_coefficients->type, kTfLiteFloat32); } const TfLiteTensor* cell_layer_norm_coefficients = GetOptionalInputTensor(context, node, kCellLayerNormCoefficientsTensor); TF_LITE_ENSURE(context, cell_layer_norm_coefficients != nullptr); TF_LITE_ENSURE_EQ(context, cell_layer_norm_coefficients->dims->size, 1); TF_LITE_ENSURE_EQ(context, cell_layer_norm_coefficients->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, cell_layer_norm_coefficients->type, kTfLiteInt16); } else { TF_LITE_ENSURE_TYPES_EQ(context, cell_layer_norm_coefficients->type, kTfLiteFloat32); } const TfLiteTensor* output_layer_norm_coefficients = GetOptionalInputTensor( context, node, kOutputLayerNormCoefficientsTensor); TF_LITE_ENSURE(context, output_layer_norm_coefficients != nullptr); TF_LITE_ENSURE_EQ(context, output_layer_norm_coefficients->dims->size, 1); TF_LITE_ENSURE_EQ(context, output_layer_norm_coefficients->dims->data[0], n_cell); if (is_integer) { TF_LITE_ENSURE_TYPES_EQ(context, output_layer_norm_coefficients->type, kTfLiteInt16); } else { TF_LITE_ENSURE_TYPES_EQ(context, output_layer_norm_coefficients->type, kTfLiteFloat32); } } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output = GetOutput(context, node, 0); const TfLiteTensor* input = GetInput(context, node, 0); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: MaxEvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt8: MaxEvalQuantizedInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt16: MaxEvalQuantizedInt16<kernel_type>(context, node, params, data, input, output); break; default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); switch (input1->type) { case kTfLiteInt32: { return EvalImpl<int32_t>(context, data->requires_broadcast, input1, input2, output); } case kTfLiteInt64: { return EvalImpl<int64_t>(context, data->requires_broadcast, input1, input2, output); } case kTfLiteFloat32: { return EvalImpl<float>(context, data->requires_broadcast, input1, input2, output); } default: { context->ReportError(context, "Type '%s' is not supported by floor_mod.", TfLiteTypeGetName(input1->type)); return kTfLiteError; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* data = GetInput(context, node, kInputDataTensor); const TfLiteTensor* segment_ids = GetInput(context, node, kInputSegmentIdsTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE(context, data->type == kTfLiteInt32 || data->type == kTfLiteFloat32); TF_LITE_ENSURE_EQ(context, segment_ids->type, kTfLiteInt32); if (!IsConstantTensor(data) || !IsConstantTensor(segment_ids)) { SetTensorToDynamic(output); return kTfLiteOk; } return ResizeOutputTensor(context, data, segment_ids, output); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_); const TfLiteTensor* input_resource_id_tensor = GetInput(context, node, kInputVariableId); const TfLiteTensor* input_value_tensor = GetInput(context, node, kInputValue); int resource_id = input_resource_id_tensor->data.i32[0]; auto& resources = subgraph->resources(); resource::CreateResourceVariableIfNotAvailable(&resources, resource_id); auto* variable = resource::GetResourceVariable(&resources, resource_id); TF_LITE_ENSURE(context, variable != nullptr); variable->AssignFrom(input_value_tensor); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors. As part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages. We also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`). PiperOrigin-RevId: 332521299 Change-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor& gradient = ctx->input(0); const Tensor& input = ctx->input(1); Tensor* input_backprop = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &input_backprop)); OP_REQUIRES( ctx, input.IsSameSize(gradient), errors::InvalidArgument("gradient and input must be the same size")); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); const Tensor& input_min_tensor = ctx->input(2); OP_REQUIRES(ctx, input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1, errors::InvalidArgument( "Input min tensor must have dimension 1. Recieved ", input_min_tensor.dims(), ".")); const Tensor& input_max_tensor = ctx->input(3); OP_REQUIRES(ctx, input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1, errors::InvalidArgument( "Input max tensor must have dimension 1. Recieved ", input_max_tensor.dims(), ".")); if (axis_ != -1) { OP_REQUIRES( ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument("min has incorrect size, expected ", depth, " was ", input_min_tensor.dim_size(0))); OP_REQUIRES( ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument("max has incorrect size, expected ", depth, " was ", input_max_tensor.dim_size(0))); } TensorShape min_max_shape(input_min_tensor.shape()); Tensor* input_min_backprop; OP_REQUIRES_OK(ctx, ctx->allocate_output(1, min_max_shape, &input_min_backprop)); Tensor* input_max_backprop; OP_REQUIRES_OK(ctx, ctx->allocate_output(2, min_max_shape, &input_max_backprop)); if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleGradientFunctor<Device, T> f; f(ctx->eigen_device<Device>(), gradient.template flat<T>(), input.template flat<T>(), input_min_tensor.scalar<T>(), input_max_tensor.scalar<T>(), input_backprop->template flat<T>(), input_min_backprop->template scalar<T>(), input_max_backprop->template scalar<T>()); } else { functor::QuantizeAndDequantizePerChannelGradientFunctor<Device, T> f; f(ctx->eigen_device<Device>(), gradient.template flat_inner_outer_dims<T, 3>(axis_ - 1), input.template flat_inner_outer_dims<T, 3>(axis_ - 1), &input_min_tensor, &input_max_tensor, input_backprop->template flat_inner_outer_dims<T, 3>(axis_ - 1), input_min_backprop->template flat<T>(), input_max_backprop->template flat<T>()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-681'], 'message': 'Validate axis input in tf.raw_ops.QuantizeAndDequantizeV4Grad PiperOrigin-RevId: 388291385 Change-Id: I3bab68dc61d935afa96c0da021a7b722c6dc8dc8'</s>
<s>[INST] Given the following code containing errors, provide 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 *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode) { const size_t bufferSize = 1024; char szBuffer[1024]; char szTmp[256]; char *pszValue = NULL; const char *pszWild = NULL; const char *pszSingle = NULL; const char *pszEscape = NULL; int bCaseInsensitive = 0; int nLength=0, i=0, iTmp=0; FEPropertyIsLike* propIsLike; if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode || !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue) return NULL; propIsLike = (FEPropertyIsLike *)psFilterNode->pOther; pszWild = propIsLike->pszWildCard; pszSingle = propIsLike->pszSingleChar; pszEscape = propIsLike->pszEscapeChar; bCaseInsensitive = propIsLike->bCaseInsensitive; if (!pszWild || strlen(pszWild) == 0 || !pszSingle || strlen(pszSingle) == 0 || !pszEscape || strlen(pszEscape) == 0) return NULL; /* -------------------------------------------------------------------- */ /* Use operand with regular expressions. */ /* -------------------------------------------------------------------- */ szBuffer[0] = '\0'; sprintf(szTmp, "%s", " (\"["); szTmp[4] = '\0'; strlcat(szBuffer, szTmp, bufferSize); /* attribute */ strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; /*#3521 */ if(bCaseInsensitive == 1) sprintf(szTmp, "%s", "]\" ~* /"); else sprintf(szTmp, "%s", "]\" =~ /"); szTmp[7] = '\0'; strlcat(szBuffer, szTmp, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; pszValue = psFilterNode->psRightNode->pszValue; nLength = strlen(pszValue); iTmp =0; if (nLength > 0 && pszValue[0] != pszWild[0] && pszValue[0] != pszSingle[0] && pszValue[0] != pszEscape[0]) { szTmp[iTmp]= '^'; iTmp++; } for (i=0; i<nLength; i++) { if (pszValue[i] != pszWild[0] && pszValue[i] != pszSingle[0] && pszValue[i] != pszEscape[0]) { szTmp[iTmp] = pszValue[i]; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszSingle[0]) { szTmp[iTmp] = '.'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszEscape[0]) { szTmp[iTmp] = '\\'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszWild[0]) { /* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */ /* iBuffer+=17; */ szTmp[iTmp++] = '.'; szTmp[iTmp++] = '*'; szTmp[iTmp] = '\0'; } } szTmp[iTmp] = '/'; szTmp[++iTmp] = '\0'; strlcat(szBuffer, szTmp, bufferSize); strlcat(szBuffer, ")", bufferSize); return msStrdup(szBuffer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-119'], 'message': 'security fix (patch by EvenR)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { u_int tlen, pdu_type, pdu_len; const u_char *tptr; const rpki_rtr_pdu *pdu_header; tptr = pptr; tlen = len; if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (tlen >= sizeof(rpki_rtr_pdu)) { ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); /* infinite loop check */ if (!pdu_type || !pdu_len) { break; } if (tlen < pdu_len) { goto trunc; } /* * Print the PDU. */ if (rpki_rtr_pdu_print(ndo, tptr, 8)) goto trunc; tlen -= pdu_len; tptr += pdu_len; } return; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13050/RPKI-Router: fix a few bugs The decoder didn't properly check that the PDU length stored in the PDU header is correct. The only check in place was in rpki_rtr_print() and it tested whether the length is zero but that is not sufficient. Make all necessary length and bounds checks, both generic and type-specific, in rpki_rtr_pdu_print() and reduce rpki_rtr_print() to a simple loop. This also fixes a minor bug and PDU type 0 (Serial Notify from RFC 6810 Section 5.2) is valid again. In rpki_rtr_pdu_print() any protocol version was considered version 0, fix it to skip the rest of input if the PDU protocol version is unknown. Ibid, the PDU type 10 (Error Report from RFC 6810 Section 5.10) case block didn't consider the "Length of Error Text" data element mandatory, put it right. Ibid, when printing an encapsulated PDU, give itself (via recursion) respective buffer length to make it possible to tell whether the encapsulated PDU fits. Do not recurse deeper than 2nd level. Update prior RPKI-Router test cases that now stop to decode earlier because of the stricter checks. 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).'</s>
<s>[INST] Given the following code containing errors, provide 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 kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run) { int ret; sigset_t sigsaved; /* Make sure they initialize the vcpu with KVM_ARM_VCPU_INIT */ if (unlikely(vcpu->arch.target < 0)) return -ENOEXEC; ret = kvm_vcpu_first_run_init(vcpu); if (ret) return ret; if (run->exit_reason == KVM_EXIT_MMIO) { ret = kvm_handle_mmio_return(vcpu, vcpu->run); if (ret) return ret; } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved); ret = 1; run->exit_reason = KVM_EXIT_UNKNOWN; while (ret > 0) { /* * Check conditions before entering the guest */ cond_resched(); update_vttbr(vcpu->kvm); if (vcpu->arch.pause) vcpu_pause(vcpu); kvm_vgic_flush_hwstate(vcpu); kvm_timer_flush_hwstate(vcpu); local_irq_disable(); /* * Re-check atomic conditions */ if (signal_pending(current)) { ret = -EINTR; run->exit_reason = KVM_EXIT_INTR; } if (ret <= 0 || need_new_vmid_gen(vcpu->kvm)) { local_irq_enable(); kvm_timer_sync_hwstate(vcpu); kvm_vgic_sync_hwstate(vcpu); continue; } /************************************************************** * Enter the guest */ trace_kvm_entry(*vcpu_pc(vcpu)); kvm_guest_enter(); vcpu->mode = IN_GUEST_MODE; ret = kvm_call_hyp(__kvm_vcpu_run, vcpu); vcpu->mode = OUTSIDE_GUEST_MODE; vcpu->arch.last_pcpu = smp_processor_id(); kvm_guest_exit(); trace_kvm_exit(*vcpu_pc(vcpu)); /* * We may have taken a host interrupt in HYP mode (ie * while executing the guest). This interrupt is still * pending, as we haven't serviced it yet! * * We're now back in SVC mode, with interrupts * disabled. Enabling the interrupts now will have * the effect of taking the interrupt again, in SVC * mode this time. */ local_irq_enable(); /* * Back from guest *************************************************************/ kvm_timer_sync_hwstate(vcpu); kvm_vgic_sync_hwstate(vcpu); ret = handle_exit(vcpu, run, ret); } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &sigsaved, NULL); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-284'], 'message': 'ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl Some ARM KVM VCPU ioctls require the vCPU to be properly initialized with the KVM_ARM_VCPU_INIT ioctl before being used with further requests. KVM_RUN checks whether this initialization has been done, but other ioctls do not. Namely KVM_GET_REG_LIST will dereference an array with index -1 without initialization and thus leads to a kernel oops. Fix this by adding checks before executing the ioctl handlers. [ Removed superflous comment from static function - Christoffer ] Changes from v1: * moved check into a static function with a meaningful name Signed-off-by: Andre Przywara <andre.przywara@linaro.org> Signed-off-by: Christoffer Dall <cdall@cs.columbia.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_path lpath; int cache_valid = card->cache.valid, df_from_cache = 0; int rv, ii; LOG_FUNC_CALLED(ctx); memcpy(&lpath, path, sizeof(struct sc_path)); if (file_out) *file_out = NULL; sc_log(ctx, "iasecc_select_file(card:%p) path.len %"SC_FORMAT_LEN_SIZE_T"u; path.type %i; aid_len %"SC_FORMAT_LEN_SIZE_T"u", card, path->len, path->type, path->aid.len); sc_log(ctx, "iasecc_select_file() path:%s", sc_print_path(path)); sc_print_cache(card); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { sc_log(ctx, "EF.ATR(aid:'%s')", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : ""); rv = iasecc_select_mf(card, file_out); LOG_TEST_RET(ctx, rv, "MF selection error"); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2); lpath.len -= 2; } } if (lpath.aid.len) { struct sc_file *file = NULL; struct sc_path ppath; sc_log(ctx, "iasecc_select_file() select parent AID:%p/%"SC_FORMAT_LEN_SIZE_T"u", lpath.aid.value, lpath.aid.len); sc_log(ctx, "iasecc_select_file() select parent AID:%s", sc_dump_hex(lpath.aid.value, lpath.aid.len)); memset(&ppath, 0, sizeof(ppath)); memcpy(ppath.value, lpath.aid.value, lpath.aid.len); ppath.len = lpath.aid.len; ppath.type = SC_PATH_TYPE_DF_NAME; if (card->cache.valid && card->cache.current_df && card->cache.current_df->path.len == lpath.aid.len && !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len)) df_from_cache = 1; rv = iasecc_select_file(card, &ppath, &file); LOG_TEST_RET(ctx, rv, "select AID path failed"); if (file_out) *file_out = file; else sc_file_free(file); if (lpath.type == SC_PATH_TYPE_DF_NAME) lpath.type = SC_PATH_TYPE_FROM_CURRENT; } if (lpath.type == SC_PATH_TYPE_PATH) lpath.type = SC_PATH_TYPE_FROM_CURRENT; if (!lpath.len) LOG_FUNC_RETURN(ctx, SC_SUCCESS); sc_print_cache(card); if (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME && card->cache.current_df->path.len == lpath.len && !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) { sc_log(ctx, "returns current DF path %s", sc_print_path(&card->cache.current_df->path)); if (file_out) { sc_file_free(*file_out); sc_file_dup(file_out, card->cache.current_df); } sc_print_cache(card); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } do { struct sc_apdu apdu; struct sc_file *file = NULL; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int pathlen = lpath.len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); if (card->type != SC_CARD_TYPE_IASECC_GEMALTO && card->type != SC_CARD_TYPE_IASECC_OBERTHUR && card->type != SC_CARD_TYPE_IASECC_SAGEM && card->type != SC_CARD_TYPE_IASECC_AMOS && card->type != SC_CARD_TYPE_IASECC_MI && card->type != SC_CARD_TYPE_IASECC_MI2) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card"); if (lpath.type == SC_PATH_TYPE_FILE_ID) { apdu.p1 = 0x02; if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) { apdu.p1 = 0x01; apdu.p2 = 0x04; } if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) { apdu.p1 = 0x09; if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else if (lpath.type == SC_PATH_TYPE_PARENT) { apdu.p1 = 0x03; pathlen = 0; apdu.cse = SC_APDU_CASE_2_SHORT; } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { apdu.p1 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else { sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type); LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "iasecc_select_file() invalid PATH type"); } for (ii=0; ii<2; ii++) { apdu.lc = pathlen; apdu.data = lpath.value; apdu.datalen = pathlen; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (rv == SC_ERROR_INCORRECT_PARAMETERS && lpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) { apdu.p2 = 0x0C; continue; } if (ii) { /* 'SELECT AID' do not returned FCP. Try to emulate. */ apdu.resplen = sizeof(rbuf); rv = iasecc_emulate_fcp(ctx, &apdu); LOG_TEST_RET(ctx, rv, "Failed to emulate DF FCP"); } break; } /* * Using of the cached DF and EF can cause problems in the multi-thread environment. * FIXME: introduce config. option that invalidates this cache outside the locked card session, * (or invent something else) */ if (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) { sc_invalidate_cache(card); sc_log(ctx, "iasecc_select_file() file not found, retry without cached DF"); if (file_out) { sc_file_free(*file_out); *file_out = NULL; } rv = iasecc_select_file(card, path, file_out); LOG_FUNC_RETURN(ctx, rv); } LOG_TEST_RET(ctx, rv, "iasecc_select_file() check SW failed"); sc_log(ctx, "iasecc_select_file() apdu.resp %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen) { sc_log(ctx, "apdu.resp %02X:%02X:%02X...", apdu.resp[0], apdu.resp[1], apdu.resp[2]); switch (apdu.resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = lpath; rv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen); if (rv) LOG_FUNC_RETURN(ctx, rv); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } sc_log(ctx, "FileType %i", file->type); if (file->type == SC_FILE_TYPE_DF) { if (card->cache.valid) sc_file_free(card->cache.current_df); card->cache.current_df = NULL; if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_df, file); card->cache.valid = 1; } else { if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) { sc_file_free(*file_out); *file_out = file; } else { sc_file_free(file); } } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { sc_file_free(card->cache.current_df); card->cache.current_df = NULL; sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } } while(0); sc_print_cache(card); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-674'], 'message': 'iasecc: fixed unbound recursion'</s>
<s>[INST] Given the following code containing errors, provide 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 DDeviceDiskInfoPrivate::openDataStream(int index) { if (process) { process->deleteLater(); } process = new QProcess(); QObject::connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), process, [this] (int code, QProcess::ExitStatus status) { if (isClosing()) return; if (status == QProcess::CrashExit) { setErrorString(QObject::tr("process \"%1 %2\" crashed").arg(process->program()).arg(process->arguments().join(" "))); } else if (code != 0) { setErrorString(QObject::tr("Failed to perform process \"%1 %2\", error: %3").arg(process->program()).arg(process->arguments().join(" ")).arg(QString::fromUtf8(process->readAllStandardError()))); } }); switch (currentScope) { case DDiskInfo::Headgear: { if (type != DDiskInfo::Disk) { setErrorString(QObject::tr("\"%1\" is not a disk device").arg(filePath())); return false; } if (currentMode == DDiskInfo::Read) { process->start(QStringLiteral("dd if=%1 bs=512 count=2048 status=none").arg(filePath()), QIODevice::ReadOnly); } else { process->start(QStringLiteral("dd of=%1 bs=512 status=none conv=fsync").arg(filePath())); } break; } case DDiskInfo::PartitionTable: { if (type != DDiskInfo::Disk) { setErrorString(QObject::tr("\"%1\" is not a disk device").arg(filePath())); return false; } if (currentMode == DDiskInfo::Read) process->start(QStringLiteral("sfdisk -d %1").arg(filePath()), QIODevice::ReadOnly); else process->start(QStringLiteral("sfdisk %1 --no-reread").arg(filePath())); break; } case DDiskInfo::Partition: { const DPartInfo &part = (index == 0 && currentMode == DDiskInfo::Write) ? DDevicePartInfo(filePath()) : q->getPartByNumber(index); if (!part) { dCDebug("Part is null(index: %d)", index); return false; } dCDebug("Try open device: %s, mode: %s", qPrintable(part.filePath()), currentMode == DDiskInfo::Read ? "Read" : "Write"); if (Helper::isMounted(part.filePath())) { if (Helper::umountDevice(part.filePath())) { part.d->mountPoint.clear(); } else { setErrorString(QObject::tr("\"%1\" is busy").arg(part.filePath())); return false; } } if (currentMode == DDiskInfo::Read) { const QString &executer = Helper::getPartcloneExecuter(part); process->start(QStringLiteral("%1 -s %2 -o - -c -z %3 -L /tmp/partclone.log").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly); } else { process->start(QStringLiteral("partclone.restore -s - -o %2 -z %3 -L /tmp/partclone.log").arg(part.filePath()).arg(Global::bufferSize)); } break; } case DDiskInfo::JsonInfo: { process->deleteLater(); process = 0; buffer.setData(q->toJson()); break; } default: return false; } if (process) { if (!process->waitForStarted()) { setErrorString(QObject::tr("Failed to start \"%1 %2\", error: %3").arg(process->program()).arg(process->arguments().join(" ")).arg(process->errorString())); return false; } dCDebug("The \"%s %s\" command start finished", qPrintable(process->program()), qPrintable(process->arguments().join(" "))); } bool ok = process ? process->isOpen() : buffer.open(QIODevice::ReadOnly); if (!ok) { setErrorString(QObject::tr("Failed to open process, error: %1").arg(process ? process->errorString(): buffer.errorString())); } return ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'fix: Do not use the "/tmp" directory https://github.com/linuxdeepin/deepin-clone/issues/16 https://bugzilla.opensuse.org/show_bug.cgi?id=1130388'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); OP_REQUIRES( ctx, (axis_ == -1 || axis_ < input.shape().dims()), errors::InvalidArgument("Shape must be at least rank ", axis_ + 1, " but is rank ", input.shape().dims())); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); Tensor input_min_tensor; Tensor input_max_tensor; Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); if (axis_ == -1) { auto min_val = input_min_tensor.scalar<T>()(); auto max_val = input_max_tensor.scalar<T>()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument("Invalid range: input_min ", min_val, " > input_max ", max_val)); } else { OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument( "input_min_tensor has incorrect size, was ", input_min_tensor.dim_size(0), " expected ", depth, " to match dim ", axis_, " of the input ", input_min_tensor.shape())); OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument( "input_max_tensor has incorrect size, was ", input_max_tensor.dim_size(0), " expected ", depth, " to match dim ", axis_, " of the input ", input_max_tensor.shape())); } } else { auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth}); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, range_shape, &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, range_shape, &input_max_tensor)); } if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f; f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->flat<T>()); } else { functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f; f(ctx->eigen_device<Device>(), input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->template flat_inner_outer_dims<T, 3>(axis_ - 1)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-665', 'CWE-787'], 'message': 'Fix the CHECK failure in tf.raw_ops.QuantizeAndDequantizeV2. PiperOrigin-RevId: 371361603 Change-Id: Ia70e34d41adaadddf928e95e5e5c5c97d5bc60d0'</s>
<s>[INST] Given the following code containing errors, provide 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 StreamTcpTest10 (void) { Packet *p = SCMalloc(SIZE_OF_PACKET); FAIL_IF(unlikely(p == NULL)); Flow f; ThreadVars tv; StreamTcpThread stt; TCPHdr tcph; uint8_t payload[4]; memset(p, 0, SIZE_OF_PACKET); PacketQueue pq; memset(&pq,0,sizeof(PacketQueue)); memset (&f, 0, sizeof(Flow)); memset(&tv, 0, sizeof (ThreadVars)); memset(&stt, 0, sizeof (StreamTcpThread)); memset(&tcph, 0, sizeof (TCPHdr)); FLOW_INITIALIZE(&f); p->flow = &f; StreamTcpUTInit(&stt.ra_ctx); stream_config.async_oneside = TRUE; tcph.th_win = htons(5480); tcph.th_seq = htonl(10); tcph.th_ack = htonl(11); tcph.th_flags = TH_SYN; p->tcph = &tcph; FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); p->tcph->th_seq = htonl(11); p->tcph->th_ack = htonl(11); p->tcph->th_flags = TH_ACK; p->flowflags = FLOW_PKT_TOSERVER; FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); p->tcph->th_seq = htonl(11); p->tcph->th_ack = htonl(11); p->tcph->th_flags = TH_ACK|TH_PUSH; p->flowflags = FLOW_PKT_TOSERVER; StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/ p->payload = payload; p->payload_len = 3; FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); p->tcph->th_seq = htonl(6); p->tcph->th_ack = htonl(11); p->tcph->th_flags = TH_ACK|TH_PUSH; p->flowflags = FLOW_PKT_TOSERVER; StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/ p->payload = payload; p->payload_len = 3; FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED); FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)); FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 && ((TcpSession *)(p->flow->protoctx))->server.next_seq != 11); StreamTcpSessionClear(p->flow->protoctx); SCFree(p); FLOW_DESTROY(&f); StreamTcpUTDeinit(stt.ra_ctx); PASS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'stream: reject broken ACK packets Fix evasion posibility by rejecting packets with a broken ACK field. These packets have a non-0 ACK field, but do not have a ACK flag set. Bug #3324. Reported-by: Nicolas Adba (cherry picked from commit fa692df37a796c3330c81988d15ef1a219afc006)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; int r; union { struct kvm_lapic_state *lapic; struct kvm_xsave *xsave; struct kvm_xcrs *xcrs; void *buffer; } u; u.buffer = NULL; switch (ioctl) { case KVM_GET_LAPIC: { r = -EINVAL; if (!vcpu->arch.apic) goto out; u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL); r = -ENOMEM; if (!u.lapic) goto out; r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state))) goto out; r = 0; break; } case KVM_SET_LAPIC: { r = -EINVAL; if (!vcpu->arch.apic) goto out; u.lapic = memdup_user(argp, sizeof(*u.lapic)); if (IS_ERR(u.lapic)) return PTR_ERR(u.lapic); r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic); break; } case KVM_INTERRUPT: { struct kvm_interrupt irq; r = -EFAULT; if (copy_from_user(&irq, argp, sizeof irq)) goto out; r = kvm_vcpu_ioctl_interrupt(vcpu, &irq); break; } case KVM_NMI: { r = kvm_vcpu_ioctl_nmi(vcpu); break; } case KVM_SET_CPUID: { struct kvm_cpuid __user *cpuid_arg = argp; struct kvm_cpuid cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries); break; } case KVM_SET_CPUID2: { struct kvm_cpuid2 __user *cpuid_arg = argp; struct kvm_cpuid2 cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid, cpuid_arg->entries); break; } case KVM_GET_CPUID2: { struct kvm_cpuid2 __user *cpuid_arg = argp; struct kvm_cpuid2 cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid, cpuid_arg->entries); if (r) goto out; r = -EFAULT; if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid)) goto out; r = 0; break; } case KVM_GET_MSRS: r = msr_io(vcpu, argp, kvm_get_msr, 1); break; case KVM_SET_MSRS: r = msr_io(vcpu, argp, do_set_msr, 0); break; case KVM_TPR_ACCESS_REPORTING: { struct kvm_tpr_access_ctl tac; r = -EFAULT; if (copy_from_user(&tac, argp, sizeof tac)) goto out; r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &tac, sizeof tac)) goto out; r = 0; break; }; case KVM_SET_VAPIC_ADDR: { struct kvm_vapic_addr va; r = -EINVAL; if (!irqchip_in_kernel(vcpu->kvm)) goto out; r = -EFAULT; if (copy_from_user(&va, argp, sizeof va)) goto out; r = 0; kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr); break; } case KVM_X86_SETUP_MCE: { u64 mcg_cap; r = -EFAULT; if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap)) goto out; r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap); break; } case KVM_X86_SET_MCE: { struct kvm_x86_mce mce; r = -EFAULT; if (copy_from_user(&mce, argp, sizeof mce)) goto out; r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce); break; } case KVM_GET_VCPU_EVENTS: { struct kvm_vcpu_events events; kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events); r = -EFAULT; if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events))) break; r = 0; break; } case KVM_SET_VCPU_EVENTS: { struct kvm_vcpu_events events; r = -EFAULT; if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events))) break; r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events); break; } case KVM_GET_DEBUGREGS: { struct kvm_debugregs dbgregs; kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs); r = -EFAULT; if (copy_to_user(argp, &dbgregs, sizeof(struct kvm_debugregs))) break; r = 0; break; } case KVM_SET_DEBUGREGS: { struct kvm_debugregs dbgregs; r = -EFAULT; if (copy_from_user(&dbgregs, argp, sizeof(struct kvm_debugregs))) break; r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs); break; } case KVM_GET_XSAVE: { u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL); r = -ENOMEM; if (!u.xsave) break; kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave); r = -EFAULT; if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave))) break; r = 0; break; } case KVM_SET_XSAVE: { u.xsave = memdup_user(argp, sizeof(*u.xsave)); if (IS_ERR(u.xsave)) return PTR_ERR(u.xsave); r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave); break; } case KVM_GET_XCRS: { u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL); r = -ENOMEM; if (!u.xcrs) break; kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs); r = -EFAULT; if (copy_to_user(argp, u.xcrs, sizeof(struct kvm_xcrs))) break; r = 0; break; } case KVM_SET_XCRS: { u.xcrs = memdup_user(argp, sizeof(*u.xcrs)); if (IS_ERR(u.xcrs)) return PTR_ERR(u.xcrs); r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs); break; } case KVM_SET_TSC_KHZ: { u32 user_tsc_khz; r = -EINVAL; user_tsc_khz = (u32)arg; if (user_tsc_khz >= kvm_max_guest_tsc_khz) goto out; if (user_tsc_khz == 0) user_tsc_khz = tsc_khz; kvm_set_tsc_khz(vcpu, user_tsc_khz); r = 0; goto out; } case KVM_GET_TSC_KHZ: { r = vcpu->arch.virtual_tsc_khz; goto out; } case KVM_KVMCLOCK_CTRL: { r = kvm_set_guest_paused(vcpu); goto out; } default: r = -EINVAL; } out: kfree(u.buffer); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <ahonig@google.com> Cc: stable@vger.kernel.org Signed-off-by: Andrew Honig <ahonig@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_winop(void) { int arg1 = term.csi_argv[1], arg2 = term.csi_argv[2]; if (*cfg.suppress_win && contains(cfg.suppress_win, term.csi_argv[0])) // skip suppressed window operation return; switch (term.csi_argv[0]) { when 1: win_set_iconic(false); when 2: win_set_iconic(true); when 3: win_set_pos(arg1, arg2); when 4: win_set_pixels(arg1, arg2); when 5: if (term.csi_argc != 1) return; win_set_zorder(true); // top when 6: if (term.csi_argc != 1) return; win_set_zorder(false); // bottom when 7: win_invalidate_all(false); // refresh when 8: { int def1 = term.csi_argv_defined[1], def2 = term.csi_argv_defined[2]; int rows, cols; win_get_screen_chars(&rows, &cols); win_set_chars(arg1 ?: def1 ? rows : term.rows, arg2 ?: def2 ? cols : term.cols); } when 9: { if (term.csi_argc != 2) return; // Ps = 9 ; 0 -> Restore maximized window. // Ps = 9 ; 1 -> Maximize window (i.e., resize to screen size). // Ps = 9 ; 2 -> Maximize window vertically. // Ps = 9 ; 3 -> Maximize window horizontally. int rows0 = term.rows0, cols0 = term.cols0; if (arg1 == 2) { // maximize window vertically win_set_geom(0, -1, 0, -1); term.rows0 = rows0; term.cols0 = cols0; } else if (arg1 == 3) { // maximize window horizontally win_set_geom(-1, 0, -1, 0); term.rows0 = rows0; term.cols0 = cols0; } else if (arg1 == 1) { win_maximise(1); term.rows0 = rows0; term.cols0 = cols0; } else if (arg1 == 0) { win_maximise(0); win_set_chars(rows0, cols0); } } when 10: if (term.csi_argc != 2) return; // Ps = 1 0 ; 0 -> Undo full-screen mode. // Ps = 1 0 ; 1 -> Change to full-screen. // Ps = 1 0 ; 2 -> Toggle full-screen. if (arg1 == 2) win_maximise(-2); else if (arg1 == 1 || arg1 == 0) win_maximise(arg1 ? 2 : 0); when 11: child_write(win_is_iconic() ? "\e[2t" : "\e[1t", 4); when 13: { int x, y; win_get_scrpos(&x, &y, arg1 == 2); child_printf("\e[3;%u;%ut", (ushort)x, (ushort)y); } when 14: { int height, width; win_get_pixels(&height, &width, arg1 == 2); child_printf("\e[4;%d;%dt", height, width); } when 15: { int w, h; search_monitors(&w, &h, 0, false, 0); child_printf("\e[5;%d;%dt", h, w); } when 16: child_printf("\e[6;%d;%dt", cell_height, cell_width); when 18: child_printf("\e[8;%d;%dt", term.rows, term.cols); when 19: { #ifdef size_of_monitor_only #warning not what xterm reports int rows, cols; win_get_screen_chars(&rows, &cols); child_printf("\e[9;%d;%dt", rows, cols); #else int w, h; search_monitors(&w, &h, 0, false, 0); child_printf("\e[9;%d;%dt", h / cell_height, w / cell_width); #endif } when 22: if (arg1 == 0 || arg1 == 2) win_save_title(); when 23: if (arg1 == 0 || arg1 == 2) win_restore_title(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-770'], 'message': 'tame some window operations, just in case'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PJ_DEF(pj_status_t) pjmedia_wav_playlist_create(pj_pool_t *pool, const pj_str_t *port_label, const pj_str_t file_list[], int file_count, unsigned ptime, unsigned options, pj_ssize_t buff_size, pjmedia_port **p_port) { struct playlist_port *fport; pjmedia_audio_format_detail *afd; pj_off_t pos; pj_status_t status; int index; pj_bool_t has_wave_info = PJ_FALSE; pj_str_t tmp_port_label; char filename[PJ_MAXPATH]; /* filename for open operations. */ /* Check arguments. */ PJ_ASSERT_RETURN(pool && file_list && file_count && p_port, PJ_EINVAL); /* Normalize port_label */ if (port_label == NULL || port_label->slen == 0) { tmp_port_label = pj_str("WAV playlist"); port_label = &tmp_port_label; } /* Be sure all files exist */ for (index=0; index<file_count; index++) { PJ_ASSERT_RETURN(file_list[index].slen >= 0, PJ_ETOOSMALL); if (file_list[index].slen >= PJ_MAXPATH) return PJ_ENAMETOOLONG; pj_memcpy(filename, file_list[index].ptr, file_list[index].slen); filename[file_list[index].slen] = '\0'; /* Check the file really exists. */ if (!pj_file_exists(filename)) { PJ_LOG(4,(THIS_FILE, "WAV playlist error: file '%s' not found", filename)); return PJ_ENOTFOUND; } } /* Normalize ptime */ if (ptime == 0) ptime = 20; /* Create fport instance. */ fport = create_file_list_port(pool, port_label); if (!fport) { return PJ_ENOMEM; } afd = pjmedia_format_get_audio_format_detail(&fport->base.info.fmt, 1); /* start with the first file. */ fport->current_file = 0; fport->max_file = file_count; /* Create file descriptor list */ fport->fd_list = (pj_oshandle_t*) pj_pool_zalloc(pool, sizeof(pj_oshandle_t)*file_count); if (!fport->fd_list) { return PJ_ENOMEM; } /* Create file size list */ fport->fsize_list = (pj_off_t*) pj_pool_alloc(pool, sizeof(pj_off_t)*file_count); if (!fport->fsize_list) { return PJ_ENOMEM; } /* Create start of WAVE data list */ fport->start_data_list = (unsigned*) pj_pool_alloc(pool, sizeof(unsigned)*file_count); if (!fport->start_data_list) { return PJ_ENOMEM; } /* Create data len list */ fport->data_len_list = (unsigned*) pj_pool_alloc(pool, sizeof(unsigned)*file_count); if (!fport->data_len_list) { return PJ_ENOMEM; } /* Create data left list */ fport->data_left_list = (unsigned*) pj_pool_alloc(pool, sizeof(unsigned)*file_count); if (!fport->data_left_list) { return PJ_ENOMEM; } /* Create file position list */ fport->fpos_list = (pj_off_t*) pj_pool_alloc(pool, sizeof(pj_off_t)*file_count); if (!fport->fpos_list) { return PJ_ENOMEM; } /* Create file buffer once for this operation. */ if (buff_size < 1) buff_size = PJMEDIA_FILE_PORT_BUFSIZE; fport->bufsize = (pj_uint32_t)buff_size; /* Create buffer. */ fport->buf = (char*) pj_pool_alloc(pool, fport->bufsize); if (!fport->buf) { return PJ_ENOMEM; } /* Initialize port */ fport->options = options; fport->readpos = fport->buf; /* ok run this for all files to be sure all are good for playback. */ for (index=file_count-1; index>=0; index--) { pjmedia_wave_hdr wavehdr; pj_ssize_t size_to_read, size_read; /* we end with the last one so we are good to go if still in function*/ pj_memcpy(filename, file_list[index].ptr, file_list[index].slen); filename[file_list[index].slen] = '\0'; /* Get the file size. */ fport->current_file = index; fport->fsize_list[index] = pj_file_size(filename); /* Size must be more than WAVE header size */ if (fport->fsize_list[index] <= sizeof(pjmedia_wave_hdr)) { status = PJMEDIA_ENOTVALIDWAVE; goto on_error; } /* Open file. */ status = pj_file_open( pool, filename, PJ_O_RDONLY, &fport->fd_list[index]); if (status != PJ_SUCCESS) goto on_error; /* Read the file header plus fmt header only. */ size_read = size_to_read = sizeof(wavehdr) - 8; status = pj_file_read( fport->fd_list[index], &wavehdr, &size_read); if (status != PJ_SUCCESS) { goto on_error; } if (size_read != size_to_read) { status = PJMEDIA_ENOTVALIDWAVE; goto on_error; } /* Normalize WAVE header fields values from little-endian to host * byte order. */ pjmedia_wave_hdr_file_to_host(&wavehdr); /* Validate WAVE file. */ if (wavehdr.riff_hdr.riff != PJMEDIA_RIFF_TAG || wavehdr.riff_hdr.wave != PJMEDIA_WAVE_TAG || wavehdr.fmt_hdr.fmt != PJMEDIA_FMT_TAG) { TRACE_((THIS_FILE, "actual value|expected riff=%x|%x, wave=%x|%x fmt=%x|%x", wavehdr.riff_hdr.riff, PJMEDIA_RIFF_TAG, wavehdr.riff_hdr.wave, PJMEDIA_WAVE_TAG, wavehdr.fmt_hdr.fmt, PJMEDIA_FMT_TAG)); status = PJMEDIA_ENOTVALIDWAVE; goto on_error; } /* Must be PCM with 16bits per sample */ if (wavehdr.fmt_hdr.fmt_tag != 1 || wavehdr.fmt_hdr.bits_per_sample != 16) { status = PJMEDIA_EWAVEUNSUPP; goto on_error; } /* Block align must be 2*nchannels */ if (wavehdr.fmt_hdr.block_align != wavehdr.fmt_hdr.nchan * BYTES_PER_SAMPLE) { status = PJMEDIA_EWAVEUNSUPP; goto on_error; } /* If length of fmt_header is greater than 16, skip the remaining * fmt header data. */ if (wavehdr.fmt_hdr.len > 16) { size_to_read = wavehdr.fmt_hdr.len - 16; status = pj_file_setpos(fport->fd_list[index], size_to_read, PJ_SEEK_CUR); if (status != PJ_SUCCESS) { goto on_error; } } /* Repeat reading the WAVE file until we have 'data' chunk */ for (;;) { pjmedia_wave_subchunk subchunk; size_read = 8; status = pj_file_read(fport->fd_list[index], &subchunk, &size_read); if (status != PJ_SUCCESS || size_read != 8) { status = PJMEDIA_EWAVETOOSHORT; goto on_error; } /* Normalize endianness */ PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&subchunk); /* Break if this is "data" chunk */ if (subchunk.id == PJMEDIA_DATA_TAG) { wavehdr.data_hdr.data = PJMEDIA_DATA_TAG; wavehdr.data_hdr.len = subchunk.len; break; } /* Otherwise skip the chunk contents */ size_to_read = subchunk.len; status = pj_file_setpos(fport->fd_list[index], size_to_read, PJ_SEEK_CUR); if (status != PJ_SUCCESS) { goto on_error; } } /* Current file position now points to start of data */ status = pj_file_getpos(fport->fd_list[index], &pos); fport->start_data_list[index] = (unsigned)pos; fport->data_len_list[index] = wavehdr.data_hdr.len; fport->data_left_list[index] = wavehdr.data_hdr.len; /* Validate length. */ if (wavehdr.data_hdr.len > fport->fsize_list[index] - fport->start_data_list[index]) { status = PJMEDIA_EWAVEUNSUPP; goto on_error; } if (wavehdr.data_hdr.len < ptime * wavehdr.fmt_hdr.sample_rate * wavehdr.fmt_hdr.nchan / 1000) { status = PJMEDIA_EWAVETOOSHORT; goto on_error; } /* It seems like we have a valid WAVE file. */ /* Update port info if we don't have one, otherwise check * that the WAV file has the same attributes as previous files. */ if (!has_wave_info) { afd->channel_count = wavehdr.fmt_hdr.nchan; afd->clock_rate = wavehdr.fmt_hdr.sample_rate; afd->bits_per_sample = wavehdr.fmt_hdr.bits_per_sample; afd->frame_time_usec = ptime * 1000; afd->avg_bps = afd->max_bps = afd->clock_rate * afd->channel_count * afd->bits_per_sample; has_wave_info = PJ_TRUE; } else { /* Check that this file has the same characteristics as the other * files. */ if (wavehdr.fmt_hdr.nchan != afd->channel_count || wavehdr.fmt_hdr.sample_rate != afd->clock_rate || wavehdr.fmt_hdr.bits_per_sample != afd->bits_per_sample) { /* This file has different characteristics than the other * files. */ PJ_LOG(4,(THIS_FILE, "WAV playlist error: file '%s' has differrent number" " of channels, sample rate, or bits per sample", filename)); status = PJMEDIA_EWAVEUNSUPP; goto on_error; } } /* If file is shorter than buffer size, adjust buffer size to file * size. Otherwise EOF callback will be called multiple times when * file_fill_buffer() is called. */ if (wavehdr.data_hdr.len < (unsigned)buff_size) buff_size = wavehdr.data_hdr.len; /* Create file buffer. */ fport->bufsize = (pj_uint32_t)buff_size; /* Set initial position of the file. */ fport->fpos_list[index] = fport->start_data_list[index]; } /* Fill up the buffer. */ status = file_fill_buffer(fport); if (status != PJ_SUCCESS) { goto on_error; } /* Done. */ *p_port = &fport->base; PJ_LOG(4,(THIS_FILE, "WAV playlist '%.*s' created: samp.rate=%d, ch=%d, bufsize=%uKB", (int)port_label->slen, port_label->ptr, afd->clock_rate, afd->channel_count, fport->bufsize / 1000)); return PJ_SUCCESS; on_error: for (index=0; index<file_count; ++index) { if (fport->fd_list[index] != 0) pj_file_close(fport->fd_list[index]); } return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Merge pull request from GHSA-rwgw-vwxg-q799 * Prevent potential infinite loop when parsing WAV format file * Check if subchunk is negative. * Fix and add checks * Change data type from pj_ssize_t to long. * Modify check * Fix leak file descriptor and modify check on wav_playlist * Move overflow/underflow check to pj_file_setpos() * Use macro to simplify check * modification based on comments * Remove unnecessary casting * Modification based on comments'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline u32 net_hash_mix(const struct net *net) { #ifdef CONFIG_NET_NS return (u32)(((unsigned long)net) >> ilog2(sizeof(*net))); #else return 0; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-190', 'CWE-326'], 'message': 'netns: provide pure entropy for net_hash_mix() net_hash_mix() currently uses kernel address of a struct net, and is used in many places that could be used to reveal this address to a patient attacker, thus defeating KASLR, for the typical case (initial net namespace, &init_net is not dynamically allocated) I believe the original implementation tried to avoid spending too many cycles in this function, but security comes first. Also provide entropy regardless of CONFIG_NET_NS. Fixes: 0b4419162aa6 ("netns: introduce the net_hash_mix "salt" for hashes") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Pavel Emelyanov <xemul@openvz.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static cmark_node *try_opening_table_row(cmark_syntax_extension *self, cmark_parser *parser, cmark_node *parent_container, unsigned char *input, int len) { cmark_node *table_row_block; table_row *row; if (cmark_parser_is_blank(parser)) return NULL; table_row_block = cmark_parser_add_child(parser, parent_container, CMARK_NODE_TABLE_ROW, parent_container->start_column); cmark_node_set_syntax_extension(table_row_block, self); table_row_block->end_column = parent_container->end_column; table_row_block->as.opaque = parser->mem->calloc(1, sizeof(node_table_row)); row = row_from_string(self, parser, input + cmark_parser_get_first_nonspace(parser), len - cmark_parser_get_first_nonspace(parser)); { cmark_llist *tmp; int i, table_columns = get_n_table_columns(parent_container); for (tmp = row->cells, i = 0; tmp && i < table_columns; tmp = tmp->next, ++i) { node_cell *cell = (node_cell *) tmp->data; cmark_node *node = cmark_parser_add_child(parser, table_row_block, CMARK_NODE_TABLE_CELL, parent_container->start_column + cell->start_offset); node->internal_offset = cell->internal_offset; node->end_column = parent_container->start_column + cell->end_offset; cmark_node_set_string_content(node, (char *) cell->buf->ptr); cmark_node_set_syntax_extension(node, self); } for (; i < table_columns; ++i) { cmark_node *node = cmark_parser_add_child( parser, table_row_block, CMARK_NODE_TABLE_CELL, 0); cmark_node_set_syntax_extension(node, self); } } free_table_row(parser->mem, row); cmark_parser_advance_offset(parser, (char *)input, len - 1 - cmark_parser_get_offset(parser), false); return table_row_block; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'prevent integer overflow in row_from_string * added explicit check for UINT16_MAX boundary on row->n_columns * added additional checks for row_from_string NULL returns to prevent NULL dereferences on error cases * added additional check to ensure n_columns between marker and header rows always match prior to any alignment processing * allocate alignment array based on marker rows rather than header rows * prevent memory leak on dangling node when encountering row_from_string error in try_opening_table_row * add explicit integer overflow error marker to not overload offset semantics in row_from_string with other implied error conditions'</s>
<s>[INST] Given the following code containing errors, provide 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 asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: // if (avio_feof(s->pb)) { // ret = 0; // } avio_seek(s->pb, current_pos, SEEK_SET); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-399', 'CWE-703'], 'message': 'avformat/asfdec: Fix DoS in asf_build_simple_index() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team 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: kg_unseal_v1_iov(krb5_context context, OM_uint32 *minor_status, krb5_gss_ctx_id_rec *ctx, gss_iov_buffer_desc *iov, int iov_count, size_t token_wrapper_len, int *conf_state, gss_qop_t *qop_state, int toktype) { OM_uint32 code; gss_iov_buffer_t header; gss_iov_buffer_t trailer; unsigned char *ptr; int sealalg; int signalg; krb5_checksum cksum; krb5_checksum md5cksum; size_t cksum_len = 0; size_t conflen = 0; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; md5cksum.length = cksum.length = 0; md5cksum.contents = cksum.contents = NULL; header = kg_locate_header_iov(iov, iov_count, toktype); assert(header != NULL); trailer = kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); if (trailer != NULL && trailer->buffer.length != 0) { *minor_status = (OM_uint32)KRB5_BAD_MSIZE; return GSS_S_DEFECTIVE_TOKEN; } if (header->buffer.length < token_wrapper_len + 14) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } ptr = (unsigned char *)header->buffer.value + token_wrapper_len; signalg = ptr[0]; signalg |= ptr[1] << 8; sealalg = ptr[2]; sealalg |= ptr[3] << 8; if (ptr[4] != 0xFF || ptr[5] != 0xFF) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if (toktype != KG_TOK_WRAP_MSG && sealalg != 0xFFFF) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if (toktype == KG_TOK_WRAP_MSG && !(sealalg == 0xFFFF || sealalg == ctx->sealalg)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_WRAP_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ code = kg_get_seq_num(context, ctx->seq, ptr + 14, ptr + 6, &direction, &seqnum); if (code != 0) { *minor_status = code; return GSS_S_BAD_SIG; } /* decode the message, if SEAL */ if (toktype == KG_TOK_WRAP_MSG) { if (sealalg != 0xFFFF) { if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; size_t i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } assert(enc_key->length == 16); for (i = 0; i < enc_key->length; i++) ((char *)enc_key->contents)[i] ^= 0xF0; code = kg_arcfour_docrypt_iov(context, enc_key, 0, &bigend_seqnum[0], 4, iov, iov_count); krb5_free_keyblock(context, enc_key); } else { code = kg_decrypt_iov(context, 0, ((ctx->gss_flags & GSS_C_DCE_STYLE) != 0), 0 /*EC*/, 0 /*RRC*/, ctx->enc, KG_USAGE_SEAL, NULL, iov, iov_count); } if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } } conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); } if (header->buffer.length != token_wrapper_len + 14 + cksum_len + conflen) { retval = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } /* compute the checksum of the message */ /* initialize the checksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort(); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } md5cksum.length = sumlen; /* compute the checksum of the message */ code = kg_make_checksum_iov_v1(context, md5cksum.checksum_type, cksum_len, ctx->seq, ctx->enc, sign_usage, iov, iov_count, toktype, &md5cksum); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } cksum.length = cksum_len; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; default: code = 0; retval = GSS_S_DEFECTIVE_TOKEN; goto cleanup; break; } if (code != 0) { code = 0; retval = GSS_S_BAD_SIG; goto cleanup; } /* * For GSS_C_DCE_STYLE, the caller manages the padding, because the * pad length is in the RPC PDU. The value of the padding may be * uninitialized. For normal GSS, the last bytes of the decrypted * data contain the pad length. kg_fixup_padding_iov() will find * this and fixup the last data IOV appropriately. */ if (toktype == KG_TOK_WRAP_MSG && (ctx->gss_flags & GSS_C_DCE_STYLE) == 0) { retval = kg_fixup_padding_iov(&code, iov, iov_count); if (retval != GSS_S_COMPLETE) goto cleanup; } if (conf_state != NULL) *conf_state = (sealalg != 0xFFFF); if (qop_state != NULL) *qop_state = GSS_C_QOP_DEFAULT; if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { *minor_status = (OM_uint32)G_BAD_DIRECTION; retval = GSS_S_BAD_SIG; } code = 0; retval = g_order_check(&ctx->seqstate, (gssint_uint64)seqnum); cleanup: krb5_free_checksum_contents(context, &md5cksum); *minor_status = code; return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Handle invalid RFC 1964 tokens [CVE-2014-4341...] Detect the following cases which would otherwise cause invalid memory accesses and/or integer underflow: * An RFC 1964 token being processed by an RFC 4121-only context [CVE-2014-4342] * A header with fewer than 22 bytes after the token ID or an incomplete checksum [CVE-2014-4341 CVE-2014-4342] * A ciphertext shorter than the confounder [CVE-2014-4341] * A declared padding length longer than the plaintext [CVE-2014-4341] If we detect a bad pad byte, continue on to compute the checksum to avoid creating a padding oracle, but treat the checksum as invalid even if it compares equal. CVE-2014-4341: In MIT krb5, an unauthenticated remote attacker with the ability to inject packets into a legitimately established GSSAPI application session can cause a program crash due to invalid memory references when attempting to read beyond the end of a buffer. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C CVE-2014-4342: In MIT krb5 releases krb5-1.7 and later, an unauthenticated remote attacker with the ability to inject packets into a legitimately established GSSAPI application session can cause a program crash due to invalid memory references when reading beyond the end of a buffer or by causing a null pointer dereference. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C [tlyu@mit.edu: CVE summaries, CVSS] (cherry picked from commit fb99962cbd063ac04c9a9d2cc7c75eab73f3533d) ticket: 7949 version_fixed: 1.12.2 status: resolved'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ftoa_bounded_extra(JsVarFloat val,char *str, size_t len, int radix, int fractionalDigits) { const JsVarFloat stopAtError = 0.0000001; if (isnan(val)) strncpy(str,"NaN",len); else if (!isfinite(val)) { if (val<0) strncpy(str,"-Infinity",len); else strncpy(str,"Infinity",len); } else { if (val<0) { if (--len <= 0) { *str=0; return; } // bounds check *(str++) = '-'; val = -val; } // what if we're really close to an integer? Just use that... if (((JsVarInt)(val+stopAtError)) == (1+(JsVarInt)val)) val = (JsVarFloat)(1+(JsVarInt)val); JsVarFloat d = 1; while (d*radix <= val) d*=radix; while (d >= 1) { int v = (int)(val / d); val -= v*d; if (--len <= 0) { *str=0; return; } // bounds check *(str++) = itoch(v); d /= radix; } #ifndef USE_NO_FLOATS if (((fractionalDigits<0) && val>0) || fractionalDigits>0) { bool hasPt = false; val*=radix; while (((fractionalDigits<0) && (fractionalDigits>-12) && (val > stopAtError)) || (fractionalDigits > 0)) { int v = (int)(val+((fractionalDigits==1) ? 0.4 : 0.00000001) ); val = (val-v)*radix; if (v==radix) v=radix-1; if (!hasPt) { hasPt = true; if (--len <= 0) { *str=0; return; } // bounds check *(str++)='.'; } if (--len <= 0) { *str=0; return; } // bounds check *(str++)=itoch(v); fractionalDigits--; } } #endif *(str++)=0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix strncat/cpy bounding issues (fix #1425)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cmsPipeline* DefaultICCintents(cmsContext ContextID, cmsUInt32Number nProfiles, cmsUInt32Number TheIntents[], cmsHPROFILE hProfiles[], cmsBool BPC[], cmsFloat64Number AdaptationStates[], cmsUInt32Number dwFlags) { cmsPipeline* Lut = NULL; cmsPipeline* Result; cmsHPROFILE hProfile; cmsMAT3 m; cmsVEC3 off; cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace; cmsProfileClassSignature ClassSig; cmsUInt32Number i, Intent; // For safety if (nProfiles == 0) return NULL; // Allocate an empty LUT for holding the result. 0 as channel count means 'undefined' Result = cmsPipelineAlloc(ContextID, 0, 0); if (Result == NULL) return NULL; CurrentColorSpace = cmsGetColorSpace(hProfiles[0]); for (i=0; i < nProfiles; i++) { cmsBool lIsDeviceLink, lIsInput; hProfile = hProfiles[i]; ClassSig = cmsGetDeviceClass(hProfile); lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass ); // First profile is used as input unless devicelink or abstract if ((i == 0) && !lIsDeviceLink) { lIsInput = TRUE; } else { // Else use profile in the input direction if current space is not PCS lIsInput = (CurrentColorSpace != cmsSigXYZData) && (CurrentColorSpace != cmsSigLabData); } Intent = TheIntents[i]; if (lIsInput || lIsDeviceLink) { ColorSpaceIn = cmsGetColorSpace(hProfile); ColorSpaceOut = cmsGetPCS(hProfile); } else { ColorSpaceIn = cmsGetPCS(hProfile); ColorSpaceOut = cmsGetColorSpace(hProfile); } if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) { cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch"); goto Error; } // If devicelink is found, then no custom intent is allowed and we can // read the LUT to be applied. Settings don't apply here. if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) { // Get the involved LUT from the profile Lut = _cmsReadDevicelinkLUT(hProfile, Intent); if (Lut == NULL) goto Error; // What about abstract profiles? if (ClassSig == cmsSigAbstractClass && i > 0) { if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error; } else { _cmsMAT3identity(&m); _cmsVEC3init(&off, 0, 0, 0); } if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error; } else { if (lIsInput) { // Input direction means non-pcs connection, so proceed like devicelinks Lut = _cmsReadInputLUT(hProfile, Intent); if (Lut == NULL) goto Error; } else { // Output direction means PCS connection. Intent may apply here Lut = _cmsReadOutputLUT(hProfile, Intent); if (Lut == NULL) goto Error; if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error; if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error; } } // Concatenate to the output LUT if (!cmsPipelineCat(Result, Lut)) goto Error; cmsPipelineFree(Lut); // Update current space CurrentColorSpace = ColorSpaceOut; } return Result; Error: cmsPipelineFree(Lut); if (Result != NULL) cmsPipelineFree(Result); return NULL; cmsUNUSED_PARAMETER(dwFlags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'Fix a double free on error recovering'</s>
<s>[INST] Given the following code containing errors, provide 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 imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick) { const char *quote = "`\"\\"; if (!quote_backtick) quote++; char *pt = dest; const char *s = src; *pt++ = '"'; /* save room for trailing quote-char */ dlen -= 2; for (; *s && dlen; s++) { if (strchr(quote, *s)) { dlen -= 2; if (dlen == 0) break; *pt++ = '\\'; *pt++ = *s; } else { *pt++ = *s; dlen--; } } *pt++ = '"'; *pt = '\0'; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-191'], 'message': 'Check for int underflow in imap_quote_string'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct task_struct *dup_task_struct(struct task_struct *orig) { struct task_struct *tsk; struct thread_info *ti; unsigned long *stackend; int err; prepare_to_copy(orig); tsk = alloc_task_struct(); if (!tsk) return NULL; ti = alloc_thread_info(tsk); if (!ti) { free_task_struct(tsk); return NULL; } err = arch_dup_task_struct(tsk, orig); if (err) goto out; tsk->stack = ti; err = prop_local_init_single(&tsk->dirties); if (err) goto out; setup_thread_stack(tsk, orig); clear_user_return_notifier(tsk); stackend = end_of_stack(tsk); *stackend = STACK_END_MAGIC; /* for overflow detection */ #ifdef CONFIG_CC_STACKPROTECTOR tsk->stack_canary = get_random_int(); #endif /* One for us, one for whoever does the "release_task()" (usually parent) */ atomic_set(&tsk->usage,2); atomic_set(&tsk->fs_excl, 0); #ifdef CONFIG_BLK_DEV_IO_TRACE tsk->btrace_seq = 0; #endif tsk->splice_pipe = NULL; account_kernel_stack(ti, 1); return tsk; out: free_thread_info(ti); free_task_struct(tsk); return NULL; } ; 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: const AST *Scanner::lex_cls(bool neg) { std::vector<ASTRange> *cls = new std::vector<ASTRange>; uint32_t u, l; const loc_t &loc0 = tok_loc(); loc_t loc = cur_loc(); fst: tok = cur; #line 3805 "src/parse/lex.cc" { unsigned char yych; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych == ']') goto yy576; #line 747 "../src/parse/lex.re" { l = lex_cls_chr(); goto snd; } #line 3813 "src/parse/lex.cc" yy576: ++cur; #line 746 "../src/parse/lex.re" { return ast_cls(loc0, cls, neg); } #line 3818 "src/parse/lex.cc" } #line 748 "../src/parse/lex.re" snd: #line 3824 "src/parse/lex.cc" { unsigned char yych; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*(mar = cur); if (yych == '-') goto yy581; yy580: #line 751 "../src/parse/lex.re" { u = l; goto add; } #line 3833 "src/parse/lex.cc" yy581: yych = (unsigned char)*++cur; if (yych != ']') goto yy583; cur = mar; goto yy580; yy583: ++cur; cur -= 1; #line 752 "../src/parse/lex.re" { u = lex_cls_chr(); if (l > u) { msg.warn.swapped_range(loc, l, u); std::swap(l, u); } goto add; } #line 3851 "src/parse/lex.cc" } #line 760 "../src/parse/lex.re" add: cls->push_back(ASTRange(l, u, loc)); loc = cur_loc(); goto fst; } ; 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::set_sourceline () { sourceline: tok = cur; #line 5401 "src/parse/lex.cc" { unsigned char yych; static const unsigned char yybm[] = { 0, 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, 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) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= '\r') { if (yych <= '\t') { if (yych >= 0x01) goto yy829; } else { if (yych <= '\n') goto yy831; if (yych <= '\f') goto yy829; goto yy833; } } else { if (yych <= '"') { if (yych <= '!') goto yy829; goto yy834; } else { if (yych <= '0') goto yy829; if (yych <= '9') goto yy835; goto yy829; } } ++cur; #line 884 "../src/parse/lex.re" { --cur; return; } #line 5461 "src/parse/lex.cc" yy829: ++cur; yy830: #line 885 "../src/parse/lex.re" { goto sourceline; } #line 5467 "src/parse/lex.cc" yy831: ++cur; #line 883 "../src/parse/lex.re" { pos = tok = cur; return; } #line 5472 "src/parse/lex.cc" yy833: yych = (unsigned char)*++cur; if (yych == '\n') goto yy831; goto yy830; yy834: yych = (unsigned char)*(mar = ++cur); if (yych <= 0x00) goto yy830; if (yych == '\n') goto yy830; goto yy839; yy835: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yybm[0+yych] & 64) { goto yy835; } #line 864 "../src/parse/lex.re" { uint32_t l; if (!s_to_u32_unsafe(tok, cur, l)) { msg.error(tok_loc(), "line number overflow"); exit(1); } set_line(l); goto sourceline; } #line 5499 "src/parse/lex.cc" yy838: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; yy839: if (yybm[0+yych] & 128) { goto yy838; } if (yych <= '\n') goto yy840; if (yych <= '"') goto yy841; goto yy843; yy840: cur = mar; goto yy830; yy841: ++cur; #line 874 "../src/parse/lex.re" { Input &in = get_input(); std::string &name = in.escaped_name; name = escape_backslashes(getstr(tok + 1, cur - 1)); in.fidx = static_cast<uint32_t>(msg.filenames.size()); msg.filenames.push_back(name); goto sourceline; } #line 5525 "src/parse/lex.cc" yy843: ++cur; if (lim <= cur) { if (!fill(1)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yych <= 0x00) goto yy840; if (yych == '\n') goto yy840; goto yy838; } #line 886 "../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 yy19; default: goto yy17; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Scanner::lex_opt_name(std::string &name) { tok = cur; #line 1142 "src/parse/lex.cc" { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*(mar = cur); if (yych <= 0x1F) { if (yych <= '\n') { if (yych >= '\t') { yyt1 = cur; goto yy209; } } else { if (yych == '\r') { yyt1 = cur; goto yy209; } } } else { if (yych <= '*') { if (yych <= ' ') { yyt1 = cur; goto yy209; } if (yych >= '*') { yyt1 = cur; goto yy211; } } else { if (yych == ':') goto yy213; } } yy208: #line 301 "../src/parse/lex.re" { msg.error(cur_loc(), "ill-formed start of a block: expected a space, a" " newline, a colon followed by a block name, or the end of block `*" "/`"); return false; } #line 1215 "src/parse/lex.cc" yy209: ++cur; cur = yyt1; #line 308 "../src/parse/lex.re" { name.clear(); return true; } #line 1221 "src/parse/lex.cc" yy211: yych = (unsigned char)*++cur; if (yych == '/') goto yy209; yy212: cur = mar; goto yy208; yy213: yych = (unsigned char)*++cur; if (yych <= '^') { if (yych <= '@') goto yy212; if (yych >= '[') goto yy212; } else { if (yych == '`') goto yy212; if (yych >= '{') goto yy212; } yy214: ++cur; if ((lim - cur) < 2) { if (!fill(2)) { error("unexpected end of input"); exit(1); } } yych = (unsigned char)*cur; if (yybm[0+yych] & 128) { goto yy214; } if (yych <= '\r') { if (yych <= 0x08) goto yy212; if (yych <= '\n') { yyt1 = cur; goto yy216; } if (yych <= '\f') goto yy212; yyt1 = cur; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy212; yyt1 = cur; } else { if (yych == '*') { yyt1 = cur; goto yy218; } goto yy212; } } yy216: ++cur; cur = yyt1; #line 309 "../src/parse/lex.re" { name.assign(tok + 1, cur); return true; } #line 1269 "src/parse/lex.cc" yy218: yych = (unsigned char)*++cur; if (yych == '/') goto yy216; goto yy212; } #line 310 "../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>