text
stringlengths
517
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags) { struct frag *f; struct list_head *item; int rec, num, group; BUG_ON (!data || !frags); if (size < 2 * VBLK_SIZE_HEAD) { ldm_error("Value of size is to small."); return false; } group = get_unaligned_be32(data + 0x08); rec = get_unaligned_be16(data + 0x0C); num = get_unaligned_be16(data + 0x0E); if ((num < 1) || (num > 4)) { ldm_error ("A VBLK claims to have %d parts.", num); return false; } if (rec >= num) { ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num); return false; } list_for_each (item, frags) { f = list_entry (item, struct frag, list); if (f->group == group) goto found; } f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL); if (!f) { ldm_crit ("Out of memory."); return false; } f->group = group; f->num = num; f->rec = rec; f->map = 0xFF << num; list_add_tail (&f->list, frags); found: if (f->map & (1 << rec)) { ldm_error ("Duplicate VBLK, part %d.", rec); f->map &= 0x7F; /* Mark the group as broken */ return false; } f->map |= (1 << rec); data += VBLK_SIZE_HEAD; size -= VBLK_SIZE_HEAD; memcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix for buffer overflow in ldm_frag_add not sufficient As Ben Hutchings discovered [1], the patch for CVE-2011-1017 (buffer overflow in ldm_frag_add) is not sufficient. The original patch in commit c340b1d64000 ("fs/partitions/ldm.c: fix oops caused by corrupted partition table") does not consider that, for subsequent fragments, previously allocated memory is used. [1] http://lkml.org/lkml/2011/5/6/407 Reported-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: Timo Warns <warns@pre-sense.de> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* const context) override { // node_ids const Tensor* node_ids_t; OP_REQUIRES_OK(context, context->input("node_ids", &node_ids_t)); const auto node_ids = node_ids_t->vec<int32>(); // gradients const Tensor* gradients_t; OP_REQUIRES_OK(context, context->input("gradients", &gradients_t)); const auto gradients = gradients_t->matrix<float>(); // hessians const Tensor* hessians_t; OP_REQUIRES_OK(context, context->input("hessians", &hessians_t)); const auto hessians = hessians_t->matrix<float>(); // bucketized_features OpInputList bucketized_features_list; OP_REQUIRES_OK(context, context->input_list("bucketized_features_list", &bucketized_features_list)); // Infer batch size. const int64_t batch_size = node_ids_t->dim_size(0); // Allocate temporary stats tensor (Rank 4). Tensor temp_stats_double_t; OP_REQUIRES_OK(context, context->allocate_temp( DT_DOUBLE, {num_features_, max_splits_, num_buckets_, 2}, &temp_stats_double_t)); auto temp_stats_double = temp_stats_double_t.tensor<double, 4>(); temp_stats_double.setZero(); // Partition by node, and then bucketize. for (int feature_idx = 0; feature_idx < num_features_; ++feature_idx) { const auto& features = bucketized_features_list[feature_idx].vec<int32>(); for (int i = 0; i < batch_size; ++i) { const int32_t node = node_ids(i); const int32_t bucket = features(i); temp_stats_double(feature_idx, node, bucket, 0) += gradients(i, 0); temp_stats_double(feature_idx, node, bucket, 1) += hessians(i, 0); } } // Copy temp tensor over to output tensor. Tensor* output_stats_summary_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output( "stats_summary", temp_stats_double_t.shape(), &output_stats_summary_t)); output_stats_summary_t->tensor<float, 4>() = temp_stats_double.template cast<float>(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-369'], 'message': 'Fixing security fixes in boosted trees ops PiperOrigin-RevId: 405669548 Change-Id: Iae224d240d1779bcc02405c2fff99785644fbd0d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int unit_name_path_escape(const char *f, char **ret) { char *p, *s; assert(f); assert(ret); p = strdupa(f); if (!p) return -ENOMEM; path_simplify(p); if (empty_or_root(p)) s = strdup("-"); else { if (!path_is_normalized(p)) return -EINVAL; /* Truncate trailing slashes */ delete_trailing_chars(p, "/"); /* Truncate leading slashes */ p = skip_leading_chars(p, "/"); s = unit_name_escape(p); } if (!s) return -ENOMEM; *ret = s; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'basic/unit-name: do not use strdupa() on a path The path may have unbounded length, for example through a fuse mount. CVE-2021-33910: attacked controlled alloca() leads to crash in systemd and ultimately a kernel panic. Systemd parses the content of /proc/self/mountinfo and each mountpoint is passed to mount_setup_unit(), which calls unit_name_path_escape() underneath. A local attacker who is able to mount a filesystem with a very long path can crash systemd and the whole system. https://bugzilla.redhat.com/show_bug.cgi?id=1970887 The resulting string length is bounded by UNIT_NAME_MAX, which is 256. But we can't easily check the length after simplification before doing the simplification, which in turns uses a copy of the string we can write to. So we can't reject paths that are too long before doing the duplication. Hence the most obvious solution is to switch back to strdup(), as before 7410616cd9dbbec97cf98d75324da5cda2b2f7a2. (cherry picked from commit 441e0115646d54f080e5c3bb0ba477c892861ab9)'</s>
<s>[INST] Given the following code containing errors, provide 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 ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node, const TfLiteTensor* input, const TfLiteTensor* size_splits, const TfLiteTensor* axis) { int axis_value = GetTensorData<int>(axis)[0]; if (axis_value < 0) { axis_value += NumDimensions(input); } std::vector<int64_t> size_splits_vector; if (size_splits->type == kTfLiteInt32) { GetSizeSplitsVector<int32_t>(size_splits, &size_splits_vector); } else if (size_splits->type == kTfLiteInt64) { GetSizeSplitsVector<int64_t>(size_splits, &size_splits_vector); } else { context->ReportError(context, "size_splits only support type int32|int64."); return kTfLiteError; } int minus_one_index = -1; int64_t size_splits_sum = 0; for (int i = 0; i < size_splits_vector.size(); ++i) { if (size_splits_vector.at(i) == -1) { if (minus_one_index == -1) { minus_one_index = i; } else { context->ReportError(context, "The size_splits contains more than one -1."); } } else { size_splits_sum += size_splits_vector.at(i); } } const int input_size = SizeOfDimension(input, axis_value); if (minus_one_index != -1) { if (size_splits_sum > input_size) { context->ReportError( context, "The sum of size_splits must be less than the dimension of value."); } else { size_splits_vector[minus_one_index] = input_size - size_splits_sum; } } else if (size_splits_sum != input_size) { context->ReportError( context, "The size_splits must sum to the dimension of value along axis."); } for (int i = 0; i < NumOutputs(node); ++i) { TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims); output_dims->data[axis_value] = size_splits_vector.at(i); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &output)); TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims)); } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent array OOB read/write PiperOrigin-RevId: 371026165 Change-Id: I26ac6372c87246e03c7eb8c94e84c84d86054b36'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((s->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ skip_bits1(gb); /* marker */ get_bits(gb, 15); /* latter_half_bitrate */ skip_bits1(gb); /* marker */ get_bits(gb, 15); /* first_half_vbv_buffer_size */ skip_bits1(gb); /* marker */ get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ skip_bits1(gb); /* marker */ get_bits(gb, 15); /* latter_half_vbv_occupancy */ skip_bits1(gb); /* marker */ } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection won't be overriden. */ if (s->picture_number == 0) s->low_delay = 0; } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(gb, "before time_increment_resolution"); s->avctx->time_base.den = get_bits(gb, 16); if (!s->avctx->time_base.den) { av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n"); s->avctx->time_base.num = 0; return -1; } ctx->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->time_base.num = get_bits(gb, ctx->time_increment_bits); else s->avctx->time_base.num = 1; ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(gb, "before width"); width = get_bits(gb, 13); check_marker(gb, "before height"); height = get_bits(gb, 13); check_marker(gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width skip_bits1(gb); /* marker */ skip_bits(gb, 13); // sprite_height skip_bits1(gb); /* marker */ skip_bits(gb, 13); // sprite_left skip_bits1(gb); /* marker */ skip_bits(gb, 13); // sprite_top skip_bits1(gb); /* marker */ } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return -1; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; /* load default matrixes */ for (i = 0; i < 64; i++) { int j = s->dsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->dsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->dsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->dsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->dsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, %s%s%s%s\n", s->avctx->time_base.num, s->avctx->time_base.den, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'avcodec/mpeg4videodec: Check for bitstream overread in decode_vol_header() Fixes out of array read Fixes: 08e48e9daae7d8f8ab6dbe3919e797e5-asan_heap-oob_157461c_5295_cov_1266798650_firefing.mpg Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'Move "exit_robust_list" into mm_release() We don't want to get rid of the futexes just at exit() time, we want to drop them when doing an execve() too, since that gets rid of the previous VM image too. Doing it at mm_release() time means that we automatically always do it when we disassociate a VM map from the task. Reported-by: pageexec@freemail.hu Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Nick Piggin <npiggin@suse.de> Cc: Hugh Dickins <hugh@veritas.com> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Brad Spengler <spender@grsecurity.net> Cc: Alex Efros <powerman@powerman.name> Cc: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: AP_DECLARE(int) ap_process_request_internal(request_rec *r) { int file_req = (r->main && r->filename); int access_status; core_dir_config *d; /* Ignore embedded %2F's in path for proxy requests */ if (!r->proxyreq && r->parsed_uri.path) { d = ap_get_core_module_config(r->per_dir_config); if (d->allow_encoded_slashes) { access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes); } else { access_status = ap_unescape_url(r->parsed_uri.path); } if (access_status) { if (access_status == HTTP_NOT_FOUND) { if (! d->allow_encoded_slashes) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026) "found %%2f (encoded '/') in URI " "(decoded='%s'), returning 404", r->parsed_uri.path); } } return access_status; } } ap_getparents(r->uri); /* OK --- shrinking transformations... */ /* All file subrequests are a huge pain... they cannot bubble through the * next several steps. Only file subrequests are allowed an empty uri, * otherwise let translate_name kill the request. */ if (!file_req) { if ((access_status = ap_location_walk(r))) { return access_status; } if ((access_status = ap_if_walk(r))) { return access_status; } /* Don't set per-dir loglevel if LogLevelOverride is set */ if (!r->connection->log) { d = ap_get_core_module_config(r->per_dir_config); if (d->log) r->log = d->log; } if ((access_status = ap_run_translate_name(r))) { return decl_die(access_status, "translate", r); } } /* Reset to the server default config prior to running map_to_storage */ r->per_dir_config = r->server->lookup_defaults; if ((access_status = ap_run_map_to_storage(r))) { /* This request wasn't in storage (e.g. TRACE) */ return access_status; } /* Rerun the location walk, which overrides any map_to_storage config. */ if ((access_status = ap_location_walk(r))) { return access_status; } if ((access_status = ap_if_walk(r))) { return access_status; } /* Don't set per-dir loglevel if LogLevelOverride is set */ if (!r->connection->log) { d = ap_get_core_module_config(r->per_dir_config); if (d->log) r->log = d->log; } if ((access_status = ap_run_post_perdir_config(r))) { return access_status; } /* Only on the main request! */ if (r->main == NULL) { if ((access_status = ap_run_header_parser(r))) { return access_status; } } /* Skip authn/authz if the parent or prior request passed the authn/authz, * and that configuration didn't change (this requires optimized _walk() * functions in map_to_storage that use the same merge results given * identical input.) If the config changes, we must re-auth. */ if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) { r->user = r->prev->user; r->ap_auth_type = r->prev->ap_auth_type; } else if (r->main && (r->main->per_dir_config == r->per_dir_config)) { r->user = r->main->user; r->ap_auth_type = r->main->ap_auth_type; } else { switch (ap_satisfies(r)) { case SATISFY_ALL: case SATISFY_NOSPEC: if ((access_status = ap_run_access_checker(r)) != OK) { return decl_die(access_status, "check access (with Satisfy All)", r); } access_status = ap_run_access_checker_ex(r); if (access_status == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker_ex hook: %s", r->uri); } else if (access_status != DECLINED) { return decl_die(access_status, "check access", r); } else { if ((access_status = ap_run_check_user_id(r)) != OK) { return decl_die(access_status, "check user", r); } if (r->user == NULL) { /* don't let buggy authn module crash us in authz */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027) "No authentication done but request not " "allowed without authentication for %s. " "Authentication not configured?", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; return decl_die(access_status, "check user", r); } if ((access_status = ap_run_auth_checker(r)) != OK) { return decl_die(access_status, "check authorization", r); } } break; case SATISFY_ANY: if ((access_status = ap_run_access_checker(r)) == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker hook and 'Satisfy any': %s", r->uri); break; } access_status = ap_run_access_checker_ex(r); if (access_status == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker_ex hook: %s", r->uri); } else if (access_status != DECLINED) { return decl_die(access_status, "check access", r); } else { if ((access_status = ap_run_check_user_id(r)) != OK) { return decl_die(access_status, "check user", r); } if (r->user == NULL) { /* don't let buggy authn module crash us in authz */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028) "No authentication done but request not " "allowed without authentication for %s. " "Authentication not configured?", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; return decl_die(access_status, "check user", r); } if ((access_status = ap_run_auth_checker(r)) != OK) { return decl_die(access_status, "check authorization", r); } } break; } } /* XXX Must make certain the ap_run_type_checker short circuits mime * in mod-proxy for r->proxyreq && r->parsed_uri.scheme * && !strcmp(r->parsed_uri.scheme, "http") */ if ((access_status = ap_run_type_checker(r)) != OK) { return decl_die(access_status, "find types", r); } if ((access_status = ap_run_fixups(r)) != OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s", access_status, r->uri); return access_status; } return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'SECURITY: CVE-2015-3185 (cve.mitre.org) Replacement of ap_some_auth_required (unusable in Apache httpd 2.4) with new ap_some_authn_required and ap_force_authn hook. Submitted by: breser git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 13f79535-47bb-0310-9956-ffa450edef68'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12998/IS-IS: Check for 2 bytes if we're going to fetch 2 bytes. Probably a copy-and-pasteo. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. 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 l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'l2tp: fix info leak in l2tp_ip6_recvmsg() The L2TP code for IPv6 fails to initialize the l2tp_conn_id member of struct sockaddr_l2tpip6 and therefore leaks four bytes kernel stack in l2tp_ip6_recvmsg() in case msg_name is set. Initialize l2tp_conn_id with 0 to avoid the info leak. 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 void vmx_complete_atomic_exit(struct vcpu_vmx *vmx) { u32 exit_intr_info; if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)) return; vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); exit_intr_info = vmx->exit_intr_info; /* Handle machine checks before interrupts are enabled */ if (is_machine_check(exit_intr_info)) kvm_machine_check(); /* We need to handle NMIs before interrupts are enabled */ if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR && (exit_intr_info & INTR_INFO_VALID_MASK)) { kvm_before_handle_nmi(&vmx->vcpu); asm("int $2"); kvm_after_handle_nmi(&vmx->vcpu); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-388'], 'message': 'kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF) When L2 exits to L0 due to "exception or NMI", software exceptions (#BP and #OF) for which L1 has requested an intercept should be handled by L1 rather than L0. Previously, only hardware exceptions were forwarded to L1. Signed-off-by: Jim Mattson <jmattson@google.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tgs_build_reply(krb5_context context, krb5_kdc_configuration *config, KDC_REQ *req, KDC_REQ_BODY *b, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, const krb5_keyblock *replykey, int rk_is_subkey, krb5_ticket *ticket, krb5_data *reply, const char *from, const char **e_text, AuthorizationData **auth_data, const struct sockaddr *from_addr) { krb5_error_code ret; krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL; krb5_principal krbtgt_out_principal = NULL; char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL; hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL; HDB *clientdb, *s4u2self_impersonated_clientdb; krb5_realm ref_realm = NULL; EncTicketPart *tgt = &ticket->ticket; krb5_principals spp = NULL; const EncryptionKey *ekey; krb5_keyblock sessionkey; krb5_kvno kvno; krb5_data rspac; const char *our_realm = /* Realm of this KDC */ krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1); char **capath = NULL; size_t num_capath = 0; hdb_entry_ex *krbtgt_out = NULL; METHOD_DATA enc_pa_data; PrincipalName *s; Realm r; EncTicketPart adtkt; char opt_str[128]; int signedpath = 0; Key *tkey_check; Key *tkey_sign; int flags = HDB_F_FOR_TGS_REQ; memset(&sessionkey, 0, sizeof(sessionkey)); memset(&adtkt, 0, sizeof(adtkt)); krb5_data_zero(&rspac); memset(&enc_pa_data, 0, sizeof(enc_pa_data)); s = b->sname; r = b->realm; /* * Always to do CANON, see comment below about returned server principal (rsp). */ flags |= HDB_F_CANON; if(b->kdc_options.enc_tkt_in_skey){ Ticket *t; hdb_entry_ex *uu; krb5_principal p; Key *uukey; krb5uint32 second_kvno = 0; krb5uint32 *kvno_ptr = NULL; if(b->additional_tickets == NULL || b->additional_tickets->len == 0){ ret = KRB5KDC_ERR_BADOPTION; /* ? */ kdc_log(context, config, 0, "No second ticket present in request"); goto out; } t = &b->additional_tickets->val[0]; if(!get_krbtgt_realm(&t->sname)){ kdc_log(context, config, 0, "Additional ticket is not a ticket-granting ticket"); ret = KRB5KDC_ERR_POLICY; goto out; } _krb5_principalname2krb5_principal(context, &p, t->sname, t->realm); if(t->enc_part.kvno){ second_kvno = *t->enc_part.kvno; kvno_ptr = &second_kvno; } ret = _kdc_db_fetch(context, config, p, HDB_F_GET_KRBTGT, kvno_ptr, NULL, &uu); krb5_free_principal(context, p); if(ret){ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } ret = hdb_enctype2key(context, &uu->entry, NULL, t->enc_part.etype, &uukey); if(ret){ _kdc_free_ent(context, uu); ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0); _kdc_free_ent(context, uu); if(ret) goto out; ret = verify_flags(context, config, &adtkt, spn); if (ret) goto out; s = &adtkt.cname; r = adtkt.crealm; } _krb5_principalname2krb5_principal(context, &sp, *s, r); ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm); ret = krb5_unparse_name(context, cp, &cpn); if (ret) goto out; unparse_flags (KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), opt_str, sizeof(opt_str)); if(*opt_str) kdc_log(context, config, 0, "TGS-REQ %s from %s for %s [%s]", cpn, from, spn, opt_str); else kdc_log(context, config, 0, "TGS-REQ %s from %s for %s", cpn, from, spn); /* * Fetch server */ server_lookup: ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags, NULL, NULL, &server); if (ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", sp); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { free(ref_realm); ref_realm = strdup(server->entry.principal->realm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } kdc_log(context, config, 5, "Returning a referral to realm %s for " "server %s.", ref_realm, spn); krb5_free_principal(context, sp); sp = NULL; ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); if (ret) goto out; free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; goto server_lookup; } else if (ret) { const char *new_rlm, *msg; Realm req_rlm; krb5_realm *realms; if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) { if (capath == NULL) { /* With referalls, hierarchical capaths are always enabled */ ret = _krb5_find_capath(context, tgt->crealm, our_realm, req_rlm, TRUE, &capath, &num_capath); if (ret) goto out; } new_rlm = num_capath > 0 ? capath[--num_capath] : NULL; if (new_rlm) { kdc_log(context, config, 5, "krbtgt from %s via %s for " "realm %s not found, trying %s", tgt->crealm, our_realm, req_rlm, new_rlm); free(ref_realm); ref_realm = strdup(new_rlm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; goto server_lookup; } } else if (need_referral(context, config, &b->kdc_options, sp, &realms)) { if (strcmp(realms[0], sp->realm) != 0) { kdc_log(context, config, 5, "Returning a referral to realm %s for " "server %s that was not found", realms[0], spn); krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, realms[0], NULL); free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) { krb5_free_host_realm(context, realms); goto out; } free(ref_realm); ref_realm = strdup(realms[0]); krb5_free_host_realm(context, realms); goto server_lookup; } krb5_free_host_realm(context, realms); } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, "Server not found in database: %s: %s", spn, msg); krb5_free_error_message(context, msg); if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } /* the name returned to the client depend on what was asked for, * return canonical name if kdc_options.canonicalize was set, the * client wants the true name of the principal, if not it just * wants the name its asked for. */ if (b->kdc_options.canonicalize) rsp = server->entry.principal; else rsp = sp; /* * Select enctype, return key and kvno. */ { krb5_enctype etype; if(b->kdc_options.enc_tkt_in_skey) { size_t i; ekey = &adtkt.key; for(i = 0; i < b->etype.len; i++) if (b->etype.val[i] == adtkt.key.keytype) break; if(i == b->etype.len) { kdc_log(context, config, 0, "Addition ticket have not matching etypes"); krb5_clear_error_message(context); ret = KRB5KDC_ERR_ETYPE_NOSUPP; goto out; } etype = b->etype.val[i]; kvno = 0; } else { Key *skey; ret = _kdc_find_etype(context, krb5_principal_is_krbtgt(context, sp) ? config->tgt_use_strongest_session_key : config->svc_use_strongest_session_key, FALSE, server, b->etype.val, b->etype.len, &etype, NULL); if(ret) { kdc_log(context, config, 0, "Server (%s) has no support for etypes", spn); goto out; } ret = _kdc_get_preferred_key(context, config, server, spn, NULL, &skey); if(ret) { kdc_log(context, config, 0, "Server (%s) has no supported etypes", spn); goto out; } ekey = &skey->key; kvno = server->entry.kvno; } ret = krb5_generate_random_keyblock(context, etype, &sessionkey); if (ret) goto out; } /* * Check that service is in the same realm as the krbtgt. If it's * not the same, it's someone that is using a uni-directional trust * backward. */ /* * Validate authoriation data */ ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */ krbtgt_etype, &tkey_check); if(ret) { kdc_log(context, config, 0, "Failed to find key for krbtgt PAC check"); goto out; } /* * Now refetch the primary krbtgt, and get the current kvno (the * sign check may have been on an old kvno, and the server may * have been an incoming trust) */ ret = krb5_make_principal(context, &krbtgt_out_principal, our_realm, KRB5_TGS_NAME, our_realm, NULL); if (ret) { kdc_log(context, config, 0, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n); if (ret) { kdc_log(context, config, 0, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = _kdc_db_fetch(context, config, krbtgt_out_principal, HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out); if (ret) { char *ktpn = NULL; ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn); kdc_log(context, config, 0, "No such principal %s (needed for authz-data signature keys) " "while processing TGS-REQ for service %s with krbtg %s", krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>"); free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } /* * The first realm is the realm of the service, the second is * krbtgt/<this>/@REALM component of the krbtgt DN the request was * encrypted to. The redirection via the krbtgt_out entry allows * the DB to possibly correct the case of the realm (Samba4 does * this) before the strcmp() */ if (strcmp(krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) { char *ktpn; ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn); kdc_log(context, config, 0, "Request with wrong krbtgt: %s", (ret == 0) ? ktpn : "<unknown>"); if(ret == 0) free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n, NULL, &tkey_sign); if (ret) { kdc_log(context, config, 0, "Failed to find key for krbtgt PAC signature"); goto out; } ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL, tkey_sign->key.keytype, &tkey_sign); if(ret) { kdc_log(context, config, 0, "Failed to find key for krbtgt PAC signature"); goto out; } ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags, NULL, &clientdb, &client); if(ret == HDB_ERR_NOT_FOUND_HERE) { /* This is OK, we are just trying to find out if they have * been disabled or deleted in the meantime, missing secrets * is OK */ } else if(ret){ const char *krbtgt_realm, *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal); if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) { if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; kdc_log(context, config, 1, "Client no longer in database: %s", cpn); goto out; } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 1, "Client not found in database: %s", msg); krb5_free_error_message(context, msg); } ret = check_PAC(context, config, cp, NULL, client, server, krbtgt, &tkey_check->key, ekey, &tkey_sign->key, tgt, &rspac, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, "Verify PAC failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* also check the krbtgt for signature */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, tgt, &spp, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, "KRB5SignedPath check failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Process request */ /* by default the tgt principal matches the client principal */ tp = cp; tpn = cpn; if (client) { const PA_DATA *sdata; int i = 0; sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER); if (sdata) { krb5_crypto crypto; krb5_data datack; PA_S4U2Self self; const char *str; ret = decode_PA_S4U2Self(sdata->padata_value.data, sdata->padata_value.length, &self, NULL); if (ret) { kdc_log(context, config, 0, "Failed to decode PA-S4U2Self"); goto out; } ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack); if (ret) goto out; ret = krb5_crypto_init(context, &tgt->key, 0, &crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); krb5_data_free(&datack); kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg); krb5_free_error_message(context, msg); goto out; } ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, datack.data, datack.length, &self.cksum); krb5_data_free(&datack); krb5_crypto_destroy(context, crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); kdc_log(context, config, 0, "krb5_verify_checksum failed for S4U2Self: %s", msg); krb5_free_error_message(context, msg); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, self.name, self.realm); free_PA_S4U2Self(&self); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */ if(rspac.data) { krb5_pac p = NULL; krb5_data_free(&rspac); ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags, NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client); if (ret) { const char *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; msg = krb5_get_error_message(context, ret); kdc_log(context, config, 1, "S2U4Self principal to impersonate %s not found in database: %s", tpn, msg); krb5_free_error_message(context, msg); goto out; } ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p); if (ret) { kdc_log(context, config, 0, "PAC generation failed for -- %s", tpn); goto out; } if (p != NULL) { ret = _krb5_pac_sign(context, p, ticket->ticket.authtime, s4u2self_impersonated_client->entry.principal, ekey, &tkey_sign->key, &rspac); krb5_pac_free(context, p); if (ret) { kdc_log(context, config, 0, "PAC signing failed for -- %s", tpn); goto out; } } } /* * Check that service doing the impersonating is * requesting a ticket to it-self. */ ret = check_s4u2self(context, config, clientdb, client, sp); if (ret) { kdc_log(context, config, 0, "S4U2Self: %s is not allowed " "to impersonate to service " "(tried for user %s to service %s)", cpn, tpn, spn); goto out; } /* * If the service isn't trusted for authentication to * delegation, remove the forward flag. */ if (client->entry.flags.trusted_for_delegation) { str = "[forwardable]"; } else { b->kdc_options.forwardable = 0; str = ""; } kdc_log(context, config, 0, "s4u2self %s impersonating %s to " "service %s %s", cpn, tpn, spn, str); } } /* * Constrained delegation */ if (client != NULL && b->additional_tickets != NULL && b->additional_tickets->len != 0 && b->kdc_options.enc_tkt_in_skey == 0) { int ad_signedpath = 0; Key *clientkey; Ticket *t; /* * Require that the KDC have issued the service's krbtgt (not * self-issued ticket with kimpersonate(1). */ if (!signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 0, "Constrained delegation done on service ticket %s/%s", cpn, spn); goto out; } t = &b->additional_tickets->val[0]; ret = hdb_enctype2key(context, &client->entry, hdb_kvno2keys(context, &client->entry, t->enc_part.kvno ? * t->enc_part.kvno : 0), t->enc_part.etype, &clientkey); if(ret){ ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0); if (ret) { kdc_log(context, config, 0, "failed to decrypt ticket for " "constrained delegation from %s to %s ", cpn, spn); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, adtkt.cname, adtkt.crealm); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; ret = _krb5_principalname2krb5_principal(context, &dp, t->sname, t->realm); if (ret) goto out; ret = krb5_unparse_name(context, dp, &dpn); if (ret) goto out; /* check that ticket is valid */ if (adtkt.flags.forwardable == 0) { kdc_log(context, config, 0, "Missing forwardable flag on ticket for " "constrained delegation from %s (%s) as %s to %s ", cpn, dpn, tpn, spn); ret = KRB5KDC_ERR_BADOPTION; goto out; } ret = check_constrained_delegation(context, config, clientdb, client, server, sp); if (ret) { kdc_log(context, config, 0, "constrained delegation from %s (%s) as %s to %s not allowed", cpn, dpn, tpn, spn); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { goto out; } krb5_data_free(&rspac); /* * generate the PAC for the user. * * TODO: pass in t->sname and t->realm and build * a S4U_DELEGATION_INFO blob to the PAC. */ ret = check_PAC(context, config, tp, dp, client, server, krbtgt, &clientkey->key, ekey, &tkey_sign->key, &adtkt, &rspac, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, "Verify delegated PAC failed to %s for client" "%s (%s) as %s from %s with %s", spn, cpn, dpn, tpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Check that the KDC issued the user's ticket. */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, &adtkt, NULL, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, "KRB5SignedPath check from service %s failed " "for delegation to %s for client %s (%s)" "from %s failed with %s", spn, tpn, dpn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } if (!ad_signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 0, "Ticket not signed with PAC nor SignedPath service %s failed " "for delegation to %s for client %s (%s)" "from %s", spn, tpn, dpn, cpn, from); goto out; } kdc_log(context, config, 0, "constrained delegation for %s " "from %s (%s) to %s", tpn, cpn, dpn, spn); } /* * Check flags */ ret = kdc_check_flags(context, config, client, cpn, server, spn, FALSE); if(ret) goto out; if((b->kdc_options.validate || b->kdc_options.renew) && !krb5_principal_compare(context, krbtgt->entry.principal, server->entry.principal)){ kdc_log(context, config, 0, "Inconsistent request."); ret = KRB5KDC_ERR_SERVER_NOMATCH; goto out; } /* check for valid set of addresses */ if(!_kdc_check_addresses(context, config, tgt->caddr, from_addr)) { ret = KRB5KRB_AP_ERR_BADADDR; kdc_log(context, config, 0, "Request from wrong address"); goto out; } /* * If this is an referral, add server referral data to the * auth_data reply . */ if (ref_realm) { PA_DATA pa; krb5_crypto crypto; kdc_log(context, config, 0, "Adding server referral to %s", ref_realm); ret = krb5_crypto_init(context, &sessionkey, 0, &crypto); if (ret) goto out; ret = build_server_referral(context, config, crypto, ref_realm, NULL, s, &pa.padata_value); krb5_crypto_destroy(context, crypto); if (ret) { kdc_log(context, config, 0, "Failed building server referral"); goto out; } pa.padata_type = KRB5_PADATA_SERVER_REFERRAL; ret = add_METHOD_DATA(&enc_pa_data, &pa); krb5_data_free(&pa.padata_value); if (ret) { kdc_log(context, config, 0, "Add server referral METHOD-DATA failed"); goto out; } } /* * */ ret = tgs_make_reply(context, config, b, tp, tgt, replykey, rk_is_subkey, ekey, &sessionkey, kvno, *auth_data, server, rsp, spn, client, cp, krbtgt_out, tkey_sign->key.keytype, spp, &rspac, &enc_pa_data, e_text, reply); out: if (tpn != cpn) free(tpn); free(spn); free(cpn); free(dpn); free(krbtgt_out_n); _krb5_free_capath(context, capath); krb5_data_free(&rspac); krb5_free_keyblock_contents(context, &sessionkey); if(krbtgt_out) _kdc_free_ent(context, krbtgt_out); if(server) _kdc_free_ent(context, server); if(client) _kdc_free_ent(context, client); if(s4u2self_impersonated_client) _kdc_free_ent(context, s4u2self_impersonated_client); if (tp && tp != cp) krb5_free_principal(context, tp); krb5_free_principal(context, cp); krb5_free_principal(context, dp); krb5_free_principal(context, sp); krb5_free_principal(context, krbtgt_out_principal); free(ref_realm); free_METHOD_DATA(&enc_pa_data); free_EncTicketPart(&adtkt); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'Fix transit path validation CVE-2017-6594 Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm to not be added to the transit path of issued tickets. This may, in some cases, enable bypass of capath policy in Heimdal versions 1.5 through 7.2. Note, this may break sites that rely on the bug. With the bug some incomplete [capaths] worked, that should not have. These may now break authentication in some cross-realm configurations.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval **rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && cursor[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 495 "ext/standard/var_unserializer.c" { YYCTYPE 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy13; case 'N': goto yy5; case 'R': goto yy2; case 'S': goto yy10; case 'a': goto yy11; case 'b': goto yy6; case 'd': goto yy8; case 'i': goto yy7; case 'o': goto yy12; case 'r': goto yy4; case 's': goto yy9; case '}': goto yy14; default: goto yy16; } yy2: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: #line 860 "ext/standard/var_unserializer.re" { return 0; } #line 557 "ext/standard/var_unserializer.c" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy89; goto yy3; yy5: yych = *++YYCURSOR; if (yych == ';') goto yy87; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy83; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy77; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy53; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy46; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy39; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy32; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy14: ++YYCURSOR; #line 854 "ext/standard/var_unserializer.re" { /* this is the case where we have less data than planned */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 606 "ext/standard/var_unserializer.c" yy16: yych = *++YYCURSOR; goto yy3; yy17: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych == '+') goto yy19; yy18: YYCURSOR = YYMARKER; goto yy3; yy19: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } goto yy18; yy20: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych <= '/') goto yy18; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 707 "ext/standard/var_unserializer.re" { size_t len, len2, len3, maxlen; long elements; char *class_name; zend_class_entry *ce; zend_class_entry **pce; int incomplete_class = 0; int custom_object = 0; zval *user_func; zval *retval_ptr; zval **args[1]; zval *arg_func_name; if (!var_hash) return 0; if (*start == 'C') { custom_object = 1; } INIT_PZVAL(*rval); len2 = len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len || len == 0) { *p = start + 2; return 0; } class_name = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR+1) != ':') { *p = YYCURSOR+1; return 0; } len3 = strspn(class_name, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\"); if (len3 != len) { *p = YYCURSOR + len3 - len; return 0; } class_name = estrndup(class_name, len); do { /* Try to find class directly */ BG(serialize_lock)++; if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { efree(class_name); return 0; } ce = *pce; break; } BG(serialize_lock)--; if (EG(exception)) { efree(class_name); return 0; } /* Check for unserialize callback */ if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Call unserialize callback */ MAKE_STD_ZVAL(user_func); ZVAL_STRING(user_func, PG(unserialize_callback_func), 1); args[0] = &arg_func_name; MAKE_STD_ZVAL(arg_func_name); ZVAL_STRING(arg_func_name, class_name, 1); BG(serialize_lock)++; if (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { efree(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "defined (%s) but not found", user_func->value.str.val); incomplete_class = 1; ce = PHP_IC_ENTRY; zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); break; } BG(serialize_lock)--; if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { efree(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); return 0; } /* The callback function may have defined the class */ if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) { ce = *pce; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Function %s() hasn't defined the class it was called for", user_func->value.str.val); incomplete_class = 1; ce = PHP_IC_ENTRY; } zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); break; } while (1); *p = YYCURSOR; if (custom_object) { int ret; ret = object_custom(UNSERIALIZE_PASSTHRU, ce); if (ret && incomplete_class) { php_store_class_name(*rval, class_name, len2); } efree(class_name); return ret; } elements = object_common1(UNSERIALIZE_PASSTHRU, ce); if (incomplete_class) { php_store_class_name(*rval, class_name, len2); } efree(class_name); return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 784 "ext/standard/var_unserializer.c" yy25: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy26; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; goto yy18; } yy26: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy27: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 698 "ext/standard/var_unserializer.re" { if (!var_hash) return 0; INIT_PZVAL(*rval); return object_common2(UNSERIALIZE_PASSTHRU, object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR)); } #line 818 "ext/standard/var_unserializer.c" yy32: yych = *++YYCURSOR; if (yych == '+') goto yy33; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; goto yy18; yy33: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy34: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '{') goto yy18; ++YYCURSOR; #line 677 "ext/standard/var_unserializer.re" { long elements = parse_iv(start + 2); /* use iv() not uiv() in order to check data range */ *p = YYCURSOR; if (!var_hash) return 0; if (elements < 0) { return 0; } INIT_PZVAL(*rval); array_init_size(*rval, elements); if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } #line 860 "ext/standard/var_unserializer.c" yy39: yych = *++YYCURSOR; if (yych == '+') goto yy40; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; goto yy18; yy40: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy41: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 642 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } if ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) { return 0; } if (*(YYCURSOR) != '"') { efree(str); *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { efree(str); *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_STRINGL(*rval, str, len, 0); return 1; } #line 916 "ext/standard/var_unserializer.c" yy46: yych = *++YYCURSOR; if (yych == '+') goto yy47; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; goto yy18; yy47: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy48: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 609 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_STRINGL(*rval, str, len, 1); return 1; } #line 970 "ext/standard/var_unserializer.c" yy53: yych = *++YYCURSOR; if (yych <= '/') { if (yych <= ',') { if (yych == '+') goto yy57; goto yy18; } else { if (yych <= '-') goto yy55; if (yych <= '.') goto yy60; goto yy18; } } else { if (yych <= 'I') { if (yych <= '9') goto yy58; if (yych <= 'H') goto yy18; goto yy56; } else { if (yych != 'N') goto yy18; } } yych = *++YYCURSOR; if (yych == 'A') goto yy76; goto yy18; yy55: yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy60; goto yy18; } else { if (yych <= '9') goto yy58; if (yych != 'I') goto yy18; } yy56: yych = *++YYCURSOR; if (yych == 'N') goto yy72; goto yy18; yy57: yych = *++YYCURSOR; if (yych == '.') goto yy60; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy58: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ':') { if (yych <= '.') { if (yych <= '-') goto yy18; goto yy70; } else { if (yych <= '/') goto yy18; if (yych <= '9') goto yy58; goto yy18; } } else { if (yych <= 'E') { if (yych <= ';') goto yy63; if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy60: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy61: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy61; if (yych <= ':') goto yy18; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy63: ++YYCURSOR; #line 599 "ext/standard/var_unserializer.re" { #if SIZEOF_LONG == 4 use_double: #endif *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL)); return 1; } #line 1068 "ext/standard/var_unserializer.c" yy65: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy66; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; } yy66: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy69; goto yy18; } else { if (yych <= '-') goto yy69; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; } yy67: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; if (yych == ';') goto yy63; goto yy18; yy69: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; yy70: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy70; if (yych <= ':') goto yy18; goto yy63; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy72: yych = *++YYCURSOR; if (yych != 'F') goto yy18; yy73: yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 584 "ext/standard/var_unserializer.re" { *p = YYCURSOR; INIT_PZVAL(*rval); if (!strncmp(start + 2, "NAN", 3)) { ZVAL_DOUBLE(*rval, php_get_nan()); } else if (!strncmp(start + 2, "INF", 3)) { ZVAL_DOUBLE(*rval, php_get_inf()); } else if (!strncmp(start + 2, "-INF", 4)) { ZVAL_DOUBLE(*rval, -php_get_inf()); } return 1; } #line 1142 "ext/standard/var_unserializer.c" yy76: yych = *++YYCURSOR; if (yych == 'N') goto yy73; goto yy18; yy77: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy78; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; goto yy18; } yy78: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy79: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; if (yych != ';') goto yy18; ++YYCURSOR; #line 557 "ext/standard/var_unserializer.re" { #if SIZEOF_LONG == 4 int digits = YYCURSOR - start - 3; if (start[2] == '-' || start[2] == '+') { digits--; } /* Use double for large long values that were serialized on a 64-bit system */ if (digits >= MAX_LENGTH_OF_LONG - 1) { if (digits == MAX_LENGTH_OF_LONG - 1) { int cmp = strncmp(YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1); if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) { goto use_double; } } else { goto use_double; } } #endif *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_LONG(*rval, parse_iv(start + 2)); return 1; } #line 1196 "ext/standard/var_unserializer.c" yy83: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= '2') goto yy18; yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 550 "ext/standard/var_unserializer.re" { *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_BOOL(*rval, parse_iv(start + 2)); return 1; } #line 1211 "ext/standard/var_unserializer.c" yy87: ++YYCURSOR; #line 543 "ext/standard/var_unserializer.re" { *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_NULL(*rval); return 1; } #line 1221 "ext/standard/var_unserializer.c" yy89: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy90; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; goto yy18; } yy90: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy91: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; if (yych != ';') goto yy18; ++YYCURSOR; #line 520 "ext/standard/var_unserializer.re" { long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) { return 0; } if (*rval == *rval_ref) return 0; if (*rval != NULL) { var_push_dtor_no_addref(var_hash, rval); } *rval = *rval_ref; Z_ADDREF_PP(rval); Z_UNSET_ISREF_PP(rval); return 1; } #line 1267 "ext/standard/var_unserializer.c" yy95: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy96; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; goto yy18; } yy96: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy97: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; if (yych != ';') goto yy18; ++YYCURSOR; #line 499 "ext/standard/var_unserializer.re" { long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) { return 0; } if (*rval != NULL) { var_push_dtor_no_addref(var_hash, rval); } *rval = *rval_ref; Z_ADDREF_PP(rval); Z_SET_ISREF_PP(rval); return 1; } #line 1311 "ext/standard/var_unserializer.c" } #line 862 "ext/standard/var_unserializer.re" return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: friend H AbslHashValue(H h, const TensorKey& k) { const uint8* d = static_cast<uint8*>(k.data()); size_t s = k.AllocatedBytes(); std::vector<uint8> vec; vec.reserve(s); for (int i = 0; i < s; i++) { vec.push_back(d[i]); } return H::combine(std::move(h), s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'Fix TensorKey hash function. The original hash function only used total estimated `AllocatedBytes()`, which (a) is an estimate per tensor, and (b) is a very poor hash function for constants (e.g. `int32_t`). It also tried to access individual tensor bytes through `tensor.data()` of size `AllocatedBytes()`. This led to ASAN failures because the `AllocatedBytes()` is an estimate of total bytes allocated by a tensor, including any pointed-to constructs (e.g. strings), and does not refer to contiguous bytes in the `.data()` buffer. We couldn't use this byte vector anyways, since types like `tstring` include pointers, whereas we need to hash the string values themselves. Modified the hash function to more closely mirror the `==` operator. This correctly handles `tstring` and any numeric types that do have contiguous storage. Other types are currently left as unimplemented. PiperOrigin-RevId: 446265413'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error) /* {{{ */ { int read_size, len; zend_off_t read_len; unsigned char buf[1024]; php_stream_rewind(fp); switch (sig_type) { case PHAR_SIG_OPENSSL: { #ifdef PHAR_HAVE_OPENSSL BIO *in; EVP_PKEY *key; EVP_MD *mdtype = (EVP_MD *) EVP_sha1(); EVP_MD_CTX md_ctx; #else int tempsig; #endif zend_string *pubkey = NULL; char *pfile; php_stream *pfp; #ifndef PHAR_HAVE_OPENSSL if (!zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) { if (error) { spprintf(error, 0, "openssl not loaded"); } return FAILURE; } #endif /* use __FILE__ . '.pubkey' for public key file */ spprintf(&pfile, 0, "%s.pubkey", fname); pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL); efree(pfile); if (!pfp || !(pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0)) || !ZSTR_LEN(pubkey)) { if (pfp) { php_stream_close(pfp); } if (error) { spprintf(error, 0, "openssl public key could not be read"); } return FAILURE; } php_stream_close(pfp); #ifndef PHAR_HAVE_OPENSSL tempsig = sig_len; if (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0, &sig, &tempsig)) { if (pubkey) { zend_string_release(pubkey); } if (error) { spprintf(error, 0, "openssl signature could not be verified"); } return FAILURE; } if (pubkey) { zend_string_release(pubkey); } sig_len = tempsig; #else in = BIO_new_mem_buf(pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0); if (NULL == in) { zend_string_release(pubkey); if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); BIO_free(in); zend_string_release(pubkey); if (NULL == key) { if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } EVP_VerifyInit(&md_ctx, mdtype); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } php_stream_seek(fp, 0, SEEK_SET); while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) { EVP_VerifyUpdate (&md_ctx, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } if (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) { /* 1: signature verified, 0: signature does not match, -1: failed signature operation */ EVP_MD_CTX_cleanup(&md_ctx); if (error) { spprintf(error, 0, "broken openssl signature"); } return FAILURE; } EVP_MD_CTX_cleanup(&md_ctx); #endif *signature_len = phar_hex_str((const char*)sig, sig_len, signature); } break; #ifdef PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; PHP_SHA512_CTX context; PHP_SHA512Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA512Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA512Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; PHP_SHA256_CTX context; PHP_SHA256Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA256Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA256Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (error) { spprintf(error, 0, "unsupported signature"); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; PHP_SHA1_CTX context; PHP_SHA1Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA1Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA1Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } case PHAR_SIG_MD5: { unsigned char digest[16]; PHP_MD5_CTX context; PHP_MD5Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_MD5Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_MD5Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } default: if (error) { spprintf(error, 0, "broken or unsupported signature"); } return FAILURE; } return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile (cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: win_exchange(long Prenum) { frame_T *frp; frame_T *frp2; win_T *wp; win_T *wp2; int temp; if (ERROR_IF_ANY_POPUP_WINDOW) return; if (ONE_WINDOW) // just one window { beep_flush(); return; } #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * find window to exchange with */ if (Prenum) { frp = curwin->w_frame->fr_parent->fr_child; while (frp != NULL && --Prenum > 0) frp = frp->fr_next; } else if (curwin->w_frame->fr_next != NULL) // Swap with next frp = curwin->w_frame->fr_next; else // Swap last window in row/col with previous frp = curwin->w_frame->fr_prev; // We can only exchange a window with another window, not with a frame // containing windows. if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin) return; wp = frp->fr_win; /* * 1. remove curwin from the list. Remember after which window it was in wp2 * 2. insert curwin before wp in the list * if wp != wp2 * 3. remove wp from the list * 4. insert wp after wp2 * 5. exchange the status line height and vsep width. */ wp2 = curwin->w_prev; frp2 = curwin->w_frame->fr_prev; if (wp->w_prev != curwin) { win_remove(curwin, NULL); frame_remove(curwin->w_frame); win_append(wp->w_prev, curwin); frame_insert(frp, curwin->w_frame); } if (wp != wp2) { win_remove(wp, NULL); frame_remove(wp->w_frame); win_append(wp2, wp); if (frp2 == NULL) frame_insert(wp->w_frame->fr_parent->fr_child, wp->w_frame); else frame_append(frp2, wp->w_frame); } temp = curwin->w_status_height; curwin->w_status_height = wp->w_status_height; wp->w_status_height = temp; temp = curwin->w_vsep_width; curwin->w_vsep_width = wp->w_vsep_width; wp->w_vsep_width = temp; frame_fix_height(curwin); frame_fix_height(wp); frame_fix_width(curwin); frame_fix_width(wp); (void)win_comp_pos(); // recompute window positions win_enter(wp, TRUE); redraw_all_later(NOT_VALID); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'patch 8.2.4154: ml_get error when exchanging windows in Visual mode Problem: ml_get error when exchanging windows in Visual mode. Solution: Correct end of Visual area when entering another buffer.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fb_mmap(struct file *file, struct vm_area_struct * vma) { struct fb_info *info = file_fb_info(file); struct fb_ops *fb; unsigned long off; unsigned long start; u32 len; if (!info) return -ENODEV; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) return -EINVAL; off = vma->vm_pgoff << PAGE_SHIFT; fb = info->fbops; if (!fb) return -ENODEV; mutex_lock(&info->mm_lock); if (fb->fb_mmap) { int res; res = fb->fb_mmap(info, vma); mutex_unlock(&info->mm_lock); return res; } /* frame buffer memory */ start = info->fix.smem_start; len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len); if (off >= len) { /* memory mapped io */ off -= len; if (info->var.accel_flags) { mutex_unlock(&info->mm_lock); return -EINVAL; } start = info->fix.mmio_start; len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.mmio_len); } mutex_unlock(&info->mm_lock); start &= PAGE_MASK; if ((vma->vm_end - vma->vm_start + off) > len) return -EINVAL; off += start; vma->vm_pgoff = off >> PAGE_SHIFT; /* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by io_remap_pfn_range()*/ vma->vm_page_prot = vm_get_page_prot(vma->vm_flags); fb_pgprotect(file, vma, off); if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot)) return -EAGAIN; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'vm: convert fb_mmap to vm_iomap_memory() helper This is my example conversion of a few existing mmap users. The fb_mmap() case is a good example because it is a bit more complicated than some: fb_mmap() mmaps one of two different memory areas depending on the page offset of the mmap (but happily there is never any mixing of the two, so the helper function still works). 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: construct_command_line(struct manager_ctx *manager, struct server *server) { static char cmd[BUF_SIZE]; char *method = manager->method; int i; build_config(working_dir, server); if (server->method) method = server->method; memset(cmd, 0, BUF_SIZE); snprintf(cmd, BUF_SIZE, "%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf", executable, method, manager->manager_address, working_dir, server->port, working_dir, server->port); if (manager->acl != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl); } if (manager->timeout != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout); } #ifdef HAVE_SETRLIMIT if (manager->nofile) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile); } #endif if (manager->user != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user); } if (manager->verbose) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -v"); } if (server->mode == NULL && manager->mode == UDP_ONLY) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -U"); } if (server->mode == NULL && manager->mode == TCP_AND_UDP) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -u"); } if (server->fast_open[0] == 0 && manager->fast_open) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --fast-open"); } if (manager->ipv6first) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -6"); } if (manager->mtu) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu); } if (server->plugin == NULL && manager->plugin) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin); } if (server->plugin_opts == NULL && manager->plugin_opts) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts); } for (i = 0; i < manager->nameserver_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]); } for (i = 0; i < manager->host_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]); } // Always enable reuse port { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --reuse-port"); } if (verbose) { LOGI("cmd: %s", cmd); } return cmd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78', 'CWE-787'], 'message': 'Fix #1734'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mincore_unmapped_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { walk->private += __mincore_unmapped_range(addr, end, walk->vma, walk->private); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-319'], 'message': 'Change mincore() to count "mapped" pages rather than "cached" pages The semantics of what "in core" means for the mincore() system call are somewhat unclear, but Linux has always (since 2.3.52, which is when mincore() was initially done) treated it as "page is available in page cache" rather than "page is mapped in the mapping". The problem with that traditional semantic is that it exposes a lot of system cache state that it really probably shouldn't, and that users shouldn't really even care about. So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use). In many ways the old semantics were somewhat insane even aside from the information leak issue. From the very beginning (and that beginning is a long time ago: 2.3.52 was released in March 2000, I think), the code had a comment saying Later we can get more picky about what "in core" means precisely. and this is that "later". Admittedly it is much later than is really comfortable. NOTE! This is a real semantic change, and it is for example known to change the output of "fincore", since that program literally does a mmmap without populating it, and then doing "mincore()" on that mapping that doesn't actually have any pages in it. I'm hoping that nobody actually has any workflow that cares, and the info leak is real. We may have to do something different if it turns out that people have valid reasons to want the old semantics, and if we can limit the information leak sanely. Cc: Kevin Easton <kevin@guarana.org> Cc: Jiri Kosina <jikos@kernel.org> Cc: Masatake YAMATO <yamato@redhat.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Greg KH <gregkh@linuxfoundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Michal Hocko <mhocko@suse.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_F(RouterTest, MissingRequiredHeaders) { NiceMock<Http::MockRequestEncoder> encoder; Http::ResponseDecoder* response_decoder = nullptr; EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_, newStream(_, _)) .WillOnce(Invoke( [&](Http::ResponseDecoder& decoder, Http::ConnectionPool::Callbacks& callbacks) -> Http::ConnectionPool::Cancellable* { response_decoder = &decoder; callbacks.onPoolReady(encoder, cm_.thread_local_cluster_.conn_pool_.host_, upstream_stream_info_, Http::Protocol::Http10); return nullptr; })); expectResponseTimerCreate(); Http::TestRequestHeaderMapImpl headers; HttpTestUtility::addDefaultHeaders(headers); headers.removeMethod(); EXPECT_CALL(encoder, encodeHeaders(_, _)) .WillOnce(Invoke([](const Http::RequestHeaderMap& headers, bool) -> Http::Status { return Http::HeaderUtility::checkRequiredRequestHeaders(headers); })); EXPECT_CALL( callbacks_, sendLocalReply(Http::Code::ServiceUnavailable, testing::Eq("missing required header: :method"), _, _, "filter_removed_required_request_headers{missing required header: :method}")) .WillOnce(testing::InvokeWithoutArgs([] {})); router_.decodeHeaders(headers, true); router_.onDestroy(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': '[1.20] CVE-2022-21655 Crash with direct_response Signed-off-by: Otto van der Schaaf <ovanders@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int err = 0; lock_sock(sk); /* * This works for seqpacket too. The receiver has ordered the * queue for us! We do one quick check first though */ if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Now we can treat all alike */ skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; if (!ax25_sk(sk)->pidincl) skb_pull(skb, 1); /* Remove PID */ skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (msg->msg_namelen != 0) { struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; ax25_digi digi; ax25_address src; const unsigned char *mac = skb_mac_header(skb); ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL, &digi, NULL, NULL); sax->sax25_family = AF_AX25; /* We set this correctly, even though we may not let the application know the digi calls further down (because it did NOT ask to know them). This could get political... **/ sax->sax25_ndigis = digi.ndigi; sax->sax25_call = src; if (sax->sax25_ndigis != 0) { int ct; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax; for (ct = 0; ct < digi.ndigi; ct++) fsa->fsa_digipeater[ct] = digi.calls[ct]; } msg->msg_namelen = sizeof(struct full_sockaddr_ax25); } skb_free_datagram(sk, skb); err = copied; out: release_sock(sk); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ax25: fix info leak via msg_name in ax25_recvmsg() When msg_namelen is non-zero the sockaddr info gets filled out, as requested, but the code fails to initialize the padding bytes of struct sockaddr_ax25 inserted by the compiler for alignment. Additionally the msg_namelen value is updated to sizeof(struct full_sockaddr_ax25) but is not always filled up to this size. Both issues lead to the fact that the code will leak uninitialized kernel stack bytes in net/socket.c. Fix both issues by initializing the memory with memset(0). Cc: Ralf Baechle <ralf@linux-mips.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: ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length) { register const struct rip6 *rp = (const struct rip6 *)dat; register const struct netinfo6 *ni; register u_int amt; register u_int i; int j; int trunc; if (ndo->ndo_snapend < dat) return; amt = ndo->ndo_snapend - dat; i = min(length, amt); if (i < (sizeof(struct rip6) - sizeof(struct netinfo6))) return; i -= (sizeof(struct rip6) - sizeof(struct netinfo6)); switch (rp->rip6_cmd) { case RIP6_REQUEST: j = length / sizeof(*ni); if (j == 1 && rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6 && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) { ND_PRINT((ndo, " ripng-req dump")); break; } if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-req %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-req %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, 0); } break; case RIP6_RESPONSE: j = length / sizeof(*ni); if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-resp %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, ni->rip6_metric); } if (trunc) ND_PRINT((ndo, "[|ripng]")); break; default: ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length)); break; } if (rp->rip6_vers != RIP6_VERSION) ND_PRINT((ndo, " [vers %d]", rp->rip6_vers)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-12992/RIPng: Clean up bounds checking. Do bounds checking as we access items. Scan the list of netinfo6 entries based on the supplied packet length, without taking the captured length into account; let the aforementioned bounds checking handle that. 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 sd_e_h(GWindow gw, GEvent *event) { struct sd_data *sd = GDrawGetUserData(gw); if ( sd==NULL ) return( true ); if ( event->type==et_close ) { SD_DoCancel( sd ); } else if ( event->type==et_char ) { if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) { help("scripting.html"); return( true ); } return( false ); } else if ( event->type == et_map ) /* Above palettes */ GDrawRaise(gw); else if ( event->type == et_resize ) GDrawRequestExpose(gw,NULL,false); return( true ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Warn users before discarding their unsaved scripts (#3852) * Warn users before discarding their unsaved scripts This closes #3846.'</s>
<s>[INST] Given the following code containing errors, provide 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 operator()(OpKernelContext* ctx, bool use_cudnn, bool cudnn_use_autotune, const Tensor& input, const Tensor& filter, int row_dilation, int col_dilation, int row_stride, int col_stride, const Padding& padding, const std::vector<int64>& explicit_paddings, Tensor* output, TensorFormat data_format) { if (data_format != FORMAT_NHWC) { ctx->SetStatus(errors::Unimplemented( "The Conv2D op currently only supports the NHWC tensor format on the " "CPU. The op was given the format: ", ToString(data_format))); return; } for (int64 explicit_padding : explicit_paddings) { if (!FastBoundsCheck(explicit_padding, std::numeric_limits<int>::max())) { ctx->SetStatus(errors::InvalidArgument("filter too large")); return; } } const int64 in_depth = input.dim_size(3); const int64 out_depth = output->dim_size(3); const int64 patch_depth = filter.dim_size(2); if (in_depth % patch_depth != 0) { ctx->SetStatus(errors::InvalidArgument( "input depth must be evenly divisible by filter depth: ", in_depth, " vs ", patch_depth)); return; } const int64 num_groups = in_depth / patch_depth; if (out_depth % num_groups != 0 || out_depth < num_groups) { ctx->SetStatus(errors::InvalidArgument( "output depth must be evenly divisible by number of groups: ", out_depth, " vs ", num_groups)); return; } if (in_depth != patch_depth) { LaunchGrouped<T>()(ctx, input, filter, row_stride, col_stride, row_dilation, col_dilation, padding, explicit_paddings, output, data_format); } else { LaunchGeneric<CPUDevice, T>()(ctx, input, filter, row_stride, col_stride, row_dilation, col_dilation, padding, explicit_paddings, output, data_format); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Fix one more FPE. PiperOrigin-RevId: 369346568 Change-Id: I840fd575962adc879713a4c9cc59e6da3331caa7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ut32 armass_assemble(const char *str, ut64 off, int thumb) { int i, j; char buf[128]; ArmOpcode aop = {.off = off}; for (i = j = 0; i < sizeof (buf) - 1 && str[i]; i++, j++) { if (str[j] == '#') { i--; continue; } buf[i] = tolower ((const ut8)str[j]); } buf[i] = 0; arm_opcode_parse (&aop, buf); aop.off = off; if (thumb < 0 || thumb > 1) { return -1; } if (!assemble[thumb] (&aop, off, buf)) { //eprintf ("armass: Unknown opcode (%s)\n", buf); return -1; } return aop.o; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix #12417/#12418 (arm assembler heap overflows)'</s>
<s>[INST] Given the following code containing errors, provide 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 RtmpProtocol::handle_chunk(RtmpPacket::Ptr packet) { auto &chunk_data = *packet; switch (chunk_data.type_id) { case MSG_ACK: { if (chunk_data.buffer.size() < 4) { throw std::runtime_error("MSG_ACK: Not enough data"); } //auto bytePeerRecv = load_be32(&chunk_data.buffer[0]); //TraceL << "MSG_ACK:" << bytePeerRecv; break; } case MSG_SET_CHUNK: { if (chunk_data.buffer.size() < 4) { throw std::runtime_error("MSG_SET_CHUNK :Not enough data"); } _chunk_size_in = load_be32(&chunk_data.buffer[0]); TraceL << "MSG_SET_CHUNK:" << _chunk_size_in; break; } case MSG_USER_CONTROL: { //user control message if (chunk_data.buffer.size() < 2) { throw std::runtime_error("MSG_USER_CONTROL: Not enough data."); } uint16_t event_type = load_be16(&chunk_data.buffer[0]); chunk_data.buffer.erase(0, 2); switch (event_type) { case CONTROL_PING_REQUEST: { if (chunk_data.buffer.size() < 4) { throw std::runtime_error("CONTROL_PING_REQUEST: Not enough data."); } uint32_t timeStamp = load_be32(&chunk_data.buffer[0]); //TraceL << "CONTROL_PING_REQUEST:" << time_stamp; sendUserControl(CONTROL_PING_RESPONSE, timeStamp); break; } case CONTROL_PING_RESPONSE: { if (chunk_data.buffer.size() < 4) { throw std::runtime_error("CONTROL_PING_RESPONSE: Not enough data."); } //uint32_t time_stamp = load_be32(&chunk_data.buffer[0]); //TraceL << "CONTROL_PING_RESPONSE:" << time_stamp; break; } case CONTROL_STREAM_BEGIN: { //开始播放 if (chunk_data.buffer.size() < 4) { WarnL << "CONTROL_STREAM_BEGIN: Not enough data:" << chunk_data.buffer.size(); break; } uint32_t stream_index = load_be32(&chunk_data.buffer[0]); onStreamBegin(stream_index); TraceL << "CONTROL_STREAM_BEGIN:" << stream_index; break; } case CONTROL_STREAM_EOF: { //暂停 if (chunk_data.buffer.size() < 4) { throw std::runtime_error("CONTROL_STREAM_EOF: Not enough data."); } uint32_t stream_index = load_be32(&chunk_data.buffer[0]); onStreamEof(stream_index); TraceL << "CONTROL_STREAM_EOF:" << stream_index; break; } case CONTROL_STREAM_DRY: { //停止播放 if (chunk_data.buffer.size() < 4) { throw std::runtime_error("CONTROL_STREAM_DRY: Not enough data."); } uint32_t stream_index = load_be32(&chunk_data.buffer[0]); onStreamDry(stream_index); TraceL << "CONTROL_STREAM_DRY:" << stream_index; break; } default: /*WarnL << "unhandled user control:" << event_type; */ break; } break; } case MSG_WIN_SIZE: { _windows_size = load_be32(&chunk_data.buffer[0]); TraceL << "MSG_WIN_SIZE:" << _windows_size; break; } case MSG_SET_PEER_BW: { _bandwidth = load_be32(&chunk_data.buffer[0]); _band_limit_type = chunk_data.buffer[4]; TraceL << "MSG_SET_PEER_BW:" << _windows_size; break; } case MSG_AGGREGATE: { auto ptr = (uint8_t *) chunk_data.buffer.data(); auto ptr_tail = ptr + chunk_data.buffer.size(); uint32_t latest_ts, timestamp; timestamp = chunk_data.time_stamp; bool first_message = true; while (ptr + 8 + 3 < ptr_tail) { auto type = *ptr; ptr += 1; auto size = load_be24(ptr); ptr += 3; auto ts = load_be24(ptr); ptr += 3; ts |= (*ptr << 24); ptr += 1; ptr += 3; //参考FFmpeg多拷贝了4个字节 size += 4; if (ptr + size > ptr_tail) { break; } if (!first_message) { timestamp += ts - latest_ts; } first_message = false; latest_ts = ts; auto sub_packet_ptr = RtmpPacket::create(); auto &sub_packet = *sub_packet_ptr; sub_packet.buffer.assign((char *)ptr, size); sub_packet.type_id = type; sub_packet.body_size = size; sub_packet.time_stamp = timestamp; sub_packet.stream_index = chunk_data.stream_index; sub_packet.chunk_id = chunk_data.chunk_id; handle_chunk(std::move(sub_packet_ptr)); ptr += size; } break; } default: onRtmpChunk(std::move(packet)); break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': '修复rtmp汇报窗口太小导致循环递归的bug:#1839'</s>
<s>[INST] Given the following code containing errors, provide 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 ecall_restore(const char *input, uint64_t input_len, char **output, uint64_t *output_len) { if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input, input_len) || !asylo::primitives::TrustedPrimitives::IsOutsideEnclave( output_len, sizeof(uint64_t))) { asylo::primitives::TrustedPrimitives::BestEffortAbort( "ecall_restore: input/output found to not be in untrusted memory."); } int result = 0; size_t tmp_output_len; try { result = asylo::Restore(input, static_cast<size_t>(input_len), output, &tmp_output_len); } catch (...) { LOG(FATAL) << "Uncaught exception in enclave"; } if (output_len) { *output_len = static_cast<uint64_t>(tmp_output_len); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check output of ecall_restore is outside enclave PiperOrigin-RevId: 334265380 Change-Id: Ifbaead6bce56f01b2a4d69f53ca508d0138f6f61'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::removePage(QPDFObjectHandle page) { int pos = findPage(page); // also ensures flat /Pages QTC::TC("qpdf", "QPDF remove page", (pos == 0) ? 0 : // remove at beginning (pos == static_cast<int>( this->m->all_pages.size() - 1)) ? 1 : // end 2); // remove in middle QPDFObjectHandle pages = getRoot().getKey("/Pages"); QPDFObjectHandle kids = pages.getKey("/Kids"); kids.eraseItem(pos); int npages = kids.getArrayNItems(); pages.replaceKey("/Count", QPDFObjectHandle::newInteger(npages)); this->m->all_pages.erase(this->m->all_pages.begin() + pos); assert(this->m->all_pages.size() == static_cast<size_t>(npages)); this->m->pageobj_to_pages_pos.erase(page.getObjGen()); assert(this->m->pageobj_to_pages_pos.size() == static_cast<size_t>(npages)); for (int i = pos; i < npages; ++i) { insertPageobjToPage(this->m->all_pages.at(i), i, false); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); // For libtool's sake.... if (strncmp(whoami, "lt-", 3) == 0) { whoami += 3; } if (argc != 3) { usage(); } char const* filename = argv[1]; int pageno = QUtil::string_to_int(argv[2]); try { QPDF pdf; pdf.processFile(filename); std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages(); if ((pageno < 1) || (static_cast<size_t>(pageno) > pages.size())) { usage(); } QPDFPageObjectHelper& page = pages.at(pageno-1); ParserCallbacks cb; page.parsePageContents(&cb); } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: RC4::RC4(unsigned char const* key_data, int key_len) { if (key_len == -1) { key_len = strlen(reinterpret_cast<char const*>(key_data)); } for (int i = 0; i < 256; ++i) { key.state[i] = i; } key.x = 0; key.y = 0; int i1 = 0; int i2 = 0; for (int i = 0; i < 256; ++i) { i2 = (key_data[i1] + key.state[i] + i2) % 256; swap_byte(key.state[i], key.state[i2]); i1 = (i1 + 1) % key_len; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pad_or_truncate_password_V4(std::string const& password) { char k1[key_bytes]; pad_or_truncate_password_V4(password, k1); return std::string(k1, key_bytes); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BitWriter::flush() { if (bit_offset < 7) { int bits_to_write = bit_offset + 1; write_bits(this->ch, this->bit_offset, 0, bits_to_write, this->pl); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pad_or_truncate_password_V4(std::string const& password, char k1[key_bytes]) { int password_bytes = std::min(static_cast<size_t>(key_bytes), password.length()); int pad_bytes = key_bytes - password_bytes; memcpy(k1, password.c_str(), password_bytes); memcpy(k1 + password_bytes, padding_string, pad_bytes); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ArgParser::argOiMinHeight(char* parameter) { o.oi_min_height = QUtil::string_to_int(parameter); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_LZWDecoder::handleCode(int code) { if (this->eod) { return; } if (code == 256) { if (! this->table.empty()) { QTC::TC("libtests", "Pl_LZWDecoder intermediate reset"); } this->table.clear(); this->code_size = 9; } else if (code == 257) { this->eod = true; } else { if (this->last_code != 256) { // Add to the table from last time. New table entry would // be what we read last plus the first character of what // we're reading now. unsigned char next = '\0'; unsigned int table_size = table.size(); if (code < 256) { // just read < 256; last time's next was code next = code; } else if (code > 257) { size_t idx = code - 258; if (idx > table_size) { throw std::runtime_error("LZWDecoder: bad code received"); } else if (idx == table_size) { // The encoder would have just created this entry, // so the first character of this entry would have // been the same as the first character of the // last entry. QTC::TC("libtests", "Pl_LZWDecoder last was table size"); next = getFirstChar(this->last_code); } else { next = getFirstChar(code); } } unsigned int new_idx = 258 + table_size; if (new_idx == 4096) { throw std::runtime_error("LZWDecoder: table full"); } addToTable(next); unsigned int change_idx = new_idx + code_change_delta; if ((change_idx == 511) || (change_idx == 1023) || (change_idx == 2047)) { ++this->code_size; } } if (code < 256) { unsigned char ch = static_cast<unsigned char>(code); getNext()->write(&ch, 1); } else { Buffer& b = table.at(code - 258); getNext()->write(b.getBuffer(), b.getSize()); } } this->last_code = code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: iterate_md5_digest(MD5& md5, MD5::Digest& digest, int iterations, int key_len) { md5.digest(digest); for (int i = 0; i < iterations; ++i) { MD5 m; m.encodeDataIncrementally(reinterpret_cast<char*>(digest), key_len); m.digest(digest); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_PNGFilter::encodeRow() { // For now, hard-code to using UP filter. unsigned char ch = 2; getNext()->write(&ch, 1); if (this->prev_row) { for (unsigned int i = 0; i < this->bytes_per_row; ++i) { ch = this->cur_row[i] - this->prev_row[i]; getNext()->write(&ch, 1); } } else { getNext()->write(this->cur_row, this->bytes_per_row); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::recoverStreamLength(PointerHolder<InputSource> input, int objid, int generation, qpdf_offset_t stream_offset) { // Try to reconstruct stream length by looking for // endstream or endobj warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), this->m->last_object_description, stream_offset, "attempting to recover stream length")); PatternFinder ef(*this, &QPDF::findEndstream); size_t length = 0; if (this->m->file->findFirst("end", stream_offset, 0, ef)) { length = this->m->file->tell() - stream_offset; // Reread endstream but, if it was endobj, don't skip that. QPDFTokenizer::Token t = readToken(this->m->file); if (t.getValue() == "endobj") { this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET); } } if (length) { int this_obj_offset = 0; QPDFObjGen this_obj(0, 0); // Make sure this is inside this object for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter = this->m->xref_table.begin(); iter != this->m->xref_table.end(); ++iter) { QPDFObjGen const& og = (*iter).first; QPDFXRefEntry const& entry = (*iter).second; if (entry.getType() == 1) { qpdf_offset_t obj_offset = entry.getOffset(); if ((obj_offset > stream_offset) && ((this_obj_offset == 0) || (this_obj_offset > obj_offset))) { this_obj_offset = obj_offset; this_obj = og; } } } if (this_obj_offset && (this_obj.getObj() == objid) && (this_obj.getGen() == generation)) { // Well, we found endstream\nendobj within the space // allowed for this object, so we're probably in good // shape. } else { QTC::TC("qpdf", "QPDF found wrong endstream in recovery"); } } if (length == 0) { warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), this->m->last_object_description, stream_offset, "unable to recover stream data;" " treating stream as empty")); } else { warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), this->m->last_object_description, stream_offset, "recovered stream length: " + QUtil::int_to_string(length))); } QTC::TC("qpdf", "QPDF recovered stream length"); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QUtil::utf16_to_utf8(std::string const& val) { std::string result; // This code uses unsigned long and unsigned short to hold // codepoint values. It requires unsigned long to be at least // 32 bits and unsigned short to be at least 16 bits, but it // will work fine if they are larger. unsigned long codepoint = 0L; size_t len = val.length(); size_t start = 0; if (is_utf16(val)) { start += 2; } // If the string has an odd number of bytes, the last byte is // ignored. for (unsigned int i = start; i < len; i += 2) { // Convert from UTF16-BE. If we get a malformed // codepoint, this code will generate incorrect output // without giving a warning. Specifically, a high // codepoint not followed by a low codepoint will be // discarded, and a low codepoint not preceded by a high // codepoint will just get its low 10 bits output. unsigned short bits = (static_cast<unsigned char>(val.at(i)) << 8) + static_cast<unsigned char>(val.at(i+1)); if ((bits & 0xFC00) == 0xD800) { codepoint = 0x10000 + ((bits & 0x3FF) << 10); continue; } else if ((bits & 0xFC00) == 0xDC00) { if (codepoint != 0) { QTC::TC("qpdf", "QUtil non-trivial UTF-16"); } codepoint += bits & 0x3FF; } else { codepoint = bits; } result += QUtil::toUTF8(codepoint); codepoint = 0; } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFFormFieldObjectHelper::getChoices() { std::vector<std::string> result; if (! isChoice()) { return result; } QPDFObjectHandle opt = getInheritableFieldValue("/Opt"); if (opt.isArray()) { size_t n = opt.getArrayNItems(); for (size_t i = 0; i < n; ++i) { QPDFObjectHandle item = opt.getArrayItem(i); if (item.isString()) { result.push_back(item.getUTF8Value()); } } } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFWriter::unparseObject(QPDFObjectHandle object, int level, unsigned int flags, size_t stream_length, bool compress) { QPDFObjGen old_og = object.getObjGen(); unsigned int child_flags = flags & ~f_stream; std::string indent; for (int i = 0; i < level; ++i) { indent += " "; } if (object.isArray()) { // Note: PDF spec 1.4 implementation note 121 states that // Acrobat requires a space after the [ in the /H key of the // linearization parameter dictionary. We'll do this // unconditionally for all arrays because it looks nicer and // doesn't make the files that much bigger. writeString("["); writeStringQDF("\n"); int n = object.getArrayNItems(); for (int i = 0; i < n; ++i) { writeStringQDF(indent); writeStringQDF(" "); writeStringNoQDF(" "); unparseChild(object.getArrayItem(i), level + 1, child_flags); writeStringQDF("\n"); } writeStringQDF(indent); writeStringNoQDF(" "); writeString("]"); } else if (object.isDictionary()) { // Make a shallow copy of this object so we can modify it // safely without affecting the original. This code makes // assumptions about things that are made true in // prepareFileForWrite, such as that certain things are direct // objects so that replacing them doesn't leave unreferenced // objects in the output. object = object.shallowCopy(); // Handle special cases for specific dictionaries. // Extensions dictionaries. // We have one of several cases: // // * We need ADBE // - We already have Extensions // - If it has the right ADBE, preserve it // - Otherwise, replace ADBE // - We don't have Extensions: create one from scratch // * We don't want ADBE // - We already have Extensions // - If it only has ADBE, remove it // - If it has other things, keep those and remove ADBE // - We have no extensions: no action required // // Before writing, we guarantee that /Extensions, if present, // is direct through the ADBE dictionary, so we can modify in // place. bool is_root = false; bool have_extensions_other = false; bool have_extensions_adbe = false; QPDFObjectHandle extensions; if (old_og == this->m->pdf.getRoot().getObjGen()) { is_root = true; if (object.hasKey("/Extensions") && object.getKey("/Extensions").isDictionary()) { extensions = object.getKey("/Extensions"); } } if (extensions.isInitialized()) { std::set<std::string> keys = extensions.getKeys(); if (keys.count("/ADBE") > 0) { have_extensions_adbe = true; keys.erase("/ADBE"); } if (keys.size() > 0) { have_extensions_other = true; } } bool need_extensions_adbe = (this->m->final_extension_level > 0); if (is_root) { if (need_extensions_adbe) { if (! (have_extensions_other || have_extensions_adbe)) { // We need Extensions and don't have it. Create // it here. QTC::TC("qpdf", "QPDFWriter create Extensions", this->m->qdf_mode ? 0 : 1); extensions = QPDFObjectHandle::newDictionary(); object.replaceKey("/Extensions", extensions); } } else if (! have_extensions_other) { // We have Extensions dictionary and don't want one. if (have_extensions_adbe) { QTC::TC("qpdf", "QPDFWriter remove existing Extensions"); object.removeKey("/Extensions"); extensions = QPDFObjectHandle(); // uninitialized } } } if (extensions.isInitialized()) { QTC::TC("qpdf", "QPDFWriter preserve Extensions"); QPDFObjectHandle adbe = extensions.getKey("/ADBE"); if (adbe.isDictionary() && adbe.hasKey("/BaseVersion") && adbe.getKey("/BaseVersion").isName() && (adbe.getKey("/BaseVersion").getName() == "/" + this->m->final_pdf_version) && adbe.hasKey("/ExtensionLevel") && adbe.getKey("/ExtensionLevel").isInteger() && (adbe.getKey("/ExtensionLevel").getIntValue() == this->m->final_extension_level)) { QTC::TC("qpdf", "QPDFWriter preserve ADBE"); } else { if (need_extensions_adbe) { extensions.replaceKey( "/ADBE", QPDFObjectHandle::parse( "<< /BaseVersion /" + this->m->final_pdf_version + " /ExtensionLevel " + QUtil::int_to_string( this->m->final_extension_level) + " >>")); } else { QTC::TC("qpdf", "QPDFWriter remove ADBE"); extensions.removeKey("/ADBE"); } } } // Stream dictionaries. if (flags & f_stream) { // Suppress /Length since we will write it manually object.removeKey("/Length"); // If /DecodeParms is an empty list, remove it. if (object.getKey("/DecodeParms").isArray() && (0 == object.getKey("/DecodeParms").getArrayNItems())) { QTC::TC("qpdf", "QPDFWriter remove empty DecodeParms"); object.removeKey("/DecodeParms"); } if (flags & f_filtered) { // We will supply our own filter and decode // parameters. object.removeKey("/Filter"); object.removeKey("/DecodeParms"); } else { // Make sure, no matter what else we have, that we // don't have /Crypt in the output filters. QPDFObjectHandle filter = object.getKey("/Filter"); QPDFObjectHandle decode_parms = object.getKey("/DecodeParms"); if (filter.isOrHasName("/Crypt")) { if (filter.isName()) { object.removeKey("/Filter"); object.removeKey("/DecodeParms"); } else { int idx = -1; for (int i = 0; i < filter.getArrayNItems(); ++i) { QPDFObjectHandle item = filter.getArrayItem(i); if (item.isName() && item.getName() == "/Crypt") { idx = i; break; } } if (idx >= 0) { // If filter is an array, then the code in // QPDF_Stream has already verified that // DecodeParms and Filters are arrays of // the same length, but if they weren't // for some reason, eraseItem does type // and bounds checking. QTC::TC("qpdf", "QPDFWriter remove Crypt"); filter.eraseItem(idx); decode_parms.eraseItem(idx); } } } } } writeString("<<"); writeStringQDF("\n"); std::set<std::string> keys = object.getKeys(); for (std::set<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { std::string const& key = *iter; writeStringQDF(indent); writeStringQDF(" "); writeStringNoQDF(" "); writeString(QPDF_Name::normalizeName(key)); writeString(" "); unparseChild(object.getKey(key), level + 1, child_flags); writeStringQDF("\n"); } if (flags & f_stream) { writeStringQDF(indent); writeStringQDF(" "); writeString(" /Length "); if (this->m->direct_stream_lengths) { writeString(QUtil::int_to_string(stream_length)); } else { writeString( QUtil::int_to_string(this->m->cur_stream_length_id)); writeString(" 0 R"); } writeStringQDF("\n"); if (compress && (flags & f_filtered)) { writeStringQDF(indent); writeStringQDF(" "); writeString(" /Filter /FlateDecode"); writeStringQDF("\n"); } } writeStringQDF(indent); writeStringNoQDF(" "); writeString(">>"); } else if (object.isStream()) { // Write stream data to a buffer. int new_id = this->m->obj_renumber[old_og]; if (! this->m->direct_stream_lengths) { this->m->cur_stream_length_id = new_id + 1; } QPDFObjectHandle stream_dict = object.getDict(); bool is_metadata = false; if (stream_dict.getKey("/Type").isName() && (stream_dict.getKey("/Type").getName() == "/Metadata")) { is_metadata = true; } bool filter = (object.isDataModified() || this->m->compress_streams || this->m->stream_decode_level); if (this->m->compress_streams) { // Don't filter if the stream is already compressed with // FlateDecode. We don't want to make it worse by getting // rid of a predictor or otherwise messing with it. We // should also avoid messing with anything that's // compressed with a lossy compression scheme, but we // don't support any of those right now. QPDFObjectHandle filter_obj = stream_dict.getKey("/Filter"); if ((! object.isDataModified()) && filter_obj.isName() && ((filter_obj.getName() == "/FlateDecode") || (filter_obj.getName() == "/Fl"))) { QTC::TC("qpdf", "QPDFWriter not recompressing /FlateDecode"); filter = false; } } bool normalize = false; bool compress = false; bool uncompress = false; if (is_metadata && ((! this->m->encrypted) || (this->m->encrypt_metadata == false))) { QTC::TC("qpdf", "QPDFWriter not compressing metadata"); filter = true; compress = false; uncompress = true; } else if (this->m->normalize_content && this->m->normalized_streams.count(old_og)) { normalize = true; filter = true; } else if (filter && this->m->compress_streams) { compress = true; QTC::TC("qpdf", "QPDFWriter compressing uncompressed stream"); } flags |= f_stream; PointerHolder<Buffer> stream_data; bool filtered = false; for (int attempt = 1; attempt <= 2; ++attempt) { pushPipeline(new Pl_Buffer("stream data")); activatePipelineStack(); filtered = object.pipeStreamData( this->m->pipeline, (((filter && normalize) ? qpdf_ef_normalize : 0) | ((filter && compress) ? qpdf_ef_compress : 0)), (filter ? (uncompress ? qpdf_dl_all : this->m->stream_decode_level) : qpdf_dl_none), false, (attempt == 1)); popPipelineStack(&stream_data); if (filter && (! filtered)) { // Try again filter = false; } else { break; } } if (filtered) { flags |= f_filtered; } else { compress = false; } this->m->cur_stream_length = stream_data->getSize(); if (is_metadata && this->m->encrypted && (! this->m->encrypt_metadata)) { // Don't encrypt stream data for the metadata stream this->m->cur_data_key.clear(); } adjustAESStreamLength(this->m->cur_stream_length); unparseObject(stream_dict, 0, flags, this->m->cur_stream_length, compress); writeString("\nstream\n"); pushEncryptionFilter(); writeBuffer(stream_data); char last_char = this->m->pipeline->getLastChar(); popPipelineStack(); if (this->m->newline_before_endstream || (this->m->qdf_mode && (last_char != '\n'))) { writeString("\n"); this->m->added_newline = true; } else { this->m->added_newline = false; } writeString("endstream"); } else if (object.isString()) { std::string val; if (this->m->encrypted && (! (flags & f_in_ostream)) && (! this->m->cur_data_key.empty())) { val = object.getStringValue(); if (this->m->encrypt_use_aes) { Pl_Buffer bufpl("encrypted string"); Pl_AES_PDF pl( "aes encrypt string", &bufpl, true, QUtil::unsigned_char_pointer(this->m->cur_data_key), this->m->cur_data_key.length()); pl.write(QUtil::unsigned_char_pointer(val), val.length()); pl.finish(); Buffer* buf = bufpl.getBuffer(); val = QPDF_String( std::string(reinterpret_cast<char*>(buf->getBuffer()), buf->getSize())).unparse(true); delete buf; } else { char* tmp = QUtil::copy_string(val); size_t vlen = val.length(); RC4 rc4(QUtil::unsigned_char_pointer(this->m->cur_data_key), this->m->cur_data_key.length()); rc4.process(QUtil::unsigned_char_pointer(tmp), vlen); val = QPDF_String(std::string(tmp, vlen)).unparse(); delete [] tmp; } } else { val = object.unparseResolved(); } writeString(val); } else { writeString(object.unparseResolved()); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFAnnotationObjectHelper::getFlags() { QPDFObjectHandle flags_obj = this->oh.getKey("/F"); return flags_obj.isInteger() ? flags_obj.getIntValue() : 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ImageInverter::provideStreamData(int objid, int generation, Pipeline* pipeline) { // Use the object and generation number supplied to look up the // image data. Then invert the image data and write the inverted // data to the pipeline. PointerHolder<Buffer> data = this->image_data[QPDFObjGen(objid, generation)]; size_t size = data->getSize(); unsigned char* buf = data->getBuffer(); unsigned char ch; for (size_t i = 0; i < size; ++i) { ch = static_cast<unsigned char>(0xff) - buf[i]; pipeline->write(&ch, 1); } pipeline->finish(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Pl_DCT::decompress(void* cinfo_p, Buffer* b) { struct jpeg_decompress_struct* cinfo = reinterpret_cast<jpeg_decompress_struct*>(cinfo_p); #if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wold-style-cast" #endif jpeg_create_decompress(cinfo); #if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ defined(__clang__)) # pragma GCC diagnostic pop #endif jpeg_buffer_src(cinfo, b); (void) jpeg_read_header(cinfo, TRUE); (void) jpeg_calc_output_dimensions(cinfo); int width = cinfo->output_width * cinfo->output_components; JSAMPARRAY buffer = (*cinfo->mem->alloc_sarray) (reinterpret_cast<j_common_ptr>(cinfo), JPOOL_IMAGE, width, 1); (void) jpeg_start_decompress(cinfo); while (cinfo->output_scanline < cinfo->output_height) { (void) jpeg_read_scanlines(cinfo, buffer, 1); this->getNext()->write(reinterpret_cast<unsigned char*>(buffer[0]), width * sizeof(buffer[0][0])); } (void) jpeg_finish_decompress(cinfo); this->getNext()->finish(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDF::lengthNextN(int first_object, int n, std::list<std::string>& errors) { int length = 0; for (int i = 0; i < n; ++i) { QPDFObjGen og(first_object + i, 0); if (this->m->xref_table.count(og) == 0) { errors.push_back( "no xref table entry for " + QUtil::int_to_string(first_object + i) + " 0"); } else { if (this->m->obj_cache.count(og) == 0) { stopOnError("found unknown object while" " calculating length for linearization data"); } length += this->m->obj_cache[og].end_after_space - getLinearizationOffset(og); } } return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char* argv[]) { bool encrypt = true; bool cbc_mode = true; char* hexkey = 0; char* infilename = 0; char* outfilename = 0; bool zero_iv = false; bool static_iv = false; bool disable_padding = false; for (int i = 1; i < argc; ++i) { char* arg = argv[i]; if ((arg[0] == '-') || (arg[0] == '+')) { if (strcmp(arg, "-cbc") == 0) { cbc_mode = false; } else if (strcmp(arg, "+cbc") == 0) { cbc_mode = true; } else if (strcmp(arg, "-decrypt") == 0) { encrypt = false; } else if (strcmp(arg, "-encrypt") == 0) { encrypt = true; } else if (strcmp(arg, "-zero-iv") == 0) { zero_iv = true; } else if (strcmp(arg, "-static-iv") == 0) { static_iv = true; } else if (strcmp(arg, "-no-padding") == 0) { disable_padding = true; } else { usage(); } } else if (argc == i + 3) { hexkey = argv[i]; infilename = argv[i+1]; outfilename = argv[i+2]; break; } else { usage(); } } if (outfilename == 0) { usage(); } unsigned int hexkeylen = strlen(hexkey); unsigned int keylen = hexkeylen / 2; FILE* infile = QUtil::safe_fopen(infilename, "rb"); FILE* outfile = QUtil::safe_fopen(outfilename, "wb"); unsigned char* key = new unsigned char[keylen]; for (unsigned int i = 0; i < strlen(hexkey); i += 2) { char t[3]; t[0] = hexkey[i]; t[1] = hexkey[i + 1]; t[2] = '\0'; long val = strtol(t, 0, 16); key[i/2] = static_cast<unsigned char>(val); } Pl_StdioFile* out = new Pl_StdioFile("stdout", outfile); Pl_AES_PDF* aes = new Pl_AES_PDF("aes_128_cbc", out, encrypt, key, keylen); delete [] key; key = 0; if (! cbc_mode) { aes->disableCBC(); } if (zero_iv) { aes->useZeroIV(); } else if (static_iv) { aes->useStaticIV(); } if (disable_padding) { aes->disablePadding(); } // 16 < buffer size, buffer_size is not a multiple of 8 for testing unsigned char buf[83]; bool done = false; while (! done) { size_t len = fread(buf, 1, sizeof(buf), infile); if (len <= 0) { done = true; } else { aes->write(buf, len); } } aes->finish(); delete aes; delete out; fclose(infile); fclose(outfile); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QUtil::safe_fopen(char const* filename, char const* mode) { FILE* f = 0; #ifdef _WIN32 // Convert the utf-8 encoded filename argument to wchar_t*. First, // convert to utf16, then to wchar_t*. Note that u16 will start // with the UTF16 marker, which we skip. std::string u16 = utf8_to_utf16(filename); size_t len = u16.length(); size_t wlen = (len / 2) - 1; PointerHolder<wchar_t> wfilenamep(true, new wchar_t[wlen + 1]); wchar_t* wfilename = wfilenamep.getPointer(); wfilename[wlen] = 0; for (unsigned int i = 2; i < len; i += 2) { wfilename[(i/2) - 1] = static_cast<wchar_t>( (static_cast<unsigned char>(u16.at(i)) << 8) + static_cast<unsigned char>(u16.at(i+1))); } PointerHolder<wchar_t> wmodep(true, new wchar_t[strlen(mode) + 1]); wchar_t* wmode = wmodep.getPointer(); wmode[strlen(mode)] = 0; for (size_t i = 0; i < strlen(mode); ++i) { wmode[i] = mode[i]; } #ifdef _MSC_VER errno_t err = _wfopen_s(&f, wfilename, wmode); if (err != 0) { errno = err; } #else f = _wfopen(wfilename, wmode); #endif if (f == 0) { throw_system_error(std::string("open ") + filename); } #else f = fopen_wrapper(std::string("open ") + filename, fopen(filename, mode)); #endif return f; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFWriter::setEncryptionParametersInternal( int V, int R, int key_len, long P, std::string const& O, std::string const& U, std::string const& OE, std::string const& UE, std::string const& Perms, std::string const& id1, std::string const& user_password, std::string const& encryption_key) { this->m->encryption_V = V; this->m->encryption_R = R; this->m->encryption_dictionary["/Filter"] = "/Standard"; this->m->encryption_dictionary["/V"] = QUtil::int_to_string(V); this->m->encryption_dictionary["/Length"] = QUtil::int_to_string(key_len * 8); this->m->encryption_dictionary["/R"] = QUtil::int_to_string(R); this->m->encryption_dictionary["/P"] = QUtil::int_to_string(P); this->m->encryption_dictionary["/O"] = QPDF_String(O).unparse(true); this->m->encryption_dictionary["/U"] = QPDF_String(U).unparse(true); if (V >= 5) { this->m->encryption_dictionary["/OE"] = QPDF_String(OE).unparse(true); this->m->encryption_dictionary["/UE"] = QPDF_String(UE).unparse(true); this->m->encryption_dictionary["/Perms"] = QPDF_String(Perms).unparse(true); } if (R >= 6) { setMinimumPDFVersion("1.7", 8); } else if (R == 5) { setMinimumPDFVersion("1.7", 3); } else if (R == 4) { setMinimumPDFVersion(this->m->encrypt_use_aes ? "1.6" : "1.5"); } else if (R == 3) { setMinimumPDFVersion("1.4"); } else { setMinimumPDFVersion("1.3"); } if ((R >= 4) && (! this->m->encrypt_metadata)) { this->m->encryption_dictionary["/EncryptMetadata"] = "false"; } if ((V == 4) || (V == 5)) { // The spec says the value for the crypt filter key can be // anything, and xpdf seems to agree. However, Adobe Reader // won't open our files unless we use /StdCF. this->m->encryption_dictionary["/StmF"] = "/StdCF"; this->m->encryption_dictionary["/StrF"] = "/StdCF"; std::string method = (this->m->encrypt_use_aes ? ((V < 5) ? "/AESV2" : "/AESV3") : "/V2"); // The PDF spec says the /Length key is optional, but the PDF // previewer on some versions of MacOS won't open encrypted // files without it. this->m->encryption_dictionary["/CF"] = "<< /StdCF << /AuthEvent /DocOpen /CFM " + method + " /Length " + std::string((V < 5) ? "16" : "32") + " >> >>"; } this->m->encrypted = true; QPDF::EncryptionData encryption_data( V, R, key_len, P, O, U, OE, UE, Perms, id1, this->m->encrypt_metadata); if (V < 5) { this->m->encryption_key = QPDF::compute_encryption_key( user_password, encryption_data); } else { this->m->encryption_key = encryption_key; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFFormFieldObjectHelper::getQuadding() { int result = 0; QPDFObjectHandle fv = getInheritableFieldValue("/Q"); if (fv.isInteger()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper Q present"); result = static_cast<int>(fv.getIntValue()); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFObjectHandle::isRectangle() { if (! isArray()) { return false; } if (getArrayNItems() != 4) { return false; } for (size_t i = 0; i < 4; ++i) { if (! getArrayItem(i).isNumber()) { return false; } } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void write_outfile(QPDF& pdf, Options& o) { if (o.split_pages) { // Generate output file pattern std::string before; std::string after; size_t len = strlen(o.outfilename); char* num_spot = strstr(const_cast<char*>(o.outfilename), "%d"); if (num_spot != 0) { QTC::TC("qpdf", "qpdf split-pages %d"); before = std::string(o.outfilename, (num_spot - o.outfilename)); after = num_spot + 2; } else if ((len >= 4) && (QUtil::strcasecmp(o.outfilename + len - 4, ".pdf") == 0)) { QTC::TC("qpdf", "qpdf split-pages .pdf"); before = std::string(o.outfilename, len - 4) + "-"; after = o.outfilename + len - 4; } else { QTC::TC("qpdf", "qpdf split-pages other"); before = std::string(o.outfilename) + "-"; } if (! o.preserve_unreferenced_page_resources) { QPDFPageDocumentHelper dh(pdf); dh.removeUnreferencedResources(); } QPDFPageLabelDocumentHelper pldh(pdf); std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages(); int pageno_len = QUtil::int_to_string(pages.size()).length(); unsigned int num_pages = pages.size(); for (unsigned int i = 0; i < num_pages; i += o.split_pages) { unsigned int first = i + 1; unsigned int last = i + o.split_pages; if (last > num_pages) { last = num_pages; } QPDF outpdf; outpdf.emptyPDF(); for (unsigned int pageno = first; pageno <= last; ++pageno) { QPDFObjectHandle page = pages.at(pageno - 1); outpdf.addPage(page, false); } if (pldh.hasPageLabels()) { std::vector<QPDFObjectHandle> labels; pldh.getLabelsForPageRange(first - 1, last - 1, 0, labels); QPDFObjectHandle page_labels = QPDFObjectHandle::newDictionary(); page_labels.replaceKey( "/Nums", QPDFObjectHandle::newArray(labels)); outpdf.getRoot().replaceKey("/PageLabels", page_labels); } std::string page_range = QUtil::int_to_string(first, pageno_len); if (o.split_pages > 1) { page_range += "-" + QUtil::int_to_string(last, pageno_len); } std::string outfile = before + page_range + after; QPDFWriter w(outpdf, outfile.c_str()); set_writer_options(outpdf, o, w); w.write(); if (o.verbose) { std::cout << whoami << ": wrote file " << outfile << std::endl; } } } else { if (strcmp(o.outfilename, "-") == 0) { o.outfilename = 0; } QPDFWriter w(pdf, o.outfilename); set_writer_options(pdf, o, w); w.write(); if (o.verbose) { std::cout << whoami << ": wrote file " << o.outfilename << std::endl; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major) This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len, RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value, const RBinDwarfCompUnitHdr *hdr, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf; const ut8 *buf_end = obuf + obuf_len; size_t j; if (!spec || !value || !hdr || !obuf || obuf_len < 0) { return NULL; } value->form = spec->attr_form; value->name = spec->attr_name; value->encoding.block.data = NULL; value->encoding.str_struct.string = NULL; value->encoding.str_struct.offset = 0; switch (spec->attr_form) { case DW_FORM_addr: switch (hdr->pointer_size) { case 1: value->encoding.address = READ (buf, ut8); break; case 2: value->encoding.address = READ (buf, ut16); break; case 4: value->encoding.address = READ (buf, ut32); break; case 8: value->encoding.address = READ (buf, ut64); break; default: eprintf("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size); return NULL; } break; case DW_FORM_block2: value->encoding.block.length = READ (buf, ut16); if (value->encoding.block.length > 0) { value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block4: value->encoding.block.length = READ (buf, ut32); if (value->encoding.block.length > 0) { ut8 *data = calloc (sizeof (ut8), value->encoding.block.length); if (data) { for (j = 0; j < value->encoding.block.length; j++) { data[j] = READ (buf, ut8); } } value->encoding.block.data = data; } break; case DW_FORM_data2: value->encoding.data = READ (buf, ut16); break; case DW_FORM_data4: value->encoding.data = READ (buf, ut32); break; case DW_FORM_data8: value->encoding.data = READ (buf, ut64); break; case DW_FORM_string: value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL; buf += (strlen ((const char*)buf) + 1); break; case DW_FORM_block: buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length); if (!buf) { return NULL; } value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } break; case DW_FORM_block1: value->encoding.block.length = READ (buf, ut8); value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } break; case DW_FORM_flag: value->encoding.flag = READ (buf, ut8); break; case DW_FORM_sdata: buf = r_leb128 (buf, &value->encoding.sdata); break; case DW_FORM_strp: value->encoding.str_struct.offset = READ (buf, ut32); if (debug_str && value->encoding.str_struct.offset < debug_str_len) { value->encoding.str_struct.string = strdup ( (const char *)(debug_str + value->encoding.str_struct.offset)); } else { value->encoding.str_struct.string = NULL; } break; case DW_FORM_udata: { ut64 ndata = 0; const ut8 *data = (const ut8*)&ndata; buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata); memcpy (&value->encoding.data, data, sizeof (value->encoding.data)); value->encoding.str_struct.string = NULL; } break; case DW_FORM_ref_addr: value->encoding.reference = READ (buf, ut64); // addr size of machine break; case DW_FORM_ref1: value->encoding.reference = READ (buf, ut8); break; case DW_FORM_ref2: value->encoding.reference = READ (buf, ut16); break; case DW_FORM_ref4: value->encoding.reference = READ (buf, ut32); break; case DW_FORM_ref8: value->encoding.reference = READ (buf, ut64); break; case DW_FORM_data1: value->encoding.data = READ (buf, ut8); break; default: eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form); value->encoding.data = 0; return NULL; } return buf; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix #8813 - segfault in dwarf 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 ssize_t ib_ucm_write(struct file *filp, const char __user *buf, size_t len, loff_t *pos) { struct ib_ucm_file *file = filp->private_data; struct ib_ucm_cmd_hdr hdr; ssize_t result; if (len < sizeof(hdr)) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof(hdr))) return -EFAULT; if (hdr.cmd >= ARRAY_SIZE(ucm_cmd_table)) return -EINVAL; if (hdr.in + sizeof(hdr) > len) return -EINVAL; result = ucm_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out); if (!result) result = len; return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <jann@thejh.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Jason Gunthorpe <jgunthorpe@obsidianresearch.com> [ Expanded check to all known write() entry points ] Cc: stable@vger.kernel.org Signed-off-by: Doug Ledford <dledford@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: isis_print_mt_capability_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len, tmp; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); len = len - 2; switch (stlv_type) { case ISIS_SUBTLV_SPB_INSTANCE: ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN); ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr))); tptr = tptr + 2; ND_PRINT((ndo, "\n\t RES: %d", EXTRACT_16BITS(tptr) >> 5)); ND_PRINT((ndo, ", V: %d", (EXTRACT_16BITS(tptr) >> 4) & 0x0001)); ND_PRINT((ndo, ", SPSource-ID: %d", (EXTRACT_32BITS(tptr) & 0x000fffff))); tptr = tptr+4; ND_PRINT((ndo, ", No of Trees: %x", *(tptr))); tmp = *(tptr++); len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; while (tmp) { ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN); ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d", *(tptr) >> 7, (*(tptr) >> 6) & 0x01, (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f))); tptr++; ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr + 4; ND_PRINT((ndo, ", BVID: %d, SPVID: %d", (EXTRACT_24BITS(tptr) >> 12) & 0x000fff, EXTRACT_24BITS(tptr) & 0x000fff)); tptr = tptr + 3; len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; tmp--; } break; case ISIS_SUBTLV_SPBM_SI: ND_TCHECK2(*tptr, 8); ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr))); tptr = tptr+2; ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12, (EXTRACT_16BITS(tptr)) & 0x0fff)); tptr = tptr+2; len = len - 8; stlv_len = stlv_len - 8; while (stlv_len >= 4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d", (EXTRACT_32BITS(tptr) >> 31), (EXTRACT_32BITS(tptr) >> 30) & 0x01, (EXTRACT_32BITS(tptr) >> 24) & 0x03f, (EXTRACT_32BITS(tptr)) & 0x0ffffff)); tptr = tptr + 4; len = len - 4; stlv_len = stlv_len - 4; } break; default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13026/IS-IS: Clean up processing of subTLVs. Add bounds checks, do a common check to make sure we captured the entire subTLV, add checks to make sure the subTLV fits within the TLV. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add tests using the capture files supplied by the reporter(s), modified so the capture files won't be rejected as an invalid capture. Update existing tests for changes to IS-IS dissector.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fep_client_open (const char *address) { FepClient *client; struct sockaddr_un sun; ssize_t sun_len; int retval; if (!address) address = getenv ("LIBFEP_CONTROL_SOCK"); if (!address) return NULL; if (strlen (address) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (address), sizeof (sun.sun_path)); free (address); return NULL; } client = xzalloc (sizeof(FepClient)); client->filter_running = false; client->messages = NULL; memset (&sun, 0, sizeof(struct sockaddr_un)); sun.sun_family = AF_UNIX; #ifdef __linux__ sun.sun_path[0] = '\0'; memcpy (sun.sun_path + 1, address, strlen (address)); sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (address) + 1; #else memcpy (sun.sun_path, address, strlen (address)); sun_len = sizeof (struct sockaddr_un); #endif client->control = socket (AF_UNIX, SOCK_STREAM, 0); if (client->control < 0) { free (client); return NULL; } retval = connect (client->control, (const struct sockaddr *) &sun, sun_len); if (retval < 0) { close (client->control); free (client); return NULL; } return client; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't use abstract Unix domain sockets'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool CModules::GetModInfo(CModInfo& ModInfo, const CString& sModule, CString& sRetMsg) { CString sModPath, sTmp; bool bSuccess; bool bHandled = false; GLOBALMODULECALL(OnGetModInfo(ModInfo, sModule, bSuccess, sRetMsg), &bHandled); if (bHandled) return bSuccess; if (!FindModPath(sModule, sModPath, sTmp)) { sRetMsg = t_f("Unable to find module {1}.")(sModule); return false; } return GetModPathInfo(ModInfo, sModule, sModPath, sRetMsg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-264'], 'message': 'Fix remote code execution and privilege escalation vulnerability. To trigger this, need to have a user already. Thanks for Jeriko One <jeriko.one@gmx.us> for finding and reporting this. CVE-2019-12816'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh) { transaction_t *transaction; struct journal_head *jh; int may_free = 1; int ret; BUFFER_TRACE(bh, "entry"); /* * It is safe to proceed here without the j_list_lock because the * buffers cannot be stolen by try_to_free_buffers as long as we are * holding the page lock. --sct */ if (!buffer_jbd(bh)) goto zap_buffer_unlocked; /* OK, we have data buffer in journaled mode */ write_lock(&journal->j_state_lock); jbd_lock_bh_state(bh); spin_lock(&journal->j_list_lock); jh = jbd2_journal_grab_journal_head(bh); if (!jh) goto zap_buffer_no_jh; /* * We cannot remove the buffer from checkpoint lists until the * transaction adding inode to orphan list (let's call it T) * is committed. Otherwise if the transaction changing the * buffer would be cleaned from the journal before T is * committed, a crash will cause that the correct contents of * the buffer will be lost. On the other hand we have to * clear the buffer dirty bit at latest at the moment when the * transaction marking the buffer as freed in the filesystem * structures is committed because from that moment on the * buffer can be reallocated and used by a different page. * Since the block hasn't been freed yet but the inode has * already been added to orphan list, it is safe for us to add * the buffer to BJ_Forget list of the newest transaction. */ transaction = jh->b_transaction; if (transaction == NULL) { /* First case: not on any transaction. If it * has no checkpoint link, then we can zap it: * it's a writeback-mode buffer so we don't care * if it hits disk safely. */ if (!jh->b_cp_transaction) { JBUFFER_TRACE(jh, "not on any transaction: zap"); goto zap_buffer; } if (!buffer_dirty(bh)) { /* bdflush has written it. We can drop it now */ goto zap_buffer; } /* OK, it must be in the journal but still not * written fully to disk: it's metadata or * journaled data... */ if (journal->j_running_transaction) { /* ... and once the current transaction has * committed, the buffer won't be needed any * longer. */ JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget"); ret = __dispose_buffer(jh, journal->j_running_transaction); jbd2_journal_put_journal_head(jh); spin_unlock(&journal->j_list_lock); jbd_unlock_bh_state(bh); write_unlock(&journal->j_state_lock); return ret; } else { /* There is no currently-running transaction. So the * orphan record which we wrote for this file must have * passed into commit. We must attach this buffer to * the committing transaction, if it exists. */ if (journal->j_committing_transaction) { JBUFFER_TRACE(jh, "give to committing trans"); ret = __dispose_buffer(jh, journal->j_committing_transaction); jbd2_journal_put_journal_head(jh); spin_unlock(&journal->j_list_lock); jbd_unlock_bh_state(bh); write_unlock(&journal->j_state_lock); return ret; } else { /* The orphan record's transaction has * committed. We can cleanse this buffer */ clear_buffer_jbddirty(bh); goto zap_buffer; } } } else if (transaction == journal->j_committing_transaction) { JBUFFER_TRACE(jh, "on committing transaction"); /* * The buffer is committing, we simply cannot touch * it. So we just set j_next_transaction to the * running transaction (if there is one) and mark * buffer as freed so that commit code knows it should * clear dirty bits when it is done with the buffer. */ set_buffer_freed(bh); if (journal->j_running_transaction && buffer_jbddirty(bh)) jh->b_next_transaction = journal->j_running_transaction; jbd2_journal_put_journal_head(jh); spin_unlock(&journal->j_list_lock); jbd_unlock_bh_state(bh); write_unlock(&journal->j_state_lock); return 0; } else { /* Good, the buffer belongs to the running transaction. * We are writing our own transaction's data, not any * previous one's, so it is safe to throw it away * (remember that we expect the filesystem to have set * i_size already for this truncate so recovery will not * expose the disk blocks we are discarding here.) */ J_ASSERT_JH(jh, transaction == journal->j_running_transaction); JBUFFER_TRACE(jh, "on running transaction"); may_free = __dispose_buffer(jh, transaction); } zap_buffer: jbd2_journal_put_journal_head(jh); zap_buffer_no_jh: spin_unlock(&journal->j_list_lock); jbd_unlock_bh_state(bh); write_unlock(&journal->j_state_lock); zap_buffer_unlocked: clear_buffer_dirty(bh); J_ASSERT_BH(bh, !buffer_jbddirty(bh)); clear_buffer_mapped(bh); clear_buffer_req(bh); clear_buffer_new(bh); bh->b_bdev = NULL; return may_free; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'jbd2: clear BH_Delay & BH_Unwritten in journal_unmap_buffer journal_unmap_buffer()'s zap_buffer: code clears a lot of buffer head state ala discard_buffer(), but does not touch _Delay or _Unwritten as discard_buffer() does. This can be problematic in some areas of the ext4 code which assume that if they have found a buffer marked unwritten or delay, then it's a live one. Perhaps those spots should check whether it is mapped as well, but if jbd2 is going to tear down a buffer, let's really tear it down completely. Without this I get some fsx failures on sub-page-block filesystems up until v3.2, at which point 4e96b2dbbf1d7e81f22047a50f862555a6cb87cb and 189e868fa8fdca702eb9db9d8afc46b5cb9144c9 make the failures go away, because buried within that large change is some more flag clearing. I still think it's worth doing in jbd2, since ->invalidatepage leads here directly, and it's the right place to clear away these flags. Signed-off-by: Eric Sandeen <sandeen@redhat.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Cc: stable@vger.kernel.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests) { static const U32 maxSrcLog = 23; static const U32 maxSampleLog = 22; size_t const srcBufferSize = (size_t)1<<maxSrcLog; size_t const dstBufferSize = (size_t)1<<maxSampleLog; size_t const cBufferSize = ZSTD_compressBound(dstBufferSize); BYTE* cNoiseBuffer[5]; BYTE* const cBuffer = (BYTE*) malloc (cBufferSize); BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize); BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize); ZSTD_CCtx* const refCtx = ZSTD_createCCtx(); ZSTD_CCtx* const ctx = ZSTD_createCCtx(); ZSTD_DCtx* const dctx = ZSTD_createDCtx(); U32 result = 0; U32 testNb = 0; U32 coreSeed = seed; UTIL_time_t const startClock = UTIL_getTime(); U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO; int const cLevelLimiter = bigTests ? 3 : 2; /* allocation */ cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize); cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize); cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize); cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize); cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize); CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx, "Not enough memory, fuzzer tests cancelled"); /* Create initial samples */ RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */ RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */ RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed); RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */ RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */ /* catch up testNb */ for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed); /* main test loop */ for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) { BYTE* srcBuffer; /* jumping pointer */ U32 lseed; size_t sampleSize, maxTestSize, totalTestSize; size_t cSize, totalCSize, totalGenSize; U64 crcOrig; BYTE* sampleBuffer; const BYTE* dict; size_t dictSize; /* notification */ if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); } else { DISPLAYUPDATE(2, "\r%6u ", testNb); } FUZ_rand(&coreSeed); { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; } /* srcBuffer selection [0-4] */ { U32 buffNb = FUZ_rand(&lseed) & 0x7F; if (buffNb & 7) buffNb=2; /* most common : compressible (P) */ else { buffNb >>= 3; if (buffNb & 7) { const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */ buffNb = tnb[buffNb >> 3]; } else { const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */ buffNb = tnb[buffNb >> 3]; } } srcBuffer = cNoiseBuffer[buffNb]; } /* select src segment */ sampleSize = FUZ_randomLength(&lseed, maxSampleLog); /* create sample buffer (to catch read error with valgrind & sanitizers) */ sampleBuffer = (BYTE*)malloc(sampleSize); CHECK(sampleBuffer==NULL, "not enough memory for sample buffer"); { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize); memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); } crcOrig = XXH64(sampleBuffer, sampleSize, 0); /* compression tests */ { int const cLevelPositive = ( FUZ_rand(&lseed) % (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) ) + 1; int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ? - (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */ cLevelPositive; DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel); cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel); CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize)); /* compression failure test : too small dest buffer */ if (cSize > 3) { const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */ const size_t tooSmallSize = cSize - missing; const U32 endMark = 0x4DC2B1A9; memcpy(dstBuffer+tooSmallSize, &endMark, 4); { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel); CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); } { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4); CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); } } } /* frame header decompression test */ { ZSTD_frameHeader zfh; CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) ); CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect"); } /* Decompressed size test */ { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize); CHECK(rSize != sampleSize, "decompressed size incorrect"); } /* successful decompression test */ DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb); { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1; size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize); CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize); { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0); CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize); } } free(sampleBuffer); /* no longer useful after this point */ /* truncated src decompression test */ DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb); { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */ size_t const tooSmallSize = cSize - missing; void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */ CHECK(cBufferTooSmall == NULL, "not enough memory !"); memcpy(cBufferTooSmall, cBuffer, tooSmallSize); { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize); CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); } free(cBufferTooSmall); } /* too small dst decompression test */ DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb); if (sampleSize > 3) { size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */ size_t const tooSmallSize = sampleSize - missing; static const BYTE token = 0xA9; dstBuffer[tooSmallSize] = token; { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize); CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); } CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow"); } /* noisy src decompression test */ if (cSize > 6) { /* insert noise into src */ { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4)); size_t pos = 4; /* preserve magic number (too easy to detect) */ for (;;) { /* keep some original src */ { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits; size_t const mask = (1<<nbBits) - 1; size_t const skipLength = FUZ_rand(&lseed) & mask; pos += skipLength; } if (pos >= cSize) break; /* add noise */ { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits; U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0; size_t const mask = (1<<nbBits) - 1; size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1; size_t const noiseLength = MIN(rNoiseLength, cSize-pos); size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength); memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength); pos += noiseLength; } } } /* decompress noisy source */ DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb); { U32 const endMark = 0xA9B1C3D6; memcpy(dstBuffer+sampleSize, &endMark, 4); { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize); /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */ CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize), "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize); } { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4); CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow"); } } } /* noisy src decompression test */ /*===== Bufferless streaming compression test, scattered segments and dictionary =====*/ DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb); { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog; U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog; int const cLevel = (FUZ_rand(&lseed) % (ZSTD_maxCLevel() - (MAX(testLog, dictLog) / cLevelLimiter))) + 1; maxTestSize = FUZ_rLogLength(&lseed, testLog); if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1; dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */ dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize)); DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n", testNb, (U32)maxTestSize, cLevel, (U32)dictSize); if (FUZ_rand(&lseed) & 0xF) { CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) ); } else { ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize); ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */, !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/, 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */ ZSTD_parameters const p = FUZ_makeParams(cPar, fPar); CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) ); } CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) ); } { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2; U32 n; XXH64_state_t xxhState; XXH64_reset(&xxhState, 0); for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) { size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog); size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize); if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */ if (totalTestSize+segmentSize > maxTestSize) break; { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize); CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult)); cSize += compressResult; } XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize); memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize); totalTestSize += segmentSize; } { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0); CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult)); cSize += flushResult; } crcOrig = XXH64_digest(&xxhState); } /* streaming decompression test */ DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb); /* ensure memory requirement is good enough (should always be true) */ { ZSTD_frameHeader zfh; CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max), "ZSTD_getFrameHeader(): error retrieving frame information"); { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize); CHECK_Z(roundBuffSize); CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN), "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)", (U32)roundBuffSize, (U32)totalTestSize ); } } if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */ CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) ); totalCSize = 0; totalGenSize = 0; while (totalCSize < cSize) { size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx); size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize); CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize)); totalGenSize += genSize; totalCSize += inSize; } CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded"); CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size") CHECK (totalCSize != cSize, "compressed data should be fully read") { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0); CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)", (U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize); } } /* for ( ; (testNb <= nbTests) */ DISPLAY("\r%u fuzzer tests completed \n", testNb-1); _cleanup: ZSTD_freeCCtx(refCtx); ZSTD_freeCCtx(ctx); ZSTD_freeDCtx(dctx); free(cNoiseBuffer[0]); free(cNoiseBuffer[1]); free(cNoiseBuffer[2]); free(cNoiseBuffer[3]); free(cNoiseBuffer[4]); free(cBuffer); free(dstBuffer); free(mirrorBuffer); return result; _output_error: result = 1; goto _cleanup; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'fixed T36302429'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void TestJlCompress::extractDir() { QFETCH(QString, zipName); QFETCH(QStringList, fileNames); QDir curDir; if (!curDir.mkpath("jlext/jldir")) { QFAIL("Couldn't mkpath jlext/jldir"); } if (!createTestFiles(fileNames)) { QFAIL("Couldn't create test files"); } if (!createTestArchive(zipName, fileNames)) { QFAIL("Couldn't create test archive"); } QStringList extracted; QCOMPARE((extracted = JlCompress::extractDir(zipName, "jlext/jldir")) .count(), fileNames.count()); foreach (QString fileName, fileNames) { QString fullName = "jlext/jldir/" + fileName; QFileInfo fileInfo(fullName); QFileInfo extInfo("tmp/" + fileName); if (!fileInfo.isDir()) QCOMPARE(fileInfo.size(), extInfo.size()); QCOMPARE(fileInfo.permissions(), extInfo.permissions()); curDir.remove(fullName); curDir.rmpath(fileInfo.dir().path()); QString absolutePath = fileInfo.absoluteFilePath(); if (fileInfo.isDir() && !absolutePath.endsWith('/')) absolutePath += '/'; QVERIFY(extracted.contains(absolutePath)); } // now test the QIODevice* overload QFile zipFile(zipName); QVERIFY(zipFile.open(QIODevice::ReadOnly)); QCOMPARE((extracted = JlCompress::extractDir(&zipFile, "jlext/jldir")) .count(), fileNames.count()); foreach (QString fileName, fileNames) { QString fullName = "jlext/jldir/" + fileName; QFileInfo fileInfo(fullName); QFileInfo extInfo("tmp/" + fileName); if (!fileInfo.isDir()) QCOMPARE(fileInfo.size(), extInfo.size()); QCOMPARE(fileInfo.permissions(), extInfo.permissions()); curDir.remove(fullName); curDir.rmpath(fileInfo.dir().path()); QString absolutePath = fileInfo.absoluteFilePath(); if (fileInfo.isDir() && !absolutePath.endsWith('/')) absolutePath += '/'; QVERIFY(extracted.contains(absolutePath)); } zipFile.close(); curDir.rmpath("jlext/jldir"); removeTestFiles(fileNames); curDir.remove(zipName); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed the Zip Slip vulnerability in JlCompress When extracting a file with a dangerous path like "../evil.exe" from a ZIP archive with JlCompress::extractDir(), the target file would be created outside of the target directory, potentially even overwriting an existing file there.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void readTOMLConf(toml::value &root) { const auto &section_common = toml::find(root, "common"); string_array default_url, insert_url; find_if_exist(section_common, "default_url", default_url, "insert_url", insert_url); global.defaultUrls = join(default_url, "|"); global.insertUrls = join(insert_url, "|"); bool filter = false; find_if_exist(section_common, "api_mode", global.APIMode, "api_access_token", global.accessToken, "exclude_remarks", global.excludeRemarks, "include_remarks", global.includeRemarks, "enable_insert", global.enableInsert, "prepend_insert_url", global.prependInsert, "enable_filter", filter, "default_external_config", global.defaultExtConfig, "base_path", global.basePath, "clash_rule_base", global.clashBase, "surge_rule_base", global.surgeBase, "surfboard_rule_base", global.surfboardBase, "mellow_rule_base", global.mellowBase, "quan_rule_base", global.quanBase, "quanx_rule_base", global.quanXBase, "loon_rule_base", global.loonBase, "proxy_config", global.proxyConfig, "proxy_ruleset", global.proxyRuleset, "proxy_subscription", global.proxySubscription, "append_proxy_type", global.appendType ); if(filter) find_if_exist(section_common, "filter_script", global.filterScript); else global.filterScript.clear(); safe_set_streams(toml::find_or<RegexMatchConfigs>(root, "userinfo", "stream_rule", RegexMatchConfigs{})); safe_set_times(toml::find_or<RegexMatchConfigs>(root, "userinfo", "time_rule", RegexMatchConfigs{})); const auto &section_node_pref = toml::find(root, "node_pref"); find_if_exist(section_node_pref, "udp_flag", global.UDPFlag, "tcp_fast_open_flag", global.TFOFlag, "skip_cert_verify_flag", global.skipCertVerify, "tls13_flag", global.TLS13Flag, "sort_flag", global.enableSort, "sort_script", global.sortScript, "filter_deprecated_nodes", global.filterDeprecated, "append_sub_userinfo", global.appendUserinfo, "clash_use_new_field_name", global.clashUseNewField, "clash_proxies_style", global.clashProxiesStyle ); auto renameconfs = toml::find_or<std::vector<toml::value>>(section_node_pref, "rename_node", {}); importItems(renameconfs, "rename_node", false); safe_set_renames(toml::get<RegexMatchConfigs>(toml::value(renameconfs))); const auto &section_managed = toml::find(root, "managed_config"); find_if_exist(section_managed, "write_managed_config", global.writeManagedConfig, "managed_config_prefix", global.managedConfigPrefix, "config_update_interval", global.updateInterval, "config_update_strict", global.updateStrict, "quanx_device_id", global.quanXDevID ); const auto &section_surge_external = toml::find(root, "surge_external_proxy"); find_if_exist(section_surge_external, "surge_ssr_path", global.surgeSSRPath, "resolve_hostname", global.surgeResolveHostname ); const auto &section_emojis = toml::find(root, "emojis"); find_if_exist(section_emojis, "add_emoji", global.addEmoji, "remove_old_emoji", global.removeEmoji ); auto emojiconfs = toml::find_or<std::vector<toml::value>>(section_emojis, "emoji", {}); importItems(emojiconfs, "emoji", false); safe_set_emojis(toml::get<RegexMatchConfigs>(toml::value(emojiconfs))); auto groups = toml::find_or<std::vector<toml::value>>(root, "custom_groups", {}); importItems(groups, "custom_groups", false); global.customProxyGroups = toml::get<ProxyGroupConfigs>(toml::value(groups)); const auto &section_ruleset = toml::find(root, "ruleset"); find_if_exist(section_ruleset, "enabled", global.enableRuleGen, "overwrite_original_rules", global.overwriteOriginalRules, "update_ruleset_on_request", global.updateRulesetOnRequest ); auto rulesets = toml::find_or<std::vector<toml::value>>(root, "rulesets", {}); importItems(rulesets, "rulesets", false); global.customRulesets = toml::get<RulesetConfigs>(toml::value(rulesets)); const auto &section_template = toml::find(root, "template"); global.templatePath = toml::find_or(section_template, "template_path", "template"); eraseElements(global.templateVars); operate_toml_kv_table(toml::find_or<std::vector<toml::table>>(section_template, "globals", {}), "key", "value", [&](const toml::value &key, const toml::value &value) { global.templateVars[key.as_string()] = value.as_string(); }); webServer.reset_redirect(); operate_toml_kv_table(toml::find_or<std::vector<toml::table>>(root, "aliases", {}), "uri", "target", [&](const toml::value &key, const toml::value &value) { webServer.append_redirect(key.as_string(), value.as_string()); }); auto tasks = toml::find_or<std::vector<toml::value>>(root, "tasks", {}); importItems(tasks, "tasks", false); global.cronTasks = toml::get<CronTaskConfigs>(toml::value(tasks)); const auto &section_server = toml::find(root, "server"); find_if_exist(section_server, "listen", global.listenAddress, "port", global.listenPort, "serve_file_root", webServer.serve_file_root ); webServer.serve_file = !webServer.serve_file_root.empty(); const auto &section_advanced = toml::find(root, "advanced"); std::string log_level; bool enable_cache = true; int cache_subscription = global.cacheSubscription, cache_config = global.cacheConfig, cache_ruleset = global.cacheRuleset; find_if_exist(section_advanced, "log_level", log_level, "print_debug_info", global.printDbgInfo, "max_pending_connections", global.maxPendingConns, "max_concurrent_threads", global.maxConcurThreads, "max_allowed_rulesets", global.maxAllowedRulesets, "max_allowed_rules", global.maxAllowedRules, "max_allowed_download_size", global.maxAllowedDownloadSize, "enable_cache", enable_cache, "cache_subscription", cache_subscription, "cache_config", cache_config, "cache_ruleset", cache_ruleset, "script_clean_context", global.scriptCleanContext, "async_fetch_ruleset", global.asyncFetchRuleset, "skip_failed_links", global.skipFailedLinks ); if(global.printDbgInfo) global.logLevel = LOG_LEVEL_VERBOSE; else { switch(hash_(log_level)) { case "warn"_hash: global.logLevel = LOG_LEVEL_WARNING; break; case "error"_hash: global.logLevel = LOG_LEVEL_ERROR; break; case "fatal"_hash: global.logLevel = LOG_LEVEL_FATAL; break; case "verbose"_hash: global.logLevel = LOG_LEVEL_VERBOSE; break; case "debug"_hash: global.logLevel = LOG_LEVEL_DEBUG; break; default: global.logLevel = LOG_LEVEL_INFO; } } if(enable_cache) { global.cacheSubscription = cache_subscription; global.cacheConfig = cache_config; global.cacheRuleset = cache_ruleset; } else { global.cacheSubscription = global.cacheConfig = global.cacheRuleset = 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-434', 'CWE-94'], 'message': 'Enhancements Add authorization check before loading scripts. Add detailed logs when loading preference settings.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ValidateInputs(OpKernelContext* ctx, const CSRSparseMatrix& sparse_matrix, const Tensor& permutation_indices, int* batch_size, int64* num_rows) { OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum<T>::value, errors::InvalidArgument( "Asked for a CSRSparseMatrix of type ", DataTypeString(DataTypeToEnum<T>::value), " but saw dtype: ", DataTypeString(sparse_matrix.dtype()))); const Tensor& dense_shape = sparse_matrix.dense_shape(); const int rank = dense_shape.dim_size(0); OP_REQUIRES(ctx, rank == 2 || rank == 3, errors::InvalidArgument("sparse matrix must have rank 2 or 3; ", "but dense_shape has size ", rank)); const int row_dim = (rank == 2) ? 0 : 1; auto dense_shape_vec = dense_shape.vec<int64>(); *num_rows = dense_shape_vec(row_dim); const int64 num_cols = dense_shape_vec(row_dim + 1); OP_REQUIRES(ctx, *num_rows == num_cols, errors::InvalidArgument("sparse matrix must be square; got: ", *num_rows, " != ", num_cols)); const TensorShape& perm_shape = permutation_indices.shape(); OP_REQUIRES( ctx, perm_shape.dims() + 1 == rank, errors::InvalidArgument( "sparse matrix must have the same rank as permutation; got: ", rank, " != ", perm_shape.dims(), " + 1.")); OP_REQUIRES( ctx, perm_shape.dim_size(rank - 2) == *num_rows, errors::InvalidArgument( "permutation must have the same number of elements in each batch " "as the number of rows in sparse matrix; got: ", perm_shape.dim_size(rank - 2), " != ", *num_rows)); *batch_size = sparse_matrix.batch_size(); if (*batch_size > 1) { OP_REQUIRES( ctx, perm_shape.dim_size(0) == *batch_size, errors::InvalidArgument("permutation must have the same batch size " "as sparse matrix; got: ", perm_shape.dim_size(0), " != ", *batch_size)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Remove `OP_REQUIRES` call from helper function. Since `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway. PiperOrigin-RevId: 369524386 Change-Id: I54f6cf9328445675ccc392e661b04336b229c9da'</s>
<s>[INST] Given the following code containing errors, provide 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 key_notify_policy_flush(const struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'af_key: initialize satype in key_notify_policy_flush() This field was left uninitialized. Some user daemons perform check against this field. Signed-off-by: Nicolas Dichtel <nicolas.dichtel@6wind.com> Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info*)skb_dst(skb); struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; __be32 frag_id = 0; int ptr, offset = 0, err=0; u8 *prevhdr, nexthdr = 0; struct net *net = dev_net(skb_dst(skb)->dev); hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (!skb->local_df && skb->len > mtu) { skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } mtu -= hlen + sizeof(struct frag_hdr); if (skb_has_frag_list(skb)) { int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb)) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < hlen) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); return -ENOMEM; } __skb_pull(skb, hlen); fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); ipv6_select_ident(fh); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); frag_id = fh->identification; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next != NULL) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(skb); if(!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); dst_release(&rt->dst); return 0; } while (frag) { skb = frag->next; kfree_skb(frag); frag = skb; } IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); dst_release(&rt->dst); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ *prevhdr = NEXTHDR_FRAGMENT; /* * Keep copying data until we run out. */ while(left > 0) { len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* * Allocate buffer. */ if ((frag = alloc_skb(len+hlen+sizeof(struct frag_hdr)+LL_ALLOCATED_SPACE(rt->dst.dev), GFP_ATOMIC)) == NULL) { NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n"); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, LL_RESERVED_SPACE(rt->dst.dev)); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; if (!frag_id) { ipv6_select_ident(fh); frag_id = fh->identification; } else fh->identification = frag_id; /* * Copy a block of the IP datagram. */ if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len)) BUG(); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); kfree_skb(skb); return err; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'ipv6: make fragment identifications less predictable IPv6 fragment identification generation is way beyond what we use for IPv4 : It uses a single generator. Its not scalable and allows DOS attacks. Now inetpeer is IPv6 aware, we can use it to provide a more secure and scalable frag ident generator (per destination, instead of system wide) This patch : 1) defines a new secure_ipv6_id() helper 2) extends inet_getid() to provide 32bit results 3) extends ipv6_select_ident() with a new dest parameter Reported-by: Fernando Gont <fernando@gont.com.ar> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err stbl_AddDTS(GF_SampleTableBox *stbl, u64 DTS, u32 *sampleNumber, u32 LastAUDefDuration, u32 nb_packed_samples) { u32 i, j, sampNum; u64 *DTSs, curDTS; Bool inserted; GF_SttsEntry *ent; GF_TimeToSampleBox *stts = stbl->TimeToSample; //reset the reading cache when adding a sample stts->r_FirstSampleInEntry = 0; *sampleNumber = 0; if (!nb_packed_samples) nb_packed_samples=1; //if we don't have an entry, that's the first one... if (!stts->nb_entries) { //assert the first DTS is 0. If not, that will break the whole file if (DTS) return GF_BAD_PARAM; stts->alloc_size = 1; stts->nb_entries = 1; stts->entries = gf_malloc(sizeof(GF_SttsEntry)); if (!stts->entries) return GF_OUT_OF_MEM; stts->entries[0].sampleCount = nb_packed_samples; stts->entries[0].sampleDelta = (nb_packed_samples>1) ? 0 : LastAUDefDuration; (*sampleNumber) = 1; stts->w_currentSampleNum = nb_packed_samples; return GF_OK; } //check the last DTS - we allow 0-duration samples (same DTS) if (DTS >= stts->w_LastDTS) { u32 nb_extra = 0; ent = &stts->entries[stts->nb_entries-1]; if (!ent->sampleDelta && (ent->sampleCount>1)) { ent->sampleDelta = (u32) ( DTS / ent->sampleCount); stts->w_LastDTS = DTS - ent->sampleDelta; } //OK, we're adding at the end if ((DTS == stts->w_LastDTS + ent->sampleDelta) //for raw audio, consider (dts==last_dts) and (dts==last_dts+2*delta) as sample append to cope with //timescale vs samplerate precision || ((nb_packed_samples>1) && ((DTS == stts->w_LastDTS) || (DTS == stts->w_LastDTS + 2*ent->sampleDelta) )) ) { (*sampleNumber) = stts->w_currentSampleNum + 1; ent->sampleCount += nb_packed_samples; stts->w_currentSampleNum += nb_packed_samples; stts->w_LastDTS = DTS + ent->sampleDelta * (nb_packed_samples-1); return GF_OK; } //we need to split the entry if (ent->sampleCount == 1) { //FIXME - we need more tests with timed text #if 0 if (stts->w_LastDTS) ent->sampleDelta += (u32) (DTS - stts->w_LastDTS); else ent->sampleDelta = (u32) DTS; #else //use this one and adjust... ent->sampleDelta = (u32) (DTS - stts->w_LastDTS); #endif ent->sampleCount ++; //little opt, merge last entry with previous one if same delta if ((stts->nb_entries>=2) && (ent->sampleDelta== stts->entries[stts->nb_entries-2].sampleDelta)) { stts->entries[stts->nb_entries-2].sampleCount += ent->sampleCount; stts->nb_entries--; } stts->w_currentSampleNum ++; stts->w_LastDTS = DTS; (*sampleNumber) = stts->w_currentSampleNum; return GF_OK; } //we definitely need to split the entry ;) ent->sampleCount --; if (nb_packed_samples>1) nb_extra = 1; if (stts->alloc_size <= stts->nb_entries + nb_extra) { ALLOC_INC(stts->alloc_size); stts->entries = gf_realloc(stts->entries, sizeof(GF_SttsEntry)*stts->alloc_size); if (!stts->entries) return GF_OUT_OF_MEM; memset(&stts->entries[stts->nb_entries], 0, sizeof(GF_SttsEntry)*(stts->alloc_size-stts->nb_entries) ); } if (nb_extra) nb_extra = stts->entries[stts->nb_entries-1].sampleDelta; ent = &stts->entries[stts->nb_entries]; stts->nb_entries++; if (nb_packed_samples==1) { ent->sampleCount = 2; ent->sampleDelta = (u32) (DTS - stts->w_LastDTS); stts->w_LastDTS = DTS; (*sampleNumber) = stts->w_currentSampleNum+1; stts->w_currentSampleNum += 1; return GF_OK; } ent->sampleCount = 1; ent->sampleDelta = (u32) (DTS - stts->w_LastDTS); ent = &stts->entries[stts->nb_entries]; stts->nb_entries++; ent->sampleCount = nb_packed_samples; ent->sampleDelta = nb_extra; stts->w_LastDTS = DTS; (*sampleNumber) = stts->w_currentSampleNum + 1; stts->w_currentSampleNum += nb_packed_samples; return GF_OK; } //unpack the DTSs and locate new sample... DTSs = (u64*)gf_malloc(sizeof(u64) * (stbl->SampleSize->sampleCount+2) ); if (!DTSs) return GF_OUT_OF_MEM; curDTS = 0; sampNum = 0; ent = NULL; inserted = 0; for (i=0; i<stts->nb_entries; i++) { ent = & stts->entries[i]; for (j = 0; j<ent->sampleCount; j++) { if (!inserted && (curDTS > DTS)) { DTSs[sampNum] = DTS; sampNum++; *sampleNumber = sampNum; inserted = 1; } DTSs[sampNum] = curDTS; curDTS += ent->sampleDelta; sampNum ++; } } if (!inserted) { gf_free(DTSs); return GF_BAD_PARAM; } /*we will at most insert 3 new entries*/ if (stts->nb_entries+3 >= stts->alloc_size) { stts->alloc_size += 3; stts->entries = gf_realloc(stts->entries, sizeof(GF_SttsEntry)*stts->alloc_size); if (!stts->entries) return GF_OUT_OF_MEM; memset(&stts->entries[stts->nb_entries], 0, sizeof(GF_SttsEntry)*(stts->alloc_size - stts->nb_entries) ); } /*repack the DTSs*/ j=0; stts->nb_entries = 1; stts->entries[0].sampleCount = 1; stts->entries[0].sampleDelta = (u32) DTSs[1] /* - (DTS[0] which is 0)*/; for (i=1; i<stbl->SampleSize->sampleCount+1; i++) { if (i == stbl->SampleSize->sampleCount) { //and by default, our last sample has the same delta as the prev stts->entries[j].sampleCount++; } else if (stts->entries[j].sampleDelta == (u32) ( DTSs[i+1] - DTSs[i]) ) { stts->entries[j].sampleCount ++; } else { stts->nb_entries ++; j++; stts->entries[j].sampleCount = 1; stts->entries[j].sampleDelta = (u32) (DTSs[i+1] - DTSs[i]); } } gf_free(DTSs); //reset the cache to the end stts->w_currentSampleNum = stbl->SampleSize->sampleCount + 1; return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fixed #1774 (fuzz)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CreateForeignServer(CreateForeignServerStmt *stmt) { Relation rel; Datum srvoptions; Datum values[Natts_pg_foreign_server]; bool nulls[Natts_pg_foreign_server]; HeapTuple tuple; Oid srvId; Oid ownerId; AclResult aclresult; ObjectAddress myself; ObjectAddress referenced; ForeignDataWrapper *fdw; rel = heap_open(ForeignServerRelationId, RowExclusiveLock); /* For now the owner cannot be specified on create. Use effective user ID. */ ownerId = GetUserId(); /* * Check that there is no other foreign server by this name. Do nothing if * IF NOT EXISTS was enforced. */ if (GetForeignServerByName(stmt->servername, true) != NULL) { if (stmt->if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("server \"%s\" already exists, skipping", stmt->servername))); heap_close(rel, RowExclusiveLock); return InvalidObjectAddress; } else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("server \"%s\" already exists", stmt->servername))); } /* * Check that the FDW exists and that we have USAGE on it. Also get the * actual FDW for option validation etc. */ fdw = GetForeignDataWrapperByName(stmt->fdwname, false); aclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_FDW, fdw->fdwname); /* * Insert tuple into pg_foreign_server. */ memset(values, 0, sizeof(values)); memset(nulls, false, sizeof(nulls)); values[Anum_pg_foreign_server_srvname - 1] = DirectFunctionCall1(namein, CStringGetDatum(stmt->servername)); values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId); values[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid); /* Add server type if supplied */ if (stmt->servertype) values[Anum_pg_foreign_server_srvtype - 1] = CStringGetTextDatum(stmt->servertype); else nulls[Anum_pg_foreign_server_srvtype - 1] = true; /* Add server version if supplied */ if (stmt->version) values[Anum_pg_foreign_server_srvversion - 1] = CStringGetTextDatum(stmt->version); else nulls[Anum_pg_foreign_server_srvversion - 1] = true; /* Start with a blank acl */ nulls[Anum_pg_foreign_server_srvacl - 1] = true; /* Add server options */ srvoptions = transformGenericOptions(ForeignServerRelationId, PointerGetDatum(NULL), stmt->options, fdw->fdwvalidator); if (PointerIsValid(DatumGetPointer(srvoptions))) values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions; else nulls[Anum_pg_foreign_server_srvoptions - 1] = true; tuple = heap_form_tuple(rel->rd_att, values, nulls); srvId = CatalogTupleInsert(rel, tuple); heap_freetuple(tuple); /* record dependencies */ myself.classId = ForeignServerRelationId; myself.objectId = srvId; myself.objectSubId = 0; referenced.classId = ForeignDataWrapperRelationId; referenced.objectId = fdw->fdwid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); recordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId); /* dependency on extension */ recordDependencyOnCurrentExtension(&myself, false); /* Post creation hook for new foreign server */ InvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0); heap_close(rel, RowExclusiveLock); return myself; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dxtory_decode_v1_rgb(AVCodecContext *avctx, AVFrame *pic, const uint8_t *src, int src_size, int id, int bpp) { int h; uint8_t *dst; int ret; if (src_size < avctx->width * avctx->height * bpp) { av_log(avctx, AV_LOG_ERROR, "packet too small\n"); return AVERROR_INVALIDDATA; } avctx->pix_fmt = id; if ((ret = ff_get_buffer(avctx, pic, 0)) < 0) return ret; dst = pic->data[0]; for (h = 0; h < avctx->height; h++) { memcpy(dst, src, avctx->width * bpp); src += avctx->width * bpp; dst += pic->linesize[0]; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'avcodec/dxtory: fix src size checks Fixes integer overflow Fixes out of array read Fixes: d104661bb59b202df7671fb19a00ca6c-asan_heap-oob_d6429d_5066_cov_1729501105_dxtory_mic.avi Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int samldb_lockout_time(struct samldb_ctx *ac) { struct ldb_context *ldb = ldb_module_get_ctx(ac->module); NTTIME lockoutTime; struct ldb_message_element *el; struct ldb_message *tmp_msg; int ret; ret = dsdb_get_expected_new_values(ac, ac->msg, "lockoutTime", &el, ac->req->operation); if (ret != LDB_SUCCESS) { return ret; } if (el == NULL || el->num_values == 0) { ldb_asprintf_errstring(ldb, "%08X: samldb: 'lockoutTime' can't be deleted!", W_ERROR_V(WERR_DS_ILLEGAL_MOD_OPERATION)); return LDB_ERR_UNWILLING_TO_PERFORM; } /* Create a temporary message for fetching the "lockoutTime" */ tmp_msg = ldb_msg_new(ac->msg); if (tmp_msg == NULL) { return ldb_module_oom(ac->module); } ret = ldb_msg_add(tmp_msg, el, 0); if (ret != LDB_SUCCESS) { return ret; } lockoutTime = ldb_msg_find_attr_as_int64(tmp_msg, "lockoutTime", 0); talloc_free(tmp_msg); if (lockoutTime != 0) { return LDB_SUCCESS; } /* lockoutTime == 0 resets badPwdCount */ ldb_msg_remove_attr(ac->msg, "badPwdCount"); ret = samdb_msg_add_int(ldb, ac->msg, ac->msg, "badPwdCount", 0); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(ac->msg, "badPwdCount"); el->flags = LDB_FLAG_MOD_REPLACE; return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) { struct ldb_message_element *el; char *s; int ret; if (ldb_msg_find_element(msg, attr) != NULL) { return LDB_SUCCESS; } s = ldb_timestring(msg, t); if (s == NULL) { return LDB_ERR_OPERATIONS_ERROR; } ret = ldb_msg_add_string(msg, attr, s); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(msg, attr); /* always set as replace. This works because on add ops, the flag is ignored */ el->flags = LDB_FLAG_MOD_REPLACE; return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tr_prepare_attributes(struct tr_context *ac) { struct ldb_context *ldb = ldb_module_get_ctx(ac->module); int ret; struct ldb_message_element *el = NULL; uint32_t account_type, user_account_control; struct ldb_dn *objectcategory = NULL; ac->mod_msg = ldb_msg_copy_shallow(ac, ac->req_msg); if (ac->mod_msg == NULL) { return ldb_oom(ldb); } ac->mod_res = talloc_zero(ac, struct ldb_result); if (ac->mod_res == NULL) { return ldb_oom(ldb); } ret = ldb_build_mod_req(&ac->mod_req, ldb, ac, ac->mod_msg, NULL, ac->mod_res, ldb_modify_default_callback, ac->req); LDB_REQ_SET_LOCATION(ac->mod_req); if (ret != LDB_SUCCESS) { return ret; } /* - remove distinguishedName - we don't need it */ ldb_msg_remove_attr(ac->mod_msg, "distinguishedName"); /* remove isRecycled */ ret = ldb_msg_add_empty(ac->mod_msg, "isRecycled", LDB_FLAG_MOD_DELETE, NULL); if (ret != LDB_SUCCESS) { ldb_asprintf_errstring(ldb, "Failed to reset isRecycled attribute: %s", ldb_strerror(ret)); return LDB_ERR_OPERATIONS_ERROR; } /* objectClass is USER */ if (samdb_find_attribute(ldb, ac->search_msg, "objectclass", "user") != NULL) { uint32_t primary_group_rid; /* restoring 'user' instance attribute is heavily borrowed from samldb.c */ /* Default values */ ret = dsdb_user_obj_set_defaults(ldb, ac->mod_msg, ac->mod_req); if (ret != LDB_SUCCESS) return ret; /* "userAccountControl" must exists on deleted object */ user_account_control = ldb_msg_find_attr_as_uint(ac->search_msg, "userAccountControl", (uint32_t)-1); if (user_account_control == (uint32_t)-1) { return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "reanimate: No 'userAccountControl' attribute found!"); } /* restore "sAMAccountType" */ ret = dsdb_user_obj_set_account_type(ldb, ac->mod_msg, user_account_control, NULL); if (ret != LDB_SUCCESS) { return ret; } /* "userAccountControl" -> "primaryGroupID" mapping */ ret = dsdb_user_obj_set_primary_group_id(ldb, ac->mod_msg, user_account_control, &primary_group_rid); if (ret != LDB_SUCCESS) { return ret; } /* * Older AD deployments don't know about the * RODC group */ if (primary_group_rid == DOMAIN_RID_READONLY_DCS) { /* TODO: check group exists */ } } /* objectClass is GROUP */ if (samdb_find_attribute(ldb, ac->search_msg, "objectclass", "group") != NULL) { /* "groupType" -> "sAMAccountType" */ uint32_t group_type; el = ldb_msg_find_element(ac->search_msg, "groupType"); if (el == NULL) { return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "reanimate: Unexpected: missing groupType attribute."); } group_type = ldb_msg_find_attr_as_uint(ac->search_msg, "groupType", 0); account_type = ds_gtype2atype(group_type); if (account_type == 0) { return ldb_error(ldb, LDB_ERR_UNWILLING_TO_PERFORM, "reanimate: Unrecognized account type!"); } ret = samdb_msg_add_uint(ldb, ac->mod_msg, ac->mod_msg, "sAMAccountType", account_type); if (ret != LDB_SUCCESS) { return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "reanimate: Failed to add sAMAccountType to restored object."); } el = ldb_msg_find_element(ac->mod_msg, "sAMAccountType"); el->flags = LDB_FLAG_MOD_REPLACE; /* Default values set by Windows */ ret = samdb_find_or_add_attribute(ldb, ac->mod_msg, "adminCount", "0"); if (ret != LDB_SUCCESS) return ret; ret = samdb_find_or_add_attribute(ldb, ac->mod_msg, "operatorCount", "0"); if (ret != LDB_SUCCESS) return ret; } /* - restore objectCategory if not present */ objectcategory = ldb_msg_find_attr_as_dn(ldb, ac, ac->search_msg, "objectCategory"); if (objectcategory == NULL) { const char *value; ret = dsdb_make_object_category(ldb, ac->schema, ac->search_msg, ac->mod_msg, &value); if (ret != LDB_SUCCESS) { return ret; } ret = ldb_msg_add_string(ac->mod_msg, "objectCategory", value); if (ret != LDB_SUCCESS) { return ret; } el = ldb_msg_find_element(ac->mod_msg, "objectCategory"); el->flags = LDB_FLAG_MOD_ADD; } return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13043/BGP: fix decoding of MVPN route types 6 and 7 RFC 6514 Section 4.6 defines the structure for Shared Tree Join (6) and Source Tree Join (7) multicast VPN route types. decode_multicast_vpn() didn't implement the Source AS field of that structure properly, adjust the offsets to put it right. 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: SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; HashTable *aht; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { return; } aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (aht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { goto outexcept; } var_push_dtor(&var_hash, &pflags); --p; /* for ';' */ flags = Z_LVAL_P(pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C' && *p!='r') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { goto outexcept; } var_push_dtor(&var_hash, &intern->array); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) { zval_ptr_dtor(&pmembers); goto outexcept; } var_push_dtor(&var_hash, &pmembers); /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (pflags) { zval_ptr_dtor(&pflags); } return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (pflags) { zval_ptr_dtor(&pflags); } zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #73029 - Missing type check when unserializing SplArray'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } s += padlen + 3; (*psig) = s; /* return SUCCESS */ return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-347'], 'message': 'wo#7449 . verify padding contents for IKEv2 RSA sig check Special thanks to Sze Yiu Chau of Purdue University (schau@purdue.edu) who reported the issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_F(ZNCTest, AwayNotify) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = ConnectClient(); client.Write("CAP LS"); client.Write("PASS :hunter2"); client.Write("NICK nick"); client.Write("USER user/test x x :x"); QByteArray cap_ls; client.ReadUntilAndGet(" LS :", cap_ls); ASSERT_THAT(cap_ls.toStdString(), AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify")))); client.Write("CAP REQ :cap-notify"); client.ReadUntil("ACK :cap-notify"); client.Write("CAP END"); client.ReadUntil(" 001 "); ircd.ReadUntil("USER"); ircd.Write("CAP user LS :away-notify"); ircd.ReadUntil("CAP REQ :away-notify"); ircd.Write("CAP user ACK :away-notify"); ircd.ReadUntil("CAP END"); ircd.Write(":server 001 user :welcome"); client.ReadUntil("CAP user NEW :away-notify"); client.Write("CAP REQ :away-notify"); client.ReadUntil("ACK :away-notify"); ircd.Write(":x!y@z AWAY :reason"); client.ReadUntil(":x!y@z AWAY :reason"); ircd.Close(); client.ReadUntil("DEL :away-notify"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix echo-message for *status Close #1705'</s>
<s>[INST] Given the following code containing errors, provide 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 flashsv_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { int buf_size = avpkt->size; FlashSVContext *s = avctx->priv_data; int h_blocks, v_blocks, h_part, v_part, i, j, ret; GetBitContext gb; int last_blockwidth = s->block_width; int last_blockheight= s->block_height; /* no supplementary picture */ if (buf_size == 0) return 0; if (buf_size < 4) return -1; init_get_bits(&gb, avpkt->data, buf_size * 8); /* start to parse the bitstream */ s->block_width = 16 * (get_bits(&gb, 4) + 1); s->image_width = get_bits(&gb, 12); s->block_height = 16 * (get_bits(&gb, 4) + 1); s->image_height = get_bits(&gb, 12); if ( last_blockwidth != s->block_width || last_blockheight!= s->block_height) av_freep(&s->blocks); if (s->ver == 2) { skip_bits(&gb, 6); if (get_bits1(&gb)) { avpriv_request_sample(avctx, "iframe"); return AVERROR_PATCHWELCOME; } if (get_bits1(&gb)) { avpriv_request_sample(avctx, "Custom palette"); return AVERROR_PATCHWELCOME; } } /* calculate number of blocks and size of border (partial) blocks */ h_blocks = s->image_width / s->block_width; h_part = s->image_width % s->block_width; v_blocks = s->image_height / s->block_height; v_part = s->image_height % s->block_height; /* the block size could change between frames, make sure the buffer * is large enough, if not, get a larger one */ if (s->block_size < s->block_width * s->block_height) { int tmpblock_size = 3 * s->block_width * s->block_height; s->tmpblock = av_realloc(s->tmpblock, tmpblock_size); if (!s->tmpblock) { av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n"); return AVERROR(ENOMEM); } if (s->ver == 2) { s->deflate_block_size = calc_deflate_block_size(tmpblock_size); if (s->deflate_block_size <= 0) { av_log(avctx, AV_LOG_ERROR, "Can't determine deflate buffer size.\n"); return -1; } s->deflate_block = av_realloc(s->deflate_block, s->deflate_block_size); if (!s->deflate_block) { av_log(avctx, AV_LOG_ERROR, "Can't allocate deflate buffer.\n"); return AVERROR(ENOMEM); } } } s->block_size = s->block_width * s->block_height; /* initialize the image size once */ if (avctx->width == 0 && avctx->height == 0) { avcodec_set_dimensions(avctx, s->image_width, s->image_height); } /* check for changes of image width and image height */ if (avctx->width != s->image_width || avctx->height != s->image_height) { av_log(avctx, AV_LOG_ERROR, "Frame width or height differs from first frame!\n"); av_log(avctx, AV_LOG_ERROR, "fh = %d, fv %d vs ch = %d, cv = %d\n", avctx->height, avctx->width, s->image_height, s->image_width); return AVERROR_INVALIDDATA; } /* we care for keyframes only in Screen Video v2 */ s->is_keyframe = (avpkt->flags & AV_PKT_FLAG_KEY) && (s->ver == 2); if (s->is_keyframe) { s->keyframedata = av_realloc(s->keyframedata, avpkt->size); memcpy(s->keyframedata, avpkt->data, avpkt->size); } if(s->ver == 2 && !s->blocks) s->blocks = av_mallocz((v_blocks + !!v_part) * (h_blocks + !!h_part) * sizeof(s->blocks[0])); av_dlog(avctx, "image: %dx%d block: %dx%d num: %dx%d part: %dx%d\n", s->image_width, s->image_height, s->block_width, s->block_height, h_blocks, v_blocks, h_part, v_part); if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0) return ret; /* loop over all block columns */ for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) { int y_pos = j * s->block_height; // vertical position in frame int cur_blk_height = (j < v_blocks) ? s->block_height : v_part; /* loop over all block rows */ for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) { int x_pos = i * s->block_width; // horizontal position in frame int cur_blk_width = (i < h_blocks) ? s->block_width : h_part; int has_diff = 0; /* get the size of the compressed zlib chunk */ int size = get_bits(&gb, 16); s->color_depth = 0; s->zlibprime_curr = 0; s->zlibprime_prev = 0; s->diff_start = 0; s->diff_height = cur_blk_height; if (8 * size > get_bits_left(&gb)) { av_frame_unref(&s->frame); return AVERROR_INVALIDDATA; } if (s->ver == 2 && size) { skip_bits(&gb, 3); s->color_depth = get_bits(&gb, 2); has_diff = get_bits1(&gb); s->zlibprime_curr = get_bits1(&gb); s->zlibprime_prev = get_bits1(&gb); if (s->color_depth != 0 && s->color_depth != 2) { av_log(avctx, AV_LOG_ERROR, "%dx%d invalid color depth %d\n", i, j, s->color_depth); return AVERROR_INVALIDDATA; } if (has_diff) { if (!s->keyframe) { av_log(avctx, AV_LOG_ERROR, "inter frame without keyframe\n"); return AVERROR_INVALIDDATA; } s->diff_start = get_bits(&gb, 8); s->diff_height = get_bits(&gb, 8); av_log(avctx, AV_LOG_DEBUG, "%dx%d diff start %d height %d\n", i, j, s->diff_start, s->diff_height); size -= 2; } if (s->zlibprime_prev) av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_prev\n", i, j); if (s->zlibprime_curr) { int col = get_bits(&gb, 8); int row = get_bits(&gb, 8); av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_curr %dx%d\n", i, j, col, row); size -= 2; avpriv_request_sample(avctx, "zlibprime_curr"); return AVERROR_PATCHWELCOME; } if (!s->blocks && (s->zlibprime_curr || s->zlibprime_prev)) { av_log(avctx, AV_LOG_ERROR, "no data available for zlib " "priming\n"); return AVERROR_INVALIDDATA; } size--; // account for flags byte } if (has_diff) { int k; int off = (s->image_height - y_pos - 1) * s->frame.linesize[0]; for (k = 0; k < cur_blk_height; k++) memcpy(s->frame.data[0] + off - k*s->frame.linesize[0] + x_pos*3, s->keyframe + off - k*s->frame.linesize[0] + x_pos*3, cur_blk_width * 3); } /* skip unchanged blocks, which have size 0 */ if (size) { if (flashsv_decode_block(avctx, avpkt, &gb, size, cur_blk_width, cur_blk_height, x_pos, y_pos, i + j * (h_blocks + !!h_part))) av_log(avctx, AV_LOG_ERROR, "error in decompression of block %dx%d\n", i, j); } } } if (s->is_keyframe && s->ver == 2) { if (!s->keyframe) { s->keyframe = av_malloc(s->frame.linesize[0] * avctx->height); if (!s->keyframe) { av_log(avctx, AV_LOG_ERROR, "Cannot allocate image data\n"); return AVERROR(ENOMEM); } } memcpy(s->keyframe, s->frame.data[0], s->frame.linesize[0] * avctx->height); } if ((ret = av_frame_ref(data, &s->frame)) < 0) return ret; *got_frame = 1; if ((get_bits_count(&gb) / 8) != buf_size) av_log(avctx, AV_LOG_ERROR, "buffer not fully consumed (%d != %d)\n", buf_size, (get_bits_count(&gb) / 8)); /* report that the buffer was completely consumed */ return buf_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'avcodec/flashsv: check diff_start/height Fixes out of array accesses Fixes Ticket2844 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static const char *skip( const char *in ) { while ( in && *in && (unsigned char) *in <= 32 ) in++; return in; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void cJSON_DeleteItemFromObject( cJSON *object, const char *string ) { cJSON_Delete( cJSON_DetachItemFromObject( object, string ) ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: const char *cJSON_GetErrorPtr( void ) { return ep; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *print_array( cJSON *item, int depth, int fmt ) { char **entries; char *out = 0, *ptr, *ret; int len = 5; cJSON *child = item->child; int numentries = 0, i = 0, fail = 0; /* How many entries in the array? */ while ( child ) { ++numentries; child = child->next; } /* Allocate an array to hold the values for each. */ if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) return 0; memset( entries, 0, numentries * sizeof(char*) ); /* Retrieve all the results. */ child = item->child; while ( child && ! fail ) { ret = print_value( child, depth + 1, fmt ); entries[i++] = ret; if ( ret ) len += strlen( ret ) + 2 + ( fmt ? 1 : 0 ); else fail = 1; child = child -> next; } /* If we didn't fail, try to malloc the output string. */ if ( ! fail ) { out = (char*) cJSON_malloc( len ); if ( ! out ) fail = 1; } /* Handle failure. */ if ( fail ) { for ( i = 0; i < numentries; ++i ) if ( entries[i] ) cJSON_free( entries[i] ); cJSON_free( entries ); return 0; } /* Compose the output array. */ *out = '['; ptr = out + 1; *ptr = 0; for ( i = 0; i < numentries; ++i ) { strcpy( ptr, entries[i] ); ptr += strlen( entries[i] ); if ( i != numentries - 1 ) { *ptr++ = ','; if ( fmt ) *ptr++ = ' '; *ptr = 0; } cJSON_free( entries[i] ); } cJSON_free( entries ); *ptr++ = ']'; *ptr++ = 0; return out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void suffix_object( cJSON *prev, cJSON *item ) { prev->next = item; item->prev = prev; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()( const int64 batch_size, const int num_rows, TTypes<int64>::ConstMatrix indices, TTypes<int32>::Vec batch_ptr, TTypes<int32>::Vec csr_row_ptr, TTypes<int32>::Vec csr_col_ind) { // Validate inputs. if (batch_ptr.size() != batch_size + 1) { return errors::InvalidArgument( "Expected batch_ptr.size() == batch_size + 1. Got: ", batch_ptr.size(), " vs. ", batch_size + 1); } if (csr_row_ptr.size() != batch_size * (num_rows + 1)) { return errors::InvalidArgument( "Expected csr_row_ptr.size() == batch_size * (num_rows + 1). Got: ", csr_row_ptr.size(), " vs. ", batch_size * (num_rows + 1)); } const int64 total_nnz = indices.dimension(0); const int rank = indices.dimension(1); if (rank == 2 && batch_size != 1) { return errors::InvalidArgument( "Expected batch_size == 1 when rank is 2. Got batch_size: ", batch_size); } if (csr_col_ind.size() != total_nnz) { return errors::InvalidArgument( "Expected csr_col_ind.size() == total_nnz. Got: ", csr_col_ind.size(), " vs. ", total_nnz); } int prev_batch = -1; if (rank == 2) { // For a single batch, the batch_ptrs are {0, total_nnz}. batch_ptr(0) = 0; ++prev_batch; for (int64 i = 0; i < total_nnz; ++i) { // For now, the rows pointers store the corresponding row counts. csr_row_ptr(indices(i, 0) + 1) += 1; csr_col_ind(i) = indices(i, 1); } } else { // rank == 3 for (int64 i = 0; i < total_nnz; ++i) { const int cur_batch = indices(i, 0); // For now, the rows pointers store the corresponding row counts. csr_row_ptr(cur_batch * (num_rows + 1) + indices(i, 1) + 1) += 1; csr_col_ind(i) = indices(i, 2); // We're at a new batch and might have skipped over empty batches. while (prev_batch < cur_batch) { // The previous batch ends at position i. batch_ptr(prev_batch + 1) = i; ++prev_batch; } } } // Set the last element of batch_ptr and account for trailing empty batches. while (prev_batch < batch_size) { batch_ptr(prev_batch + 1) = total_nnz; ++prev_batch; } // Compute the cumulative row counts for each batch. for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx) { auto* row_ptr_batch = csr_row_ptr.data() + batch_idx * (num_rows + 1); std::partial_sum(row_ptr_batch, row_ptr_batch + num_rows + 1, row_ptr_batch); } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-131', 'CWE-369'], 'message': 'Fix crash in `SparseTensorToCSRSparseMatrixCPUFunctor` PiperOrigin-RevId: 370110290 Change-Id: I4451e92661a55c2180f80d38b67a9b50bf5edec5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp) { if (dt_table[Elf32_Dyn::DT_NULL]) { return; // not 1st time; do not change upx_dt_init } Elf32_Dyn const *const dynp0 = dynp; unsigned ndx = 1+ 0; if (dynp) for (; ; ++ndx, ++dynp) { unsigned const d_tag = get_te32(&dynp->d_tag); if (d_tag < DT_NUM) { if (Elf32_Dyn::DT_NEEDED != d_tag && dt_table[d_tag] && get_te32(&dynp->d_val) != get_te32(&dynp0[-1+ dt_table[d_tag]].d_val)) { char msg[50]; snprintf(msg, sizeof(msg), "duplicate DT_%#x: [%#x] [%#x]", d_tag, -1+ dt_table[d_tag], -1+ ndx); throwCantPack(msg); } dt_table[d_tag] = ndx; } if (Elf32_Dyn::DT_NULL == d_tag) { break; // check here so that dt_table[DT_NULL] is set } } upx_dt_init = 0; if (dt_table[Elf32_Dyn::DT_INIT]) upx_dt_init = Elf32_Dyn::DT_INIT; else if (dt_table[Elf32_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_PREINIT_ARRAY; else if (dt_table[Elf32_Dyn::DT_INIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_INIT_ARRAY; unsigned const z_str = dt_table[Elf32_Dyn::DT_STRSZ]; if (z_str) { strtab_end = get_te32(&dynp0[-1+ z_str].d_val); if ((u32_t)file_size <= strtab_end) { // FIXME: weak char msg[50]; snprintf(msg, sizeof(msg), "bad DT_STRSZ %#x", strtab_end); throwCantPack(msg); } } unsigned const x_sym = dt_table[Elf32_Dyn::DT_SYMTAB]; unsigned const x_str = dt_table[Elf32_Dyn::DT_STRTAB]; if (x_sym && x_str) { upx_uint32_t const v_sym = get_te32(&dynp0[-1+ x_sym].d_val); upx_uint32_t const v_str = get_te32(&dynp0[-1+ x_str].d_val); unsigned const z_sym = dt_table[Elf32_Dyn::DT_SYMENT]; unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym) : get_te32(&dynp0[-1+ z_sym].d_val); if (sz_sym < sizeof(Elf32_Sym)) { char msg[50]; snprintf(msg, sizeof(msg), "bad DT_SYMENT %x", sz_sym); throwCantPack(msg); } if (v_sym < v_str) { symnum_end = (v_str - v_sym) / sz_sym; } if (symnum_end < 1) { throwCantPack("bad DT_SYMTAB"); } } // DT_HASH often ends at DT_SYMTAB unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH); if (v_hsh && file_image) { hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH); if (!hashtab) { char msg[40]; snprintf(msg, sizeof(msg), "bad DT_HASH %#x", v_hsh); throwCantPack(msg); } unsigned const nbucket = get_te32(&hashtab[0]); unsigned const *const buckets = &hashtab[2]; unsigned const *const chains = &buckets[nbucket]; (void)chains; unsigned const v_sym = !x_sym ? 0 : get_te32(&dynp0[-1+ x_sym].d_val); if (!nbucket || (nbucket>>31) || !v_sym || file_size <= v_sym || ((v_hsh < v_sym) && (v_sym - v_hsh) < sizeof(*buckets)*(2+ nbucket)) ) { char msg[80]; snprintf(msg, sizeof(msg), "bad DT_HASH nbucket=%#x len=%#x", nbucket, (v_sym - v_hsh)); throwCantPack(msg); } unsigned chmax = 0; for (unsigned j= 0; j < nbucket; ++j) { if (chmax < buckets[j]) { chmax = buckets[j]; } } if ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(*buckets)*(2+ nbucket) + sizeof(*chains)*(1+ chmax))) { char msg[80]; snprintf(msg, sizeof(msg), "bad DT_HASH nbucket=%#x len=%#x", nbucket, (v_sym - v_hsh)); throwCantPack(msg); } } // DT_GNU_HASH often ends at DT_SYMTAB; FIXME: not for Android? unsigned const v_gsh = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH); if (v_gsh && file_image) { gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH); if (!gashtab) { char msg[40]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH %#x", v_gsh); throwCantPack(msg); } unsigned const n_bucket = get_te32(&gashtab[0]); unsigned const symbias = get_te32(&gashtab[1]); unsigned const n_bitmask = get_te32(&gashtab[2]); unsigned const gnu_shift = get_te32(&gashtab[3]); unsigned const *const bitmask = (unsigned const *)(void const *)&gashtab[4]; unsigned const *const buckets = (unsigned const *)&bitmask[n_bitmask]; unsigned const *const hasharr = &buckets[n_bucket]; (void)hasharr; if (!n_bucket || (1u<<31) <= n_bucket /* fie on fuzzers */ || (void const *)&file_image[file_size] <= (void const *)hasharr) { char msg[80]; snprintf(msg, sizeof(msg), "bad n_bucket %#x\n", n_bucket); throwCantPack(msg); } //unsigned const *const gashend = &hasharr[n_bucket]; // minimum, except: // Rust and Android trim unused zeroes from high end of hasharr[] unsigned bmax = 0; for (unsigned j= 0; j < n_bucket; ++j) { if (buckets[j]) { if (buckets[j] < symbias) { char msg[50]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH bucket[%d] < symbias{%#x}\n", buckets[j], symbias); throwCantPack(msg); } if (bmax < buckets[j]) { bmax = buckets[j]; } } } if ((1+ bmax) < symbias) { char msg[80]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH (1+ max_bucket)=%#x < symbias=%#x", 1+ bmax, symbias); throwCantPack(msg); } bmax -= symbias; unsigned const v_sym = !x_sym ? 0 : get_te32(&dynp0[-1+ x_sym].d_val); unsigned r = 0; if (!n_bucket || !n_bitmask || !v_sym || (r=1, ((-1+ n_bitmask) & n_bitmask)) // not a power of 2 || (r=2, (8*sizeof(unsigned) <= gnu_shift)) // shifted result always == 0 || (r=3, (n_bucket>>30)) // fie on fuzzers || (r=4, (n_bitmask>>30)) || (r=5, ((file_size/sizeof(unsigned)) <= ((sizeof(*bitmask)/sizeof(unsigned))*n_bitmask + 2*n_bucket))) // FIXME: weak || (r=6, ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4 // headers + sizeof(*bitmask)*n_bitmask // bitmask + sizeof(*buckets)*n_bucket // buckets + sizeof(*hasharr)*(1+ bmax) // hasharr )) ) ) { char msg[90]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH n_bucket=%#x n_bitmask=%#x len=%#lx r=%d", n_bucket, n_bitmask, (long unsigned)(v_sym - v_gsh), r); throwCantPack(msg); } } unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx); if (e_shnum <= e_shstrndx && !(0==e_shnum && 0==e_shstrndx) ) { char msg[40]; snprintf(msg, sizeof(msg), "bad .e_shstrndx %d >= .e_shnum %d", e_shstrndx, e_shnum); throwCantPack(msg); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Defend against bad PT_DYNAMIC https://github.com/upx/upx/issues/391 modified: p_lx_elf.cpp modified: p_lx_elf.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13054/LLDP: add a missing length check In lldp_private_8023_print() the case block for subtype 4 (Maximum Frame Size TLV, IEEE 802.3bc-2009 Section 79.3.4) did not include the length check and could over-read the input buffer, put it right. 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 create_dpb(davs2_mgr_t *mgr) { davs2_seq_t *seq = &mgr->seq_info; uint8_t *mem_ptr = NULL; size_t mem_size = 0; int i; mgr->dpbsize = mgr->num_decoders + seq->picture_reorder_delay + 16; /// !!! FIXME: decide dpb buffer size ? mgr->dpbsize += 8; // FIXME: Ҫ mem_size = mgr->dpbsize * sizeof(davs2_frame_t *) + davs2_frame_get_size(seq->i_enc_width, seq->i_enc_height, seq->head.chroma_format, 1) * mgr->dpbsize + davs2_frame_get_size(seq->i_enc_width, seq->i_enc_height, seq->head.chroma_format, 0) + CACHE_LINE_SIZE * (mgr->dpbsize + 2); mem_ptr = (uint8_t *)davs2_malloc(mem_size); if (mem_ptr == NULL) { return -1; } mgr->dpb = (davs2_frame_t **)mem_ptr; mem_ptr += mgr->dpbsize * sizeof(davs2_frame_t *); ALIGN_POINTER(mem_ptr); for (i = 0; i < mgr->dpbsize; i++) { mgr->dpb[i] = davs2_frame_new(seq->i_enc_width, seq->i_enc_height, seq->head.chroma_format, &mem_ptr, 1); ALIGN_POINTER(mem_ptr); if (mgr->dpb[i] == NULL) { return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Add checking for `frame_rate_code`. Signed-off-by: luofl <falei.luo@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { return follow_dotdot_rcu(nd); } else follow_dotdot(nd); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'vfs: Test for and handle paths that are unreachable from their mnt_root In rare cases a directory can be renamed out from under a bind mount. In those cases without special handling it becomes possible to walk up the directory tree to the root dentry of the filesystem and down from the root dentry to every other file or directory on the filesystem. Like division by zero .. from an unconnected path can not be given a useful semantic as there is no predicting at which path component the code will realize it is unconnected. We certainly can not match the current behavior as the current behavior is a security hole. Therefore when encounting .. when following an unconnected path return -ENOENT. - Add a function path_connected to verify path->dentry is reachable from path->mnt.mnt_root. AKA to validate that rename did not do something nasty to the bind mount. To avoid races path_connected must be called after following a path component to it's next path component. Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err sgpd_dump(GF_Box *a, FILE * trace) { u32 i; GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a; if (!a) return GF_BAD_PARAM; gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace); if (ptr->grouping_type) fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) ); if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length); if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index); fprintf(trace, ">\n"); for (i=0; i<gf_list_count(ptr->group_descriptions); i++) { void *entry = gf_list_get(ptr->group_descriptions, i); switch (ptr->grouping_type) { case GF_ISOM_SAMPLE_GROUP_ROLL: fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance ); break; case GF_ISOM_SAMPLE_GROUP_PROL: fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance ); break; case GF_ISOM_SAMPLE_GROUP_TELE: fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable); break; case GF_ISOM_SAMPLE_GROUP_RAP: fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no"); if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known) fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples); fprintf(trace, "/>\n"); break; case GF_ISOM_SAMPLE_GROUP_SYNC: fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type); break; case GF_ISOM_SAMPLE_GROUP_SEIG: fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size); dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16); if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) { fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size); dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size); } fprintf(trace, "\"/>\n"); break; case GF_ISOM_SAMPLE_GROUP_OINF: oinf_entry_dump(entry, trace); break; case GF_ISOM_SAMPLE_GROUP_LINF: linf_dump(entry, trace); break; case GF_ISOM_SAMPLE_GROUP_TRIF: trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length); break; case GF_ISOM_SAMPLE_GROUP_NALM: nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length); break; case GF_ISOM_SAMPLE_GROUP_SAP: fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type); break; default: fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length); dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length); fprintf(trace, "\"/>\n"); } } if (!ptr->size) { switch (ptr->grouping_type) { case GF_ISOM_SAMPLE_GROUP_ROLL: fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n"); break; case GF_ISOM_SAMPLE_GROUP_PROL: fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n"); break; case GF_ISOM_SAMPLE_GROUP_TELE: fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n"); break; case GF_ISOM_SAMPLE_GROUP_RAP: fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n"); break; case GF_ISOM_SAMPLE_GROUP_SYNC: fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n"); break; case GF_ISOM_SAMPLE_GROUP_SEIG: fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n"); break; case GF_ISOM_SAMPLE_GROUP_OINF: oinf_entry_dump(NULL, trace); break; case GF_ISOM_SAMPLE_GROUP_LINF: linf_dump(NULL, trace); break; case GF_ISOM_SAMPLE_GROUP_TRIF: trif_dump(trace, NULL, 0); break; case GF_ISOM_SAMPLE_GROUP_NALM: nalm_dump(trace, NULL, 0); break; case GF_ISOM_SAMPLE_GROUP_SAP: fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n"); break; default: fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n"); } } gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace); return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fixed 2 possible heap overflows (inc. #1088)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp) { if (dt_table[Elf32_Dyn::DT_NULL]) { return; // not 1st time; do not change upx_dt_init } Elf32_Dyn const *const dynp0 = dynp; unsigned ndx = 1+ 0; if (dynp) for (; ; ++ndx, ++dynp) { unsigned const d_tag = get_te32(&dynp->d_tag); if (d_tag < DT_NUM) { if (Elf32_Dyn::DT_NEEDED != d_tag && dt_table[d_tag] && get_te32(&dynp->d_val) != get_te32(&dynp0[-1+ dt_table[d_tag]].d_val)) { char msg[50]; snprintf(msg, sizeof(msg), "duplicate DT_%#x: [%#x] [%#x]", d_tag, -1+ dt_table[d_tag], -1+ ndx); throwCantPack(msg); } dt_table[d_tag] = ndx; } if (Elf32_Dyn::DT_NULL == d_tag) { break; // check here so that dt_table[DT_NULL] is set } } upx_dt_init = 0; if (dt_table[Elf32_Dyn::DT_INIT]) upx_dt_init = Elf32_Dyn::DT_INIT; else if (dt_table[Elf32_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_PREINIT_ARRAY; else if (dt_table[Elf32_Dyn::DT_INIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_INIT_ARRAY; unsigned const z_str = dt_table[Elf32_Dyn::DT_STRSZ]; if (z_str) { strtab_end = get_te32(&dynp0[-1+ z_str].d_val); if ((u32_t)file_size <= strtab_end) { // FIXME: weak char msg[50]; snprintf(msg, sizeof(msg), "bad DT_STRSZ %#x", strtab_end); throwCantPack(msg); } } unsigned const x_sym = dt_table[Elf32_Dyn::DT_SYMTAB]; unsigned const x_str = dt_table[Elf32_Dyn::DT_STRTAB]; if (x_sym && x_str) { upx_uint32_t const v_sym = get_te32(&dynp0[-1+ x_sym].d_val); upx_uint32_t const v_str = get_te32(&dynp0[-1+ x_str].d_val); unsigned const z_sym = dt_table[Elf32_Dyn::DT_SYMENT]; unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym) : get_te32(&dynp0[-1+ z_sym].d_val); if (v_sym < v_str) { symnum_end = (v_str - v_sym) / sz_sym; } } // DT_HASH often ends at DT_SYMTAB unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH); if (v_hsh && file_image) { hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH); if (!hashtab) { char msg[40]; snprintf(msg, sizeof(msg), "bad DT_HASH %#x", v_hsh); throwCantPack(msg); } unsigned const nbucket = get_te32(&hashtab[0]); unsigned const *const buckets = &hashtab[2]; unsigned const *const chains = &buckets[nbucket]; (void)chains; unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val); if (!nbucket || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket) // FIXME: weak || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2 // headers + sizeof(*buckets)*nbucket // buckets + sizeof(*chains) *nbucket // chains )) ) { char msg[90]; snprintf(msg, sizeof(msg), "bad DT_HASH nbucket=%#x len=%#x", nbucket, (v_sym - v_hsh)); throwCantPack(msg); } } // DT_GNU_HASH often ends at DT_SYMTAB; FIXME: not for Android? unsigned const v_gsh = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH); if (v_gsh && file_image) { gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH); if (!gashtab) { char msg[40]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH %#x", v_gsh); throwCantPack(msg); } unsigned const n_bucket = get_te32(&gashtab[0]); unsigned const n_bitmask = get_te32(&gashtab[2]); unsigned const gnu_shift = get_te32(&gashtab[3]); unsigned const *const bitmask = (unsigned const *)(void const *)&gashtab[4]; unsigned const *const buckets = (unsigned const *)&bitmask[n_bitmask]; unsigned const *const hasharr = &buckets[n_bucket]; (void)hasharr; //unsigned const *const gashend = &hasharr[n_bucket]; // minimum unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val); if (!n_bucket || !n_bitmask || (-1+ n_bitmask) & n_bitmask // not a power of 2 || 8*sizeof(unsigned) <= gnu_shift // shifted result always == 0 || (n_bucket>>30) // fie on fuzzers || (n_bitmask>>30) || (file_size / sizeof(unsigned)) <= (n_bitmask + 2*n_bucket) // FIXME: weak // FIXME: next test does work for Android? || ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4 // headers + sizeof(*bitmask)*n_bitmask // bitmask + sizeof(*buckets)*n_bucket // buckets + sizeof(*hasharr)*n_bucket // hasharr )) ) { char msg[90]; snprintf(msg, sizeof(msg), "bad DT_GNU_HASH n_bucket=%#x n_bitmask=%#x len=%#x", n_bucket, n_bitmask, v_sym - v_gsh); throwCantPack(msg); } } unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx); if (e_shnum <= e_shstrndx && !(0==e_shnum && 0==e_shstrndx) ) { char msg[40]; snprintf(msg, sizeof(msg), "bad .e_shstrndx %d >= .e_shnum %d", e_shstrndx, e_shnum); throwCantPack(msg); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-369'], 'message': 'Detect bogus DT_SYMENT. https://github.com/upx/upx/issues/331 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool GetUpdateFile( update_t *p_update ) { stream_t *p_stream = NULL; char *psz_version_line = NULL; char *psz_update_data = NULL; p_stream = stream_UrlNew( p_update->p_libvlc, UPDATE_VLC_STATUS_URL ); if( !p_stream ) { msg_Err( p_update->p_libvlc, "Failed to open %s for reading", UPDATE_VLC_STATUS_URL ); goto error; } const int64_t i_read = stream_Size( p_stream ); psz_update_data = malloc( i_read + 1 ); /* terminating '\0' */ if( !psz_update_data ) goto error; if( stream_Read( p_stream, psz_update_data, i_read ) != i_read ) { msg_Err( p_update->p_libvlc, "Couldn't download update file %s", UPDATE_VLC_STATUS_URL ); goto error; } psz_update_data[i_read] = '\0'; stream_Delete( p_stream ); p_stream = NULL; /* first line : version number */ char *psz_update_data_parser = psz_update_data; size_t i_len = strcspn( psz_update_data, "\r\n" ); psz_update_data_parser += i_len; while( *psz_update_data_parser == '\r' || *psz_update_data_parser == '\n' ) psz_update_data_parser++; if( !(psz_version_line = malloc( i_len + 1)) ) goto error; strncpy( psz_version_line, psz_update_data, i_len ); psz_version_line[i_len] = '\0'; p_update->release.i_extra = 0; int ret = sscanf( psz_version_line, "%i.%i.%i.%i", &p_update->release.i_major, &p_update->release.i_minor, &p_update->release.i_revision, &p_update->release.i_extra); if( ret != 3 && ret != 4 ) { msg_Err( p_update->p_libvlc, "Update version false formated" ); goto error; } /* second line : URL */ i_len = strcspn( psz_update_data_parser, "\r\n" ); if( i_len == 0 ) { msg_Err( p_update->p_libvlc, "Update file %s is corrupted: URL missing", UPDATE_VLC_STATUS_URL ); goto error; } if( !(p_update->release.psz_url = malloc( i_len + 1)) ) goto error; strncpy( p_update->release.psz_url, psz_update_data_parser, i_len ); p_update->release.psz_url[i_len] = '\0'; psz_update_data_parser += i_len; while( *psz_update_data_parser == '\r' || *psz_update_data_parser == '\n' ) psz_update_data_parser++; /* Remaining data : description */ i_len = strlen( psz_update_data_parser ); if( i_len == 0 ) { msg_Err( p_update->p_libvlc, "Update file %s is corrupted: description missing", UPDATE_VLC_STATUS_URL ); goto error; } if( !(p_update->release.psz_desc = malloc( i_len + 1)) ) goto error; strncpy( p_update->release.psz_desc, psz_update_data_parser, i_len ); p_update->release.psz_desc[i_len] = '\0'; /* Now that we know the status is valid, we must download its signature * to authenticate it */ signature_packet_t sign; if( download_signature( VLC_OBJECT( p_update->p_libvlc ), &sign, UPDATE_VLC_STATUS_URL ) != VLC_SUCCESS ) { msg_Err( p_update->p_libvlc, "Couldn't download signature of status file" ); goto error; } if( sign.type != BINARY_SIGNATURE && sign.type != TEXT_SIGNATURE ) { msg_Err( p_update->p_libvlc, "Invalid signature type" ); goto error; } p_update->p_pkey = (public_key_t*)malloc( sizeof( public_key_t ) ); if( !p_update->p_pkey ) goto error; if( parse_public_key( videolan_public_key, sizeof( videolan_public_key ), p_update->p_pkey, NULL ) != VLC_SUCCESS ) { msg_Err( p_update->p_libvlc, "Couldn't parse embedded public key, something went really wrong..." ); FREENULL( p_update->p_pkey ); goto error; } memcpy( p_update->p_pkey->longid, videolan_public_key_longid, 8 ); if( memcmp( sign.issuer_longid, p_update->p_pkey->longid , 8 ) != 0 ) { msg_Dbg( p_update->p_libvlc, "Need to download the GPG key" ); public_key_t *p_new_pkey = download_key( VLC_OBJECT(p_update->p_libvlc), sign.issuer_longid, videolan_public_key_longid ); if( !p_new_pkey ) { msg_Err( p_update->p_libvlc, "Couldn't download GPG key" ); FREENULL( p_update->p_pkey ); goto error; } uint8_t *p_hash = hash_from_public_key( p_new_pkey ); if( !p_hash ) { msg_Err( p_update->p_libvlc, "Failed to hash signature" ); free( p_new_pkey ); FREENULL( p_update->p_pkey ); goto error; } if( verify_signature( &p_new_pkey->sig, &p_update->p_pkey->key, p_hash ) == VLC_SUCCESS ) { free( p_hash ); msg_Info( p_update->p_libvlc, "Key authenticated" ); free( p_update->p_pkey ); p_update->p_pkey = p_new_pkey; } else { free( p_hash ); msg_Err( p_update->p_libvlc, "Key signature invalid !" ); goto error; } } uint8_t *p_hash = hash_from_text( psz_update_data, &sign ); if( !p_hash ) { msg_Warn( p_update->p_libvlc, "Can't compute hash for status file" ); goto error; } else if( p_hash[0] != sign.hash_verification[0] || p_hash[1] != sign.hash_verification[1] ) { msg_Warn( p_update->p_libvlc, "Bad hash for status file" ); free( p_hash ); goto error; } else if( verify_signature( &sign, &p_update->p_pkey->key, p_hash ) != VLC_SUCCESS ) { msg_Err( p_update->p_libvlc, "BAD SIGNATURE for status file" ); free( p_hash ); goto error; } else { msg_Info( p_update->p_libvlc, "Status file authenticated" ); free( p_hash ); free( psz_version_line ); free( psz_update_data ); return true; } error: if( p_stream ) stream_Delete( p_stream ); free( psz_version_line ); free( psz_update_data ); return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'misc: update: fix buffer overflow in updater On 32 bit builds, parsing of update status files with a size of 4294967295 or more lead to an integer truncation in a call to malloc and a subsequent buffer overflow. This happened prior to checking the files' signature. The commit fixes this by disallowing overly large status files (above 65k in practice) Signed-off-by: Jean-Baptiste Kempf <jb@videolan.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: isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13055/IS-IS: fix an Extended IS Reachability sub-TLV In isis_print_is_reach_subtlv() one of the case blocks did not check that the sub-TLV "V" is actually present and could over-read the input buffer. Add a length check to fix that and remove a useless boundary check from a loop because the boundary is tested for the full length of "V" before the switch block. Update one of the prior test cases as it turns out it depended on this previously incorrect code path to make it to its own malformed structure further down the buffer, the bugfix has changed its output. 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: static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = rfcomm_pi(sk)->sec_level; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Bluetooth: RFCOMM - Fix info leak in getsockopt(BT_SECURITY) The RFCOMM code fails to initialize the key_size member of struct bt_security before copying it to userland -- that for leaking one byte kernel stack. Initialize key_size with 0 to avoid the info leak. Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: Marcel Holtmann <marcel@holtmann.org> Cc: Gustavo Padovan <gustavo@padovan.org> Cc: Johan Hedberg <johan.hedberg@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: vm_loop (vm_frame_ctx_t *frame_ctx_p) /**< frame context */ { const ecma_compiled_code_t *bytecode_header_p = frame_ctx_p->shared_p->bytecode_header_p; const uint8_t *byte_code_p = frame_ctx_p->byte_code_p; ecma_value_t *literal_start_p = frame_ctx_p->literal_start_p; ecma_value_t *stack_top_p; uint16_t encoding_limit; uint16_t encoding_delta; uint16_t register_end; uint16_t ident_end; uint16_t const_literal_end; int32_t branch_offset = 0; uint8_t branch_offset_length = 0; ecma_value_t left_value; ecma_value_t right_value; ecma_value_t result = ECMA_VALUE_EMPTY; bool is_strict = ((bytecode_header_p->status_flags & CBC_CODE_FLAGS_STRICT_MODE) != 0); /* Prepare for byte code execution. */ if (!(bytecode_header_p->status_flags & CBC_CODE_FLAGS_FULL_LITERAL_ENCODING)) { encoding_limit = CBC_SMALL_LITERAL_ENCODING_LIMIT; encoding_delta = CBC_SMALL_LITERAL_ENCODING_DELTA; } else { encoding_limit = CBC_FULL_LITERAL_ENCODING_LIMIT; encoding_delta = CBC_FULL_LITERAL_ENCODING_DELTA; } if (bytecode_header_p->status_flags & CBC_CODE_FLAGS_UINT16_ARGUMENTS) { cbc_uint16_arguments_t *args_p = (cbc_uint16_arguments_t *) (bytecode_header_p); register_end = args_p->register_end; ident_end = args_p->ident_end; const_literal_end = args_p->const_literal_end; } else { cbc_uint8_arguments_t *args_p = (cbc_uint8_arguments_t *) (bytecode_header_p); register_end = args_p->register_end; ident_end = args_p->ident_end; const_literal_end = args_p->const_literal_end; } stack_top_p = frame_ctx_p->stack_top_p; /* Outer loop for exception handling. */ while (true) { /* Internal loop for byte code execution. */ while (true) { const uint8_t *byte_code_start_p = byte_code_p; uint8_t opcode = *byte_code_p++; uint32_t opcode_data = opcode; if (opcode == CBC_EXT_OPCODE) { opcode = *byte_code_p++; opcode_data = (uint32_t) ((CBC_END + 1) + opcode); } opcode_data = vm_decode_table[opcode_data]; left_value = ECMA_VALUE_UNDEFINED; right_value = ECMA_VALUE_UNDEFINED; uint32_t operands = VM_OC_GET_ARGS_INDEX (opcode_data); if (operands >= VM_OC_GET_LITERAL) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); READ_LITERAL (literal_index, left_value); if (operands != VM_OC_GET_LITERAL) { switch (operands) { case VM_OC_GET_LITERAL_LITERAL: { uint16_t second_literal_index; READ_LITERAL_INDEX (second_literal_index); READ_LITERAL (second_literal_index, right_value); break; } case VM_OC_GET_STACK_LITERAL: { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); right_value = left_value; left_value = *(--stack_top_p); break; } default: { JERRY_ASSERT (operands == VM_OC_GET_THIS_LITERAL); right_value = left_value; left_value = ecma_copy_value (frame_ctx_p->this_binding); break; } } } } else if (operands >= VM_OC_GET_STACK) { JERRY_ASSERT (operands == VM_OC_GET_STACK || operands == VM_OC_GET_STACK_STACK); JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); left_value = *(--stack_top_p); if (operands == VM_OC_GET_STACK_STACK) { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); right_value = left_value; left_value = *(--stack_top_p); } } else if (operands == VM_OC_GET_BRANCH) { branch_offset_length = CBC_BRANCH_OFFSET_LENGTH (opcode); JERRY_ASSERT (branch_offset_length >= 1 && branch_offset_length <= 3); branch_offset = *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length != 1)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length == 3)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); } } if (opcode_data & VM_OC_BACKWARD_BRANCH) { #if JERRY_VM_EXEC_STOP if (JERRY_CONTEXT (vm_exec_stop_cb) != NULL && --JERRY_CONTEXT (vm_exec_stop_counter) == 0) { result = JERRY_CONTEXT (vm_exec_stop_cb) (JERRY_CONTEXT (vm_exec_stop_user_p)); if (ecma_is_value_undefined (result)) { JERRY_CONTEXT (vm_exec_stop_counter) = JERRY_CONTEXT (vm_exec_stop_frequency); } else { JERRY_CONTEXT (vm_exec_stop_counter) = 1; if (ecma_is_value_error_reference (result)) { ecma_raise_error_from_error_reference (result); } else { jcontext_raise_exception (result); } JERRY_ASSERT (jcontext_has_pending_exception ()); jcontext_set_abort_flag (true); result = ECMA_VALUE_ERROR; goto error; } } #endif /* JERRY_VM_EXEC_STOP */ branch_offset = -branch_offset; } } switch (VM_OC_GROUP_GET_INDEX (opcode_data)) { case VM_OC_POP: { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); ecma_free_value (*(--stack_top_p)); continue; } case VM_OC_POP_BLOCK: { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, 0)); VM_GET_REGISTERS (frame_ctx_p)[0] = *(--stack_top_p); continue; } case VM_OC_PUSH: { *stack_top_p++ = left_value; continue; } case VM_OC_PUSH_TWO: { *stack_top_p++ = left_value; *stack_top_p++ = right_value; continue; } case VM_OC_PUSH_THREE: { uint16_t literal_index; *stack_top_p++ = left_value; left_value = ECMA_VALUE_UNDEFINED; READ_LITERAL_INDEX (literal_index); READ_LITERAL (literal_index, left_value); *stack_top_p++ = right_value; *stack_top_p++ = left_value; continue; } case VM_OC_PUSH_UNDEFINED: { *stack_top_p++ = ECMA_VALUE_UNDEFINED; continue; } case VM_OC_PUSH_TRUE: { *stack_top_p++ = ECMA_VALUE_TRUE; continue; } case VM_OC_PUSH_FALSE: { *stack_top_p++ = ECMA_VALUE_FALSE; continue; } case VM_OC_PUSH_NULL: { *stack_top_p++ = ECMA_VALUE_NULL; continue; } case VM_OC_PUSH_THIS: { *stack_top_p++ = ecma_copy_value (frame_ctx_p->this_binding); continue; } case VM_OC_PUSH_0: { *stack_top_p++ = ecma_make_integer_value (0); continue; } case VM_OC_PUSH_POS_BYTE: { ecma_integer_value_t number = *byte_code_p++; *stack_top_p++ = ecma_make_integer_value (number + 1); continue; } case VM_OC_PUSH_NEG_BYTE: { ecma_integer_value_t number = *byte_code_p++; *stack_top_p++ = ecma_make_integer_value (-(number + 1)); continue; } case VM_OC_PUSH_LIT_0: { stack_top_p[0] = left_value; stack_top_p[1] = ecma_make_integer_value (0); stack_top_p += 2; continue; } case VM_OC_PUSH_LIT_POS_BYTE: { ecma_integer_value_t number = *byte_code_p++; stack_top_p[0] = left_value; stack_top_p[1] = ecma_make_integer_value (number + 1); stack_top_p += 2; continue; } case VM_OC_PUSH_LIT_NEG_BYTE: { ecma_integer_value_t number = *byte_code_p++; stack_top_p[0] = left_value; stack_top_p[1] = ecma_make_integer_value (-(number + 1)); stack_top_p += 2; continue; } case VM_OC_PUSH_OBJECT: { ecma_object_t *obj_p = ecma_create_object (ecma_builtin_get (ECMA_BUILTIN_ID_OBJECT_PROTOTYPE), 0, ECMA_OBJECT_TYPE_GENERAL); *stack_top_p++ = ecma_make_object_value (obj_p); continue; } case VM_OC_PUSH_NAMED_FUNC_EXPR: { ecma_object_t *func_p = ecma_get_object_from_value (left_value); JERRY_ASSERT (ecma_get_object_type (func_p) == ECMA_OBJECT_TYPE_FUNCTION); ecma_extended_object_t *ext_func_p = (ecma_extended_object_t *) func_p; JERRY_ASSERT (frame_ctx_p->lex_env_p == ECMA_GET_NON_NULL_POINTER_FROM_POINTER_TAG (ecma_object_t, ext_func_p->u.function.scope_cp)); ecma_object_t *name_lex_env = ecma_create_decl_lex_env (frame_ctx_p->lex_env_p); ecma_op_create_immutable_binding (name_lex_env, ecma_get_string_from_value (right_value), left_value); ECMA_SET_NON_NULL_POINTER_TAG (ext_func_p->u.function.scope_cp, name_lex_env, 0); ecma_free_value (right_value); ecma_deref_object (name_lex_env); *stack_top_p++ = left_value; continue; } case VM_OC_CREATE_BINDING: { #if !JERRY_ESNEXT JERRY_ASSERT (opcode == CBC_CREATE_VAR); #endif /* !JERRY_ESNEXT */ uint32_t literal_index; READ_LITERAL_INDEX (literal_index); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE; #if JERRY_ESNEXT if (opcode == CBC_CREATE_LET) { prop_attributes = ECMA_PROPERTY_ENUMERABLE_WRITABLE; } else if (opcode == CBC_CREATE_CONST) { prop_attributes = ECMA_PROPERTY_FLAG_ENUMERABLE; } ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); if (opcode != CBC_CREATE_VAR) { property_value_p->value = ECMA_VALUE_UNINITIALIZED; } #else /* !JERRY_ESNEXT */ ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); #endif /* JERRY_ESNEXT */ continue; } case VM_OC_VAR_EVAL: { uint32_t literal_index; ecma_value_t lit_value = ECMA_VALUE_UNDEFINED; if (opcode == CBC_CREATE_VAR_FUNC_EVAL) { uint32_t value_index; READ_LITERAL_INDEX (value_index); JERRY_ASSERT (value_index >= const_literal_end); lit_value = vm_construct_literal_object (frame_ctx_p, literal_start_p[value_index]); } READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { #if JERRY_ESNEXT && !(defined JERRY_NDEBUG) if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* JERRY_ESNEXT && !JERRY_NDEBUG */ JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); } #if JERRY_ESNEXT && !(defined JERRY_NDEBUG) if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* JERRY_ESNEXT && !JERRY_NDEBUG */ /* 'Variable declaration' */ result = ecma_op_has_binding (lex_env_p, name_p); #if JERRY_BUILTIN_PROXY if (ECMA_IS_VALUE_ERROR (result)) { goto error; } #endif /* JERRY_BUILTIN_PROXY */ ecma_property_t *prop_p = NULL; if (ecma_is_value_false (result)) { bool is_configurable = (frame_ctx_p->status_flags & VM_FRAME_CTX_DIRECT_EVAL) != 0; prop_p = ecma_op_create_mutable_binding (lex_env_p, name_p, is_configurable); if (JERRY_UNLIKELY (prop_p == ECMA_PROPERTY_POINTER_ERROR)) { result = ECMA_VALUE_ERROR; goto error; } } if (lit_value != ECMA_VALUE_UNDEFINED) { JERRY_ASSERT (ecma_is_value_object (lit_value)); if (prop_p != NULL) { JERRY_ASSERT (ecma_is_value_undefined (ECMA_PROPERTY_VALUE_PTR (prop_p)->value)); JERRY_ASSERT (ecma_is_property_writable (*prop_p)); ECMA_PROPERTY_VALUE_PTR (prop_p)->value = lit_value; ecma_free_object (lit_value); } else { result = ecma_op_put_value_lex_env_base (lex_env_p, name_p, is_strict, lit_value); ecma_free_object (lit_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } } } continue; } #if JERRY_ESNEXT case VM_OC_EXT_VAR_EVAL: { uint32_t literal_index; ecma_value_t lit_value = ECMA_VALUE_UNDEFINED; JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE); if (opcode == CBC_EXT_CREATE_VAR_FUNC_EVAL) { uint32_t value_index; READ_LITERAL_INDEX (value_index); JERRY_ASSERT (value_index >= const_literal_end); lit_value = vm_construct_literal_object (frame_ctx_p, literal_start_p[value_index]); } READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; ecma_object_t *prev_lex_env_p = NULL; while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { #if !(defined JERRY_NDEBUG) if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* !JERRY_NDEBUG */ JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); prev_lex_env_p = lex_env_p; lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); } JERRY_ASSERT (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (prev_lex_env_p != NULL && ecma_get_lex_env_type (prev_lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); ecma_property_t *property_p = ecma_find_named_property (prev_lex_env_p, name_p); ecma_property_value_t *property_value_p; if (property_p == NULL) { property_value_p = ecma_create_named_data_property (prev_lex_env_p, name_p, ECMA_PROPERTY_CONFIGURABLE_WRITABLE, NULL); if (lit_value == ECMA_VALUE_UNDEFINED) { continue; } } else { if (lit_value == ECMA_VALUE_UNDEFINED) { continue; } property_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); ecma_free_value_if_not_object (property_value_p->value); } property_value_p->value = lit_value; ecma_deref_object (ecma_get_object_from_value (lit_value)); continue; } #endif /* JERRY_ESNEXT */ case VM_OC_CREATE_ARGUMENTS: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_ARG_LIST); result = ecma_op_create_arguments_object ((vm_frame_ctx_shared_args_t *) (frame_ctx_p->shared_p), frame_ctx_p->lex_env_p); if (literal_index < register_end) { JERRY_ASSERT (VM_GET_REGISTER (frame_ctx_p, literal_index) == ECMA_VALUE_UNDEFINED); VM_GET_REGISTER (frame_ctx_p, literal_index) = result; continue; } ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE; ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); property_value_p->value = result; ecma_deref_object (ecma_get_object_from_value (result)); continue; } #if JERRY_SNAPSHOT_EXEC case VM_OC_SET_BYTECODE_PTR: { memcpy (&byte_code_p, byte_code_p++, sizeof (uintptr_t)); frame_ctx_p->byte_code_start_p = byte_code_p; continue; } #endif /* JERRY_SNAPSHOT_EXEC */ case VM_OC_INIT_ARG_OR_FUNC: { uint32_t literal_index, value_index; ecma_value_t lit_value; bool release = false; READ_LITERAL_INDEX (value_index); if (value_index < register_end) { /* Take (not copy) the reference. */ lit_value = ecma_copy_value_if_not_object (VM_GET_REGISTER (frame_ctx_p, value_index)); } else { lit_value = vm_construct_literal_object (frame_ctx_p, literal_start_p[value_index]); release = true; } READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (value_index != literal_index); JERRY_ASSERT (value_index >= register_end || literal_index >= register_end); if (literal_index < register_end) { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); JERRY_ASSERT (release); VM_GET_REGISTER (frame_ctx_p, literal_index) = lit_value; continue; } ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, ECMA_PROPERTY_FLAG_WRITABLE, NULL); JERRY_ASSERT (property_value_p->value == ECMA_VALUE_UNDEFINED); property_value_p->value = lit_value; if (release) { ecma_deref_object (ecma_get_object_from_value (lit_value)); } continue; } #if JERRY_ESNEXT case VM_OC_CHECK_VAR: { JERRY_ASSERT (CBC_FUNCTION_GET_TYPE (frame_ctx_p->shared_p->bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT); uint32_t literal_index; READ_LITERAL_INDEX (literal_index); if ((frame_ctx_p->lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) == 0) { continue; } ecma_string_t *const literal_name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_property_t *const binding_p = ecma_find_named_property (frame_ctx_p->lex_env_p, literal_name_p); if (binding_p != NULL) { result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared)); goto error; } continue; } case VM_OC_CHECK_LET: { JERRY_ASSERT (CBC_FUNCTION_GET_TYPE (frame_ctx_p->shared_p->bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT); uint32_t literal_index; READ_LITERAL_INDEX (literal_index); ecma_string_t *literal_name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; if (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { result = opfunc_lexical_scope_has_restricted_binding (frame_ctx_p, literal_name_p); if (!ecma_is_value_false (result)) { if (ecma_is_value_true (result)) { result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared)); } JERRY_ASSERT (ECMA_IS_VALUE_ERROR (result)); goto error; } continue; } result = ecma_op_has_binding (lex_env_p, literal_name_p); #if JERRY_BUILTIN_PROXY if (ECMA_IS_VALUE_ERROR (result)) { goto error; } #endif /* JERRY_BUILTIN_PROXY */ if (ecma_is_value_true (result)) { result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared)); goto error; } continue; } case VM_OC_ASSIGN_LET_CONST: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE || (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_CLASS && (frame_ctx_p->lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_LEXICAL_ENV_HAS_DATA))); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_property_t *property_p = ecma_find_named_property (frame_ctx_p->lex_env_p, name_p); JERRY_ASSERT (property_p != NULL && ECMA_PROPERTY_IS_RAW_DATA (*property_p) && (*property_p & ECMA_PROPERTY_FLAG_DATA)); JERRY_ASSERT (ECMA_PROPERTY_VALUE_PTR (property_p)->value == ECMA_VALUE_UNINITIALIZED); ECMA_PROPERTY_VALUE_PTR (property_p)->value = left_value; if (ecma_is_value_object (left_value)) { ecma_deref_object (ecma_get_object_from_value (left_value)); } continue; } case VM_OC_INIT_BINDING: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE; if (opcode == CBC_INIT_LET) { prop_attributes = ECMA_PROPERTY_ENUMERABLE_WRITABLE; } else if (opcode == CBC_INIT_CONST) { prop_attributes = ECMA_PROPERTY_FLAG_ENUMERABLE; } ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); JERRY_ASSERT (property_value_p->value == ECMA_VALUE_UNDEFINED); ecma_value_t value = *(--stack_top_p); property_value_p->value = value; ecma_deref_if_object (value); continue; } case VM_OC_THROW_CONST_ERROR: { result = ecma_raise_type_error (ECMA_ERR_MSG ("Constant bindings cannot be reassigned")); goto error; } case VM_OC_COPY_TO_GLOBAL: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { #ifndef JERRY_NDEBUG if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* !JERRY_NDEBUG */ JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); } if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); ecma_property_value_t *prop_value_p; if (property_p == NULL) { prop_value_p = ecma_create_named_data_property (lex_env_p, name_p, ECMA_PROPERTY_FLAG_WRITABLE, NULL); } else { #ifndef JERRY_NDEBUG JERRY_ASSERT (!(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); #endif /* !JERRY_NDEBUG */ prop_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); } ecma_named_data_property_assign_value (lex_env_p, prop_value_p, left_value); } else { result = ecma_op_set_mutable_binding (lex_env_p, name_p, left_value, is_strict); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } } goto free_left_value; } case VM_OC_COPY_FROM_ARG: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; ecma_object_t *arg_lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); JERRY_ASSERT ((lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) && ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (arg_lex_env_p != NULL && !(arg_lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) && ecma_get_lex_env_type (arg_lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (lex_env_p, name_p, ECMA_PROPERTY_FLAG_WRITABLE, NULL); ecma_property_t *property_p = ecma_find_named_property (arg_lex_env_p, name_p); JERRY_ASSERT (property_p != NULL); ecma_property_value_t *arg_prop_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); property_value_p->value = ecma_copy_value_if_not_object (arg_prop_value_p->value); continue; } case VM_OC_CLONE_CONTEXT: { JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE); bool copy_values = (byte_code_start_p[1] == CBC_EXT_CLONE_FULL_CONTEXT); frame_ctx_p->lex_env_p = ecma_clone_decl_lexical_environment (frame_ctx_p->lex_env_p, copy_values); continue; } case VM_OC_SET__PROTO__: { result = ecma_builtin_object_object_set_proto (stack_top_p[-1], left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_PUSH_STATIC_FIELD_FUNC: { JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE && (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_FIELD_FUNC || byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC)); bool push_computed = (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC); ecma_value_t value = stack_top_p[-1]; if (!push_computed) { stack_top_p++; } memmove (stack_top_p - 3, stack_top_p - 4, 3 * sizeof (ecma_value_t)); stack_top_p[-4] = left_value; if (!push_computed) { continue; } left_value = value; /* FALLTHRU */ } case VM_OC_ADD_COMPUTED_FIELD: { JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE && (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC || byte_code_start_p[1] == CBC_EXT_ADD_COMPUTED_FIELD || byte_code_start_p[1] == CBC_EXT_ADD_STATIC_COMPUTED_FIELD)); int index = (byte_code_start_p[1] == CBC_EXT_ADD_COMPUTED_FIELD) ? -2 : -4; result = opfunc_add_computed_field (stack_top_p[index], left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_COPY_DATA_PROPERTIES: { left_value = *(--stack_top_p); if (ecma_is_value_undefined (left_value) || ecma_is_value_null (left_value)) { continue; } result = opfunc_copy_data_properties (stack_top_p[-1], left_value, ECMA_VALUE_UNDEFINED); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_SET_COMPUTED_PROPERTY: { /* Swap values. */ left_value ^= right_value; right_value ^= left_value; left_value ^= right_value; /* FALLTHRU */ } #endif /* JERRY_ESNEXT */ case VM_OC_SET_PROPERTY: { JERRY_STATIC_ASSERT (VM_OC_NON_STATIC_FLAG == VM_OC_BACKWARD_BRANCH, vm_oc_non_static_flag_must_be_equal_to_vm_oc_backward_branch); JERRY_ASSERT ((opcode_data >> VM_OC_NON_STATIC_SHIFT) <= 0x1); ecma_string_t *prop_name_p = ecma_op_to_property_key (right_value); if (JERRY_UNLIKELY (prop_name_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } #if JERRY_ESNEXT if (JERRY_UNLIKELY (ecma_compare_ecma_string_to_magic_id (prop_name_p, LIT_MAGIC_STRING_PROTOTYPE)) && !(opcode_data & VM_OC_NON_STATIC_FLAG)) { result = ecma_raise_type_error (ECMA_ERR_MSG (ecma_error_class_is_non_configurable)); goto error; } const int index = (int) (opcode_data >> VM_OC_NON_STATIC_SHIFT) - 2; #else /* !JERRY_ESNEXT */ const int index = -1; #endif /* JERRY_ESNEXT */ ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[index]); opfunc_set_data_property (object_p, prop_name_p, left_value); ecma_deref_ecma_string (prop_name_p); goto free_both_values; } case VM_OC_SET_GETTER: case VM_OC_SET_SETTER: { JERRY_ASSERT ((opcode_data >> VM_OC_NON_STATIC_SHIFT) <= 0x1); ecma_string_t *prop_name_p = ecma_op_to_property_key (left_value); if (JERRY_UNLIKELY (prop_name_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } #if JERRY_ESNEXT if (JERRY_UNLIKELY (ecma_compare_ecma_string_to_magic_id (prop_name_p, LIT_MAGIC_STRING_PROTOTYPE)) && !(opcode_data & VM_OC_NON_STATIC_FLAG)) { result = ecma_raise_type_error (ECMA_ERR_MSG (ecma_error_class_is_non_configurable)); goto error; } const int index = (int) (opcode_data >> VM_OC_NON_STATIC_SHIFT) - 2; #else /* !JERRY_ESNEXT */ const int index = -1; #endif /* JERRY_ESNEXT */ opfunc_set_accessor (VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_SET_GETTER, stack_top_p[index], prop_name_p, right_value); ecma_deref_ecma_string (prop_name_p); goto free_both_values; } case VM_OC_PUSH_ARRAY: { /* Note: this operation cannot throw an exception */ *stack_top_p++ = ecma_make_object_value (ecma_op_new_array_object (0)); continue; } #if JERRY_ESNEXT case VM_OC_LOCAL_EVAL: { ECMA_CLEAR_LOCAL_PARSE_OPTS (); uint8_t parse_opts = *byte_code_p++; ECMA_SET_LOCAL_PARSE_OPTS (parse_opts); continue; } case VM_OC_SUPER_CALL: { uint8_t arguments_list_len = *byte_code_p++; if (opcode >= CBC_EXT_SPREAD_SUPER_CALL) { stack_top_p -= arguments_list_len; ecma_collection_t *arguments_p = opfunc_spread_arguments (stack_top_p, arguments_list_len); if (JERRY_UNLIKELY (arguments_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } stack_top_p++; ECMA_SET_INTERNAL_VALUE_POINTER (stack_top_p[-1], arguments_p); } else { stack_top_p -= arguments_list_len; } frame_ctx_p->call_operation = VM_EXEC_SUPER_CALL; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_PUSH_CLASS_ENVIRONMENT: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); opfunc_push_class_environment (frame_ctx_p, &stack_top_p, literal_start_p[literal_index]); continue; } case VM_OC_PUSH_IMPLICIT_CTOR: { *stack_top_p++ = opfunc_create_implicit_class_constructor (opcode, frame_ctx_p->shared_p->bytecode_header_p); continue; } case VM_OC_INIT_CLASS: { result = opfunc_init_class (frame_ctx_p, stack_top_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } continue; } case VM_OC_FINALIZE_CLASS: { JERRY_ASSERT (opcode == CBC_EXT_FINALIZE_NAMED_CLASS || opcode == CBC_EXT_FINALIZE_ANONYMOUS_CLASS); if (opcode == CBC_EXT_FINALIZE_NAMED_CLASS) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); left_value = literal_start_p[literal_index]; } opfunc_finalize_class (frame_ctx_p, &stack_top_p, left_value); continue; } case VM_OC_SET_FIELD_INIT: { ecma_string_t *property_name_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_CLASS_FIELD_INIT); ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[-2]); ecma_property_value_t *property_value_p = ecma_create_named_data_property (object_p, property_name_p, ECMA_PROPERTY_FIXED, NULL); property_value_p->value = left_value; property_name_p = ecma_get_internal_string (LIT_INTERNAL_MAGIC_STRING_CLASS_FIELD_COMPUTED); ecma_property_t *property_p = ecma_find_named_property (object_p, property_name_p); if (property_p != NULL) { property_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); ecma_value_t *compact_collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_value_t, property_value_p->value); compact_collection_p = ecma_compact_collection_shrink (compact_collection_p); ECMA_SET_INTERNAL_VALUE_POINTER (property_value_p->value, compact_collection_p); } goto free_left_value; } case VM_OC_RUN_FIELD_INIT: { JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_NON_ARROW_FUNC); result = opfunc_init_class_fields (frame_ctx_p->shared_p->function_object_p, frame_ctx_p->this_binding); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } continue; } case VM_OC_RUN_STATIC_FIELD_INIT: { left_value = stack_top_p[-2]; stack_top_p[-2] = stack_top_p[-1]; stack_top_p--; result = opfunc_init_static_class_fields (left_value, stack_top_p[-1]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_SET_NEXT_COMPUTED_FIELD: { ecma_integer_value_t next_index = ecma_get_integer_from_value (stack_top_p[-2]) + 1; stack_top_p[-2] = ecma_make_integer_value (next_index); stack_top_p++; JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_CLASS_FIELDS); ecma_value_t *computed_class_fields_p = VM_GET_COMPUTED_CLASS_FIELDS (frame_ctx_p); JERRY_ASSERT ((ecma_value_t) next_index < ECMA_COMPACT_COLLECTION_GET_SIZE (computed_class_fields_p)); result = stack_top_p[-2]; stack_top_p[-1] = ecma_copy_value (computed_class_fields_p[next_index]); stack_top_p[-2] = ecma_copy_value (frame_ctx_p->this_binding); break; } case VM_OC_PUSH_SUPER_CONSTRUCTOR: { result = ecma_op_function_get_super_constructor (vm_get_class_function (frame_ctx_p)); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; continue; } case VM_OC_RESOLVE_LEXICAL_THIS: { result = ecma_op_get_this_binding (frame_ctx_p->lex_env_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; continue; } case VM_OC_OBJECT_LITERAL_HOME_ENV: { if (opcode == CBC_EXT_PUSH_OBJECT_SUPER_ENVIRONMENT) { ecma_value_t obj_value = stack_top_p[-1]; ecma_object_t *obj_env_p = ecma_create_lex_env_class (frame_ctx_p->lex_env_p, 0); ECMA_SET_NON_NULL_POINTER (obj_env_p->u1.bound_object_cp, ecma_get_object_from_value (obj_value)); stack_top_p[-1] = ecma_make_object_value (obj_env_p); *stack_top_p++ = obj_value; } else { JERRY_ASSERT (opcode == CBC_EXT_POP_OBJECT_SUPER_ENVIRONMENT); ecma_deref_object (ecma_get_object_from_value (stack_top_p[-2])); stack_top_p[-2] = stack_top_p[-1]; stack_top_p--; } continue; } case VM_OC_SET_HOME_OBJECT: { int offset = opcode == CBC_EXT_OBJECT_LITERAL_SET_HOME_OBJECT_COMPUTED ? -1 : 0; opfunc_set_home_object (ecma_get_object_from_value (stack_top_p[-1]), ecma_get_object_from_value (stack_top_p[-3 + offset])); continue; } case VM_OC_SUPER_REFERENCE: { result = opfunc_form_super_reference (&stack_top_p, frame_ctx_p, left_value, opcode); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_SET_FUNCTION_NAME: { char *prefix_p = NULL; lit_utf8_size_t prefix_size = 0; if (opcode != CBC_EXT_SET_FUNCTION_NAME) { ecma_value_t prop_name_value; if (opcode == CBC_EXT_SET_CLASS_NAME) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); prop_name_value = literal_start_p[literal_index]; } else { prop_name_value = stack_top_p[-2]; } ecma_string_t *prop_name_p = ecma_op_to_property_key (prop_name_value); if (JERRY_UNLIKELY (prop_name_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } left_value = ecma_make_prop_name_value (prop_name_p); if (opcode != CBC_EXT_SET_CLASS_NAME) { ecma_ref_ecma_string (prop_name_p); ecma_free_value (stack_top_p[-2]); stack_top_p[-2] = left_value; } if (opcode == CBC_EXT_SET_COMPUTED_GETTER_NAME || opcode == CBC_EXT_SET_COMPUTED_SETTER_NAME) { prefix_p = (opcode == CBC_EXT_SET_COMPUTED_GETTER_NAME) ? "get " : "set "; prefix_size = 4; } } ecma_object_t *func_obj_p = ecma_get_object_from_value (stack_top_p[-1]); if (ecma_find_named_property (func_obj_p, ecma_get_magic_string (LIT_MAGIC_STRING_NAME)) != NULL) { ecma_free_value (left_value); continue; } ecma_property_value_t *value_p; value_p = ecma_create_named_data_property (func_obj_p, ecma_get_magic_string (LIT_MAGIC_STRING_NAME), ECMA_PROPERTY_FLAG_CONFIGURABLE, NULL); if (ecma_get_object_type (func_obj_p) == ECMA_OBJECT_TYPE_FUNCTION) { ECMA_SET_SECOND_BIT_TO_POINTER_TAG (((ecma_extended_object_t *) func_obj_p)->u.function.scope_cp); } value_p->value = ecma_op_function_form_name (ecma_get_prop_name_from_value (left_value), prefix_p, prefix_size); ecma_free_value (left_value); continue; } case VM_OC_PUSH_SPREAD_ELEMENT: { *stack_top_p++ = ECMA_VALUE_SPREAD_ELEMENT; continue; } case VM_OC_PUSH_REST_OBJECT: { vm_frame_ctx_shared_t *shared_p = frame_ctx_p->shared_p; JERRY_ASSERT (shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_ARG_LIST); const ecma_value_t *arg_list_p = ((vm_frame_ctx_shared_args_t *) shared_p)->arg_list_p; uint32_t arg_list_len = ((vm_frame_ctx_shared_args_t *) shared_p)->arg_list_len; uint16_t argument_end; if (bytecode_header_p->status_flags & CBC_CODE_FLAGS_UINT16_ARGUMENTS) { argument_end = ((cbc_uint16_arguments_t *) bytecode_header_p)->argument_end; } else { argument_end = ((cbc_uint8_arguments_t *) bytecode_header_p)->argument_end; } if (arg_list_len < argument_end) { arg_list_len = argument_end; } result = ecma_op_new_array_object_from_buffer (arg_list_p + argument_end, arg_list_len - argument_end); JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (result)); *stack_top_p++ = result; continue; } case VM_OC_ITERATOR_CONTEXT_CREATE: { result = ecma_op_get_iterator (stack_top_p[-1], ECMA_VALUE_SYNC_ITERATOR, &left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } uint32_t context_size = (uint32_t) (stack_top_p + PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION - VM_LAST_CONTEXT_END ()); stack_top_p += PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION; VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, context_size); stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_ITERATOR, context_size) | VM_CONTEXT_CLOSE_ITERATOR; stack_top_p[-2] = result; stack_top_p[-3] = left_value; continue; } case VM_OC_ITERATOR_STEP: { ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_value_t iterator = last_context_end_p[-2]; ecma_value_t next_method = last_context_end_p[-3]; result = ecma_op_iterator_step (iterator, next_method); if (ECMA_IS_VALUE_ERROR (result)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; goto error; } ecma_value_t value = ECMA_VALUE_UNDEFINED; if (!ecma_is_value_false (result)) { value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (value)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = value; goto error; } } else { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; } *stack_top_p++ = value; continue; } case VM_OC_ITERATOR_CONTEXT_END: { JERRY_ASSERT (VM_LAST_CONTEXT_END () == stack_top_p); if (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR) { stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = ecma_op_iterator_close (stack_top_p[-2]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } } stack_top_p = vm_stack_context_abort_variable_length (frame_ctx_p, stack_top_p, PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION); continue; } case VM_OC_DEFAULT_INITIALIZER: { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); if (stack_top_p[-1] != ECMA_VALUE_UNDEFINED) { byte_code_p = byte_code_start_p + branch_offset; continue; } stack_top_p--; continue; } case VM_OC_REST_INITIALIZER: { ecma_object_t *array_p = ecma_op_new_array_object (0); JERRY_ASSERT (ecma_op_object_is_fast_array (array_p)); ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_value_t iterator = last_context_end_p[-2]; ecma_value_t next_method = last_context_end_p[-3]; uint32_t index = 0; while (true) { result = ecma_op_iterator_step (iterator, next_method); if (ECMA_IS_VALUE_ERROR (result)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; ecma_deref_object (array_p); goto error; } if (ecma_is_value_false (result)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; break; } ecma_value_t value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (value)) { ecma_deref_object (array_p); result = value; goto error; } bool set_result = ecma_fast_array_set_property (array_p, index++, value); JERRY_ASSERT (set_result); ecma_free_value (value); } *stack_top_p++ = ecma_make_object_value (array_p); continue; } case VM_OC_OBJ_INIT_CONTEXT_CREATE: { left_value = stack_top_p[-1]; vm_stack_context_type_t context_type = VM_CONTEXT_OBJ_INIT; uint32_t context_stack_allocation = PARSER_OBJ_INIT_CONTEXT_STACK_ALLOCATION; if (opcode == CBC_EXT_OBJ_INIT_REST_CONTEXT_CREATE) { context_type = VM_CONTEXT_OBJ_INIT_REST; context_stack_allocation = PARSER_OBJ_INIT_REST_CONTEXT_STACK_ALLOCATION; } uint32_t context_size = (uint32_t) (stack_top_p + context_stack_allocation - VM_LAST_CONTEXT_END ()); stack_top_p += context_stack_allocation; VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, context_size); stack_top_p[-1] = VM_CREATE_CONTEXT (context_type, context_size); stack_top_p[-2] = left_value; if (context_type == VM_CONTEXT_OBJ_INIT_REST) { stack_top_p[-3] = ecma_make_object_value (ecma_op_new_array_object (0)); } continue; } case VM_OC_OBJ_INIT_CONTEXT_END: { JERRY_ASSERT (stack_top_p == VM_LAST_CONTEXT_END ()); uint32_t context_stack_allocation = PARSER_OBJ_INIT_CONTEXT_STACK_ALLOCATION; if (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_OBJ_INIT_REST) { context_stack_allocation = PARSER_OBJ_INIT_REST_CONTEXT_STACK_ALLOCATION; } stack_top_p = vm_stack_context_abort_variable_length (frame_ctx_p, stack_top_p, context_stack_allocation); continue; } case VM_OC_OBJ_INIT_PUSH_REST: { ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); if (!ecma_op_require_object_coercible (last_context_end_p[-2])) { result = ECMA_VALUE_ERROR; goto error; } ecma_object_t *prototype_p = ecma_builtin_get (ECMA_BUILTIN_ID_OBJECT_PROTOTYPE); ecma_object_t *result_object_p = ecma_create_object (prototype_p, 0, ECMA_OBJECT_TYPE_GENERAL); left_value = ecma_make_object_value (result_object_p); result = opfunc_copy_data_properties (left_value, last_context_end_p[-2], last_context_end_p[-3]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_free_value (last_context_end_p[-3]); last_context_end_p[-3] = last_context_end_p[-2]; last_context_end_p[-2] = ECMA_VALUE_UNDEFINED; *stack_top_p++ = left_value; continue; } case VM_OC_INITIALIZER_PUSH_NAME: { if (JERRY_UNLIKELY (!ecma_is_value_prop_name (left_value))) { ecma_string_t *property_key = ecma_op_to_property_key (left_value); if (property_key == NULL) { result = ECMA_VALUE_ERROR; goto error; } ecma_free_value (left_value); left_value = ecma_make_string_value (property_key); } ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_object_t *array_obj_p = ecma_get_object_from_value (last_context_end_p[-3]); JERRY_ASSERT (ecma_get_object_type (array_obj_p) == ECMA_OBJECT_TYPE_ARRAY); ecma_extended_object_t *ext_array_obj_p = (ecma_extended_object_t *) array_obj_p; ecma_fast_array_set_property (array_obj_p, ext_array_obj_p->u.array.length, left_value); /* FALLTHRU */ } case VM_OC_INITIALIZER_PUSH_PROP: { ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_value_t base = last_context_end_p[-2]; if (opcode == CBC_EXT_INITIALIZER_PUSH_PROP) { left_value = *last_context_end_p++; while (last_context_end_p < stack_top_p) { last_context_end_p[-1] = *last_context_end_p; last_context_end_p++; } stack_top_p--; } result = vm_op_get_value (base, left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_SPREAD_ARGUMENTS: { uint8_t arguments_list_len = *byte_code_p++; stack_top_p -= arguments_list_len; ecma_collection_t *arguments_p = opfunc_spread_arguments (stack_top_p, arguments_list_len); if (JERRY_UNLIKELY (arguments_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } stack_top_p++; ECMA_SET_INTERNAL_VALUE_POINTER (stack_top_p[-1], arguments_p); frame_ctx_p->call_operation = VM_EXEC_SPREAD_OP; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_CREATE_GENERATOR: { frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; vm_executable_object_t *executable_object_p; executable_object_p = opfunc_create_executable_object (frame_ctx_p, VM_CREATE_EXECUTABLE_OBJECT_GENERATOR); return ecma_make_object_value ((ecma_object_t *) executable_object_p); } case VM_OC_YIELD: { frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = --stack_top_p; return *stack_top_p; } case VM_OC_ASYNC_YIELD: { ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); opfunc_async_generator_yield (async_generator_object_p, stack_top_p[-1]); frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = --stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_ASYNC_YIELD_ITERATOR: { ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); JERRY_ASSERT (!(async_generator_object_p->u.cls.u2.executable_obj_flags & ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD)); /* Byte code is executed at the first time. */ left_value = stack_top_p[-1]; result = ecma_op_get_iterator (left_value, ECMA_VALUE_ASYNC_ITERATOR, stack_top_p - 1); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_free_value (left_value); left_value = result; result = ecma_op_iterator_next (left_value, stack_top_p[-1], ECMA_VALUE_UNDEFINED); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } result = ecma_promise_async_await (async_generator_object_p, result); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } async_generator_object_p->u.cls.u2.executable_obj_flags |= ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD; *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p) = left_value; frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_AWAIT: { if (JERRY_UNLIKELY (!(frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE))) { frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = --stack_top_p; result = opfunc_async_create_and_await (frame_ctx_p, *stack_top_p, 0); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } return result; } /* FALLTHRU */ } case VM_OC_GENERATOR_AWAIT: { ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); result = ecma_promise_async_await (async_generator_object_p, *(--stack_top_p)); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_EXT_RETURN: { result = left_value; left_value = ECMA_VALUE_UNDEFINED; ecma_value_t *stack_bottom_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; while (stack_top_p > stack_bottom_p) { ecma_fast_free_value (*(--stack_top_p)); } goto error; } case VM_OC_ASYNC_EXIT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); if (!(frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE)) { result = ecma_op_create_promise_object (ECMA_VALUE_EMPTY, ECMA_VALUE_UNDEFINED, NULL); } else { result = *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p); *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p) = ECMA_VALUE_UNDEFINED; } vm_stack_context_type_t context_type = VM_GET_CONTEXT_TYPE (stack_top_p[-1]); if (context_type == VM_CONTEXT_TRY) { JERRY_ASSERT (frame_ctx_p->context_depth == PARSER_TRY_CONTEXT_STACK_ALLOCATION); left_value = ECMA_VALUE_UNDEFINED; } else { JERRY_ASSERT (frame_ctx_p->context_depth == PARSER_FINALLY_CONTEXT_STACK_ALLOCATION); left_value = stack_top_p[-2]; } if (context_type == VM_CONTEXT_FINALLY_THROW) { ecma_reject_promise (result, left_value); } else { JERRY_ASSERT (context_type == VM_CONTEXT_TRY || context_type == VM_CONTEXT_FINALLY_RETURN); ecma_fulfill_promise (result, left_value); } ecma_free_value (left_value); frame_ctx_p->context_depth = 0; frame_ctx_p->call_operation = VM_NO_EXEC_OP; return result; } case VM_OC_STRING_CONCAT: { ecma_string_t *left_str_p = ecma_op_to_string (left_value); if (JERRY_UNLIKELY (left_str_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } ecma_string_t *right_str_p = ecma_op_to_string (right_value); if (JERRY_UNLIKELY (right_str_p == NULL)) { ecma_deref_ecma_string (left_str_p); result = ECMA_VALUE_ERROR; goto error; } ecma_string_t *result_str_p = ecma_concat_ecma_strings (left_str_p, right_str_p); ecma_deref_ecma_string (right_str_p); *stack_top_p++ = ecma_make_string_value (result_str_p); goto free_both_values; } case VM_OC_GET_TEMPLATE_OBJECT: { uint8_t tagged_idx = *byte_code_p++; ecma_collection_t *collection_p = ecma_compiled_code_get_tagged_template_collection (bytecode_header_p); JERRY_ASSERT (tagged_idx < collection_p->item_count); *stack_top_p++ = ecma_copy_value (collection_p->buffer_p[tagged_idx]); continue; } case VM_OC_PUSH_NEW_TARGET: { ecma_object_t *new_target_object_p = JERRY_CONTEXT (current_new_target_p); if (new_target_object_p == NULL) { *stack_top_p++ = ECMA_VALUE_UNDEFINED; } else { ecma_ref_object (new_target_object_p); *stack_top_p++ = ecma_make_object_value (new_target_object_p); } continue; } case VM_OC_REQUIRE_OBJECT_COERCIBLE: { if (!ecma_op_require_object_coercible (stack_top_p[-1])) { result = ECMA_VALUE_ERROR; goto error; } continue; } case VM_OC_ASSIGN_SUPER: { result = opfunc_assign_super_reference (&stack_top_p, frame_ctx_p, opcode_data); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } continue; } #endif /* JERRY_ESNEXT */ case VM_OC_PUSH_ELISON: { *stack_top_p++ = ECMA_VALUE_ARRAY_HOLE; continue; } case VM_OC_APPEND_ARRAY: { uint16_t values_length = *byte_code_p++; stack_top_p -= values_length; #if JERRY_ESNEXT if (*byte_code_start_p == CBC_EXT_OPCODE) { values_length = (uint16_t) (values_length | OPFUNC_HAS_SPREAD_ELEMENT); } #endif /* JERRY_ESNEXT */ result = opfunc_append_array (stack_top_p, values_length); #if JERRY_ESNEXT if (ECMA_IS_VALUE_ERROR (result)) { goto error; } #else /* !JERRY_ESNEXT */ JERRY_ASSERT (ecma_is_value_empty (result)); #endif /* JERRY_ESNEXT */ continue; } case VM_OC_IDENT_REFERENCE: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index < ident_end); if (literal_index < register_end) { *stack_top_p++ = ECMA_VALUE_REGISTER_REF; *stack_top_p++ = ecma_make_integer_value (literal_index); *stack_top_p++ = ecma_fast_copy_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); } else { ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *ref_base_lex_env_p; result = ecma_op_get_value_lex_env_base (frame_ctx_p->lex_env_p, &ref_base_lex_env_p, name_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_ref_object (ref_base_lex_env_p); ecma_ref_ecma_string (name_p); *stack_top_p++ = ecma_make_object_value (ref_base_lex_env_p); *stack_top_p++ = ecma_make_string_value (name_p); *stack_top_p++ = result; } continue; } case VM_OC_PROP_GET: { result = vm_op_get_value (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_PROP_REFERENCE: { /* Forms with reference requires preserving the base and offset. */ if (opcode == CBC_PUSH_PROP_REFERENCE) { left_value = stack_top_p[-2]; right_value = stack_top_p[-1]; } else if (opcode == CBC_PUSH_PROP_LITERAL_REFERENCE) { *stack_top_p++ = left_value; right_value = left_value; left_value = stack_top_p[-2]; } else { JERRY_ASSERT (opcode == CBC_PUSH_PROP_LITERAL_LITERAL_REFERENCE || opcode == CBC_PUSH_PROP_THIS_LITERAL_REFERENCE); *stack_top_p++ = left_value; *stack_top_p++ = right_value; } /* FALLTHRU */ } case VM_OC_PROP_PRE_INCR: case VM_OC_PROP_PRE_DECR: case VM_OC_PROP_POST_INCR: case VM_OC_PROP_POST_DECR: { result = vm_op_get_value (left_value, right_value); if (opcode < CBC_PRE_INCR) { left_value = ECMA_VALUE_UNDEFINED; right_value = ECMA_VALUE_UNDEFINED; } if (ECMA_IS_VALUE_ERROR (result)) { goto error; } if (opcode < CBC_PRE_INCR) { break; } stack_top_p += 2; left_value = result; right_value = ECMA_VALUE_UNDEFINED; /* FALLTHRU */ } case VM_OC_PRE_INCR: case VM_OC_PRE_DECR: case VM_OC_POST_INCR: case VM_OC_POST_DECR: { uint32_t opcode_flags = VM_OC_GROUP_GET_INDEX (opcode_data) - VM_OC_PROP_PRE_INCR; ecma_number_t result_number; byte_code_p = byte_code_start_p + 1; if (ecma_is_value_integer_number (left_value)) { result = left_value; left_value = ECMA_VALUE_UNDEFINED; ecma_integer_value_t int_value = (ecma_integer_value_t) result; ecma_integer_value_t int_increase = 0; if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG) { if (int_value > ECMA_INTEGER_NUMBER_MIN_SHIFTED) { int_increase = -(1 << ECMA_DIRECT_SHIFT); } } else if (int_value < ECMA_INTEGER_NUMBER_MAX_SHIFTED) { int_increase = 1 << ECMA_DIRECT_SHIFT; } if (JERRY_LIKELY (int_increase != 0)) { /* Postfix operators require the unmodifed number value. */ if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG) { POST_INCREASE_DECREASE_PUT_RESULT (result); } result = (ecma_value_t) (int_value + int_increase); break; } result_number = (ecma_number_t) ecma_get_integer_from_value (result); } else if (ecma_is_value_float_number (left_value)) { result = left_value; left_value = ECMA_VALUE_UNDEFINED; result_number = ecma_get_number_from_value (result); } else { result = ecma_op_to_numeric (left_value, &result_number, ECMA_TO_NUMERIC_ALLOW_BIGINT); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_free_value (left_value); left_value = ECMA_VALUE_UNDEFINED; #if JERRY_BUILTIN_BIGINT if (JERRY_UNLIKELY (ecma_is_value_bigint (result))) { ecma_bigint_unary_operation_type operation_type = ECMA_BIGINT_UNARY_INCREASE; if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG) { operation_type = ECMA_BIGINT_UNARY_DECREASE; } /* Postfix operators require the unmodifed number value. */ if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG) { POST_INCREASE_DECREASE_PUT_RESULT (result); result = ecma_bigint_unary (result, operation_type); } else { ecma_value_t original_value = result; result = ecma_bigint_unary (original_value, operation_type); ecma_free_value (original_value); } if (ECMA_IS_VALUE_ERROR (result)) { goto error; } break; } #endif /* JERRY_BUILTIN_BIGINT */ result = ecma_make_number_value (result_number); } ecma_number_t increase = ECMA_NUMBER_ONE; if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG) { /* For decrement operators */ increase = ECMA_NUMBER_MINUS_ONE; } /* Postfix operators require the unmodifed number value. */ if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG) { POST_INCREASE_DECREASE_PUT_RESULT (result); result = ecma_make_number_value (result_number + increase); break; } if (ecma_is_value_integer_number (result)) { result = ecma_make_number_value (result_number + increase); } else { result = ecma_update_float_number (result, result_number + increase); } break; } case VM_OC_ASSIGN: { result = left_value; left_value = ECMA_VALUE_UNDEFINED; break; } case VM_OC_MOV_IDENT: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index < register_end); JERRY_ASSERT (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))); ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); VM_GET_REGISTER (frame_ctx_p, literal_index) = left_value; continue; } case VM_OC_ASSIGN_PROP: { result = stack_top_p[-1]; stack_top_p[-1] = left_value; left_value = ECMA_VALUE_UNDEFINED; break; } case VM_OC_ASSIGN_PROP_THIS: { result = stack_top_p[-1]; stack_top_p[-1] = ecma_copy_value (frame_ctx_p->this_binding); *stack_top_p++ = left_value; left_value = ECMA_VALUE_UNDEFINED; break; } case VM_OC_RETURN_FUNCTION_END: { if (CBC_FUNCTION_GET_TYPE (bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT) { result = VM_GET_REGISTER (frame_ctx_p, 0); VM_GET_REGISTERS (frame_ctx_p)[0] = ECMA_VALUE_UNDEFINED; } else { result = ECMA_VALUE_UNDEFINED; } goto error; } case VM_OC_RETURN: { JERRY_ASSERT (opcode == CBC_RETURN || opcode == CBC_RETURN_WITH_LITERAL); result = left_value; left_value = ECMA_VALUE_UNDEFINED; goto error; } case VM_OC_THROW: { jcontext_raise_exception (left_value); result = ECMA_VALUE_ERROR; left_value = ECMA_VALUE_UNDEFINED; goto error; } case VM_OC_THROW_REFERENCE_ERROR: { result = ecma_raise_reference_error (ECMA_ERR_MSG ("Undefined reference")); goto error; } case VM_OC_EVAL: { JERRY_CONTEXT (status_flags) |= ECMA_STATUS_DIRECT_EVAL; JERRY_ASSERT ((*byte_code_p >= CBC_CALL && *byte_code_p <= CBC_CALL2_PROP_BLOCK) || (*byte_code_p == CBC_EXT_OPCODE && byte_code_p[1] >= CBC_EXT_SPREAD_CALL && byte_code_p[1] <= CBC_EXT_SPREAD_CALL_PROP_BLOCK)); continue; } case VM_OC_CALL: { frame_ctx_p->call_operation = VM_EXEC_CALL; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_NEW: { frame_ctx_p->call_operation = VM_EXEC_CONSTRUCT; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_ERROR: { JERRY_ASSERT (frame_ctx_p->byte_code_p[1] == CBC_EXT_ERROR); #if JERRY_DEBUGGER frame_ctx_p->byte_code_p = JERRY_CONTEXT (debugger_exception_byte_code_p); #endif /* JERRY_DEBUGGER */ result = ECMA_VALUE_ERROR; goto error; } case VM_OC_RESOLVE_BASE_FOR_CALL: { ecma_value_t this_value = stack_top_p[-3]; if (this_value == ECMA_VALUE_REGISTER_REF) { /* Lexical environment cannot be 'this' value. */ stack_top_p[-2] = ECMA_VALUE_UNDEFINED; stack_top_p[-3] = ECMA_VALUE_UNDEFINED; } else if (vm_get_implicit_this_value (&this_value)) { ecma_free_value (stack_top_p[-3]); stack_top_p[-3] = this_value; } continue; } case VM_OC_PROP_DELETE: { result = vm_op_delete_prop (left_value, right_value, is_strict); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } JERRY_ASSERT (ecma_is_value_boolean (result)); *stack_top_p++ = result; goto free_both_values; } case VM_OC_DELETE: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); if (literal_index < register_end) { *stack_top_p++ = ECMA_VALUE_FALSE; continue; } result = vm_op_delete_var (literal_start_p[literal_index], frame_ctx_p->lex_env_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } JERRY_ASSERT (ecma_is_value_boolean (result)); *stack_top_p++ = result; continue; } case VM_OC_JUMP: { byte_code_p = byte_code_start_p + branch_offset; continue; } case VM_OC_BRANCH_IF_STRICT_EQUAL: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); if (ecma_op_strict_equality_compare (value, stack_top_p[-1])) { byte_code_p = byte_code_start_p + branch_offset; ecma_free_value (*--stack_top_p); } ecma_free_value (value); continue; } case VM_OC_BRANCH_IF_TRUE: case VM_OC_BRANCH_IF_FALSE: case VM_OC_BRANCH_IF_LOGICAL_TRUE: case VM_OC_BRANCH_IF_LOGICAL_FALSE: { uint32_t opcode_flags = VM_OC_GROUP_GET_INDEX (opcode_data) - VM_OC_BRANCH_IF_TRUE; ecma_value_t value = *(--stack_top_p); bool boolean_value = ecma_op_to_boolean (value); if (opcode_flags & VM_OC_BRANCH_IF_FALSE_FLAG) { boolean_value = !boolean_value; } if (boolean_value) { byte_code_p = byte_code_start_p + branch_offset; if (opcode_flags & VM_OC_LOGICAL_BRANCH_FLAG) { /* "Push" the value back to the stack. */ ++stack_top_p; continue; } } ecma_fast_free_value (value); continue; } #if JERRY_ESNEXT case VM_OC_BRANCH_IF_NULLISH: { left_value = stack_top_p[-1]; if (!ecma_is_value_null (left_value) && !ecma_is_value_undefined (left_value)) { byte_code_p = byte_code_start_p + branch_offset; continue; } --stack_top_p; continue; } #endif /* JERRY_ESNEXT */ case VM_OC_PLUS: case VM_OC_MINUS: { result = opfunc_unary_operation (left_value, VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_PLUS); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_NOT: { *stack_top_p++ = ecma_make_boolean_value (!ecma_op_to_boolean (left_value)); JERRY_ASSERT (ecma_is_value_boolean (stack_top_p[-1])); goto free_left_value; } case VM_OC_BIT_NOT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_is_value_integer_number (left_value)) { *stack_top_p++ = (~ECMA_DIRECT_TYPE_MASK) ^ left_value; goto free_left_value; } result = do_number_bitwise_not (left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_VOID: { *stack_top_p++ = ECMA_VALUE_UNDEFINED; goto free_left_value; } case VM_OC_TYPEOF_IDENT: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index < ident_end); if (literal_index < register_end) { left_value = ecma_copy_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); } else { ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *ref_base_lex_env_p; result = ecma_op_get_value_lex_env_base (frame_ctx_p->lex_env_p, &ref_base_lex_env_p, name_p); if (ref_base_lex_env_p == NULL) { jcontext_release_exception (); result = ECMA_VALUE_UNDEFINED; } else if (ECMA_IS_VALUE_ERROR (result)) { goto error; } left_value = result; } /* FALLTHRU */ } case VM_OC_TYPEOF: { result = opfunc_typeof (left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_ADD: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer + right_integer)); continue; } if (ecma_is_value_float_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t new_value = (ecma_get_float_from_value (left_value) + ecma_get_number_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (left_value, new_value); ecma_free_number (right_value); continue; } if (ecma_is_value_float_number (right_value) && ecma_is_value_integer_number (left_value)) { ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) + ecma_get_float_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (right_value, new_value); continue; } result = opfunc_addition (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_SUB: { JERRY_STATIC_ASSERT (ECMA_INTEGER_NUMBER_MAX * 2 <= INT32_MAX && ECMA_INTEGER_NUMBER_MIN * 2 >= INT32_MIN, doubled_ecma_numbers_must_fit_into_int32_range); JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer - right_integer)); continue; } if (ecma_is_value_float_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t new_value = (ecma_get_float_from_value (left_value) - ecma_get_number_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (left_value, new_value); ecma_free_number (right_value); continue; } if (ecma_is_value_float_number (right_value) && ecma_is_value_integer_number (left_value)) { ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) - ecma_get_float_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (right_value, new_value); continue; } result = do_number_arithmetic (NUMBER_ARITHMETIC_SUBTRACTION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_MUL: { JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); JERRY_STATIC_ASSERT (ECMA_INTEGER_MULTIPLY_MAX * ECMA_INTEGER_MULTIPLY_MAX <= ECMA_INTEGER_NUMBER_MAX && -(ECMA_INTEGER_MULTIPLY_MAX * ECMA_INTEGER_MULTIPLY_MAX) >= ECMA_INTEGER_NUMBER_MIN, square_of_integer_multiply_max_must_fit_into_integer_value_range); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); if (-ECMA_INTEGER_MULTIPLY_MAX <= left_integer && left_integer <= ECMA_INTEGER_MULTIPLY_MAX && -ECMA_INTEGER_MULTIPLY_MAX <= right_integer && right_integer <= ECMA_INTEGER_MULTIPLY_MAX && left_integer != 0 && right_integer != 0) { *stack_top_p++ = ecma_integer_multiply (left_integer, right_integer); continue; } ecma_number_t multiply = (ecma_number_t) left_integer * (ecma_number_t) right_integer; *stack_top_p++ = ecma_make_number_value (multiply); continue; } if (ecma_is_value_float_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t new_value = (ecma_get_float_from_value (left_value) * ecma_get_number_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (left_value, new_value); ecma_free_number (right_value); continue; } if (ecma_is_value_float_number (right_value) && ecma_is_value_integer_number (left_value)) { ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) * ecma_get_float_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (right_value, new_value); continue; } result = do_number_arithmetic (NUMBER_ARITHMETIC_MULTIPLICATION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_DIV: { JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); result = do_number_arithmetic (NUMBER_ARITHMETIC_DIVISION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_MOD: { JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); if (right_integer != 0) { ecma_integer_value_t mod_result = left_integer % right_integer; if (mod_result != 0 || left_integer >= 0) { *stack_top_p++ = ecma_make_integer_value (mod_result); continue; } } } result = do_number_arithmetic (NUMBER_ARITHMETIC_REMAINDER, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } #if JERRY_ESNEXT case VM_OC_EXP: { result = do_number_arithmetic (NUMBER_ARITHMETIC_EXPONENTIATION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } #endif /* JERRY_ESNEXT */ case VM_OC_EQUAL: { result = opfunc_equality (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_NOT_EQUAL: { result = opfunc_equality (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = ecma_invert_boolean_value (result); goto free_both_values; } case VM_OC_STRICT_EQUAL: { bool is_equal = ecma_op_strict_equality_compare (left_value, right_value); result = ecma_make_boolean_value (is_equal); *stack_top_p++ = result; goto free_both_values; } case VM_OC_STRICT_NOT_EQUAL: { bool is_equal = ecma_op_strict_equality_compare (left_value, right_value); result = ecma_make_boolean_value (!is_equal); *stack_top_p++ = result; goto free_both_values; } case VM_OC_BIT_OR: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { *stack_top_p++ = left_value | right_value; continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_OR, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_BIT_XOR: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { *stack_top_p++ = left_value ^ right_value; continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_XOR, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_BIT_AND: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { *stack_top_p++ = left_value & right_value; continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_AND, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_LEFT_SHIFT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer << (right_integer & 0x1f))); continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_LEFT, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_RIGHT_SHIFT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_integer_value (left_integer >> (right_integer & 0x1f)); continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_RIGHT, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_UNS_RIGHT_SHIFT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { uint32_t left_uint32 = (uint32_t) ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_uint32_value (left_uint32 >> (right_integer & 0x1f)); continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_URIGHT, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_LESS: { if (ecma_are_values_integer_numbers (left_value, right_value)) { bool is_less = (ecma_integer_value_t) left_value < (ecma_integer_value_t) right_value; #if !JERRY_VM_EXEC_STOP /* This is a lookahead to the next opcode to improve performance. * If it is CBC_BRANCH_IF_TRUE_BACKWARD, execute it. */ if (*byte_code_p <= CBC_BRANCH_IF_TRUE_BACKWARD_3 && *byte_code_p >= CBC_BRANCH_IF_TRUE_BACKWARD) { byte_code_start_p = byte_code_p++; branch_offset_length = CBC_BRANCH_OFFSET_LENGTH (*byte_code_start_p); JERRY_ASSERT (branch_offset_length >= 1 && branch_offset_length <= 3); if (is_less) { branch_offset = *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length != 1)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length == 3)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); } } /* Note: The opcode is a backward branch. */ byte_code_p = byte_code_start_p - branch_offset; } else { byte_code_p += branch_offset_length; } continue; } #endif /* !JERRY_VM_EXEC_STOP */ *stack_top_p++ = ecma_make_boolean_value (is_less); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number < right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, true, false); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_GREATER: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value; ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value; *stack_top_p++ = ecma_make_boolean_value (left_integer > right_integer); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number > right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, false, false); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_LESS_EQUAL: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value; ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value; *stack_top_p++ = ecma_make_boolean_value (left_integer <= right_integer); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number <= right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, false, true); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_GREATER_EQUAL: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value; ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value; *stack_top_p++ = ecma_make_boolean_value (left_integer >= right_integer); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number >= right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, true, true); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_IN: { result = opfunc_in (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_INSTANCEOF: { result = opfunc_instanceof (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_BLOCK_CREATE_CONTEXT: { #if JERRY_ESNEXT ecma_value_t *stack_context_top_p; stack_context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; JERRY_ASSERT (stack_context_top_p == stack_top_p || stack_context_top_p == stack_top_p - 1); if (byte_code_start_p[0] != CBC_EXT_OPCODE) { branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); if (stack_context_top_p != stack_top_p) { /* Preserve the value of switch statement. */ stack_context_top_p[1] = stack_context_top_p[0]; } stack_context_top_p[0] = VM_CREATE_CONTEXT_WITH_ENV (VM_CONTEXT_BLOCK, branch_offset); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_BLOCK_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_BLOCK_CONTEXT_STACK_ALLOCATION; } else { JERRY_ASSERT (byte_code_start_p[1] == CBC_EXT_TRY_CREATE_ENV); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_TRY || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_CATCH || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_THROW || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN); JERRY_ASSERT (!(stack_context_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV)); stack_context_top_p[-1] |= VM_CONTEXT_HAS_LEX_ENV; } #else /* !JERRY_ESNEXT */ JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-2]) == VM_CONTEXT_CATCH && !(stack_top_p[-2] & VM_CONTEXT_HAS_LEX_ENV)); stack_top_p[-2] |= VM_CONTEXT_HAS_LEX_ENV; #endif /* JERRY_ESNEXT */ frame_ctx_p->lex_env_p = ecma_create_decl_lex_env (frame_ctx_p->lex_env_p); frame_ctx_p->lex_env_p->type_flags_refs |= ECMA_OBJECT_FLAG_BLOCK; continue; } case VM_OC_WITH: { ecma_value_t value = *(--stack_top_p); ecma_object_t *object_p; ecma_object_t *with_env_p; branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); result = ecma_op_to_object (value); ecma_free_value (value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } object_p = ecma_get_object_from_value (result); with_env_p = ecma_create_object_lex_env (frame_ctx_p->lex_env_p, object_p); ecma_deref_object (object_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_WITH_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_WITH_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT_WITH_ENV (VM_CONTEXT_WITH, branch_offset); with_env_p->type_flags_refs |= ECMA_OBJECT_FLAG_BLOCK; frame_ctx_p->lex_env_p = with_env_p; continue; } case VM_OC_FOR_IN_INIT: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_value_t expr_obj_value = ECMA_VALUE_UNDEFINED; ecma_collection_t *prop_names_p = opfunc_for_in (value, &expr_obj_value); ecma_free_value (value); if (prop_names_p == NULL) { #if JERRY_ESNEXT if (JERRY_UNLIKELY (ECMA_IS_VALUE_ERROR (expr_obj_value))) { result = expr_obj_value; goto error; } #endif /* JERRY_ESNEXT */ /* The collection is already released */ byte_code_p = byte_code_start_p + branch_offset; continue; } branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_IN, branch_offset); ECMA_SET_INTERNAL_VALUE_ANY_POINTER (stack_top_p[-2], prop_names_p); stack_top_p[-3] = 0; stack_top_p[-4] = expr_obj_value; #if JERRY_ESNEXT if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT) { /* No need to duplicate the first context. */ byte_code_p += 2; } #endif /* JERRY_ESNEXT */ continue; } case VM_OC_FOR_IN_GET_NEXT: { ecma_value_t *context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; ecma_collection_t *collection_p; collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, context_top_p[-2]); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_IN); uint32_t index = context_top_p[-3]; ecma_value_t *buffer_p = collection_p->buffer_p; *stack_top_p++ = buffer_p[index]; context_top_p[-3]++; continue; } case VM_OC_FOR_IN_HAS_NEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_collection_t *collection_p; collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, stack_top_p[-2]); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_IN); ecma_value_t *buffer_p = collection_p->buffer_p; ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[-4]); uint32_t index = stack_top_p[-3]; while (index < collection_p->item_count) { ecma_string_t *prop_name_p = ecma_get_prop_name_from_value (buffer_p[index]); result = ecma_op_object_has_property (object_p, prop_name_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } if (JERRY_LIKELY (ecma_is_value_true (result))) { byte_code_p = byte_code_start_p + branch_offset; break; } ecma_deref_ecma_string (prop_name_p); index++; } if (index == collection_p->item_count) { ecma_deref_object (object_p); ecma_collection_destroy (collection_p); VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION); stack_top_p -= PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION; } else { stack_top_p[-3] = index; } continue; } #if JERRY_ESNEXT case VM_OC_FOR_OF_INIT: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_value_t next_method; ecma_value_t iterator = ecma_op_get_iterator (value, ECMA_VALUE_SYNC_ITERATOR, &next_method); ecma_free_value (value); if (ECMA_IS_VALUE_ERROR (iterator)) { result = iterator; goto error; } result = ecma_op_iterator_step (iterator, next_method); if (ECMA_IS_VALUE_ERROR (result)) { ecma_free_value (iterator); ecma_free_value (next_method); goto error; } if (ecma_is_value_false (result)) { ecma_free_value (iterator); ecma_free_value (next_method); byte_code_p = byte_code_start_p + branch_offset; continue; } ecma_value_t next_value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (next_value)) { result = next_value; ecma_free_value (iterator); ecma_free_value (next_method); goto error; } branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_OF, branch_offset) | VM_CONTEXT_CLOSE_ITERATOR; stack_top_p[-2] = next_value; stack_top_p[-3] = iterator; stack_top_p[-4] = next_method; if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT) { /* No need to duplicate the first context. */ byte_code_p += 2; } continue; } case VM_OC_FOR_OF_GET_NEXT: { ecma_value_t *context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_OF || VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_AWAIT_OF); JERRY_ASSERT (context_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR); *stack_top_p++ = context_top_p[-2]; context_top_p[-2] = ECMA_VALUE_UNDEFINED; continue; } case VM_OC_FOR_OF_HAS_NEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_OF); JERRY_ASSERT (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR); stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = ecma_op_iterator_step (stack_top_p[-3], stack_top_p[-4]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } if (ecma_is_value_false (result)) { ecma_free_value (stack_top_p[-2]); ecma_free_value (stack_top_p[-3]); ecma_free_value (stack_top_p[-4]); VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION); stack_top_p -= PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION; continue; } ecma_value_t next_value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (next_value)) { result = next_value; goto error; } JERRY_ASSERT (stack_top_p[-2] == ECMA_VALUE_UNDEFINED); stack_top_p[-1] |= VM_CONTEXT_CLOSE_ITERATOR; stack_top_p[-2] = next_value; byte_code_p = byte_code_start_p + branch_offset; continue; } case VM_OC_FOR_AWAIT_OF_INIT: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_value_t next_method; result = ecma_op_get_iterator (value, ECMA_VALUE_ASYNC_ITERATOR, &next_method); ecma_free_value (value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_value_t iterator = result; result = ecma_op_iterator_next (result, next_method, ECMA_VALUE_EMPTY); if (ECMA_IS_VALUE_ERROR (result)) { ecma_free_value (iterator); ecma_free_value (next_method); goto error; } branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_AWAIT_OF_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_FOR_AWAIT_OF_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_AWAIT_OF, branch_offset); stack_top_p[-2] = ECMA_VALUE_UNDEFINED; stack_top_p[-3] = iterator; stack_top_p[-4] = next_method; if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT) { /* No need to duplicate the first context. */ byte_code_p += 2; } frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; uint16_t extra_flags = (ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD | (ECMA_AWAIT_FOR_NEXT << ECMA_AWAIT_STATE_SHIFT)); if (CBC_FUNCTION_GET_TYPE (bytecode_header_p->status_flags) == CBC_FUNCTION_ASYNC_GENERATOR || (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE)) { ecma_extended_object_t *executable_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); result = ecma_promise_async_await (executable_object_p, result); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } executable_object_p->u.cls.u2.executable_obj_flags |= extra_flags; return ECMA_VALUE_UNDEFINED; } result = opfunc_async_create_and_await (frame_ctx_p, result, extra_flags); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } return result; } case VM_OC_FOR_AWAIT_OF_HAS_NEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_AWAIT_OF); JERRY_ASSERT (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR); stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = ecma_op_iterator_next (stack_top_p[-3], stack_top_p[-4], ECMA_VALUE_EMPTY); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_extended_object_t *executable_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); result = ecma_promise_async_await (executable_object_p, result); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } uint16_t extra_flags = (ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD | (ECMA_AWAIT_FOR_NEXT << ECMA_AWAIT_STATE_SHIFT)); executable_object_p->u.cls.u2.executable_obj_flags |= extra_flags; frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_start_p + branch_offset; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ case VM_OC_TRY: { /* Try opcode simply creates the try context. */ branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_TRY_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_TRY_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_TRY, branch_offset); continue; } case VM_OC_CATCH: { /* Catches are ignored and turned to jumps. */ JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_TRY); byte_code_p = byte_code_start_p + branch_offset; continue; } case VM_OC_FINALLY: { branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_TRY || VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_CATCH); if (stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV) { ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); frame_ctx_p->lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); ecma_deref_object (lex_env_p); } VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FINALLY_CONTEXT_EXTRA_STACK_ALLOCATION); stack_top_p += PARSER_FINALLY_CONTEXT_EXTRA_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FINALLY_JUMP, branch_offset); stack_top_p[-2] = (ecma_value_t) branch_offset; continue; } case VM_OC_CONTEXT_END: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (!(stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR)); ecma_value_t context_type = VM_GET_CONTEXT_TYPE (stack_top_p[-1]); if (!VM_CONTEXT_IS_FINALLY (context_type)) { stack_top_p = vm_stack_context_abort (frame_ctx_p, stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); continue; } #if JERRY_ESNEXT if (stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV) { ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); frame_ctx_p->lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); ecma_deref_object (lex_env_p); } #endif /* JERRY_ESNEXT */ VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FINALLY_CONTEXT_STACK_ALLOCATION); stack_top_p -= PARSER_FINALLY_CONTEXT_STACK_ALLOCATION; if (context_type == VM_CONTEXT_FINALLY_RETURN) { result = *stack_top_p; goto error; } if (context_type == VM_CONTEXT_FINALLY_THROW) { jcontext_raise_exception (*stack_top_p); #if JERRY_VM_THROW JERRY_CONTEXT (status_flags) |= ECMA_STATUS_ERROR_THROWN; #endif /* JERRY_VM_THROW */ result = ECMA_VALUE_ERROR; #if JERRY_DEBUGGER JERRY_DEBUGGER_SET_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN); #endif /* JERRY_DEBUGGER */ goto error; } JERRY_ASSERT (context_type == VM_CONTEXT_FINALLY_JUMP); uint32_t jump_target = *stack_top_p; vm_stack_found_type type = vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_JUMP, jump_target); stack_top_p = frame_ctx_p->stack_top_p; switch (type) { case VM_CONTEXT_FOUND_FINALLY: { byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = jump_target; break; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_ERROR: { JERRY_ASSERT (jcontext_has_pending_exception ()); result = ECMA_VALUE_ERROR; goto error; } case VM_CONTEXT_FOUND_AWAIT: { JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = jump_target; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { byte_code_p = frame_ctx_p->byte_code_start_p + jump_target; break; } } JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); continue; } case VM_OC_JUMP_AND_EXIT_CONTEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (!jcontext_has_pending_exception ()); branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); vm_stack_found_type type = vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_JUMP, (uint32_t) branch_offset); stack_top_p = frame_ctx_p->stack_top_p; switch (type) { case VM_CONTEXT_FOUND_FINALLY: { byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = (uint32_t) branch_offset; break; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_ERROR: { JERRY_ASSERT (jcontext_has_pending_exception ()); result = ECMA_VALUE_ERROR; goto error; } case VM_CONTEXT_FOUND_AWAIT: { JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = (uint32_t) branch_offset; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { byte_code_p = frame_ctx_p->byte_code_start_p + branch_offset; break; } } JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); continue; } #if JERRY_MODULE_SYSTEM case VM_OC_MODULE_IMPORT: { left_value = *(--stack_top_p); ecma_value_t user_value = ECMA_VALUE_UNDEFINED; ecma_value_t script_value = ((cbc_uint8_arguments_t *) bytecode_header_p)->script_value; #if JERRY_SNAPSHOT_EXEC if (JERRY_UNLIKELY (!(bytecode_header_p->status_flags & CBC_CODE_FLAGS_STATIC_FUNCTION))) { #endif /* JERRY_SNAPSHOT_EXEC */ cbc_script_t *script_p = ECMA_GET_INTERNAL_VALUE_POINTER (cbc_script_t, script_value); if (script_p->refs_and_type & CBC_SCRIPT_HAS_USER_VALUE) { user_value = CBC_SCRIPT_GET_USER_VALUE (script_p); } #if JERRY_SNAPSHOT_EXEC } #endif /* JERRY_SNAPSHOT_EXEC */ result = ecma_module_import (left_value, user_value); ecma_free_value (left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; continue; } case VM_OC_MODULE_IMPORT_META: { ecma_value_t script_value = ((cbc_uint8_arguments_t *) bytecode_header_p)->script_value; cbc_script_t *script_p = ECMA_GET_INTERNAL_VALUE_POINTER (cbc_script_t, script_value); JERRY_ASSERT (script_p->refs_and_type & CBC_SCRIPT_HAS_IMPORT_META); ecma_value_t import_meta = CBC_SCRIPT_GET_IMPORT_META (script_p, script_p->refs_and_type); ecma_object_t *import_meta_object_p = ecma_get_object_from_value (import_meta); if (ecma_get_object_type (import_meta_object_p) != ECMA_OBJECT_TYPE_GENERAL) { JERRY_ASSERT (ecma_object_class_is (import_meta_object_p, ECMA_OBJECT_CLASS_MODULE)); ecma_value_t module = import_meta; import_meta_object_p = ecma_create_object (NULL, 0, ECMA_OBJECT_TYPE_GENERAL); import_meta = ecma_make_object_value (import_meta_object_p); if (JERRY_CONTEXT (module_import_meta_callback_p) != NULL) { void *user_p = JERRY_CONTEXT (module_import_meta_callback_user_p); JERRY_CONTEXT (module_import_meta_callback_p) (module, import_meta, user_p); } CBC_SCRIPT_GET_IMPORT_META (script_p, script_p->refs_and_type) = import_meta; } else { ecma_ref_object (import_meta_object_p); } *stack_top_p++ = import_meta; continue; } #endif /* JERRY_MODULE_SYSTEM */ #if JERRY_DEBUGGER case VM_OC_BREAKPOINT_ENABLED: { if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_IGNORE) { continue; } JERRY_ASSERT (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED); JERRY_ASSERT (!(frame_ctx_p->shared_p->bytecode_header_p->status_flags & CBC_CODE_FLAGS_DEBUGGER_IGNORE)); frame_ctx_p->byte_code_p = byte_code_start_p; jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { result = ECMA_VALUE_ERROR; goto error; } continue; } case VM_OC_BREAKPOINT_DISABLED: { if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_IGNORE) { continue; } JERRY_ASSERT (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED); JERRY_ASSERT (!(frame_ctx_p->shared_p->bytecode_header_p->status_flags & CBC_CODE_FLAGS_DEBUGGER_IGNORE)); frame_ctx_p->byte_code_p = byte_code_start_p; if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_STOP) && (JERRY_CONTEXT (debugger_stop_context) == NULL || JERRY_CONTEXT (debugger_stop_context) == JERRY_CONTEXT (vm_top_context_p))) { jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { result = ECMA_VALUE_ERROR; goto error; } continue; } if (JERRY_CONTEXT (debugger_message_delay) > 0) { JERRY_CONTEXT (debugger_message_delay)--; continue; } JERRY_CONTEXT (debugger_message_delay) = JERRY_DEBUGGER_MESSAGE_FREQUENCY; if (jerry_debugger_receive (NULL)) { continue; } if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_STOP) && (JERRY_CONTEXT (debugger_stop_context) == NULL || JERRY_CONTEXT (debugger_stop_context) == JERRY_CONTEXT (vm_top_context_p))) { jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { result = ECMA_VALUE_ERROR; goto error; } } continue; } #endif /* JERRY_DEBUGGER */ case VM_OC_NONE: default: { JERRY_ASSERT (VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_NONE); jerry_fatal (ERR_DISABLED_BYTE_CODE); } } JERRY_ASSERT (VM_OC_HAS_PUT_RESULT (opcode_data)); if (opcode_data & VM_OC_PUT_IDENT) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); if (literal_index < register_end) { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); VM_GET_REGISTER (frame_ctx_p, literal_index) = result; if (opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK)) { result = ecma_fast_copy_value (result); } } else { ecma_string_t *var_name_str_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_value_t put_value_result = ecma_op_put_value_lex_env_base (frame_ctx_p->lex_env_p, var_name_str_p, is_strict, result); if (ECMA_IS_VALUE_ERROR (put_value_result)) { ecma_free_value (result); result = put_value_result; goto error; } if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))) { ecma_fast_free_value (result); } } } else if (opcode_data & VM_OC_PUT_REFERENCE) { ecma_value_t property = *(--stack_top_p); ecma_value_t base = *(--stack_top_p); if (base == ECMA_VALUE_REGISTER_REF) { property = (ecma_value_t) ecma_get_integer_from_value (property); ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, property)); VM_GET_REGISTER (frame_ctx_p, property) = result; if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))) { goto free_both_values; } result = ecma_fast_copy_value (result); } else { ecma_value_t set_value_result = vm_op_set_value (base, property, result, is_strict); if (ECMA_IS_VALUE_ERROR (set_value_result)) { ecma_free_value (result); result = set_value_result; goto error; } if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))) { ecma_fast_free_value (result); goto free_both_values; } } } if (opcode_data & VM_OC_PUT_STACK) { *stack_top_p++ = result; } else if (opcode_data & VM_OC_PUT_BLOCK) { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, 0)); VM_GET_REGISTERS (frame_ctx_p)[0] = result; } free_both_values: ecma_fast_free_value (right_value); free_left_value: ecma_fast_free_value (left_value); } error: ecma_fast_free_value (left_value); ecma_fast_free_value (right_value); if (ECMA_IS_VALUE_ERROR (result)) { JERRY_ASSERT (jcontext_has_pending_exception ()); ecma_value_t *stack_bottom_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; while (stack_top_p > stack_bottom_p) { ecma_value_t stack_item = *(--stack_top_p); #if JERRY_ESNEXT if (stack_item == ECMA_VALUE_RELEASE_LEX_ENV) { opfunc_pop_lexical_environment (frame_ctx_p); continue; } #endif /* JERRY_ESNEXT */ ecma_fast_free_value (stack_item); } #if JERRY_VM_THROW if (!(JERRY_CONTEXT (status_flags) & ECMA_STATUS_ERROR_THROWN)) { JERRY_CONTEXT (status_flags) |= ECMA_STATUS_ERROR_THROWN; jerry_vm_throw_callback_t vm_throw_callback_p = JERRY_CONTEXT (vm_throw_callback_p); if (vm_throw_callback_p != NULL) { vm_throw_callback_p (JERRY_CONTEXT (error_value), JERRY_CONTEXT (vm_throw_callback_user_p)); } } #endif /* JERRY_VM_THROW */ #if JERRY_DEBUGGER const uint32_t dont_stop = (JERRY_DEBUGGER_VM_IGNORE_EXCEPTION | JERRY_DEBUGGER_VM_IGNORE | JERRY_DEBUGGER_VM_EXCEPTION_THROWN); if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) && !(frame_ctx_p->shared_p->bytecode_header_p->status_flags & (CBC_CODE_FLAGS_DEBUGGER_IGNORE | CBC_CODE_FLAGS_STATIC_FUNCTION)) && !(JERRY_CONTEXT (debugger_flags) & dont_stop)) { /* Save the error to a local value, because the engine enters breakpoint mode after, therefore an evaluation error, or user-created error throw would overwrite it. */ ecma_value_t current_error_value = JERRY_CONTEXT (error_value); if (jerry_debugger_send_exception_string (current_error_value)) { jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_EXCEPTION_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { ecma_free_value (current_error_value); } else { JERRY_CONTEXT (error_value) = current_error_value; } JERRY_DEBUGGER_SET_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN); } } #endif /* JERRY_DEBUGGER */ } JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); if (frame_ctx_p->context_depth == 0) { /* In most cases there is no context. */ frame_ctx_p->call_operation = VM_NO_EXEC_OP; return result; } if (!ECMA_IS_VALUE_ERROR (result)) { switch (vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_RETURN, 0)) { case VM_CONTEXT_FOUND_FINALLY: { stack_top_p = frame_ctx_p->stack_top_p; byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); stack_top_p[-2] = result; continue; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_ERROR: { JERRY_ASSERT (jcontext_has_pending_exception ()); ecma_free_value (result); stack_top_p = frame_ctx_p->stack_top_p; result = ECMA_VALUE_ERROR; break; } case VM_CONTEXT_FOUND_AWAIT: { stack_top_p = frame_ctx_p->stack_top_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN); stack_top_p[-2] = result; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { goto finish; } } } JERRY_ASSERT (jcontext_has_pending_exception ()); if (!jcontext_has_pending_abort ()) { switch (vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_THROW, 0)) { case VM_CONTEXT_FOUND_FINALLY: { stack_top_p = frame_ctx_p->stack_top_p; byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (!(stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV)); #if JERRY_DEBUGGER JERRY_DEBUGGER_CLEAR_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN); #endif /* JERRY_DEBUGGER */ result = jcontext_take_exception (); if (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_THROW) { stack_top_p[-2] = result; continue; } JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_CATCH); *stack_top_p++ = result; continue; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_AWAIT: { JERRY_ASSERT (VM_GET_CONTEXT_TYPE (frame_ctx_p->stack_top_p[-1]) == VM_CONTEXT_FINALLY_THROW); return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { break; } } } else { do { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); stack_top_p = vm_stack_context_abort (frame_ctx_p, stack_top_p); } while (frame_ctx_p->context_depth > 0); } finish: frame_ctx_p->call_operation = VM_NO_EXEC_OP; return result; } } /* vm_loop */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix for-in collection cleanup on abrupt 'has' result (#4807) This patch fixes #4747 JerryScript-DCO-1.0-Signed-off-by: Robert Fancsik robert.fancsik@h-lab.eu'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent) { GF_Err e; u32 i, k, offsetInChunk, size, chunk_num; GF_ChunkOffsetBox *stco; GF_ChunkLargeOffsetBox *co64; GF_StscEntry *ent; (*offset) = 0; (*chunkNumber) = (*descIndex) = 0; if (out_ent) (*out_ent) = NULL; if (!stbl || !sampleNumber) return GF_BAD_PARAM; if (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE; if (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) { ent = &stbl->SampleToChunk->entries[sampleNumber-1]; if (!ent) return GF_BAD_PARAM; (*descIndex) = ent->sampleDescriptionIndex; (*chunkNumber) = sampleNumber; if (out_ent) *out_ent = ent; if ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) { stco = (GF_ChunkOffsetBox *)stbl->ChunkOffset; if (!stco->offsets) return GF_ISOM_INVALID_FILE; (*offset) = (u64) stco->offsets[sampleNumber - 1]; } else { co64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset; if (!co64->offsets) return GF_ISOM_INVALID_FILE; (*offset) = co64->offsets[sampleNumber - 1]; } return GF_OK; } //check our cache: if desired sample is at or above current cache entry, start from here if (stbl->SampleToChunk->firstSampleInCurrentChunk && (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) { i = stbl->SampleToChunk->currentIndex; ent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex]; GetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl); k = stbl->SampleToChunk->currentChunk; } //otherwise start from first entry else { i = 0; stbl->SampleToChunk->currentIndex = 0; stbl->SampleToChunk->currentChunk = 1; stbl->SampleToChunk->ghostNumber = 1; stbl->SampleToChunk->firstSampleInCurrentChunk = 1; ent = &stbl->SampleToChunk->entries[0]; GetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl); k = stbl->SampleToChunk->currentChunk; } //first get the chunk for (; i < stbl->SampleToChunk->nb_entries; i++) { assert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber); //corrupted file (less sample2chunk info than sample count if (k > stbl->SampleToChunk->ghostNumber) { return GF_ISOM_INVALID_FILE; } //check if sample is in current chunk u32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k; u32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk; if (ent->samplesPerChunk) nb_chunks_for_sample /= ent->samplesPerChunk; if ( (nb_chunks_for_sample <= max_chunks_in_entry) && (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber) ) { stbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk; stbl->SampleToChunk->currentChunk += nb_chunks_for_sample; goto sample_found; } max_chunks_in_entry += 1; stbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk; stbl->SampleToChunk->currentChunk += max_chunks_in_entry; //not in this entry, get the next entry if not the last one if (i+1 != stbl->SampleToChunk->nb_entries) { ent = &stbl->SampleToChunk->entries[i+1]; //update the GhostNumber GetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl); //update the entry in our cache stbl->SampleToChunk->currentIndex = i+1; stbl->SampleToChunk->currentChunk = 1; k = 1; } } //if we get here, gasp, the sample was not found return GF_ISOM_INVALID_FILE; sample_found: (*descIndex) = ent->sampleDescriptionIndex; (*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1; if (out_ent) *out_ent = ent; if (! *chunkNumber) return GF_ISOM_INVALID_FILE; //ok, get the size of all the previous samples in the chunk offsetInChunk = 0; //constant size if (stbl->SampleSize && stbl->SampleSize->sampleSize) { u32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk; offsetInChunk += diff * stbl->SampleSize->sampleSize; } else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) { offsetInChunk = stbl->r_last_offset_in_chunk; } else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) { e = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size); if (e) return e; stbl->r_last_offset_in_chunk += size; stbl->r_last_sample_num = sampleNumber; offsetInChunk = stbl->r_last_offset_in_chunk; } else { //warning, firstSampleInChunk is at least 1 - not 0 for (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) { e = stbl_GetSampleSize(stbl->SampleSize, i, &size); if (e) return e; offsetInChunk += size; } stbl->r_last_chunk_num = chunk_num; stbl->r_last_sample_num = sampleNumber; stbl->r_last_offset_in_chunk = offsetInChunk; } //OK, that's the size of our offset in the chunk //now get the chunk if ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) { stco = (GF_ChunkOffsetBox *)stbl->ChunkOffset; if (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE; (*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk; } else { co64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset; if (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE; (*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk; } return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-401'], 'message': 'fixed #1705'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefragRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DefragInOrderSimpleTest", DefragInOrderSimpleTest); UtRegisterTest("DefragReverseSimpleTest", DefragReverseSimpleTest); UtRegisterTest("DefragSturgesNovakBsdTest", DefragSturgesNovakBsdTest); UtRegisterTest("DefragSturgesNovakLinuxTest", DefragSturgesNovakLinuxTest); UtRegisterTest("DefragSturgesNovakWindowsTest", DefragSturgesNovakWindowsTest); UtRegisterTest("DefragSturgesNovakSolarisTest", DefragSturgesNovakSolarisTest); UtRegisterTest("DefragSturgesNovakFirstTest", DefragSturgesNovakFirstTest); UtRegisterTest("DefragSturgesNovakLastTest", DefragSturgesNovakLastTest); UtRegisterTest("DefragIPv4NoDataTest", DefragIPv4NoDataTest); UtRegisterTest("DefragIPv4TooLargeTest", DefragIPv4TooLargeTest); UtRegisterTest("IPV6DefragInOrderSimpleTest", IPV6DefragInOrderSimpleTest); UtRegisterTest("IPV6DefragReverseSimpleTest", IPV6DefragReverseSimpleTest); UtRegisterTest("IPV6DefragSturgesNovakBsdTest", IPV6DefragSturgesNovakBsdTest); UtRegisterTest("IPV6DefragSturgesNovakLinuxTest", IPV6DefragSturgesNovakLinuxTest); UtRegisterTest("IPV6DefragSturgesNovakWindowsTest", IPV6DefragSturgesNovakWindowsTest); UtRegisterTest("IPV6DefragSturgesNovakSolarisTest", IPV6DefragSturgesNovakSolarisTest); UtRegisterTest("IPV6DefragSturgesNovakFirstTest", IPV6DefragSturgesNovakFirstTest); UtRegisterTest("IPV6DefragSturgesNovakLastTest", IPV6DefragSturgesNovakLastTest); UtRegisterTest("DefragVlanTest", DefragVlanTest); UtRegisterTest("DefragVlanQinQTest", DefragVlanQinQTest); UtRegisterTest("DefragTrackerReuseTest", DefragTrackerReuseTest); UtRegisterTest("DefragTimeoutTest", DefragTimeoutTest); UtRegisterTest("DefragMfIpv4Test", DefragMfIpv4Test); UtRegisterTest("DefragMfIpv6Test", DefragMfIpv6Test); #endif /* UNITTESTS */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host.'</s>
<s>[INST] Given the following code containing errors, provide 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 Phase2() final { Local<Context> context_handle = Deref(context); Context::Scope context_scope{context_handle}; Local<Value> key_inner = key->CopyInto(); Local<Object> object = Local<Object>::Cast(Deref(reference)); // Delete key before transferring in, potentially freeing up some v8 heap Unmaybe(object->Delete(context_handle, key_inner)); Local<Value> val_inner = val->TransferIn(); did_set = Unmaybe(object->Set(context_handle, key_inner, val_inner)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-913'], 'message': 'Don't invoke accessors or proxies via Reference functions'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr, UINT32 ChannelId, wStream* data) { UINT status = CHANNEL_RC_OK; DVCMAN_CHANNEL* channel; size_t dataSize = Stream_GetRemainingLength(data); channel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId); if (!channel) { /* Windows 8.1 tries to open channels not created. * Ignore cases like this. */ WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %"PRIu32" not found!", ChannelId); return CHANNEL_RC_OK; } if (channel->dvc_data) { /* Fragmented data */ if (Stream_GetPosition(channel->dvc_data) + dataSize > (UINT32) Stream_Capacity( channel->dvc_data)) { WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!"); Stream_Release(channel->dvc_data); channel->dvc_data = NULL; return ERROR_INVALID_DATA; } Stream_Write(channel->dvc_data, Stream_Pointer(data), dataSize); if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length) { Stream_SealLength(channel->dvc_data); Stream_SetPosition(channel->dvc_data, 0); status = channel->channel_callback->OnDataReceived(channel->channel_callback, channel->dvc_data); Stream_Release(channel->dvc_data); channel->dvc_data = NULL; } } else { status = channel->channel_callback->OnDataReceived(channel->channel_callback, data); } return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix for #4866: Added additional length checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (index >= dtypes_.size()) { return Status(errors::InvalidArgument( "Index '", index, "' for key '", key.scalar<int64>()(), "' was out of bounds '", dtypes_.size(), "'.")); } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops. PiperOrigin-RevId: 387738023 Change-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (tuple[index].has_value()) { return Status(errors::InvalidArgument( "The tensor for index '", index, "' for key '", key.scalar<int64>()(), "' was already initialized '", dtypes_.size(), "'.")); } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops. PiperOrigin-RevId: 387738023 Change-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/, const std::string& params, const std::string& provider) const { #if defined(BOTAN_HAS_BEARSSL) if(provider == "bearssl" || provider.empty()) { try { return make_bearssl_ecdsa_sig_op(*this, params); } catch(Lookup_Error& e) { if(provider == "bearssl") throw; } } #endif #if defined(BOTAN_HAS_OPENSSL) if(provider == "openssl" || provider.empty()) { try { return make_openssl_ecdsa_sig_op(*this, params); } catch(Lookup_Error& e) { if(provider == "openssl") throw; } } #endif if(provider == "base" || provider.empty()) return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params)); throw Provider_Not_Found(algo_name(), provider); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'</s>
<s>[INST] Given the following code containing errors, provide 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 filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; LutContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; AVFrame *out; uint8_t *inrow, *outrow, *inrow0, *outrow0; int i, j, plane, direct = 0; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } if (s->is_rgb) { /* packed */ inrow0 = in ->data[0]; outrow0 = out->data[0]; for (i = 0; i < in->height; i ++) { int w = inlink->w; const uint8_t (*tab)[256] = (const uint8_t (*)[256])s->lut; inrow = inrow0; outrow = outrow0; for (j = 0; j < w; j++) { switch (s->step) { case 4: outrow[3] = tab[3][inrow[3]]; // Fall-through case 3: outrow[2] = tab[2][inrow[2]]; // Fall-through case 2: outrow[1] = tab[1][inrow[1]]; // Fall-through default: outrow[0] = tab[0][inrow[0]]; } outrow += s->step; inrow += s->step; } inrow0 += in ->linesize[0]; outrow0 += out->linesize[0]; } } else { /* planar */ for (plane = 0; plane < 4 && in->data[plane]; plane++) { int vsub = plane == 1 || plane == 2 ? s->vsub : 0; int hsub = plane == 1 || plane == 2 ? s->hsub : 0; int h = FF_CEIL_RSHIFT(inlink->h, vsub); int w = FF_CEIL_RSHIFT(inlink->w, hsub); inrow = in ->data[plane]; outrow = out->data[plane]; for (i = 0; i < h; i++) { const uint8_t *tab = s->lut[plane]; for (j = 0; j < w; j++) outrow[j] = tab[inrow[j]]; inrow += in ->linesize[plane]; outrow += out->linesize[plane]; } } } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool parse_reconnect(struct pool *pool, json_t *val) { char *sockaddr_url, *stratum_port, *tmp; char *url, *port, address[256]; if (opt_disable_client_reconnect) { applog(LOG_WARNING, "Stratum client.reconnect forbidden, aborting."); return false; } memset(address, 0, 255); url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; sprintf(address, "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'stratum: parse_reconnect(): treat pool-sent URL as untrusted. Thanks to Mick Ayzenberg <mick@dejavusecurity.com> for reminding that this existed and highlighting the offender. Also to Luke-jr for actually fixing this in bfgminer. :D'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: main(int argc, char **argv) { const char *safepath = SAFE_PATH; const char *confpath = NULL; char *shargv[] = { NULL, NULL }; char *sh; const char *cmd; char cmdline[LINE_MAX]; char myname[_PW_NAME_LEN + 1]; struct passwd *original_pw, *target_pw; struct rule *rule; uid_t uid; uid_t target = 0; gid_t groups[NGROUPS_MAX + 1]; int ngroups; int i, ch; int sflag = 0; int nflag = 0; char cwdpath[PATH_MAX]; const char *cwd; char *login_style = NULL; char **envp; #ifndef linux setprogname("doas"); #endif #ifndef linux closefrom(STDERR_FILENO + 1); #endif uid = getuid(); while ((ch = getopt(argc, argv, "a:C:nsu:")) != -1) { /* while ((ch = getopt(argc, argv, "a:C:Lnsu:")) != -1) { */ switch (ch) { case 'a': login_style = optarg; break; case 'C': confpath = optarg; break; /* case 'L': i = open("/dev/tty", O_RDWR); if (i != -1) ioctl(i, TIOCCLRVERAUTH); exit(i != -1); */ case 'u': if (parseuid(optarg, &target) != 0) errx(1, "unknown user"); break; case 'n': nflag = 1; break; case 's': sflag = 1; break; default: usage(); break; } } argv += optind; argc -= optind; if (confpath) { if (sflag) usage(); } else if ((!sflag && !argc) || (sflag && argc)) usage(); original_pw = getpwuid(uid); if (! original_pw) err(1, "getpwuid failed"); if (strlcpy(myname, original_pw->pw_name, sizeof(myname)) >= sizeof(myname)) errx(1, "pw_name too long"); ngroups = getgroups(NGROUPS_MAX, groups); if (ngroups == -1) err(1, "can't get groups"); groups[ngroups++] = getgid(); if (sflag) { sh = getenv("SHELL"); if (sh == NULL || *sh == '\0') { shargv[0] = strdup(original_pw->pw_shell); if (shargv[0] == NULL) err(1, NULL); } else shargv[0] = sh; argv = shargv; argc = 1; } if (confpath) { checkconfig(confpath, argc, argv, uid, groups, ngroups, target); exit(1); /* fail safe */ } if (geteuid()) errx(1, "not installed setuid"); parseconfig(DOAS_CONF, 1); /* cmdline is used only for logging, no need to abort on truncate */ (void)strlcpy(cmdline, argv[0], sizeof(cmdline)); for (i = 1; i < argc; i++) { if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline)) break; if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline)) break; } cmd = argv[0]; if (!permit(uid, groups, ngroups, &rule, target, cmd, (const char **)argv + 1)) { syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed command for %s: %s", myname, cmdline); errc(1, EPERM, NULL); } if (!(rule->options & NOPASS)) { if (nflag) errx(1, "Authorization required"); #if defined(USE_BSD_AUTH) authuser(myname, login_style, rule->options & PERSIST); #elif defined(USE_PAM) #define PAM_END(msg) do { \ syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); \ warnx("%s: %s", msg, pam_strerror(pamh, pam_err)); \ pam_end(pamh, pam_err); \ exit(EXIT_FAILURE); \ } while (/*CONSTCOND*/0) pam_handle_t *pamh = NULL; int pam_err; /* #ifndef linux */ int temp_stdin; /* openpam_ttyconv checks if stdin is a terminal and * if it is then does not bother to open /dev/tty. * The result is that PAM writes the password prompt * directly to stdout. In scenarios where stdin is a * terminal, but stdout is redirected to a file * e.g. by running doas ls &> ls.out interactively, * the password prompt gets written to ls.out as well. * By closing stdin first we forces PAM to read/write * to/from the terminal directly. We restore stdin * after authenticating. */ temp_stdin = dup(STDIN_FILENO); if (temp_stdin == -1) err(1, "dup"); close(STDIN_FILENO); /* #else */ /* force password prompt to display on stderr, not stdout */ int temp_stdout = dup(1); if (temp_stdout == -1) err(1, "dup"); close(1); if (dup2(2, 1) == -1) err(1, "dup2"); /* #endif */ pam_err = pam_start("doas", myname, &pamc, &pamh); if (pam_err != PAM_SUCCESS) { if (pamh != NULL) PAM_END("pam_start"); syslog(LOG_ERR, "pam_start failed: %s", pam_strerror(pamh, pam_err)); errx(EXIT_FAILURE, "pam_start failed"); } switch (pam_err = pam_authenticate(pamh, PAM_SILENT)) { case PAM_SUCCESS: switch (pam_err = pam_acct_mgmt(pamh, PAM_SILENT)) { case PAM_SUCCESS: break; case PAM_NEW_AUTHTOK_REQD: pam_err = pam_chauthtok(pamh, PAM_SILENT|PAM_CHANGE_EXPIRED_AUTHTOK); if (pam_err != PAM_SUCCESS) PAM_END("pam_chauthtok"); break; case PAM_AUTH_ERR: case PAM_USER_UNKNOWN: case PAM_MAXTRIES: syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname); errx(EXIT_FAILURE, "second authentication failed"); break; default: PAM_END("pam_acct_mgmt"); break; } break; case PAM_AUTH_ERR: case PAM_USER_UNKNOWN: case PAM_MAXTRIES: syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname); errx(EXIT_FAILURE, "authentication failed"); break; default: PAM_END("pam_authenticate"); break; } pam_end(pamh, pam_err); #ifndef linux /* Re-establish stdin */ if (dup2(temp_stdin, STDIN_FILENO) == -1) err(1, "dup2"); close(temp_stdin); #else /* Re-establish stdout */ close(1); if (dup2(temp_stdout, 1) == -1) err(1, "dup2"); #endif #else #error No auth module! #endif } /* if (pledge("stdio rpath getpw exec id", NULL) == -1) err(1, "pledge"); */ target_pw = getpwuid(target); if (! target_pw) errx(1, "no passwd entry for target"); #if defined(HAVE_LOGIN_CAP_H) if (setusercontext(NULL, target_pw, target, LOGIN_SETGROUP | LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK | LOGIN_SETUSER) != 0) errx(1, "failed to set user context for target"); #endif /* if (pledge("stdio rpath exec", NULL) == -1) err(1, "pledge"); */ if (getcwd(cwdpath, sizeof(cwdpath)) == NULL) cwd = "(failed)"; else cwd = cwdpath; /* if (pledge("stdio exec", NULL) == -1) err(1, "pledge"); */ #ifndef HAVE_LOGIN_CAP_H /* If we effectively are root, set the UID to actually be root to avoid permission errors. */ if (target != 0) setuid(target); if ( geteuid() == ROOT_UID ) setuid(ROOT_UID); #endif syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s", myname, cmdline, target_pw->pw_name, cwd); envp = prepenv(rule, original_pw, target_pw); if (rule->cmd) { if (setenv("PATH", safepath, 1) == -1) err(1, "failed to set PATH '%s'", safepath); } execvpe(cmd, argv, envp); if (errno == ENOENT) errx(1, "%s: command not found", cmd); err(1, "%s", cmd); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'fix the setusercontext(3) workaround Seeing this being used on even more system like Illumos with this ugly and security critical bug open makes me cringe every time I check if it was finally fixed. I reported it directly to the maintainer in 2017. I reported it to pkgsrc-security@netbsd.org without a response.'</s>