idx
int64
project
string
commit_id
string
project_url
string
commit_url
string
commit_message
string
target
int64
func
string
func_hash
string
file_name
string
file_hash
string
cwe
string
cve
string
cve_desc
string
nvd_url
string
198,374
tensorflow
803404044ae7a1efac48ba82d74111fce1ddb09a
https://github.com/tensorflow/tensorflow
https://github.com/tensorflow/tensorflow/commit/803404044ae7a1efac48ba82d74111fce1ddb09a
Fix security vulnerability with LSTMBlockCellOp PiperOrigin-RevId: 446028341
1
void Compute(OpKernelContext* ctx) override { const Tensor* x_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("x", &x_tensor)); const Tensor* cs_prev_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("cs_prev", &cs_prev_tensor)); const Tensor* h_prev_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("h_prev", &h_prev_tensor)); const Tensor* w_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("w", &w_tensor)); const Tensor* wci_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("wci", &wci_tensor)); const Tensor* wcf_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("wcf", &wcf_tensor)); const Tensor* wco_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("wco", &wco_tensor)); const Tensor* b_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("b", &b_tensor)); const int64_t batch_size = x_tensor->dim_size(0); const int64_t input_size = x_tensor->dim_size(1); const int64_t cell_size = cs_prev_tensor->dim_size(1); // Sanity checks for our input shapes. OP_REQUIRES(ctx, cs_prev_tensor->dim_size(0) == batch_size, errors::InvalidArgument("cs_prev.dims(0) != batch_size: ", cs_prev_tensor->dim_size(0), " vs. ", batch_size)); OP_REQUIRES(ctx, cs_prev_tensor->dim_size(1) == cell_size, errors::InvalidArgument("cs_prev.dims(1) != cell_size: ", cs_prev_tensor->dim_size(1), " vs. ", cell_size)); OP_REQUIRES(ctx, h_prev_tensor->dim_size(0) == batch_size, errors::InvalidArgument("h_prev.dims(0) != batch_size: ", h_prev_tensor->dim_size(0), " vs. ", batch_size)); OP_REQUIRES(ctx, h_prev_tensor->dim_size(1) == cell_size, errors::InvalidArgument( "h_prev.dims(1) != cell_size: ", h_prev_tensor->dim_size(1), " vs. ", cell_size)); OP_REQUIRES(ctx, w_tensor->dim_size(0) == input_size + cell_size, errors::InvalidArgument( "w.dim_size(0) != input_size + cell_size: ", w_tensor->dim_size(0), " vs. ", input_size + cell_size)); OP_REQUIRES(ctx, w_tensor->dim_size(1) == cell_size * 4, errors::InvalidArgument( "w.dim_size(1) != cell_size * 4: ", w_tensor->dim_size(1), " vs. ", cell_size * 4)); OP_REQUIRES(ctx, b_tensor->dim_size(0) == cell_size * 4, errors::InvalidArgument( "b.dim_size(0) != cell_size * 4: ", b_tensor->dim_size(0), " vs. ", cell_size * 4)); // Allocate our output tensors. Tensor* i_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {"h_prev"}, "i", TensorShape({batch_size, cell_size}), &i_tensor)); Tensor* cs_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("cs", TensorShape({batch_size, cell_size}), &cs_tensor)); Tensor* f_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("f", TensorShape({batch_size, cell_size}), &f_tensor)); Tensor* o_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {"cs_prev"}, "o", TensorShape({batch_size, cell_size}), &o_tensor)); Tensor* ci_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("ci", TensorShape({batch_size, cell_size}), &ci_tensor)); Tensor* co_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("co", TensorShape({batch_size, cell_size}), &co_tensor)); Tensor* h_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("h", TensorShape({batch_size, cell_size}), &h_tensor)); // Allocate our temp tensors. Tensor xh_tensor; OP_REQUIRES_OK(ctx, ctx->allocate_temp( DataTypeToEnum<T>::v(), TensorShape({batch_size, input_size + cell_size}), &xh_tensor)); Tensor gates_tensor; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::v(), TensorShape({batch_size, cell_size * 4}), &gates_tensor)); const Device& device = ctx->eigen_device<Device>(); functor::LSTMBlockCellFprop<Device, T, USE_CUBLAS, gate_layout>( batch_size, input_size, cell_size)( ctx, device, forget_bias_, cell_clip_, use_peephole_, x_tensor->matrix<T>(), cs_prev_tensor->matrix<T>(), h_prev_tensor->matrix<T>(), w_tensor->matrix<T>(), wci_tensor->vec<T>(), wcf_tensor->vec<T>(), wco_tensor->vec<T>(), b_tensor->vec<T>(), xh_tensor.matrix<T>(), i_tensor->matrix<T>(), cs_tensor->matrix<T>(), f_tensor->matrix<T>(), o_tensor->matrix<T>(), ci_tensor->matrix<T>(), co_tensor->matrix<T>(), gates_tensor.matrix<T>(), h_tensor->matrix<T>()); }
332787893197526379241591780916041422587
lstm_ops.cc
94555141575162353468670590418949369497
CWE-703
CVE-2022-29200
TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.LSTMBlockCell` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code does not validate the ranks of any of the arguments to this API call. This results in `CHECK`-failures when the elements of the tensor are accessed. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-29200
273,407
tensorflow
803404044ae7a1efac48ba82d74111fce1ddb09a
https://github.com/tensorflow/tensorflow
https://github.com/tensorflow/tensorflow/commit/803404044ae7a1efac48ba82d74111fce1ddb09a
Fix security vulnerability with LSTMBlockCellOp PiperOrigin-RevId: 446028341
0
void Compute(OpKernelContext* ctx) override { const Tensor* x_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("x", &x_tensor)); const Tensor* cs_prev_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("cs_prev", &cs_prev_tensor)); const Tensor* h_prev_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("h_prev", &h_prev_tensor)); const Tensor* w_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("w", &w_tensor)); const Tensor* wci_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("wci", &wci_tensor)); const Tensor* wcf_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("wcf", &wcf_tensor)); const Tensor* wco_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("wco", &wco_tensor)); const Tensor* b_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->input("b", &b_tensor)); const int64_t batch_size = x_tensor->dim_size(0); const int64_t input_size = x_tensor->dim_size(1); const int64_t cell_size = cs_prev_tensor->dim_size(1); // Sanity checks for our input shapes. OP_REQUIRES(ctx, cs_prev_tensor->dim_size(0) == batch_size, errors::InvalidArgument("cs_prev.dims(0) != batch_size: ", cs_prev_tensor->dim_size(0), " vs. ", batch_size)); OP_REQUIRES(ctx, cs_prev_tensor->dim_size(1) == cell_size, errors::InvalidArgument("cs_prev.dims(1) != cell_size: ", cs_prev_tensor->dim_size(1), " vs. ", cell_size)); OP_REQUIRES(ctx, h_prev_tensor->dim_size(0) == batch_size, errors::InvalidArgument("h_prev.dims(0) != batch_size: ", h_prev_tensor->dim_size(0), " vs. ", batch_size)); OP_REQUIRES(ctx, h_prev_tensor->dim_size(1) == cell_size, errors::InvalidArgument( "h_prev.dims(1) != cell_size: ", h_prev_tensor->dim_size(1), " vs. ", cell_size)); OP_REQUIRES(ctx, w_tensor->dim_size(0) == input_size + cell_size, errors::InvalidArgument( "w.dim_size(0) != input_size + cell_size: ", w_tensor->dim_size(0), " vs. ", input_size + cell_size)); OP_REQUIRES(ctx, w_tensor->dim_size(1) == cell_size * 4, errors::InvalidArgument( "w.dim_size(1) != cell_size * 4: ", w_tensor->dim_size(1), " vs. ", cell_size * 4)); OP_REQUIRES(ctx, b_tensor->dim_size(0) == cell_size * 4, errors::InvalidArgument( "b.dim_size(0) != cell_size * 4: ", b_tensor->dim_size(0), " vs. ", cell_size * 4)); // Allocate our output tensors. Tensor* i_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {"h_prev"}, "i", TensorShape({batch_size, cell_size}), &i_tensor)); Tensor* cs_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("cs", TensorShape({batch_size, cell_size}), &cs_tensor)); Tensor* f_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("f", TensorShape({batch_size, cell_size}), &f_tensor)); Tensor* o_tensor = nullptr; OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {"cs_prev"}, "o", TensorShape({batch_size, cell_size}), &o_tensor)); Tensor* ci_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("ci", TensorShape({batch_size, cell_size}), &ci_tensor)); Tensor* co_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("co", TensorShape({batch_size, cell_size}), &co_tensor)); Tensor* h_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output("h", TensorShape({batch_size, cell_size}), &h_tensor)); // Allocate our temp tensors. Tensor xh_tensor; OP_REQUIRES_OK(ctx, ctx->allocate_temp( DataTypeToEnum<T>::v(), TensorShape({batch_size, input_size + cell_size}), &xh_tensor)); Tensor gates_tensor; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::v(), TensorShape({batch_size, cell_size * 4}), &gates_tensor)); const Device& device = ctx->eigen_device<Device>(); // Sanity check that each of the tensors have the required NDIMS. OP_REQUIRES(ctx, x_tensor->dims() == 2, errors::InvalidArgument("x_tensor must be rank 2 but is rank ", x_tensor->dims(), ".")); OP_REQUIRES( ctx, cs_prev_tensor->dims() == 2, errors::InvalidArgument("cs_prev_tensor must be rank 2 but is rank ", cs_prev_tensor->dims(), ".")); OP_REQUIRES( ctx, h_prev_tensor->dims() == 2, errors::InvalidArgument("h_prev_tensor must be rank 2 but is rank ", h_prev_tensor->dims(), ".")); OP_REQUIRES(ctx, w_tensor->dims() == 2, errors::InvalidArgument("w_tensor must be rank 2 but is rank ", w_tensor->dims(), ".")); OP_REQUIRES( ctx, wci_tensor->dims() == 1, errors::InvalidArgument("wci_tensor must be rank 1 but is rank ", wci_tensor->dims(), ".")); OP_REQUIRES( ctx, wcf_tensor->dims() == 1, errors::InvalidArgument("wcf_tensor must be rank 1 but is rank ", wci_tensor->dims(), ".")); OP_REQUIRES( ctx, wco_tensor->dims() == 1, errors::InvalidArgument("wco_tensor must be rank 1 but is rank ", wco_tensor->dims(), ".")); OP_REQUIRES(ctx, b_tensor->dims() == 1, errors::InvalidArgument("b_tensor must be rank 1 but is rank ", b_tensor->dims(), ".")); OP_REQUIRES(ctx, xh_tensor.dims() == 2, errors::InvalidArgument("xh_tensor must be rank 2 but is rank ", xh_tensor.dims(), ".")); OP_REQUIRES(ctx, i_tensor->dims() == 2, errors::InvalidArgument("i_tensor must be rank 2 but is rank ", i_tensor->dims(), ".")); OP_REQUIRES(ctx, cs_tensor->dims() == 2, errors::InvalidArgument("cs_tensor must be rank 2 but is rank ", cs_tensor->dims(), ".")); OP_REQUIRES(ctx, f_tensor->dims() == 2, errors::InvalidArgument("f_tensor must be rank 2 but is rank ", f_tensor->dims(), ".")); OP_REQUIRES(ctx, o_tensor->dims() == 2, errors::InvalidArgument("o_tensor must be rank 2 but is rank ", o_tensor->dims(), ".")); OP_REQUIRES(ctx, ci_tensor->dims() == 2, errors::InvalidArgument("ci_tensor must be rank 2 but is rank ", ci_tensor->dims(), ".")); OP_REQUIRES(ctx, co_tensor->dims() == 2, errors::InvalidArgument("co_tensor must be rank 2 but is rank ", co_tensor->dims(), ".")); OP_REQUIRES( ctx, gates_tensor.dims() == 2, errors::InvalidArgument("gates_tensor must be rank 2 but is rank ", gates_tensor.dims(), ".")); OP_REQUIRES(ctx, h_tensor->dims() == 2, errors::InvalidArgument("h_tensor must be rank 2 but is rank ", h_tensor->dims(), ".")); functor::LSTMBlockCellFprop<Device, T, USE_CUBLAS, gate_layout>( batch_size, input_size, cell_size)( ctx, device, forget_bias_, cell_clip_, use_peephole_, x_tensor->matrix<T>(), cs_prev_tensor->matrix<T>(), h_prev_tensor->matrix<T>(), w_tensor->matrix<T>(), wci_tensor->vec<T>(), wcf_tensor->vec<T>(), wco_tensor->vec<T>(), b_tensor->vec<T>(), xh_tensor.matrix<T>(), i_tensor->matrix<T>(), cs_tensor->matrix<T>(), f_tensor->matrix<T>(), o_tensor->matrix<T>(), ci_tensor->matrix<T>(), co_tensor->matrix<T>(), gates_tensor.matrix<T>(), h_tensor->matrix<T>()); }
258695141881627595709406834872901892471
lstm_ops.cc
177796578902754451713518476941050283987
CWE-703
CVE-2022-29200
TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.raw_ops.LSTMBlockCell` does not fully validate the input arguments. This results in a `CHECK`-failure which can be used to trigger a denial of service attack. The code does not validate the ranks of any of the arguments to this API call. This results in `CHECK`-failures when the elements of the tensor are accessed. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-29200
198,399
uftpd
0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd
https://github.com/troglobit/uftpd
https://github.com/troglobit/uftpd/commit/0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd
FTP: Fix buffer overflow in PORT parser, reported by Aaron Esau Signed-off-by: Joachim Nilsson <[email protected]>
1
static void handle_PORT(ctrl_t *ctrl, char *str) { int a, b, c, d, e, f; char addr[INET_ADDRSTRLEN]; struct sockaddr_in sin; if (ctrl->data_sd > 0) { uev_io_stop(&ctrl->data_watcher); close(ctrl->data_sd); ctrl->data_sd = -1; } /* Convert PORT command's argument to IP address + port */ sscanf(str, "%d,%d,%d,%d,%d,%d", &a, &b, &c, &d, &e, &f); sprintf(addr, "%d.%d.%d.%d", a, b, c, d); /* Check IPv4 address using inet_aton(), throw away converted result */ if (!inet_aton(addr, &(sin.sin_addr))) { ERR(0, "Invalid address '%s' given to PORT command", addr); send_msg(ctrl->sd, "500 Illegal PORT command.\r\n"); return; } strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address)); ctrl->data_port = e * 256 + f; DBG("Client PORT command accepted for %s:%d", ctrl->data_address, ctrl->data_port); send_msg(ctrl->sd, "200 PORT command successful.\r\n"); }
5389607465091397932741652441661168107
ftpcmd.c
13134413350440209021234166619599968419
CWE-787
CVE-2020-20276
An unauthenticated stack-based buffer overflow vulnerability in common.c's handle_PORT in uftpd FTP server versions 2.10 and earlier can be abused to cause a crash and could potentially lead to remote code execution.
https://nvd.nist.gov/vuln/detail/CVE-2020-20276
273,880
uftpd
0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd
https://github.com/troglobit/uftpd
https://github.com/troglobit/uftpd/commit/0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd
FTP: Fix buffer overflow in PORT parser, reported by Aaron Esau Signed-off-by: Joachim Nilsson <[email protected]>
0
static void handle_PORT(ctrl_t *ctrl, char *str) { int a, b, c, d, e, f; char addr[INET_ADDRSTRLEN]; struct sockaddr_in sin; if (ctrl->data_sd > 0) { uev_io_stop(&ctrl->data_watcher); close(ctrl->data_sd); ctrl->data_sd = -1; } /* Convert PORT command's argument to IP address + port */ sscanf(str, "%d,%d,%d,%d,%d,%d", &a, &b, &c, &d, &e, &f); snprintf(addr, sizeof(addr), "%d.%d.%d.%d", a, b, c, d); /* Check IPv4 address using inet_aton(), throw away converted result */ if (!inet_aton(addr, &(sin.sin_addr))) { ERR(0, "Invalid address '%s' given to PORT command", addr); send_msg(ctrl->sd, "500 Illegal PORT command.\r\n"); return; } strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address)); ctrl->data_port = e * 256 + f; DBG("Client PORT command accepted for %s:%d", ctrl->data_address, ctrl->data_port); send_msg(ctrl->sd, "200 PORT command successful.\r\n"); }
215142570245126978636842618721615711400
ftpcmd.c
153621949674732808138354001734428365570
CWE-787
CVE-2020-20276
An unauthenticated stack-based buffer overflow vulnerability in common.c's handle_PORT in uftpd FTP server versions 2.10 and earlier can be abused to cause a crash and could potentially lead to remote code execution.
https://nvd.nist.gov/vuln/detail/CVE-2020-20276
198,439
mruby
3cf291f72224715942beaf8553e42ba8891ab3c6
https://github.com/mruby/mruby
https://github.com/mruby/mruby/commit/3cf291f72224715942beaf8553e42ba8891ab3c6
vm.c: create break object before clearing GC arena. Otherwise it possibly cause use-after-free.
1
mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc) { /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */ const mrb_irep *irep = proc->body.irep; const mrb_pool_value *pool = irep->pool; const mrb_sym *syms = irep->syms; mrb_code insn; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; uint32_t a; uint16_t b; uint16_t c; mrb_sym mid; const struct mrb_irep_catch_handler *ch; #ifdef DIRECT_THREADED static const void * const optable[] = { #define OPCODE(x,_) &&L_OP_ ## x, #include "mruby/ops.h" #undef OPCODE }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; mrb_gc_arena_restore(mrb, ai); if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb_vm_ci_proc_set(mrb->c->ci, proc); #define regs (mrb->c->ci->stack) INIT_DISPATCH { CASE(OP_NOP, Z) { /* do nothing */ NEXT; } CASE(OP_MOVE, BB) { regs[a] = regs[b]; NEXT; } CASE(OP_LOADL, BB) { switch (pool[b].tt) { /* number */ case IREP_TT_INT32: regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32); break; case IREP_TT_INT64: #if defined(MRB_INT64) regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64); break; #else #if defined(MRB_64BIT) if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) { regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64); break; } #endif goto L_INT_OVERFLOW; #endif case IREP_TT_BIGINT: goto L_INT_OVERFLOW; #ifndef MRB_NO_FLOAT case IREP_TT_FLOAT: regs[a] = mrb_float_value(mrb, pool[b].u.f); break; #endif default: /* should not happen (tt:string) */ regs[a] = mrb_nil_value(); break; } NEXT; } CASE(OP_LOADI, BB) { SET_FIXNUM_VALUE(regs[a], b); NEXT; } CASE(OP_LOADINEG, BB) { SET_FIXNUM_VALUE(regs[a], -b); NEXT; } CASE(OP_LOADI__1,B) goto L_LOADI; CASE(OP_LOADI_0,B) goto L_LOADI; CASE(OP_LOADI_1,B) goto L_LOADI; CASE(OP_LOADI_2,B) goto L_LOADI; CASE(OP_LOADI_3,B) goto L_LOADI; CASE(OP_LOADI_4,B) goto L_LOADI; CASE(OP_LOADI_5,B) goto L_LOADI; CASE(OP_LOADI_6,B) goto L_LOADI; CASE(OP_LOADI_7, B) { L_LOADI: SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0); NEXT; } CASE(OP_LOADI16, BS) { SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b); NEXT; } CASE(OP_LOADI32, BSS) { SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c)); NEXT; } CASE(OP_LOADSYM, BB) { SET_SYM_VALUE(regs[a], syms[b]); NEXT; } CASE(OP_LOADNIL, B) { SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_LOADSELF, B) { regs[a] = regs[0]; NEXT; } CASE(OP_LOADT, B) { SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF, B) { SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGV, BB) { mrb_value val = mrb_gv_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETGV, BB) { mrb_gv_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETSV, BB) { mrb_value val = mrb_vm_special_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETSV, BB) { mrb_vm_special_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETIV, BB) { regs[a] = mrb_iv_get(mrb, regs[0], syms[b]); NEXT; } CASE(OP_SETIV, BB) { mrb_iv_set(mrb, regs[0], syms[b], regs[a]); NEXT; } CASE(OP_GETCV, BB) { mrb_value val; val = mrb_vm_cv_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETCV, BB) { mrb_vm_cv_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETIDX, B) { mrb_value va = regs[a], vb = regs[a+1]; switch (mrb_type(va)) { case MRB_TT_ARRAY: if (!mrb_integer_p(vb)) goto getidx_fallback; regs[a] = mrb_ary_entry(va, mrb_integer(vb)); break; case MRB_TT_HASH: va = mrb_hash_get(mrb, va, vb); regs[a] = va; break; case MRB_TT_STRING: switch (mrb_type(vb)) { case MRB_TT_INTEGER: case MRB_TT_STRING: case MRB_TT_RANGE: va = mrb_str_aref(mrb, va, vb, mrb_undef_value()); regs[a] = va; break; default: goto getidx_fallback; } break; default: getidx_fallback: mid = MRB_OPSYM(aref); goto L_SEND_SYM; } NEXT; } CASE(OP_SETIDX, B) { c = 2; mid = MRB_OPSYM(aset); SET_NIL_VALUE(regs[a+3]); goto L_SENDB_SYM; } CASE(OP_GETCONST, BB) { mrb_value v = mrb_vm_const_get(mrb, syms[b]); regs[a] = v; NEXT; } CASE(OP_SETCONST, BB) { mrb_vm_const_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETMCNST, BB) { mrb_value v = mrb_const_get(mrb, regs[a], syms[b]); regs[a] = v; NEXT; } CASE(OP_SETMCNST, BB) { mrb_const_set(mrb, regs[a+1], syms[b], regs[a]); NEXT; } CASE(OP_GETUPVAR, BBB) { mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (e && b < MRB_ENV_LEN(e)) { *regs_a = e->stack[b]; } else { *regs_a = mrb_nil_value(); } NEXT; } CASE(OP_SETUPVAR, BBB) { struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP, S) { pc += (int16_t)a; JUMP; } CASE(OP_JMPIF, BS) { if (mrb_test(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPNOT, BS) { if (!mrb_test(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPNIL, BS) { if (mrb_nil_p(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPUW, S) { a = (uint32_t)((pc - irep->iseq) + (int16_t)a); CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) { struct RBreak *brk = (struct RBreak*)mrb->exc; mrb_value target = mrb_break_value_get(brk); mrb_assert(mrb_integer_p(target)); a = (uint32_t)mrb_integer(target); mrb_assert(a >= 0 && a < irep->ilen); } CHECKPOINT_MAIN(RBREAK_TAG_JUMP) { ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE); if (ch) { /* avoiding a jump from a catch handler into the same handler */ if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) { THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a)); } } } CHECKPOINT_END(RBREAK_TAG_JUMP); mrb->exc = NULL; /* clear break object */ pc = irep->iseq + a; JUMP; } CASE(OP_EXCEPT, B) { mrb_value exc; if (mrb->exc == NULL) { exc = mrb_nil_value(); } else { switch (mrb->exc->tt) { case MRB_TT_BREAK: case MRB_TT_EXCEPTION: exc = mrb_obj_value(mrb->exc); break; default: mrb_assert(!"bad mrb_type"); exc = mrb_nil_value(); break; } mrb->exc = NULL; } regs[a] = exc; NEXT; } CASE(OP_RESCUE, BB) { mrb_value exc = regs[a]; /* exc on stack */ mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR, "class or module required for rescue clause"); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); NEXT; } CASE(OP_RAISEIF, B) { mrb_value exc = regs[a]; if (mrb_break_p(exc)) { mrb->exc = mrb_obj_ptr(exc); goto L_BREAK; } mrb_exc_set(mrb, exc); if (mrb->exc) { goto L_RAISE; } NEXT; } CASE(OP_SSEND, BBB) { regs[a] = regs[0]; insn = OP_SEND; } goto L_SENDB; CASE(OP_SSENDB, BBB) { regs[a] = regs[0]; } goto L_SENDB; CASE(OP_SEND, BBB) goto L_SENDB; L_SEND_SYM: c = 1; /* push nil after arguments */ SET_NIL_VALUE(regs[a+2]); goto L_SENDB_SYM; CASE(OP_SENDB, BBB) L_SENDB: mid = syms[b]; L_SENDB_SYM: { mrb_callinfo *ci = mrb->c->ci; mrb_method_t m; struct RClass *cls; mrb_value recv, blk; ARGUMENT_NORMALIZE(a, &c, insn); recv = regs[a]; cls = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &cls, mid); if (MRB_METHOD_UNDEF_P(m)) { m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0); mid = MRB_SYM(method_missing); } /* push callinfo */ ci = cipush(mrb, a, 0, cls, NULL, mid, c); if (MRB_METHOD_CFUNC_P(m)) { if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); mrb_vm_ci_proc_set(ci, p); recv = p->body.func(mrb, recv); } else { if (MRB_METHOD_NOARG_P(m)) { check_method_noarg(mrb, ci); } recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (mrb_proc_p(blk)) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) { p->flags |= MRB_PROC_ORPHAN; } } if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */ if (ci->cci == CINFO_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } ci->stack[0] = recv; /* pop stackpos */ ci = cipop(mrb); pc = ci->pc; } else { /* setup environment for calling method */ mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m))); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs); pc = irep->iseq; } } JUMP; CASE(OP_CALL, Z) { mrb_callinfo *ci = mrb->c->ci; mrb_value recv = ci->stack[0]; struct RProc *m = mrb_proc_ptr(recv); /* replace callinfo */ ci->u.target_class = MRB_PROC_TARGET_CLASS(m); mrb_vm_ci_proc_set(ci, m); if (MRB_PROC_ENV_P(m)) { ci->mid = MRB_PROC_ENV(m)->mid; } /* prepare stack */ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; /* pop stackpos */ ci = cipop(mrb); pc = ci->pc; ci[1].stack[0] = recv; irep = mrb->c->ci->proc->body.irep; } else { /* setup environment for calling method */ proc = m; irep = m->body.irep; if (!irep) { mrb->c->ci->stack[0] = mrb_nil_value(); a = 0; c = OP_R_NORMAL; goto L_OP_RETURN_BODY; } mrb_int nargs = mrb_ci_bidx(ci)+1; if (nargs < irep->nregs) { mrb_stack_extend(mrb, irep->nregs); stack_clear(regs+nargs, irep->nregs-nargs); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; } pool = irep->pool; syms = irep->syms; JUMP; } CASE(OP_SUPER, BB) { mrb_method_t m; struct RClass *cls; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; const struct RProc *p = ci->proc; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(p); if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */ mid = p->e.env->mid; /* restore old mid */ } if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) { target_class = mrb_vm_ci_target_class(ci); } else if (target_class->tt == MRB_TT_MODULE) { target_class = mrb_vm_ci_target_class(ci); if (!target_class || target_class->tt != MRB_TT_ICLASS) { goto super_typeerror; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { super_typeerror: ; mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR, "self has wrong type to call super in this context"); mrb_exc_set(mrb, exc); goto L_RAISE; } ARGUMENT_NORMALIZE(a, &b, OP_SUPER); cls = target_class->super; m = mrb_method_search_vm(mrb, &cls, mid); if (MRB_METHOD_UNDEF_P(m)) { m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1); mid = MRB_SYM(method_missing); } /* push callinfo */ ci = cipush(mrb, a, 0, cls, NULL, mid, b); /* prepare stack */ ci->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; if (MRB_METHOD_PROC_P(m)) { mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m)); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; mrb_assert(!mrb_break_p(v)); if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */ if (ci->cci == CINFO_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->ci->stack[0] = v; ci = cipop(mrb); pc = ci->pc; } else { /* setup environment for calling method */ mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m))); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs); pc = irep->iseq; } JUMP; } CASE(OP_ARGARY, BS) { mrb_int m1 = (b>>11)&0x3f; mrb_int r = (b>>10)&0x1; mrb_int m2 = (b>>5)&0x1f; mrb_int kd = (b>>4)&0x1; mrb_int lv = (b>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; mrb_int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } if (kd) { regs[a+1] = stack[m1+r+m2]; regs[a+2] = stack[m1+r+m2+1]; } else { regs[a+1] = stack[m1+r+m2]; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER, W) { mrb_int m1 = MRB_ASPEC_REQ(a); mrb_int o = MRB_ASPEC_OPT(a); mrb_int r = MRB_ASPEC_REST(a); mrb_int m2 = MRB_ASPEC_POST(a); mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0; /* unused int b = MRB_ASPEC_BLOCK(a); */ mrb_int const len = m1 + o + r + m2; mrb_callinfo *ci = mrb->c->ci; mrb_int argc = ci->n; mrb_value *argv = regs+1; mrb_value * const argv0 = argv; mrb_int const kw_pos = len + kd; /* where kwhash should be */ mrb_int const blk_pos = kw_pos + 1; /* where block should be */ mrb_value blk = regs[mrb_ci_bidx(ci)]; mrb_value kdict = mrb_nil_value(); /* keyword arguments */ if (ci->nk > 0) { mrb_int kidx = mrb_ci_kidx(ci); kdict = regs[kidx]; if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) { kdict = mrb_nil_value(); ci->nk = 0; } } if (!kd && !mrb_nil_p(kdict)) { if (argc < 14) { ci->n++; argc++; /* include kdict in normal arguments */ } else if (argc == 14) { /* pack arguments and kdict */ regs[1] = mrb_ary_new_from_values(mrb, argc+1, &regs[1]); argc = ci->n = 15; } else {/* argc == 15 */ /* push kdict to packed arguments */ mrb_ary_push(mrb, regs[1], regs[2]); } ci->nk = 0; } if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) { kdict = mrb_hash_dup(mrb, kdict); } /* arguments is passed with Array */ if (argc == 15) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } /* strict argument check */ if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } /* extract first argument array to arguments */ else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } /* rest arguments */ mrb_value rest = mrb_nil_value(); if (argc < len) { mrb_int mlen = m2; if (argc < m1+m2) { mlen = m1 < argc ? argc - m1 : 0; } /* copy mandatory and optional arguments */ if (argv0 != argv && argv) { value_move(&regs[1], argv, argc-mlen); /* m1 + o */ } if (argc < m1) { stack_clear(&regs[argc+1], m1-argc); } /* copy post mandatory arguments */ if (mlen) { value_move(&regs[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(&regs[len-m2+mlen+1], m2-mlen); } /* initialize rest arguments with empty Array */ if (r) { rest = mrb_ary_new_capa(mrb, 0); regs[m1+o+1] = rest; } /* skip initializer of passed arguments */ if (o > 0 && argc > m1+m2) pc += (argc - m1 - m2)*3; } else { mrb_int rnum = 0; if (argv0 != argv) { value_move(&regs[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); regs[m1+o+1] = rest; } if (m2 > 0 && argc-m2 > m1) { value_move(&regs[m1+o+r+1], &argv[m1+o+rnum], m2); } pc += o*3; } /* need to be update blk first to protect blk from GC */ regs[blk_pos] = blk; /* move block */ if (kd) { if (mrb_nil_p(kdict)) kdict = mrb_hash_new_capa(mrb, 0); regs[kw_pos] = kdict; /* set kwhash */ } /* format arguments for generated code */ mrb->c->ci->n = len; /* clear local (but non-argument) variables */ if (irep->nlocals-blk_pos-1 > 0) { stack_clear(&regs[blk_pos+1], irep->nlocals-blk_pos-1); } JUMP; } CASE(OP_KARG, BB) { mrb_value k = mrb_symbol_value(syms[b]); mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict, v; if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) { mrb_value str = mrb_format(mrb, "missing keyword: %v", k); mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str)); goto L_RAISE; } v = mrb_hash_get(mrb, kdict, k); regs[a] = v; mrb_hash_delete_key(mrb, kdict, k); NEXT; } CASE(OP_KEY_P, BB) { mrb_value k = mrb_symbol_value(syms[b]); mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; mrb_bool key_p = FALSE; if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) { key_p = mrb_hash_key_p(mrb, kdict, k); } regs[a] = mrb_bool_value(key_p); NEXT; } CASE(OP_KEYEND, Z) { mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) { mrb_value keys = mrb_hash_keys(mrb, kdict); mrb_value key1 = RARRAY_PTR(keys)[0]; mrb_value str = mrb_format(mrb, "unknown keyword: %v", key1); mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str)); goto L_RAISE; } NEXT; } CASE(OP_BREAK, B) { c = OP_R_BREAK; goto L_RETURN; } CASE(OP_RETURN_BLK, B) { c = OP_R_RETURN; goto L_RETURN; } CASE(OP_RETURN, B) c = OP_R_NORMAL; L_RETURN: { mrb_callinfo *ci; ci = mrb->c->ci; if (ci->mid) { mrb_value blk = regs[mrb_ci_bidx(ci)]; if (mrb_proc_p(blk)) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { L_RAISE: ci = mrb->c->ci; if (ci == mrb->c->cibase) { ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL); if (ch == NULL) goto L_FTOP; goto L_CATCH; } while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) { ci = cipop(mrb); if (ci[1].cci == CINFO_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } pc = ci[0].pc; if (ci == mrb->c->cibase) { ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL); if (ch == NULL) { L_FTOP: /* fiber top */ if (mrb->c == mrb->root_c) { mrb->c->ci->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } } L_CATCH: if (ch == NULL) goto L_STOP; if (FALSE) { L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */ ci = mrb->c->ci; } proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, irep->nregs); pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target); } else { mrb_int acc; mrb_value v; ci = mrb->c->ci; v = regs[a]; mrb_gc_protect(mrb, v); switch (c) { case OP_R_RETURN: /* Fall through to OP_R_NORMAL otherwise */ if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { const struct RProc *dst; mrb_callinfo *cibase; cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } /* check jump destination */ while (cibase <= ci && ci->proc != dst) { if (ci->cci > CINFO_NONE) { /* jump cross C boundary */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { /* no jump destination */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci = mrb->c->ci; while (cibase <= ci && ci->proc != dst) { CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) { cibase = mrb->c->cibase; dst = top_proc(mrb, proc); } CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK); ci = cipop(mrb); pc = ci->pc; } proc = ci->proc; mrb->exc = NULL; /* clear break object */ break; } /* fallthrough */ case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; c = mrb->c; if (!c->prev) { /* toplevel return */ regs[irep->nlocals] = v; goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP); } if (!c->vmexec && c->prev->ci == c->prev->cibase) { mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, "double resume"); mrb_exc_set(mrb, exc); goto L_RAISE; } CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) { c = mrb->c; } CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL); /* automatic yield at the end */ c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; mrb->c->status = MRB_FIBER_RUNNING; c->prev = NULL; if (c->vmexec) { mrb_gc_arena_restore(mrb, ai); c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } ci = mrb->c->ci; } CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_RETURN) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN); mrb->exc = NULL; /* clear break object */ break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR, "break from proc-closure"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK); /* break from fiber block */ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->cci > CINFO_NONE) { ci = cipop(mrb); mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { struct RBreak *brk; L_BREAK: brk = (struct RBreak*)mrb->exc; proc = mrb_break_proc_get(brk); v = mrb_break_value_get(brk); ci = mrb->c->ci; switch (mrb_break_tag_get(brk)) { #define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n); RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS) #undef DISPATCH_CHECKPOINTS default: mrb_assert(!"wrong break tag"); } } while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) { if (ci[-1].cci == CINFO_SKIP) { goto L_BREAK_ERROR; } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER); ci = cipop(mrb); pc = ci->pc; } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET); if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } mrb->exc = NULL; /* clear break object */ break; default: /* cannot happen */ break; } mrb_assert(ci == mrb->c->ci); mrb_assert(mrb->exc == NULL); if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->cci; ci = cipop(mrb); if (acc == CINFO_SKIP || acc == CINFO_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; DEBUG(fprintf(stderr, "from :%s\n", mrb_sym_name(mrb, ci->mid))); proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci[1].stack[0] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_BLKPUSH, BS) { int m1 = (b>>11)&0x3f; int r = (b>>10)&0x1; int m2 = (b>>5)&0x1f; int kd = (b>>4)&0x1; int lv = (b>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) || MRB_ENV_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2+kd])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2+kd]; NEXT; } L_INT_OVERFLOW: { mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, "integer overflow"); mrb_exc_set(mrb, exc); } goto L_RAISE; #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH(op_name) \ /* need to check if op is overridden */ \ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { \ OP_MATH_CASE_INTEGER(op_name); \ OP_MATH_CASE_FLOAT(op_name, integer, float); \ OP_MATH_CASE_FLOAT(op_name, float, integer); \ OP_MATH_CASE_FLOAT(op_name, float, float); \ OP_MATH_CASE_STRING_##op_name(); \ default: \ mid = MRB_OPSYM(op_name); \ goto L_SEND_SYM; \ } \ NEXT; #define OP_MATH_CASE_INTEGER(op_name) \ case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER): \ { \ mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z; \ if (mrb_int_##op_name##_overflow(x, y, &z)) \ OP_MATH_OVERFLOW_INT(); \ else \ SET_INT_VALUE(mrb,regs[a], z); \ } \ break #ifdef MRB_NO_FLOAT #define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0 #else #define OP_MATH_CASE_FLOAT(op_name, t1, t2) \ case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2): \ { \ mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \ SET_FLOAT_VALUE(mrb, regs[a], z); \ } \ break #endif #define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW #define OP_MATH_CASE_STRING_add() \ case TYPES2(MRB_TT_STRING, MRB_TT_STRING): \ regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); \ mrb_gc_arena_restore(mrb, ai); \ break #define OP_MATH_CASE_STRING_sub() (void)0 #define OP_MATH_CASE_STRING_mul() (void)0 #define OP_MATH_OP_add + #define OP_MATH_OP_sub - #define OP_MATH_OP_mul * #define OP_MATH_TT_integer MRB_TT_INTEGER #define OP_MATH_TT_float MRB_TT_FLOAT CASE(OP_ADD, B) { OP_MATH(add); } CASE(OP_SUB, B) { OP_MATH(sub); } CASE(OP_MUL, B) { OP_MATH(mul); } CASE(OP_DIV, B) { #ifndef MRB_NO_FLOAT mrb_float x, y, f; #endif /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER): { mrb_int x = mrb_integer(regs[a]); mrb_int y = mrb_integer(regs[a+1]); mrb_int div = mrb_div_int(mrb, x, y); SET_INT_VALUE(mrb, regs[a], div); } NEXT; #ifndef MRB_NO_FLOAT case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT): x = (mrb_float)mrb_integer(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER): x = mrb_float(regs[a]); y = (mrb_float)mrb_integer(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: mid = MRB_OPSYM(div); goto L_SEND_SYM; } #ifndef MRB_NO_FLOAT f = mrb_div_float(x, y); SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } #define OP_MATHI(op_name) \ /* need to check if op is overridden */ \ switch (mrb_type(regs[a])) { \ OP_MATHI_CASE_INTEGER(op_name); \ OP_MATHI_CASE_FLOAT(op_name); \ default: \ SET_INT_VALUE(mrb,regs[a+1], b); \ mid = MRB_OPSYM(op_name); \ goto L_SEND_SYM; \ } \ NEXT; #define OP_MATHI_CASE_INTEGER(op_name) \ case MRB_TT_INTEGER: \ { \ mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z; \ if (mrb_int_##op_name##_overflow(x, y, &z)) \ OP_MATH_OVERFLOW_INT(); \ else \ SET_INT_VALUE(mrb,regs[a], z); \ } \ break #ifdef MRB_NO_FLOAT #define OP_MATHI_CASE_FLOAT(op_name) (void)0 #else #define OP_MATHI_CASE_FLOAT(op_name) \ case MRB_TT_FLOAT: \ { \ mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b; \ SET_FLOAT_VALUE(mrb, regs[a], z); \ } \ break #endif CASE(OP_ADDI, BB) { OP_MATHI(add); } CASE(OP_SUBI, BB) { OP_MATHI(sub); } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_NO_FLOAT #define OP_CMP(op,sym) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ default:\ mid = MRB_OPSYM(sym);\ goto L_SEND_SYM;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #else #define OP_CMP(op, sym) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\ break;\ default:\ mid = MRB_OPSYM(sym);\ goto L_SEND_SYM;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #endif CASE(OP_EQ, B) { if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==,eq); } NEXT; } CASE(OP_LT, B) { OP_CMP(<,lt); NEXT; } CASE(OP_LE, B) { OP_CMP(<=,le); NEXT; } CASE(OP_GT, B) { OP_CMP(>,gt); NEXT; } CASE(OP_GE, B) { OP_CMP(>=,ge); NEXT; } CASE(OP_ARRAY, BB) { regs[a] = mrb_ary_new_from_values(mrb, b, &regs[a]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARRAY2, BBB) { regs[a] = mrb_ary_new_from_values(mrb, c, &regs[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT, B) { mrb_value splat = mrb_ary_splat(mrb, regs[a+1]); if (mrb_nil_p(regs[a])) { regs[a] = splat; } else { mrb_assert(mrb_array_p(regs[a])); mrb_ary_concat(mrb, regs[a], splat); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH, BB) { mrb_assert(mrb_array_p(regs[a])); for (mrb_int i=0; i<b; i++) { mrb_ary_push(mrb, regs[a], regs[a+i+1]); } NEXT; } CASE(OP_ARYDUP, B) { mrb_value ary = regs[a]; if (mrb_array_p(ary)) { ary = mrb_ary_new_from_values(mrb, RARRAY_LEN(ary), RARRAY_PTR(ary)); } else { ary = mrb_ary_new_from_values(mrb, 1, &ary); } regs[a] = ary; NEXT; } CASE(OP_AREF, BBB) { mrb_value v = regs[b]; if (!mrb_array_p(v)) { if (c == 0) { regs[a] = v; } else { SET_NIL_VALUE(regs[a]); } } else { v = mrb_ary_ref(mrb, v, c); regs[a] = v; } NEXT; } CASE(OP_ASET, BBB) { mrb_assert(mrb_array_p(regs[a])); mrb_ary_set(mrb, regs[b], c, regs[a]); NEXT; } CASE(OP_APOST, BBB) { mrb_value v = regs[a]; int pre = b; int post = c; struct RArray *ary; int len, idx; if (!mrb_array_p(v)) { v = mrb_ary_new_from_values(mrb, 1, &regs[a]); } ary = mrb_ary_ptr(v); len = (int)ARY_LEN(ary); if (len > pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+pre<len; idx++) { regs[a+idx] = ARY_PTR(ary)[pre+idx]; } while (idx < post) { SET_NIL_VALUE(regs[a+idx]); idx++; } } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_INTERN, B) { mrb_assert(mrb_string_p(regs[a])); mrb_sym sym = mrb_intern_str(mrb, regs[a]); regs[a] = mrb_symbol_value(sym); NEXT; } CASE(OP_SYMBOL, BB) { size_t len; mrb_sym sym; mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0); len = pool[b].tt >> 2; if (pool[b].tt & IREP_TT_SFLAG) { sym = mrb_intern_static(mrb, pool[b].u.str, len); } else { sym = mrb_intern(mrb, pool[b].u.str, len); } regs[a] = mrb_symbol_value(sym); NEXT; } CASE(OP_STRING, BB) { mrb_int len; mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0); len = pool[b].tt >> 2; if (pool[b].tt & IREP_TT_SFLAG) { regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len); } else { regs[a] = mrb_str_new(mrb, pool[b].u.str, len); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_STRCAT, B) { mrb_assert(mrb_string_p(regs[a])); mrb_str_concat(mrb, regs[a], regs[a+1]); NEXT; } CASE(OP_HASH, BB) { mrb_value hash = mrb_hash_new_capa(mrb, b); int i; int lim = a+b*2; for (i=a; i<lim; i+=2) { mrb_hash_set(mrb, hash, regs[i], regs[i+1]); } regs[a] = hash; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_HASHADD, BB) { mrb_value hash; int i; int lim = a+b*2+1; hash = regs[a]; mrb_ensure_hash_type(mrb, hash); for (i=a+1; i<lim; i+=2) { mrb_hash_set(mrb, hash, regs[i], regs[i+1]); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_HASHCAT, B) { mrb_value hash = regs[a]; mrb_assert(mrb_hash_p(hash)); mrb_hash_merge(mrb, hash, regs[a+1]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_LAMBDA, BB) c = OP_L_LAMBDA; L_MAKE_LAMBDA: { struct RProc *p; const mrb_irep *nirep = irep->reps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_BLOCK, BB) { c = OP_L_BLOCK; goto L_MAKE_LAMBDA; } CASE(OP_METHOD, BB) { c = OP_L_METHOD; goto L_MAKE_LAMBDA; } CASE(OP_RANGE_INC, B) { mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_RANGE_EXC, B) { mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS, B) { regs[a] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS, BB) { struct RClass *c = 0, *baseclass; mrb_value base, super; mrb_sym id = syms[b]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); if (!baseclass) baseclass = mrb->object_class; base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE, BB) { struct RClass *cls = 0, *baseclass; mrb_value base; mrb_sym id = syms[b]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); if (!baseclass) baseclass = mrb->object_class; base = mrb_obj_value(baseclass); } cls = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(cls); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC, BB) { mrb_value recv = regs[a]; struct RProc *p; const mrb_irep *nirep = irep->reps[b]; /* prepare closure */ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; /* prepare call stack */ cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0); irep = p->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, irep->nregs); stack_clear(regs+1, irep->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_DEF, BB) { struct RClass *target = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; mrb_sym mid = syms[b]; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, target, mid, m); mrb_method_added(mrb, target, mid); mrb_gc_arena_restore(mrb, ai); regs[a] = mrb_symbol_value(mid); NEXT; } CASE(OP_SCLASS, B) { regs[a] = mrb_singleton_class(mrb, regs[a]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS, B) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; regs[a] = mrb_obj_value(target); NEXT; } CASE(OP_ALIAS, BB) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; mrb_alias_method(mrb, target, syms[a], syms[b]); mrb_method_added(mrb, target, syms[a]); NEXT; } CASE(OP_UNDEF, B) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; mrb_undef_method_id(mrb, target, syms[a]); NEXT; } CASE(OP_DEBUG, Z) { FETCH_BBB(); #ifdef MRB_USE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_NO_STDIO printf("OP_DEBUG %d %d %d\n", a, b, c); #else abort(); #endif #endif NEXT; } CASE(OP_ERR, B) { size_t len = pool[a].tt >> 2; mrb_value exc; mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0); exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len); mrb_exc_set(mrb, exc); goto L_RAISE; } CASE(OP_EXT1, Z) { insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include "mruby/ops.h" #undef OPCODE } pc--; NEXT; } CASE(OP_EXT2, Z) { insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include "mruby/ops.h" #undef OPCODE } pc--; NEXT; } CASE(OP_EXT3, Z) { uint8_t insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include "mruby/ops.h" #undef OPCODE } pc--; NEXT; } CASE(OP_STOP, Z) { /* stop VM */ CHECKPOINT_RESTORE(RBREAK_TAG_STOP) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_STOP) { UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value()); } CHECKPOINT_END(RBREAK_TAG_STOP); L_STOP: mrb->jmp = prev_jmp; if (mrb->exc) { mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION); return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { mrb_callinfo *ci = mrb->c->ci; while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) { ci = cipop(mrb); } exc_catched = TRUE; pc = ci->pc; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }
109885974444796302561569813029771831944
vm.c
83886473477345826235413068203214397377
CWE-288
CVE-2022-1212
Use-After-Free in str_escape in mruby/mruby in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.
https://nvd.nist.gov/vuln/detail/CVE-2022-1212
274,773
mruby
3cf291f72224715942beaf8553e42ba8891ab3c6
https://github.com/mruby/mruby
https://github.com/mruby/mruby/commit/3cf291f72224715942beaf8553e42ba8891ab3c6
vm.c: create break object before clearing GC arena. Otherwise it possibly cause use-after-free.
0
mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc) { /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */ const mrb_irep *irep = proc->body.irep; const mrb_pool_value *pool = irep->pool; const mrb_sym *syms = irep->syms; mrb_code insn; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; uint32_t a; uint16_t b; uint16_t c; mrb_sym mid; const struct mrb_irep_catch_handler *ch; #ifdef DIRECT_THREADED static const void * const optable[] = { #define OPCODE(x,_) &&L_OP_ ## x, #include "mruby/ops.h" #undef OPCODE }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; mrb_gc_arena_restore(mrb, ai); if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb_vm_ci_proc_set(mrb->c->ci, proc); #define regs (mrb->c->ci->stack) INIT_DISPATCH { CASE(OP_NOP, Z) { /* do nothing */ NEXT; } CASE(OP_MOVE, BB) { regs[a] = regs[b]; NEXT; } CASE(OP_LOADL, BB) { switch (pool[b].tt) { /* number */ case IREP_TT_INT32: regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32); break; case IREP_TT_INT64: #if defined(MRB_INT64) regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64); break; #else #if defined(MRB_64BIT) if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) { regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64); break; } #endif goto L_INT_OVERFLOW; #endif case IREP_TT_BIGINT: goto L_INT_OVERFLOW; #ifndef MRB_NO_FLOAT case IREP_TT_FLOAT: regs[a] = mrb_float_value(mrb, pool[b].u.f); break; #endif default: /* should not happen (tt:string) */ regs[a] = mrb_nil_value(); break; } NEXT; } CASE(OP_LOADI, BB) { SET_FIXNUM_VALUE(regs[a], b); NEXT; } CASE(OP_LOADINEG, BB) { SET_FIXNUM_VALUE(regs[a], -b); NEXT; } CASE(OP_LOADI__1,B) goto L_LOADI; CASE(OP_LOADI_0,B) goto L_LOADI; CASE(OP_LOADI_1,B) goto L_LOADI; CASE(OP_LOADI_2,B) goto L_LOADI; CASE(OP_LOADI_3,B) goto L_LOADI; CASE(OP_LOADI_4,B) goto L_LOADI; CASE(OP_LOADI_5,B) goto L_LOADI; CASE(OP_LOADI_6,B) goto L_LOADI; CASE(OP_LOADI_7, B) { L_LOADI: SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0); NEXT; } CASE(OP_LOADI16, BS) { SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b); NEXT; } CASE(OP_LOADI32, BSS) { SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c)); NEXT; } CASE(OP_LOADSYM, BB) { SET_SYM_VALUE(regs[a], syms[b]); NEXT; } CASE(OP_LOADNIL, B) { SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_LOADSELF, B) { regs[a] = regs[0]; NEXT; } CASE(OP_LOADT, B) { SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF, B) { SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGV, BB) { mrb_value val = mrb_gv_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETGV, BB) { mrb_gv_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETSV, BB) { mrb_value val = mrb_vm_special_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETSV, BB) { mrb_vm_special_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETIV, BB) { regs[a] = mrb_iv_get(mrb, regs[0], syms[b]); NEXT; } CASE(OP_SETIV, BB) { mrb_iv_set(mrb, regs[0], syms[b], regs[a]); NEXT; } CASE(OP_GETCV, BB) { mrb_value val; val = mrb_vm_cv_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETCV, BB) { mrb_vm_cv_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETIDX, B) { mrb_value va = regs[a], vb = regs[a+1]; switch (mrb_type(va)) { case MRB_TT_ARRAY: if (!mrb_integer_p(vb)) goto getidx_fallback; regs[a] = mrb_ary_entry(va, mrb_integer(vb)); break; case MRB_TT_HASH: va = mrb_hash_get(mrb, va, vb); regs[a] = va; break; case MRB_TT_STRING: switch (mrb_type(vb)) { case MRB_TT_INTEGER: case MRB_TT_STRING: case MRB_TT_RANGE: va = mrb_str_aref(mrb, va, vb, mrb_undef_value()); regs[a] = va; break; default: goto getidx_fallback; } break; default: getidx_fallback: mid = MRB_OPSYM(aref); goto L_SEND_SYM; } NEXT; } CASE(OP_SETIDX, B) { c = 2; mid = MRB_OPSYM(aset); SET_NIL_VALUE(regs[a+3]); goto L_SENDB_SYM; } CASE(OP_GETCONST, BB) { mrb_value v = mrb_vm_const_get(mrb, syms[b]); regs[a] = v; NEXT; } CASE(OP_SETCONST, BB) { mrb_vm_const_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETMCNST, BB) { mrb_value v = mrb_const_get(mrb, regs[a], syms[b]); regs[a] = v; NEXT; } CASE(OP_SETMCNST, BB) { mrb_const_set(mrb, regs[a+1], syms[b], regs[a]); NEXT; } CASE(OP_GETUPVAR, BBB) { mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (e && b < MRB_ENV_LEN(e)) { *regs_a = e->stack[b]; } else { *regs_a = mrb_nil_value(); } NEXT; } CASE(OP_SETUPVAR, BBB) { struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP, S) { pc += (int16_t)a; JUMP; } CASE(OP_JMPIF, BS) { if (mrb_test(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPNOT, BS) { if (!mrb_test(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPNIL, BS) { if (mrb_nil_p(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPUW, S) { a = (uint32_t)((pc - irep->iseq) + (int16_t)a); CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) { struct RBreak *brk = (struct RBreak*)mrb->exc; mrb_value target = mrb_break_value_get(brk); mrb_assert(mrb_integer_p(target)); a = (uint32_t)mrb_integer(target); mrb_assert(a >= 0 && a < irep->ilen); } CHECKPOINT_MAIN(RBREAK_TAG_JUMP) { ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE); if (ch) { /* avoiding a jump from a catch handler into the same handler */ if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) { THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a)); } } } CHECKPOINT_END(RBREAK_TAG_JUMP); mrb->exc = NULL; /* clear break object */ pc = irep->iseq + a; JUMP; } CASE(OP_EXCEPT, B) { mrb_value exc; if (mrb->exc == NULL) { exc = mrb_nil_value(); } else { switch (mrb->exc->tt) { case MRB_TT_BREAK: case MRB_TT_EXCEPTION: exc = mrb_obj_value(mrb->exc); break; default: mrb_assert(!"bad mrb_type"); exc = mrb_nil_value(); break; } mrb->exc = NULL; } regs[a] = exc; NEXT; } CASE(OP_RESCUE, BB) { mrb_value exc = regs[a]; /* exc on stack */ mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR, "class or module required for rescue clause"); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); NEXT; } CASE(OP_RAISEIF, B) { mrb_value exc = regs[a]; if (mrb_break_p(exc)) { mrb->exc = mrb_obj_ptr(exc); goto L_BREAK; } mrb_exc_set(mrb, exc); if (mrb->exc) { goto L_RAISE; } NEXT; } CASE(OP_SSEND, BBB) { regs[a] = regs[0]; insn = OP_SEND; } goto L_SENDB; CASE(OP_SSENDB, BBB) { regs[a] = regs[0]; } goto L_SENDB; CASE(OP_SEND, BBB) goto L_SENDB; L_SEND_SYM: c = 1; /* push nil after arguments */ SET_NIL_VALUE(regs[a+2]); goto L_SENDB_SYM; CASE(OP_SENDB, BBB) L_SENDB: mid = syms[b]; L_SENDB_SYM: { mrb_callinfo *ci = mrb->c->ci; mrb_method_t m; struct RClass *cls; mrb_value recv, blk; ARGUMENT_NORMALIZE(a, &c, insn); recv = regs[a]; cls = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &cls, mid); if (MRB_METHOD_UNDEF_P(m)) { m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0); mid = MRB_SYM(method_missing); } /* push callinfo */ ci = cipush(mrb, a, 0, cls, NULL, mid, c); if (MRB_METHOD_CFUNC_P(m)) { if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); mrb_vm_ci_proc_set(ci, p); recv = p->body.func(mrb, recv); } else { if (MRB_METHOD_NOARG_P(m)) { check_method_noarg(mrb, ci); } recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (mrb_proc_p(blk)) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) { p->flags |= MRB_PROC_ORPHAN; } } if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */ if (ci->cci == CINFO_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } ci->stack[0] = recv; /* pop stackpos */ ci = cipop(mrb); pc = ci->pc; } else { /* setup environment for calling method */ mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m))); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs); pc = irep->iseq; } } JUMP; CASE(OP_CALL, Z) { mrb_callinfo *ci = mrb->c->ci; mrb_value recv = ci->stack[0]; struct RProc *m = mrb_proc_ptr(recv); /* replace callinfo */ ci->u.target_class = MRB_PROC_TARGET_CLASS(m); mrb_vm_ci_proc_set(ci, m); if (MRB_PROC_ENV_P(m)) { ci->mid = MRB_PROC_ENV(m)->mid; } /* prepare stack */ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; /* pop stackpos */ ci = cipop(mrb); pc = ci->pc; ci[1].stack[0] = recv; irep = mrb->c->ci->proc->body.irep; } else { /* setup environment for calling method */ proc = m; irep = m->body.irep; if (!irep) { mrb->c->ci->stack[0] = mrb_nil_value(); a = 0; c = OP_R_NORMAL; goto L_OP_RETURN_BODY; } mrb_int nargs = mrb_ci_bidx(ci)+1; if (nargs < irep->nregs) { mrb_stack_extend(mrb, irep->nregs); stack_clear(regs+nargs, irep->nregs-nargs); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; } pool = irep->pool; syms = irep->syms; JUMP; } CASE(OP_SUPER, BB) { mrb_method_t m; struct RClass *cls; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; const struct RProc *p = ci->proc; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(p); if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */ mid = p->e.env->mid; /* restore old mid */ } if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) { target_class = mrb_vm_ci_target_class(ci); } else if (target_class->tt == MRB_TT_MODULE) { target_class = mrb_vm_ci_target_class(ci); if (!target_class || target_class->tt != MRB_TT_ICLASS) { goto super_typeerror; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { super_typeerror: ; mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR, "self has wrong type to call super in this context"); mrb_exc_set(mrb, exc); goto L_RAISE; } ARGUMENT_NORMALIZE(a, &b, OP_SUPER); cls = target_class->super; m = mrb_method_search_vm(mrb, &cls, mid); if (MRB_METHOD_UNDEF_P(m)) { m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1); mid = MRB_SYM(method_missing); } /* push callinfo */ ci = cipush(mrb, a, 0, cls, NULL, mid, b); /* prepare stack */ ci->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; if (MRB_METHOD_PROC_P(m)) { mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m)); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; mrb_assert(!mrb_break_p(v)); if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */ if (ci->cci == CINFO_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->ci->stack[0] = v; ci = cipop(mrb); pc = ci->pc; } else { /* setup environment for calling method */ mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m))); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs); pc = irep->iseq; } JUMP; } CASE(OP_ARGARY, BS) { mrb_int m1 = (b>>11)&0x3f; mrb_int r = (b>>10)&0x1; mrb_int m2 = (b>>5)&0x1f; mrb_int kd = (b>>4)&0x1; mrb_int lv = (b>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; mrb_int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } if (kd) { regs[a+1] = stack[m1+r+m2]; regs[a+2] = stack[m1+r+m2+1]; } else { regs[a+1] = stack[m1+r+m2]; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER, W) { mrb_int m1 = MRB_ASPEC_REQ(a); mrb_int o = MRB_ASPEC_OPT(a); mrb_int r = MRB_ASPEC_REST(a); mrb_int m2 = MRB_ASPEC_POST(a); mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0; /* unused int b = MRB_ASPEC_BLOCK(a); */ mrb_int const len = m1 + o + r + m2; mrb_callinfo *ci = mrb->c->ci; mrb_int argc = ci->n; mrb_value *argv = regs+1; mrb_value * const argv0 = argv; mrb_int const kw_pos = len + kd; /* where kwhash should be */ mrb_int const blk_pos = kw_pos + 1; /* where block should be */ mrb_value blk = regs[mrb_ci_bidx(ci)]; mrb_value kdict = mrb_nil_value(); /* keyword arguments */ if (ci->nk > 0) { mrb_int kidx = mrb_ci_kidx(ci); kdict = regs[kidx]; if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) { kdict = mrb_nil_value(); ci->nk = 0; } } if (!kd && !mrb_nil_p(kdict)) { if (argc < 14) { ci->n++; argc++; /* include kdict in normal arguments */ } else if (argc == 14) { /* pack arguments and kdict */ regs[1] = mrb_ary_new_from_values(mrb, argc+1, &regs[1]); argc = ci->n = 15; } else {/* argc == 15 */ /* push kdict to packed arguments */ mrb_ary_push(mrb, regs[1], regs[2]); } ci->nk = 0; } if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) { kdict = mrb_hash_dup(mrb, kdict); } /* arguments is passed with Array */ if (argc == 15) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } /* strict argument check */ if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } /* extract first argument array to arguments */ else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } /* rest arguments */ mrb_value rest = mrb_nil_value(); if (argc < len) { mrb_int mlen = m2; if (argc < m1+m2) { mlen = m1 < argc ? argc - m1 : 0; } /* copy mandatory and optional arguments */ if (argv0 != argv && argv) { value_move(&regs[1], argv, argc-mlen); /* m1 + o */ } if (argc < m1) { stack_clear(&regs[argc+1], m1-argc); } /* copy post mandatory arguments */ if (mlen) { value_move(&regs[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(&regs[len-m2+mlen+1], m2-mlen); } /* initialize rest arguments with empty Array */ if (r) { rest = mrb_ary_new_capa(mrb, 0); regs[m1+o+1] = rest; } /* skip initializer of passed arguments */ if (o > 0 && argc > m1+m2) pc += (argc - m1 - m2)*3; } else { mrb_int rnum = 0; if (argv0 != argv) { value_move(&regs[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); regs[m1+o+1] = rest; } if (m2 > 0 && argc-m2 > m1) { value_move(&regs[m1+o+r+1], &argv[m1+o+rnum], m2); } pc += o*3; } /* need to be update blk first to protect blk from GC */ regs[blk_pos] = blk; /* move block */ if (kd) { if (mrb_nil_p(kdict)) kdict = mrb_hash_new_capa(mrb, 0); regs[kw_pos] = kdict; /* set kwhash */ } /* format arguments for generated code */ mrb->c->ci->n = len; /* clear local (but non-argument) variables */ if (irep->nlocals-blk_pos-1 > 0) { stack_clear(&regs[blk_pos+1], irep->nlocals-blk_pos-1); } JUMP; } CASE(OP_KARG, BB) { mrb_value k = mrb_symbol_value(syms[b]); mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict, v; if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) { mrb_value str = mrb_format(mrb, "missing keyword: %v", k); mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str)); goto L_RAISE; } v = mrb_hash_get(mrb, kdict, k); regs[a] = v; mrb_hash_delete_key(mrb, kdict, k); NEXT; } CASE(OP_KEY_P, BB) { mrb_value k = mrb_symbol_value(syms[b]); mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; mrb_bool key_p = FALSE; if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) { key_p = mrb_hash_key_p(mrb, kdict, k); } regs[a] = mrb_bool_value(key_p); NEXT; } CASE(OP_KEYEND, Z) { mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) { mrb_value keys = mrb_hash_keys(mrb, kdict); mrb_value key1 = RARRAY_PTR(keys)[0]; mrb_value str = mrb_format(mrb, "unknown keyword: %v", key1); mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str)); goto L_RAISE; } NEXT; } CASE(OP_BREAK, B) { c = OP_R_BREAK; goto L_RETURN; } CASE(OP_RETURN_BLK, B) { c = OP_R_RETURN; goto L_RETURN; } CASE(OP_RETURN, B) c = OP_R_NORMAL; L_RETURN: { mrb_callinfo *ci; ci = mrb->c->ci; if (ci->mid) { mrb_value blk = regs[mrb_ci_bidx(ci)]; if (mrb_proc_p(blk)) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { L_RAISE: ci = mrb->c->ci; if (ci == mrb->c->cibase) { ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL); if (ch == NULL) goto L_FTOP; goto L_CATCH; } while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) { ci = cipop(mrb); if (ci[1].cci == CINFO_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } pc = ci[0].pc; if (ci == mrb->c->cibase) { ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL); if (ch == NULL) { L_FTOP: /* fiber top */ if (mrb->c == mrb->root_c) { mrb->c->ci->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } } L_CATCH: if (ch == NULL) goto L_STOP; if (FALSE) { L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */ ci = mrb->c->ci; } proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, irep->nregs); pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target); } else { mrb_int acc; mrb_value v; ci = mrb->c->ci; v = regs[a]; mrb_gc_protect(mrb, v); switch (c) { case OP_R_RETURN: /* Fall through to OP_R_NORMAL otherwise */ if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { const struct RProc *dst; mrb_callinfo *cibase; cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } /* check jump destination */ while (cibase <= ci && ci->proc != dst) { if (ci->cci > CINFO_NONE) { /* jump cross C boundary */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { /* no jump destination */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci = mrb->c->ci; while (cibase <= ci && ci->proc != dst) { CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) { cibase = mrb->c->cibase; dst = top_proc(mrb, proc); } CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK); ci = cipop(mrb); pc = ci->pc; } proc = ci->proc; mrb->exc = NULL; /* clear break object */ break; } /* fallthrough */ case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; c = mrb->c; if (!c->prev) { /* toplevel return */ regs[irep->nlocals] = v; goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP); } if (!c->vmexec && c->prev->ci == c->prev->cibase) { mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, "double resume"); mrb_exc_set(mrb, exc); goto L_RAISE; } CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) { c = mrb->c; } CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL); /* automatic yield at the end */ c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; mrb->c->status = MRB_FIBER_RUNNING; c->prev = NULL; if (c->vmexec) { mrb_gc_arena_restore(mrb, ai); c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } ci = mrb->c->ci; } CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_RETURN) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN); mrb->exc = NULL; /* clear break object */ break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR, "break from proc-closure"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK); /* break from fiber block */ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->cci > CINFO_NONE) { ci = cipop(mrb); mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v); mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { struct RBreak *brk; L_BREAK: brk = (struct RBreak*)mrb->exc; proc = mrb_break_proc_get(brk); v = mrb_break_value_get(brk); ci = mrb->c->ci; switch (mrb_break_tag_get(brk)) { #define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n); RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS) #undef DISPATCH_CHECKPOINTS default: mrb_assert(!"wrong break tag"); } } while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) { if (ci[-1].cci == CINFO_SKIP) { goto L_BREAK_ERROR; } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER); ci = cipop(mrb); pc = ci->pc; } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET); if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } mrb->exc = NULL; /* clear break object */ break; default: /* cannot happen */ break; } mrb_assert(ci == mrb->c->ci); mrb_assert(mrb->exc == NULL); if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->cci; ci = cipop(mrb); if (acc == CINFO_SKIP || acc == CINFO_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; DEBUG(fprintf(stderr, "from :%s\n", mrb_sym_name(mrb, ci->mid))); proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci[1].stack[0] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_BLKPUSH, BS) { int m1 = (b>>11)&0x3f; int r = (b>>10)&0x1; int m2 = (b>>5)&0x1f; int kd = (b>>4)&0x1; int lv = (b>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) || MRB_ENV_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2+kd])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2+kd]; NEXT; } L_INT_OVERFLOW: { mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, "integer overflow"); mrb_exc_set(mrb, exc); } goto L_RAISE; #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH(op_name) \ /* need to check if op is overridden */ \ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { \ OP_MATH_CASE_INTEGER(op_name); \ OP_MATH_CASE_FLOAT(op_name, integer, float); \ OP_MATH_CASE_FLOAT(op_name, float, integer); \ OP_MATH_CASE_FLOAT(op_name, float, float); \ OP_MATH_CASE_STRING_##op_name(); \ default: \ mid = MRB_OPSYM(op_name); \ goto L_SEND_SYM; \ } \ NEXT; #define OP_MATH_CASE_INTEGER(op_name) \ case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER): \ { \ mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z; \ if (mrb_int_##op_name##_overflow(x, y, &z)) \ OP_MATH_OVERFLOW_INT(); \ else \ SET_INT_VALUE(mrb,regs[a], z); \ } \ break #ifdef MRB_NO_FLOAT #define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0 #else #define OP_MATH_CASE_FLOAT(op_name, t1, t2) \ case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2): \ { \ mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \ SET_FLOAT_VALUE(mrb, regs[a], z); \ } \ break #endif #define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW #define OP_MATH_CASE_STRING_add() \ case TYPES2(MRB_TT_STRING, MRB_TT_STRING): \ regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); \ mrb_gc_arena_restore(mrb, ai); \ break #define OP_MATH_CASE_STRING_sub() (void)0 #define OP_MATH_CASE_STRING_mul() (void)0 #define OP_MATH_OP_add + #define OP_MATH_OP_sub - #define OP_MATH_OP_mul * #define OP_MATH_TT_integer MRB_TT_INTEGER #define OP_MATH_TT_float MRB_TT_FLOAT CASE(OP_ADD, B) { OP_MATH(add); } CASE(OP_SUB, B) { OP_MATH(sub); } CASE(OP_MUL, B) { OP_MATH(mul); } CASE(OP_DIV, B) { #ifndef MRB_NO_FLOAT mrb_float x, y, f; #endif /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER): { mrb_int x = mrb_integer(regs[a]); mrb_int y = mrb_integer(regs[a+1]); mrb_int div = mrb_div_int(mrb, x, y); SET_INT_VALUE(mrb, regs[a], div); } NEXT; #ifndef MRB_NO_FLOAT case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT): x = (mrb_float)mrb_integer(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER): x = mrb_float(regs[a]); y = (mrb_float)mrb_integer(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: mid = MRB_OPSYM(div); goto L_SEND_SYM; } #ifndef MRB_NO_FLOAT f = mrb_div_float(x, y); SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } #define OP_MATHI(op_name) \ /* need to check if op is overridden */ \ switch (mrb_type(regs[a])) { \ OP_MATHI_CASE_INTEGER(op_name); \ OP_MATHI_CASE_FLOAT(op_name); \ default: \ SET_INT_VALUE(mrb,regs[a+1], b); \ mid = MRB_OPSYM(op_name); \ goto L_SEND_SYM; \ } \ NEXT; #define OP_MATHI_CASE_INTEGER(op_name) \ case MRB_TT_INTEGER: \ { \ mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z; \ if (mrb_int_##op_name##_overflow(x, y, &z)) \ OP_MATH_OVERFLOW_INT(); \ else \ SET_INT_VALUE(mrb,regs[a], z); \ } \ break #ifdef MRB_NO_FLOAT #define OP_MATHI_CASE_FLOAT(op_name) (void)0 #else #define OP_MATHI_CASE_FLOAT(op_name) \ case MRB_TT_FLOAT: \ { \ mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b; \ SET_FLOAT_VALUE(mrb, regs[a], z); \ } \ break #endif CASE(OP_ADDI, BB) { OP_MATHI(add); } CASE(OP_SUBI, BB) { OP_MATHI(sub); } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_NO_FLOAT #define OP_CMP(op,sym) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ default:\ mid = MRB_OPSYM(sym);\ goto L_SEND_SYM;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #else #define OP_CMP(op, sym) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\ break;\ default:\ mid = MRB_OPSYM(sym);\ goto L_SEND_SYM;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #endif CASE(OP_EQ, B) { if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==,eq); } NEXT; } CASE(OP_LT, B) { OP_CMP(<,lt); NEXT; } CASE(OP_LE, B) { OP_CMP(<=,le); NEXT; } CASE(OP_GT, B) { OP_CMP(>,gt); NEXT; } CASE(OP_GE, B) { OP_CMP(>=,ge); NEXT; } CASE(OP_ARRAY, BB) { regs[a] = mrb_ary_new_from_values(mrb, b, &regs[a]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARRAY2, BBB) { regs[a] = mrb_ary_new_from_values(mrb, c, &regs[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT, B) { mrb_value splat = mrb_ary_splat(mrb, regs[a+1]); if (mrb_nil_p(regs[a])) { regs[a] = splat; } else { mrb_assert(mrb_array_p(regs[a])); mrb_ary_concat(mrb, regs[a], splat); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH, BB) { mrb_assert(mrb_array_p(regs[a])); for (mrb_int i=0; i<b; i++) { mrb_ary_push(mrb, regs[a], regs[a+i+1]); } NEXT; } CASE(OP_ARYDUP, B) { mrb_value ary = regs[a]; if (mrb_array_p(ary)) { ary = mrb_ary_new_from_values(mrb, RARRAY_LEN(ary), RARRAY_PTR(ary)); } else { ary = mrb_ary_new_from_values(mrb, 1, &ary); } regs[a] = ary; NEXT; } CASE(OP_AREF, BBB) { mrb_value v = regs[b]; if (!mrb_array_p(v)) { if (c == 0) { regs[a] = v; } else { SET_NIL_VALUE(regs[a]); } } else { v = mrb_ary_ref(mrb, v, c); regs[a] = v; } NEXT; } CASE(OP_ASET, BBB) { mrb_assert(mrb_array_p(regs[a])); mrb_ary_set(mrb, regs[b], c, regs[a]); NEXT; } CASE(OP_APOST, BBB) { mrb_value v = regs[a]; int pre = b; int post = c; struct RArray *ary; int len, idx; if (!mrb_array_p(v)) { v = mrb_ary_new_from_values(mrb, 1, &regs[a]); } ary = mrb_ary_ptr(v); len = (int)ARY_LEN(ary); if (len > pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+pre<len; idx++) { regs[a+idx] = ARY_PTR(ary)[pre+idx]; } while (idx < post) { SET_NIL_VALUE(regs[a+idx]); idx++; } } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_INTERN, B) { mrb_assert(mrb_string_p(regs[a])); mrb_sym sym = mrb_intern_str(mrb, regs[a]); regs[a] = mrb_symbol_value(sym); NEXT; } CASE(OP_SYMBOL, BB) { size_t len; mrb_sym sym; mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0); len = pool[b].tt >> 2; if (pool[b].tt & IREP_TT_SFLAG) { sym = mrb_intern_static(mrb, pool[b].u.str, len); } else { sym = mrb_intern(mrb, pool[b].u.str, len); } regs[a] = mrb_symbol_value(sym); NEXT; } CASE(OP_STRING, BB) { mrb_int len; mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0); len = pool[b].tt >> 2; if (pool[b].tt & IREP_TT_SFLAG) { regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len); } else { regs[a] = mrb_str_new(mrb, pool[b].u.str, len); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_STRCAT, B) { mrb_assert(mrb_string_p(regs[a])); mrb_str_concat(mrb, regs[a], regs[a+1]); NEXT; } CASE(OP_HASH, BB) { mrb_value hash = mrb_hash_new_capa(mrb, b); int i; int lim = a+b*2; for (i=a; i<lim; i+=2) { mrb_hash_set(mrb, hash, regs[i], regs[i+1]); } regs[a] = hash; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_HASHADD, BB) { mrb_value hash; int i; int lim = a+b*2+1; hash = regs[a]; mrb_ensure_hash_type(mrb, hash); for (i=a+1; i<lim; i+=2) { mrb_hash_set(mrb, hash, regs[i], regs[i+1]); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_HASHCAT, B) { mrb_value hash = regs[a]; mrb_assert(mrb_hash_p(hash)); mrb_hash_merge(mrb, hash, regs[a+1]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_LAMBDA, BB) c = OP_L_LAMBDA; L_MAKE_LAMBDA: { struct RProc *p; const mrb_irep *nirep = irep->reps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_BLOCK, BB) { c = OP_L_BLOCK; goto L_MAKE_LAMBDA; } CASE(OP_METHOD, BB) { c = OP_L_METHOD; goto L_MAKE_LAMBDA; } CASE(OP_RANGE_INC, B) { mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_RANGE_EXC, B) { mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS, B) { regs[a] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS, BB) { struct RClass *c = 0, *baseclass; mrb_value base, super; mrb_sym id = syms[b]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); if (!baseclass) baseclass = mrb->object_class; base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE, BB) { struct RClass *cls = 0, *baseclass; mrb_value base; mrb_sym id = syms[b]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); if (!baseclass) baseclass = mrb->object_class; base = mrb_obj_value(baseclass); } cls = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(cls); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC, BB) { mrb_value recv = regs[a]; struct RProc *p; const mrb_irep *nirep = irep->reps[b]; /* prepare closure */ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; /* prepare call stack */ cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0); irep = p->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, irep->nregs); stack_clear(regs+1, irep->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_DEF, BB) { struct RClass *target = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; mrb_sym mid = syms[b]; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, target, mid, m); mrb_method_added(mrb, target, mid); mrb_gc_arena_restore(mrb, ai); regs[a] = mrb_symbol_value(mid); NEXT; } CASE(OP_SCLASS, B) { regs[a] = mrb_singleton_class(mrb, regs[a]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS, B) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; regs[a] = mrb_obj_value(target); NEXT; } CASE(OP_ALIAS, BB) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; mrb_alias_method(mrb, target, syms[a], syms[b]); mrb_method_added(mrb, target, syms[a]); NEXT; } CASE(OP_UNDEF, B) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; mrb_undef_method_id(mrb, target, syms[a]); NEXT; } CASE(OP_DEBUG, Z) { FETCH_BBB(); #ifdef MRB_USE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_NO_STDIO printf("OP_DEBUG %d %d %d\n", a, b, c); #else abort(); #endif #endif NEXT; } CASE(OP_ERR, B) { size_t len = pool[a].tt >> 2; mrb_value exc; mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0); exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len); mrb_exc_set(mrb, exc); goto L_RAISE; } CASE(OP_EXT1, Z) { insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include "mruby/ops.h" #undef OPCODE } pc--; NEXT; } CASE(OP_EXT2, Z) { insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include "mruby/ops.h" #undef OPCODE } pc--; NEXT; } CASE(OP_EXT3, Z) { uint8_t insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include "mruby/ops.h" #undef OPCODE } pc--; NEXT; } CASE(OP_STOP, Z) { /* stop VM */ CHECKPOINT_RESTORE(RBREAK_TAG_STOP) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_STOP) { UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value()); } CHECKPOINT_END(RBREAK_TAG_STOP); L_STOP: mrb->jmp = prev_jmp; if (mrb->exc) { mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION); return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { mrb_callinfo *ci = mrb->c->ci; while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) { ci = cipop(mrb); } exc_catched = TRUE; pc = ci->pc; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }
262390391813698997711941819907139112508
vm.c
37245825949579697049526879083139270753
CWE-288
CVE-2022-1212
Use-After-Free in str_escape in mruby/mruby in GitHub repository mruby/mruby prior to 3.2. Possible arbitrary code execution if being exploited.
https://nvd.nist.gov/vuln/detail/CVE-2022-1212
198,449
pjproject
450baca94f475345542c6953832650c390889202
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/450baca94f475345542c6953832650c390889202
Merge pull request from GHSA-26j7-ww69-c4qj
1
PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, pjstun_msg *msg) { pj_uint16_t msg_type, msg_len; char *p_attr; PJ_CHECK_STACK(); msg->hdr = (pjstun_msg_hdr*)buf; msg_type = pj_ntohs(msg->hdr->type); switch (msg_type) { case PJSTUN_BINDING_REQUEST: case PJSTUN_BINDING_RESPONSE: case PJSTUN_BINDING_ERROR_RESPONSE: case PJSTUN_SHARED_SECRET_REQUEST: case PJSTUN_SHARED_SECRET_RESPONSE: case PJSTUN_SHARED_SECRET_ERROR_RESPONSE: break; default: PJ_LOG(4,(THIS_FILE, "Error: unknown msg type %d", msg_type)); return PJLIB_UTIL_ESTUNINMSGTYPE; } msg_len = pj_ntohs(msg->hdr->length); if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) { PJ_LOG(4,(THIS_FILE, "Error: invalid msg_len %d (expecting %d)", msg_len, buf_len - sizeof(pjstun_msg_hdr))); return PJLIB_UTIL_ESTUNINMSGLEN; } msg->attr_count = 0; p_attr = (char*)buf + sizeof(pjstun_msg_hdr); while (msg_len > 0) { pjstun_attr_hdr **attr = &msg->attr[msg->attr_count]; pj_uint32_t len; pj_uint16_t attr_type; *attr = (pjstun_attr_hdr*)p_attr; len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr); len = (len + 3) & ~3; if (msg_len < len) { PJ_LOG(4,(THIS_FILE, "Error: length mismatch in attr %d", msg->attr_count)); return PJLIB_UTIL_ESTUNINATTRLEN; } attr_type = pj_ntohs((*attr)->type); if (attr_type > PJSTUN_ATTR_REFLECTED_FROM && attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR) { PJ_LOG(5,(THIS_FILE, "Warning: unknown attr type %x in attr %d. " "Attribute was ignored.", attr_type, msg->attr_count)); } msg_len = (pj_uint16_t)(msg_len - len); p_attr += len; ++msg->attr_count; } return PJ_SUCCESS; }
324794898254091416853424941566787120064
stun_simple.c
304268271857931505815837287097781884670
CWE-787
CVE-2022-31031
PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions prior to and including 2.12.1 a stack buffer overflow vulnerability affects PJSIP users that use STUN in their applications, either by: setting a STUN server in their account/media config in PJSUA/PJSUA2 level, or directly using `pjlib-util/stun_simple` API. A patch is available in commit 450baca which should be included in the next release. There are no known workarounds for this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-31031
274,814
pjproject
450baca94f475345542c6953832650c390889202
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/450baca94f475345542c6953832650c390889202
Merge pull request from GHSA-26j7-ww69-c4qj
0
PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, pjstun_msg *msg) { pj_uint16_t msg_type, msg_len; char *p_attr; int attr_max_cnt = PJ_ARRAY_SIZE(msg->attr); PJ_CHECK_STACK(); msg->hdr = (pjstun_msg_hdr*)buf; msg_type = pj_ntohs(msg->hdr->type); switch (msg_type) { case PJSTUN_BINDING_REQUEST: case PJSTUN_BINDING_RESPONSE: case PJSTUN_BINDING_ERROR_RESPONSE: case PJSTUN_SHARED_SECRET_REQUEST: case PJSTUN_SHARED_SECRET_RESPONSE: case PJSTUN_SHARED_SECRET_ERROR_RESPONSE: break; default: PJ_LOG(4,(THIS_FILE, "Error: unknown msg type %d", msg_type)); return PJLIB_UTIL_ESTUNINMSGTYPE; } msg_len = pj_ntohs(msg->hdr->length); if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) { PJ_LOG(4,(THIS_FILE, "Error: invalid msg_len %d (expecting %d)", msg_len, buf_len - sizeof(pjstun_msg_hdr))); return PJLIB_UTIL_ESTUNINMSGLEN; } msg->attr_count = 0; p_attr = (char*)buf + sizeof(pjstun_msg_hdr); while (msg_len > 0 && msg->attr_count < attr_max_cnt) { pjstun_attr_hdr **attr = &msg->attr[msg->attr_count]; pj_uint32_t len; pj_uint16_t attr_type; *attr = (pjstun_attr_hdr*)p_attr; len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr); len = (len + 3) & ~3; if (msg_len < len) { PJ_LOG(4,(THIS_FILE, "Error: length mismatch in attr %d", msg->attr_count)); return PJLIB_UTIL_ESTUNINATTRLEN; } attr_type = pj_ntohs((*attr)->type); if (attr_type > PJSTUN_ATTR_REFLECTED_FROM && attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR) { PJ_LOG(5,(THIS_FILE, "Warning: unknown attr type %x in attr %d. " "Attribute was ignored.", attr_type, msg->attr_count)); } msg_len = (pj_uint16_t)(msg_len - len); p_attr += len; ++msg->attr_count; } if (msg->attr_count == attr_max_cnt) { PJ_LOG(4, (THIS_FILE, "Warning: max number attribute %d reached.", attr_max_cnt)); } return PJ_SUCCESS; }
200469816079159611843255339356668630427
stun_simple.c
232929880993033123827596664617421496425
CWE-787
CVE-2022-31031
PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions prior to and including 2.12.1 a stack buffer overflow vulnerability affects PJSIP users that use STUN in their applications, either by: setting a STUN server in their account/media config in PJSUA/PJSUA2 level, or directly using `pjlib-util/stun_simple` API. A patch is available in commit 450baca which should be included in the next release. There are no known workarounds for this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-31031
198,452
tensorflow
a989426ee1346693cc015792f11d715f6944f2b8
https://github.com/tensorflow/tensorflow
https://github.com/tensorflow/tensorflow/commit/a989426ee1346693cc015792f11d715f6944f2b8
Improve to cover scale value greater than one PiperOrigin-RevId: 433050921
1
void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output, bool requires_broadcast) { if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) { auto input1_offset = -input1->params.zero_point; auto input2_offset = -input2->params.zero_point; const int left_shift = 8; int32 input1_multiplier; int input1_shift; QuantizeMultiplierSmallerThanOneExp(input1->params.scale, &input1_multiplier, &input1_shift); int32 input2_multiplier; int input2_shift; QuantizeMultiplierSmallerThanOneExp(input2->params.scale, &input2_multiplier, &input2_shift); ComparisonParams op_params; op_params.left_shift = left_shift; op_params.input1_offset = input1_offset; op_params.input1_multiplier = input1_multiplier; op_params.input1_shift = input1_shift; op_params.input2_offset = input2_offset; op_params.input2_multiplier = input2_multiplier; op_params.input2_shift = input2_shift; if (requires_broadcast) { reference_ops::BroadcastComparison4DSlowWithScaling<input_dtype, opname>( op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1), GetTensorShape(input2), GetTensorData<input_dtype>(input2), GetTensorShape(output), GetTensorData<bool>(output)); } else { reference_ops::ComparisonWithScaling<input_dtype, opname>( op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1), GetTensorShape(input2), GetTensorData<input_dtype>(input2), GetTensorShape(output), GetTensorData<bool>(output)); } } }
284336502909303651692457957640037138117
comparisons.cc
224870261654956140630544765652331160875
CWE-703
CVE-2022-29212
TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, certain TFLite models that were created using TFLite model converter would crash when loaded in the TFLite interpreter. The culprit is that during quantization the scale of values could be greater than 1 but code was always assuming sub-unit scaling. Thus, since code was calling `QuantizeMultiplierSmallerThanOneExp`, the `TFLITE_CHECK_LT` assertion would trigger and abort the process. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-29212
274,865
tensorflow
a989426ee1346693cc015792f11d715f6944f2b8
https://github.com/tensorflow/tensorflow
https://github.com/tensorflow/tensorflow/commit/a989426ee1346693cc015792f11d715f6944f2b8
Improve to cover scale value greater than one PiperOrigin-RevId: 433050921
0
void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output, bool requires_broadcast) { if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) { auto input1_offset = -input1->params.zero_point; auto input2_offset = -input2->params.zero_point; const int left_shift = 8; int32 input1_multiplier; int32 input2_multiplier; int input1_shift; int input2_shift; QuantizeMultiplier(input1->params.scale, &input1_multiplier, &input1_shift); QuantizeMultiplier(input2->params.scale, &input2_multiplier, &input2_shift); ComparisonParams op_params; op_params.left_shift = left_shift; op_params.input1_offset = input1_offset; op_params.input1_multiplier = input1_multiplier; op_params.input1_shift = input1_shift; op_params.input2_offset = input2_offset; op_params.input2_multiplier = input2_multiplier; op_params.input2_shift = input2_shift; if (requires_broadcast) { reference_ops::BroadcastComparison4DSlowWithScaling<input_dtype, opname>( op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1), GetTensorShape(input2), GetTensorData<input_dtype>(input2), GetTensorShape(output), GetTensorData<bool>(output)); } else { reference_ops::ComparisonWithScaling<input_dtype, opname>( op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1), GetTensorShape(input2), GetTensorData<input_dtype>(input2), GetTensorShape(output), GetTensorData<bool>(output)); } } }
213386004946249159247710639352470904167
comparisons.cc
191046017812634874260331571010514719419
CWE-703
CVE-2022-29212
TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, certain TFLite models that were created using TFLite model converter would crash when loaded in the TFLite interpreter. The culprit is that during quantization the scale of values could be greater than 1 but code was always assuming sub-unit scaling. Thus, since code was calling `QuantizeMultiplierSmallerThanOneExp`, the `TFLITE_CHECK_LT` assertion would trigger and abort the process. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-29212
198,476
njs
6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6
https://github.com/nginx/njs
https://github.com/nginx/njs/commit/6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6
Fixed recursive async function calls. Previously, PromiseCapability record was stored (function->context) directly in function object during a function invocation. This is not correct, because PromiseCapability record should be linked to current execution context. As a result, function->context is overwritten with consecutive recursive calls which results in use-after-free. This closes #451 issue on Github.
1
njs_await_fulfilled(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, njs_index_t unused) { njs_int_t ret; njs_value_t **cur_local, **cur_closures, **cur_temp, *value; njs_frame_t *frame, *async_frame; njs_function_t *function; njs_async_ctx_t *ctx; njs_native_frame_t *top, *async; ctx = vm->top_frame->function->context; value = njs_arg(args, nargs, 1); if (njs_is_error(value)) { goto failed; } async_frame = ctx->await; async = &async_frame->native; async->previous = vm->top_frame; function = async->function; cur_local = vm->levels[NJS_LEVEL_LOCAL]; cur_closures = vm->levels[NJS_LEVEL_CLOSURE]; cur_temp = vm->levels[NJS_LEVEL_TEMP]; top = vm->top_frame; frame = vm->active_frame; vm->levels[NJS_LEVEL_LOCAL] = async->local; vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(async->function); vm->levels[NJS_LEVEL_TEMP] = async->temp; vm->top_frame = async; vm->active_frame = async_frame; *njs_scope_value(vm, ctx->index) = *value; vm->retval = *value; vm->top_frame->retval = &vm->retval; function->context = ctx->capability; function->await = ctx; ret = njs_vmcode_interpreter(vm, ctx->pc); function->context = NULL; function->await = NULL; vm->levels[NJS_LEVEL_LOCAL] = cur_local; vm->levels[NJS_LEVEL_CLOSURE] = cur_closures; vm->levels[NJS_LEVEL_TEMP] = cur_temp; vm->top_frame = top; vm->active_frame = frame; if (ret == NJS_OK) { ret = njs_function_call(vm, njs_function(&ctx->capability->resolve), &njs_value_undefined, &vm->retval, 1, &vm->retval); njs_async_context_free(vm, ctx); } else if (ret == NJS_AGAIN) { ret = NJS_OK; } else if (ret == NJS_ERROR) { if (njs_is_memory_error(vm, &vm->retval)) { return NJS_ERROR; } value = &vm->retval; goto failed; } return ret; failed: (void) njs_function_call(vm, njs_function(&ctx->capability->reject), &njs_value_undefined, value, 1, &vm->retval); njs_async_context_free(vm, ctx); return NJS_ERROR; }
241518720909355358001984532864321433833
njs_async.c
139542101989914499952242434630508544825
CWE-416
CVE-2022-25139
njs through 0.7.0, used in NGINX, was discovered to contain a heap use-after-free in njs_await_fulfilled.
https://nvd.nist.gov/vuln/detail/CVE-2022-25139
275,525
njs
6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6
https://github.com/nginx/njs
https://github.com/nginx/njs/commit/6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6
Fixed recursive async function calls. Previously, PromiseCapability record was stored (function->context) directly in function object during a function invocation. This is not correct, because PromiseCapability record should be linked to current execution context. As a result, function->context is overwritten with consecutive recursive calls which results in use-after-free. This closes #451 issue on Github.
0
njs_await_fulfilled(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, njs_index_t unused) { njs_int_t ret; njs_value_t **cur_local, **cur_closures, **cur_temp, *value; njs_frame_t *frame, *async_frame; njs_async_ctx_t *ctx; njs_native_frame_t *top, *async; ctx = vm->top_frame->function->context; value = njs_arg(args, nargs, 1); if (njs_is_error(value)) { goto failed; } async_frame = ctx->await; async = &async_frame->native; async->previous = vm->top_frame; cur_local = vm->levels[NJS_LEVEL_LOCAL]; cur_closures = vm->levels[NJS_LEVEL_CLOSURE]; cur_temp = vm->levels[NJS_LEVEL_TEMP]; top = vm->top_frame; frame = vm->active_frame; vm->levels[NJS_LEVEL_LOCAL] = async->local; vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(async->function); vm->levels[NJS_LEVEL_TEMP] = async->temp; vm->top_frame = async; vm->active_frame = async_frame; *njs_scope_value(vm, ctx->index) = *value; vm->retval = *value; vm->top_frame->retval = &vm->retval; ret = njs_vmcode_interpreter(vm, ctx->pc, ctx->capability, ctx); vm->levels[NJS_LEVEL_LOCAL] = cur_local; vm->levels[NJS_LEVEL_CLOSURE] = cur_closures; vm->levels[NJS_LEVEL_TEMP] = cur_temp; vm->top_frame = top; vm->active_frame = frame; if (ret == NJS_OK) { ret = njs_function_call(vm, njs_function(&ctx->capability->resolve), &njs_value_undefined, &vm->retval, 1, &vm->retval); njs_async_context_free(vm, ctx); } else if (ret == NJS_AGAIN) { ret = NJS_OK; } else if (ret == NJS_ERROR) { if (njs_is_memory_error(vm, &vm->retval)) { return NJS_ERROR; } value = &vm->retval; goto failed; } return ret; failed: (void) njs_function_call(vm, njs_function(&ctx->capability->reject), &njs_value_undefined, value, 1, &vm->retval); njs_async_context_free(vm, ctx); return NJS_ERROR; }
111576454892773184522255566086081823579
njs_async.c
224952791495383164899496869298957477614
CWE-416
CVE-2022-25139
njs through 0.7.0, used in NGINX, was discovered to contain a heap use-after-free in njs_await_fulfilled.
https://nvd.nist.gov/vuln/detail/CVE-2022-25139
198,499
micro-ecc
1b5f5cea5145c96dd8791b9b2c41424fc74c2172
https://github.com/kmackay/micro-ecc
https://github.com/kmackay/micro-ecc/commit/1b5f5cea5145c96dd8791b9b2c41424fc74c2172
Fix for #168
1
static int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uECC_word_t *k, uint8_t *signature, uECC_Curve curve) { uECC_word_t tmp[uECC_MAX_WORDS]; uECC_word_t s[uECC_MAX_WORDS]; uECC_word_t *k2[2] = {tmp, s}; #if uECC_VLI_NATIVE_LITTLE_ENDIAN uECC_word_t *p = (uECC_word_t *)signature; #else uECC_word_t p[uECC_MAX_WORDS * 2]; #endif uECC_word_t carry; wordcount_t num_words = curve->num_words; wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); bitcount_t num_n_bits = curve->num_n_bits; /* Make sure 0 < k < curve_n */ if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) { return 0; } carry = regularize_k(k, tmp, s, curve); EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve); if (uECC_vli_isZero(p, num_words)) { return 0; } /* If an RNG function was specified, get a random number to prevent side channel analysis of k. */ if (!g_rng_function) { uECC_vli_clear(tmp, num_n_words); tmp[0] = 1; } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) { return 0; } /* Prevent side channel analysis of uECC_vli_modInv() to determine bits of k / the private key by premultiplying by a random number */ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */ uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */ #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */ #endif #if uECC_VLI_NATIVE_LITTLE_ENDIAN bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); #else uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */ #endif s[num_n_words - 1] = 0; uECC_vli_set(s, p, num_words); uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */ bits2int(tmp, message_hash, hash_size, curve); uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */ uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */ if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) { return 0; } #if uECC_VLI_NATIVE_LITTLE_ENDIAN bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s, curve->num_bytes); #else uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s); #endif return 1; }
250707445511654521220716932779019293116
uECC.c
221730154760089899908262595980065132519
CWE-415
CVE-2020-27209
The ECDSA operation of the micro-ecc library 1.0 is vulnerable to simple power analysis attacks which allows an adversary to extract the private ECC key.
https://nvd.nist.gov/vuln/detail/CVE-2020-27209
275,987
micro-ecc
1b5f5cea5145c96dd8791b9b2c41424fc74c2172
https://github.com/kmackay/micro-ecc
https://github.com/kmackay/micro-ecc/commit/1b5f5cea5145c96dd8791b9b2c41424fc74c2172
Fix for #168
0
static int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uECC_word_t *k, uint8_t *signature, uECC_Curve curve) { uECC_word_t tmp[uECC_MAX_WORDS]; uECC_word_t s[uECC_MAX_WORDS]; uECC_word_t *k2[2] = {tmp, s}; uECC_word_t *initial_Z = 0; #if uECC_VLI_NATIVE_LITTLE_ENDIAN uECC_word_t *p = (uECC_word_t *)signature; #else uECC_word_t p[uECC_MAX_WORDS * 2]; #endif uECC_word_t carry; wordcount_t num_words = curve->num_words; wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); bitcount_t num_n_bits = curve->num_n_bits; /* Make sure 0 < k < curve_n */ if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) { return 0; } carry = regularize_k(k, tmp, s, curve); /* If an RNG function was specified, try to get a random initial Z value to improve protection against side-channel attacks. */ if (g_rng_function) { if (!uECC_generate_random_int(k2[carry], curve->p, num_words)) { return 0; } initial_Z = k2[carry]; } EccPoint_mult(p, curve->G, k2[!carry], initial_Z, num_n_bits + 1, curve); if (uECC_vli_isZero(p, num_words)) { return 0; } /* If an RNG function was specified, get a random number to prevent side channel analysis of k. */ if (!g_rng_function) { uECC_vli_clear(tmp, num_n_words); tmp[0] = 1; } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) { return 0; } /* Prevent side channel analysis of uECC_vli_modInv() to determine bits of k / the private key by premultiplying by a random number */ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */ uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */ #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */ #endif #if uECC_VLI_NATIVE_LITTLE_ENDIAN bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); #else uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */ #endif s[num_n_words - 1] = 0; uECC_vli_set(s, p, num_words); uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */ bits2int(tmp, message_hash, hash_size, curve); uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */ uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */ if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) { return 0; } #if uECC_VLI_NATIVE_LITTLE_ENDIAN bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s, curve->num_bytes); #else uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s); #endif return 1; }
118273926663441096280456772911326940472
uECC.c
232283246719977371910544173978221438887
CWE-415
CVE-2020-27209
The ECDSA operation of the micro-ecc library 1.0 is vulnerable to simple power analysis attacks which allows an adversary to extract the private ECC key.
https://nvd.nist.gov/vuln/detail/CVE-2020-27209
198,523
tensorflow
5ecec9c6fbdbc6be03295685190a45e7eee726ab
https://github.com/tensorflow/tensorflow
https://github.com/tensorflow/tensorflow/commit/5ecec9c6fbdbc6be03295685190a45e7eee726ab
Prevent use after free. A very old version of the code used `result` as a simple pointer to a resource. Two years later, the pointer got changed to a `unique_ptr` but author forgot to remove the call to `Unref`. Three years after that, we finally uncover the UAF. PiperOrigin-RevId: 387924872 Change-Id: I70fb6f199164de49fac20c168132a07b84903f9b
1
void Compute(OpKernelContext* context) override { // Get the stamp token. const Tensor* stamp_token_t; OP_REQUIRES_OK(context, context->input("stamp_token", &stamp_token_t)); int64_t stamp_token = stamp_token_t->scalar<int64>()(); // Get the tree ensemble proto. const Tensor* tree_ensemble_serialized_t; OP_REQUIRES_OK(context, context->input("tree_ensemble_serialized", &tree_ensemble_serialized_t)); std::unique_ptr<BoostedTreesEnsembleResource> result( new BoostedTreesEnsembleResource()); if (!result->InitFromSerialized( tree_ensemble_serialized_t->scalar<tstring>()(), stamp_token)) { result->Unref(); OP_REQUIRES( context, false, errors::InvalidArgument("Unable to parse tree ensemble proto.")); } // Only create one, if one does not exist already. Report status for all // other exceptions. auto status = CreateResource(context, HandleFromInput(context, 0), result.release()); if (status.code() != tensorflow::error::ALREADY_EXISTS) { OP_REQUIRES_OK(context, status); } }
151034027968901870222536100864741418474
resource_ops.cc
40939400980967911969144269399937980796
CWE-416
CVE-2021-37652
TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation for `tf.raw_ops.BoostedTreesCreateEnsemble` can result in a use after free error if an attacker supplies specially crafted arguments. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/boosted_trees/resource_ops.cc#L55) uses a reference counted resource and decrements the refcount if the initialization fails, as it should. However, when the code was written, the resource was represented as a naked pointer but later refactoring has changed it to be a smart pointer. Thus, when the pointer leaves the scope, a subsequent `free`-ing of the resource occurs, but this fails to take into account that the refcount has already reached 0, thus the resource has been already freed. During this double-free process, members of the resource object are accessed for cleanup but they are invalid as the entire resource has been freed. We have patched the issue in GitHub commit 5ecec9c6fbdbc6be03295685190a45e7eee726ab. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.
https://nvd.nist.gov/vuln/detail/CVE-2021-37652
276,447
tensorflow
5ecec9c6fbdbc6be03295685190a45e7eee726ab
https://github.com/tensorflow/tensorflow
https://github.com/tensorflow/tensorflow/commit/5ecec9c6fbdbc6be03295685190a45e7eee726ab
Prevent use after free. A very old version of the code used `result` as a simple pointer to a resource. Two years later, the pointer got changed to a `unique_ptr` but author forgot to remove the call to `Unref`. Three years after that, we finally uncover the UAF. PiperOrigin-RevId: 387924872 Change-Id: I70fb6f199164de49fac20c168132a07b84903f9b
0
void Compute(OpKernelContext* context) override { // Get the stamp token. const Tensor* stamp_token_t; OP_REQUIRES_OK(context, context->input("stamp_token", &stamp_token_t)); int64_t stamp_token = stamp_token_t->scalar<int64>()(); // Get the tree ensemble proto. const Tensor* tree_ensemble_serialized_t; OP_REQUIRES_OK(context, context->input("tree_ensemble_serialized", &tree_ensemble_serialized_t)); std::unique_ptr<BoostedTreesEnsembleResource> result( new BoostedTreesEnsembleResource()); if (!result->InitFromSerialized( tree_ensemble_serialized_t->scalar<tstring>()(), stamp_token)) { result->Unref(); result.release(); // Needed due to the `->Unref` above, to prevent UAF OP_REQUIRES( context, false, errors::InvalidArgument("Unable to parse tree ensemble proto.")); } // Only create one, if one does not exist already. Report status for all // other exceptions. auto status = CreateResource(context, HandleFromInput(context, 0), result.release()); if (status.code() != tensorflow::error::ALREADY_EXISTS) { OP_REQUIRES_OK(context, status); } }
115602178708451028825719002696661348197
resource_ops.cc
61383399308207725848810164035477638721
CWE-416
CVE-2021-37652
TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation for `tf.raw_ops.BoostedTreesCreateEnsemble` can result in a use after free error if an attacker supplies specially crafted arguments. The [implementation](https://github.com/tensorflow/tensorflow/blob/f24faa153ad31a4b51578f8181d3aaab77a1ddeb/tensorflow/core/kernels/boosted_trees/resource_ops.cc#L55) uses a reference counted resource and decrements the refcount if the initialization fails, as it should. However, when the code was written, the resource was represented as a naked pointer but later refactoring has changed it to be a smart pointer. Thus, when the pointer leaves the scope, a subsequent `free`-ing of the resource occurs, but this fails to take into account that the refcount has already reached 0, thus the resource has been already freed. During this double-free process, members of the resource object are accessed for cleanup but they are invalid as the entire resource has been freed. We have patched the issue in GitHub commit 5ecec9c6fbdbc6be03295685190a45e7eee726ab. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.
https://nvd.nist.gov/vuln/detail/CVE-2021-37652
198,545
u-boot
8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409
https://github.com/u-boot/u-boot
https://github.com/u-boot/u-boot/commit/8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409
i2c: fix stack buffer overflow vulnerability in i2c md command When running "i2c md 0 0 80000100", the function do_i2c_md parses the length into an unsigned int variable named length. The value is then moved to a signed variable: int nbytes = length; #define DISP_LINE_LEN 16 int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes; ret = dm_i2c_read(dev, addr, linebuf, linebytes); On systems where integers are 32 bits wide, 0x80000100 is a negative value to "nbytes > DISP_LINE_LEN" is false and linebytes gets assigned 0x80000100 instead of 16. The consequence is that the function which reads from the i2c device (dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill but with a size parameter which is too large. In some cases, this could trigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c (used with "nexell,s5pxx18-i2c" bus), the size is actually truncated to a 16-bit integer. This is because function i2c_transfer expects an unsigned short length. In such a case, an attacker who can control the response of an i2c device can overwrite the return address of a function and execute arbitrary code through Return-Oriented Programming. Fix this issue by using unsigned integers types in do_i2c_md. While at it, make also alen unsigned, as signed sizes can cause vulnerabilities when people forgot to check that they can be negative. Signed-off-by: Nicolas Iooss <[email protected]> Reviewed-by: Heiko Schocher <[email protected]>
1
static int do_i2c_md(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]) { uint chip; uint addr, length; int alen; int j, nbytes, linebytes; int ret; #if CONFIG_IS_ENABLED(DM_I2C) struct udevice *dev; #endif /* We use the last specified parameters, unless new ones are * entered. */ chip = i2c_dp_last_chip; addr = i2c_dp_last_addr; alen = i2c_dp_last_alen; length = i2c_dp_last_length; if (argc < 3) return CMD_RET_USAGE; if ((flag & CMD_FLAG_REPEAT) == 0) { /* * New command specified. */ /* * I2C chip address */ chip = hextoul(argv[1], NULL); /* * I2C data address within the chip. This can be 1 or * 2 bytes long. Some day it might be 3 bytes long :-). */ addr = hextoul(argv[2], NULL); alen = get_alen(argv[2], DEFAULT_ADDR_LEN); if (alen > 3) return CMD_RET_USAGE; /* * If another parameter, it is the length to display. * Length is the number of objects, not number of bytes. */ if (argc > 3) length = hextoul(argv[3], NULL); } #if CONFIG_IS_ENABLED(DM_I2C) ret = i2c_get_cur_bus_chip(chip, &dev); if (!ret && alen != -1) ret = i2c_set_chip_offset_len(dev, alen); if (ret) return i2c_report_err(ret, I2C_ERR_READ); #endif /* * Print the lines. * * We buffer all read data, so we can make sure data is read only * once. */ nbytes = length; do { unsigned char linebuf[DISP_LINE_LEN]; unsigned char *cp; linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes; #if CONFIG_IS_ENABLED(DM_I2C) ret = dm_i2c_read(dev, addr, linebuf, linebytes); #else ret = i2c_read(chip, addr, alen, linebuf, linebytes); #endif if (ret) return i2c_report_err(ret, I2C_ERR_READ); else { printf("%04x:", addr); cp = linebuf; for (j=0; j<linebytes; j++) { printf(" %02x", *cp++); addr++; } puts (" "); cp = linebuf; for (j=0; j<linebytes; j++) { if ((*cp < 0x20) || (*cp > 0x7e)) puts ("."); else printf("%c", *cp); cp++; } putc ('\n'); } nbytes -= linebytes; } while (nbytes > 0); i2c_dp_last_chip = chip; i2c_dp_last_addr = addr; i2c_dp_last_alen = alen; i2c_dp_last_length = length; return 0; }
336388644236353594568664801027238457577
i2c.c
135764079202241918781821738561519186738
CWE-787
CVE-2022-34835
In Das U-Boot through 2022.07-rc5, an integer signedness error and resultant stack-based buffer overflow in the "i2c md" command enables the corruption of the return address pointer of the do_i2c_md function.
https://nvd.nist.gov/vuln/detail/CVE-2022-34835
276,921
u-boot
8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409
https://github.com/u-boot/u-boot
https://github.com/u-boot/u-boot/commit/8f8c04bf1ebbd2f72f1643e7ad9617dafa6e5409
i2c: fix stack buffer overflow vulnerability in i2c md command When running "i2c md 0 0 80000100", the function do_i2c_md parses the length into an unsigned int variable named length. The value is then moved to a signed variable: int nbytes = length; #define DISP_LINE_LEN 16 int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes; ret = dm_i2c_read(dev, addr, linebuf, linebytes); On systems where integers are 32 bits wide, 0x80000100 is a negative value to "nbytes > DISP_LINE_LEN" is false and linebytes gets assigned 0x80000100 instead of 16. The consequence is that the function which reads from the i2c device (dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill but with a size parameter which is too large. In some cases, this could trigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c (used with "nexell,s5pxx18-i2c" bus), the size is actually truncated to a 16-bit integer. This is because function i2c_transfer expects an unsigned short length. In such a case, an attacker who can control the response of an i2c device can overwrite the return address of a function and execute arbitrary code through Return-Oriented Programming. Fix this issue by using unsigned integers types in do_i2c_md. While at it, make also alen unsigned, as signed sizes can cause vulnerabilities when people forgot to check that they can be negative. Signed-off-by: Nicolas Iooss <[email protected]> Reviewed-by: Heiko Schocher <[email protected]>
0
static int do_i2c_md(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]) { uint chip; uint addr, length; uint alen; uint j, nbytes, linebytes; int ret; #if CONFIG_IS_ENABLED(DM_I2C) struct udevice *dev; #endif /* We use the last specified parameters, unless new ones are * entered. */ chip = i2c_dp_last_chip; addr = i2c_dp_last_addr; alen = i2c_dp_last_alen; length = i2c_dp_last_length; if (argc < 3) return CMD_RET_USAGE; if ((flag & CMD_FLAG_REPEAT) == 0) { /* * New command specified. */ /* * I2C chip address */ chip = hextoul(argv[1], NULL); /* * I2C data address within the chip. This can be 1 or * 2 bytes long. Some day it might be 3 bytes long :-). */ addr = hextoul(argv[2], NULL); alen = get_alen(argv[2], DEFAULT_ADDR_LEN); if (alen > 3) return CMD_RET_USAGE; /* * If another parameter, it is the length to display. * Length is the number of objects, not number of bytes. */ if (argc > 3) length = hextoul(argv[3], NULL); } #if CONFIG_IS_ENABLED(DM_I2C) ret = i2c_get_cur_bus_chip(chip, &dev); if (!ret && alen != -1) ret = i2c_set_chip_offset_len(dev, alen); if (ret) return i2c_report_err(ret, I2C_ERR_READ); #endif /* * Print the lines. * * We buffer all read data, so we can make sure data is read only * once. */ nbytes = length; do { unsigned char linebuf[DISP_LINE_LEN]; unsigned char *cp; linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes; #if CONFIG_IS_ENABLED(DM_I2C) ret = dm_i2c_read(dev, addr, linebuf, linebytes); #else ret = i2c_read(chip, addr, alen, linebuf, linebytes); #endif if (ret) return i2c_report_err(ret, I2C_ERR_READ); else { printf("%04x:", addr); cp = linebuf; for (j=0; j<linebytes; j++) { printf(" %02x", *cp++); addr++; } puts (" "); cp = linebuf; for (j=0; j<linebytes; j++) { if ((*cp < 0x20) || (*cp > 0x7e)) puts ("."); else printf("%c", *cp); cp++; } putc ('\n'); } nbytes -= linebytes; } while (nbytes > 0); i2c_dp_last_chip = chip; i2c_dp_last_addr = addr; i2c_dp_last_alen = alen; i2c_dp_last_length = length; return 0; }
4295672649069929583389307772574603935
i2c.c
148650655652553671361921673670735435868
CWE-787
CVE-2022-34835
In Das U-Boot through 2022.07-rc5, an integer signedness error and resultant stack-based buffer overflow in the "i2c md" command enables the corruption of the return address pointer of the do_i2c_md function.
https://nvd.nist.gov/vuln/detail/CVE-2022-34835
198,556
mruby
da48e7dbb20024c198493b8724adae1b842083aa
https://github.com/mruby/mruby
https://github.com/mruby/mruby/commit/da48e7dbb20024c198493b8724adae1b842083aa
fiber.c: should pack 15+ arguments in an array.
1
fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; enum mrb_fiber_state status; mrb_value value; fiber_check_cfunc(mrb, c); status = c->status; switch (status) { case MRB_FIBER_TRANSFERRED: if (resume) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } break; case MRB_FIBER_RUNNING: case MRB_FIBER_RESUMED: mrb_raise(mrb, E_FIBER_ERROR, "double resume"); break; case MRB_FIBER_TERMINATED: mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); break; default: break; } old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); fiber_switch_context(mrb, c); if (status == MRB_FIBER_CREATED) { mrb_value *b, *e; if (!c->ci->proc) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (current)"); } mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */ b = c->stbase+1; e = b + len; while (b<e) { *b++ = *a++; } if (vmexec) { c->ci--; /* pop dummy callinfo */ } c->cibase->n = len; value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); if (vmexec) { c->ci[1].stack[0] = value; } } if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci->proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; }
47008074931842386485122959067604053158
fiber.c
246157146670999327331490014943475085458
CWE-703
CVE-2022-0890
NULL Pointer Dereference in GitHub repository mruby/mruby prior to 3.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0890
276,993
mruby
da48e7dbb20024c198493b8724adae1b842083aa
https://github.com/mruby/mruby
https://github.com/mruby/mruby/commit/da48e7dbb20024c198493b8724adae1b842083aa
fiber.c: should pack 15+ arguments in an array.
0
fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; enum mrb_fiber_state status; mrb_value value; fiber_check_cfunc(mrb, c); status = c->status; switch (status) { case MRB_FIBER_TRANSFERRED: if (resume) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } break; case MRB_FIBER_RUNNING: case MRB_FIBER_RESUMED: mrb_raise(mrb, E_FIBER_ERROR, "double resume"); break; case MRB_FIBER_TERMINATED: mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); break; default: break; } old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); fiber_switch_context(mrb, c); if (status == MRB_FIBER_CREATED) { mrb_value *b, *e; if (!c->ci->proc) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (current)"); } if (vmexec) { c->ci--; /* pop dummy callinfo */ } if (len >= 15) { mrb_stack_extend(mrb, 3); /* for receiver, args and (optional) block */ c->stbase[1] = mrb_ary_new_from_values(mrb, len, a); len = 15; } else { mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */ b = c->stbase+1; e = b + len; while (b<e) { *b++ = *a++; } } c->cibase->n = len; value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); if (vmexec) { c->ci[1].stack[0] = value; } } if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci->proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; }
103355671348819190033706386778999083640
fiber.c
198318116371258140758763628769197309767
CWE-703
CVE-2022-0890
NULL Pointer Dereference in GitHub repository mruby/mruby prior to 3.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0890
198,566
libmobi
eafc415bc6067e72577f70d6dd5acbf057ce6e6f
https://github.com/bfabiszewski/libmobi
https://github.com/bfabiszewski/libmobi/commit/eafc415bc6067e72577f70d6dd5acbf057ce6e6f
Fix wrong boundary checks in inflections parser resulting in stack buffer over-read with corrupt input
1
MOBI_RET mobi_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) { int pos = *decoded_size; char mod = 'i'; char dir = '<'; char olddir; unsigned char c; while ((c = *rule++)) { if (c <= 4) { mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */ olddir = dir; dir = (c & 2) ? '<' : '>'; /* left, right */ if (olddir != dir && olddir) { pos = (c & 2) ? *decoded_size : 0; } } else if (c > 10 && c < 20) { if (dir == '>') { pos = *decoded_size; } pos -= c - 10; dir = 0; if (pos < 0 || pos > *decoded_size) { debug_print("Position setting failed (%s)\n", decoded); return MOBI_DATA_CORRUPT; } } else { if (mod == 'i') { const unsigned char *s = decoded + pos; unsigned char *d = decoded + pos + 1; const int l = *decoded_size - pos; if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) { debug_print("Out of buffer in %s at pos: %i\n", decoded, pos); return MOBI_DATA_CORRUPT; } memmove(d, s, (size_t) l); decoded[pos] = c; (*decoded_size)++; if (dir == '>') { pos++; } } else { if (dir == '<') { pos--; } const unsigned char *s = decoded + pos + 1; unsigned char *d = decoded + pos; const int l = *decoded_size - pos; if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) { debug_print("Out of buffer in %s at pos: %i\n", decoded, pos); return MOBI_DATA_CORRUPT; } if (decoded[pos] != c) { debug_print("Character mismatch in %s at pos: %i (%c != %c)\n", decoded, pos, decoded[pos], c); return MOBI_DATA_CORRUPT; } memmove(d, s, (size_t) l); (*decoded_size)--; } } } return MOBI_SUCCESS; }
38529228609046084805262566640890540140
index.c
309095437889005741044332361577356993393
CWE-787
CVE-2022-1533
Buffer Over-read in GitHub repository bfabiszewski/libmobi prior to 0.11. This vulnerability is capable of arbitrary code execution.
https://nvd.nist.gov/vuln/detail/CVE-2022-1533
277,489
libmobi
eafc415bc6067e72577f70d6dd5acbf057ce6e6f
https://github.com/bfabiszewski/libmobi
https://github.com/bfabiszewski/libmobi/commit/eafc415bc6067e72577f70d6dd5acbf057ce6e6f
Fix wrong boundary checks in inflections parser resulting in stack buffer over-read with corrupt input
0
MOBI_RET mobi_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) { int pos = *decoded_size; char mod = 'i'; char dir = '<'; char olddir; unsigned char c; while ((c = *rule++)) { if (c <= 4) { mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */ olddir = dir; dir = (c & 2) ? '<' : '>'; /* left, right */ if (olddir != dir && olddir) { pos = (c & 2) ? *decoded_size : 0; } } else if (c > 10 && c < 20) { if (dir == '>') { pos = *decoded_size; } pos -= c - 10; dir = 0; } else { if (mod == 'i') { const unsigned char *s = decoded + pos; unsigned char *d = decoded + pos + 1; const int l = *decoded_size - pos; if (pos < 0 || l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) { debug_print("Out of buffer in %s at pos: %i\n", decoded, pos); return MOBI_DATA_CORRUPT; } memmove(d, s, (size_t) l); decoded[pos] = c; (*decoded_size)++; if (dir == '>') { pos++; } } else { if (dir == '<') { pos--; } const unsigned char *s = decoded + pos + 1; unsigned char *d = decoded + pos; const int l = *decoded_size - pos; if (pos < 0 || l < 0 || s + l > decoded + INDX_INFLBUF_SIZEMAX) { debug_print("Out of buffer in %s at pos: %i\n", decoded, pos); return MOBI_DATA_CORRUPT; } if (decoded[pos] != c) { debug_print("Character mismatch in %s at pos: %i (%c != %c)\n", decoded, pos, decoded[pos], c); return MOBI_DATA_CORRUPT; } memmove(d, s, (size_t) l); (*decoded_size)--; } } } return MOBI_SUCCESS; }
110952141184880818056037191705831585689
index.c
108195340824579059268746364836110051712
CWE-787
CVE-2022-1533
Buffer Over-read in GitHub repository bfabiszewski/libmobi prior to 0.11. This vulnerability is capable of arbitrary code execution.
https://nvd.nist.gov/vuln/detail/CVE-2022-1533
198,662
vim
dc5490e2cbc8c16022a23b449b48c1bd0083f366
https://github.com/vim/vim
https://github.com/vim/vim/commit/dc5490e2cbc8c16022a23b449b48c1bd0083f366
patch 8.2.4215: illegal memory access when copying lines in Visual mode Problem: Illegal memory access when copying lines in Visual mode. Solution: Adjust the Visual position after copying lines.
1
ex_copy(linenr_T line1, linenr_T line2, linenr_T n) { linenr_T count; char_u *p; count = line2 - line1 + 1; if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { curbuf->b_op_start.lnum = n + 1; curbuf->b_op_end.lnum = n + count; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } /* * there are three situations: * 1. destination is above line1 * 2. destination is between line1 and line2 * 3. destination is below line2 * * n = destination (when starting) * curwin->w_cursor.lnum = destination (while copying) * line1 = start of source (while copying) * line2 = end of source (while copying) */ if (u_save(n, n + 1) == FAIL) return; curwin->w_cursor.lnum = n; while (line1 <= line2) { // need to use vim_strsave() because the line will be unlocked within // ml_append() p = vim_strsave(ml_get(line1)); if (p != NULL) { ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE); vim_free(p); } // situation 2: skip already copied lines if (line1 == n) line1 = curwin->w_cursor.lnum; ++line1; if (curwin->w_cursor.lnum < line1) ++line1; if (curwin->w_cursor.lnum < line2) ++line2; ++curwin->w_cursor.lnum; } appended_lines_mark(n, count); msgmore((long)count); }
97186272074546929960699343746519426256
ex_cmds.c
233687213068218474878856624724146444666
CWE-787
CVE-2022-0361
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0361
279,948
vim
dc5490e2cbc8c16022a23b449b48c1bd0083f366
https://github.com/vim/vim
https://github.com/vim/vim/commit/dc5490e2cbc8c16022a23b449b48c1bd0083f366
patch 8.2.4215: illegal memory access when copying lines in Visual mode Problem: Illegal memory access when copying lines in Visual mode. Solution: Adjust the Visual position after copying lines.
0
ex_copy(linenr_T line1, linenr_T line2, linenr_T n) { linenr_T count; char_u *p; count = line2 - line1 + 1; if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { curbuf->b_op_start.lnum = n + 1; curbuf->b_op_end.lnum = n + count; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } /* * there are three situations: * 1. destination is above line1 * 2. destination is between line1 and line2 * 3. destination is below line2 * * n = destination (when starting) * curwin->w_cursor.lnum = destination (while copying) * line1 = start of source (while copying) * line2 = end of source (while copying) */ if (u_save(n, n + 1) == FAIL) return; curwin->w_cursor.lnum = n; while (line1 <= line2) { // need to use vim_strsave() because the line will be unlocked within // ml_append() p = vim_strsave(ml_get(line1)); if (p != NULL) { ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE); vim_free(p); } // situation 2: skip already copied lines if (line1 == n) line1 = curwin->w_cursor.lnum; ++line1; if (curwin->w_cursor.lnum < line1) ++line1; if (curwin->w_cursor.lnum < line2) ++line2; ++curwin->w_cursor.lnum; } appended_lines_mark(n, count); if (VIsual_active) check_pos(curbuf, &VIsual); msgmore((long)count); }
145586714597549785258872355387518968620
ex_cmds.c
316790051330868655972553819181856040285
CWE-787
CVE-2022-0361
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0361
198,692
ipsec
7bab09631c2a303f87a7eb7e3d69e888673b9b7e
https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec
https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git/commit/?id=7bab09631c2a303f87a7eb7e3d69e888673b9b7e
xfrm: policy: check policy direction value The 'dir' parameter in xfrm_migrate() is a user-controlled byte which is used as an array index. This can lead to an out-of-bound access, kernel lockup and DoS. Add a check for the 'dir' value. This fixes CVE-2017-11600. References: https://bugzilla.redhat.com/show_bug.cgi?id=1474928 Fixes: 80c9abaabf42 ("[XFRM]: Extension for dynamic update of endpoint address(es)") Cc: <[email protected]> # v2.6.21-rc1 Reported-by: "bo Zhang" <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Signed-off-by: Steffen Klassert <[email protected]>
1
int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, struct xfrm_migrate *m, int num_migrate, struct xfrm_kmaddress *k, struct net *net, struct xfrm_encap_tmpl *encap) { int i, err, nx_cur = 0, nx_new = 0; struct xfrm_policy *pol = NULL; struct xfrm_state *x, *xc; struct xfrm_state *x_cur[XFRM_MAX_DEPTH]; struct xfrm_state *x_new[XFRM_MAX_DEPTH]; struct xfrm_migrate *mp; if ((err = xfrm_migrate_check(m, num_migrate)) < 0) goto out; /* Stage 1 - find policy */ if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) { err = -ENOENT; goto out; } /* Stage 2 - find and update state(s) */ for (i = 0, mp = m; i < num_migrate; i++, mp++) { if ((x = xfrm_migrate_state_find(mp, net))) { x_cur[nx_cur] = x; nx_cur++; xc = xfrm_state_migrate(x, mp, encap); if (xc) { x_new[nx_new] = xc; nx_new++; } else { err = -ENODATA; goto restore_state; } } } /* Stage 3 - update policy */ if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0) goto restore_state; /* Stage 4 - delete old state(s) */ if (nx_cur) { xfrm_states_put(x_cur, nx_cur); xfrm_states_delete(x_cur, nx_cur); } /* Stage 5 - announce */ km_migrate(sel, dir, type, m, num_migrate, k, encap); xfrm_pol_put(pol); return 0; out: return err; restore_state: if (pol) xfrm_pol_put(pol); if (nx_cur) xfrm_states_put(x_cur, nx_cur); if (nx_new) xfrm_states_delete(x_new, nx_new); return err; }
263415810499121443569228863944466057298
xfrm_policy.c
279839085612343169676292983391622616816
CWE-125
CVE-2017-11600
net/xfrm/xfrm_policy.c in the Linux kernel through 4.12.3, when CONFIG_XFRM_MIGRATE is enabled, does not ensure that the dir value of xfrm_userpolicy_id is XFRM_POLICY_MAX or less, which allows local users to cause a denial of service (out-of-bounds access) or possibly have unspecified other impact via an XFRM_MSG_MIGRATE xfrm Netlink message.
https://nvd.nist.gov/vuln/detail/CVE-2017-11600
281,119
ipsec
7bab09631c2a303f87a7eb7e3d69e888673b9b7e
https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec
https://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git/commit/?id=7bab09631c2a303f87a7eb7e3d69e888673b9b7e
xfrm: policy: check policy direction value The 'dir' parameter in xfrm_migrate() is a user-controlled byte which is used as an array index. This can lead to an out-of-bound access, kernel lockup and DoS. Add a check for the 'dir' value. This fixes CVE-2017-11600. References: https://bugzilla.redhat.com/show_bug.cgi?id=1474928 Fixes: 80c9abaabf42 ("[XFRM]: Extension for dynamic update of endpoint address(es)") Cc: <[email protected]> # v2.6.21-rc1 Reported-by: "bo Zhang" <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Signed-off-by: Steffen Klassert <[email protected]>
0
int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, struct xfrm_migrate *m, int num_migrate, struct xfrm_kmaddress *k, struct net *net, struct xfrm_encap_tmpl *encap) { int i, err, nx_cur = 0, nx_new = 0; struct xfrm_policy *pol = NULL; struct xfrm_state *x, *xc; struct xfrm_state *x_cur[XFRM_MAX_DEPTH]; struct xfrm_state *x_new[XFRM_MAX_DEPTH]; struct xfrm_migrate *mp; /* Stage 0 - sanity checks */ if ((err = xfrm_migrate_check(m, num_migrate)) < 0) goto out; if (dir >= XFRM_POLICY_MAX) { err = -EINVAL; goto out; } /* Stage 1 - find policy */ if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) { err = -ENOENT; goto out; } /* Stage 2 - find and update state(s) */ for (i = 0, mp = m; i < num_migrate; i++, mp++) { if ((x = xfrm_migrate_state_find(mp, net))) { x_cur[nx_cur] = x; nx_cur++; xc = xfrm_state_migrate(x, mp, encap); if (xc) { x_new[nx_new] = xc; nx_new++; } else { err = -ENODATA; goto restore_state; } } } /* Stage 3 - update policy */ if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0) goto restore_state; /* Stage 4 - delete old state(s) */ if (nx_cur) { xfrm_states_put(x_cur, nx_cur); xfrm_states_delete(x_cur, nx_cur); } /* Stage 5 - announce */ km_migrate(sel, dir, type, m, num_migrate, k, encap); xfrm_pol_put(pol); return 0; out: return err; restore_state: if (pol) xfrm_pol_put(pol); if (nx_cur) xfrm_states_put(x_cur, nx_cur); if (nx_new) xfrm_states_delete(x_new, nx_new); return err; }
215751416433603359127168568868479758173
xfrm_policy.c
14403382265138763697521162606727348451
CWE-125
CVE-2017-11600
net/xfrm/xfrm_policy.c in the Linux kernel through 4.12.3, when CONFIG_XFRM_MIGRATE is enabled, does not ensure that the dir value of xfrm_userpolicy_id is XFRM_POLICY_MAX or less, which allows local users to cause a denial of service (out-of-bounds access) or possibly have unspecified other impact via an XFRM_MSG_MIGRATE xfrm Netlink message.
https://nvd.nist.gov/vuln/detail/CVE-2017-11600
198,695
MilkyTracker
fd607a3439fcdd0992e5efded3c16fc79c804e34
https://github.com/milkytracker/MilkyTracker
https://github.com/milkytracker/MilkyTracker/commit/fd607a3439fcdd0992e5efded3c16fc79c804e34
Fix #184: Heap overflow in S3M loader
1
mp_sint32 LoaderS3M::load(XMFileBase& f, XModule* module) { module->cleanUp(); // this will make code much easier to read TXMHeader* header = &module->header; TXMInstrument* instr = module->instr; TXMSample* smp = module->smp; TXMPattern* phead = module->phead; // we're already out of memory here if (!phead || !instr || !smp) return MP_OUT_OF_MEMORY; f.read(&header->name,1,28); header->whythis1a = f.readByte(); if (f.readByte() != 16) return MP_LOADER_FAILED; // no ST3 module f.readByte(); // skip something f.readByte(); // skip something header->ordnum = f.readWord(); // number of positions in order list (songlength) mp_ubyte* orders = new mp_ubyte[header->ordnum]; if (orders == NULL) return MP_OUT_OF_MEMORY; header->insnum = f.readWord(); // number of instruments header->patnum = f.readWord(); // number of patterns mp_sint32 flags = f.readWord(); // st3 flags mp_sint32 Cvt = f.readWord(); header->flags = XModule::MODULE_ST3NEWINSTRUMENT | XModule::MODULE_ST3DUALCOMMANDS; if (Cvt == 0x1300 || (flags & 64)) header->flags |= module->MODULE_OLDS3MVOLSLIDES; header->flags |= module->MODULE_ST3NOTECUT; /*mp_uword Ffi = */f.readWord(); f.read(header->sig,1,4); header->mainvol = module->vol64to255(f.readByte()); // initial main volume header->tempo = f.readByte(); // tempo header->speed = f.readByte(); // speed f.readByte(); // global volume? skipped... f.readByte(); // ignore GUS click removal /*mp_ubyte dp = */f.readByte(); f.readDword(); // skip something f.readDword(); // skip something f.readWord(); // skip some more... mp_ubyte channelSettings[32]; f.read(channelSettings,1,32); mp_sint32 numChannels = 0; for (numChannels = 0; numChannels < 32; numChannels++) if (channelSettings[numChannels] == 255) break; header->channum = numChannels; // number of channels f.read(orders,1,header->ordnum); mp_sint32 j = 0, i = 0; for (i = 0; i < header->ordnum; i++) { if (orders[i] == 255) break; header->ord[j++] = orders[i]; } header->ordnum = j; // final songlength delete[] orders; mp_uword* insParaPtrs = new mp_uword[header->insnum]; if (insParaPtrs == NULL) return MP_OUT_OF_MEMORY; f.readWords(insParaPtrs,header->insnum); mp_uword* patParaPtrs = new mp_uword[header->patnum]; if (patParaPtrs == NULL) { delete[] insParaPtrs; return MP_OUT_OF_MEMORY; } f.readWords(patParaPtrs,header->patnum); //for (i = 0; i < header->insnum; i++) //{ // printf("%x\n",insParaPtrs[i]*16); //} ////////////////////// // read instruments // ////////////////////// mp_uint32* samplePtrs = new mp_uint32[header->insnum]; if (samplePtrs == NULL) { delete[] insParaPtrs; delete[] patParaPtrs; return MP_OUT_OF_MEMORY; } memset(samplePtrs,0,sizeof(mp_uint32)*header->insnum); mp_sint32 s = 0; for (i = 0; i < header->insnum; i++) { mp_uint32 insOffs = insParaPtrs[i]*16; if (insOffs) { f.seekWithBaseOffset(insOffs); // We can only read that if it's a sample mp_ubyte type = f.readByte(); if (type == 1) { f.read(smp[s].name,1,12); // read dos filename mp_ubyte bOffs = f.readByte(); mp_uword wOffs = f.readWord(); // stupid fileoffsets samplePtrs[i] = (((mp_uint32)bOffs<<16)+(mp_uint32)wOffs)*16; smp[s].flags = 1; smp[s].pan = 0x80; smp[s].samplen = f.readDword(); smp[s].loopstart = f.readDword(); mp_sint32 looplen = ((mp_sint32)f.readDword() - (mp_sint32)smp[s].loopstart); if (looplen < 0) looplen = 0; smp[s].looplen = looplen; smp[s].vol = module->vol64to255(f.readByte()); f.readByte(); // skip something smp[s].res = f.readByte() == 0x04 ? 0xAD : 0; // packing mp_ubyte flags = f.readByte(); // looping if (flags & 1) { smp[s].type = 1; } // 16 bit sample if (flags & 4) { smp[s].type |= 16; smp[s].samplen >>= 1; smp[s].loopstart >>= 1; smp[s].looplen >>= 1; } mp_uint32 c4spd = f.readDword(); XModule::convertc4spd(c4spd,&smp[s].finetune,&smp[s].relnote); #ifdef VERBOSE printf("%i, %i\n",c4spd,module->getc4spd(smp[s].relnote,smp[s].finetune)); #endif f.readDword(); // skip something f.readDword(); // skip two internal words f.readDword(); // skip internal dword f.read(instr[i].name,1,28); // instrument name f.readDword(); // skip signature if (samplePtrs[i] && smp[s].samplen) { instr[i].samp=1; for (j=0;j<120;j++) instr[i].snum[j] = s; s++; } } else if (type == 0) { samplePtrs[i] = 0; mp_ubyte buffer[12]; f.read(buffer,1,12); // read dos filename f.readByte(); f.readWord(); f.readDword(); f.readDword(); f.readDword(); f.readByte(); f.readByte(); // skip something f.readByte(); // skip packing f.readByte(); f.readDword(); f.readDword(); // skip something f.readDword(); // skip two internal words f.readDword(); // skip internal dword f.read(instr[i].name,1,28); // instrument name f.readDword(); // skip signature } else { samplePtrs[i] = 0; } } } ////////////////////// // read patterns // ////////////////////// mp_ubyte* pattern = new mp_ubyte[64*32*5]; if (pattern == NULL) { delete[] insParaPtrs; delete[] patParaPtrs; delete[] samplePtrs; return MP_OUT_OF_MEMORY; } mp_uint32 songMaxChannels = 1; for (i = 0; i < header->patnum; i++) { for (j = 0; j < 32*64; j++) { pattern[j*5] = 0xFF; pattern[j*5+1] = 0; pattern[j*5+2] = 0xFF; pattern[j*5+3] = 0xFF; pattern[j*5+4] = 0; } mp_uint32 patOffs = patParaPtrs[i]*16; mp_uint32 maxChannels = 1; if (patOffs) { f.seekWithBaseOffset(patOffs); mp_uint32 size = f.readWord(); if (size > 2) { size-=2; mp_ubyte* packed = new mp_ubyte[size+5]; if (packed == NULL) { delete[] insParaPtrs; delete[] patParaPtrs; delete[] samplePtrs; delete[] pattern; return MP_OUT_OF_MEMORY; } memset(packed, 0, size); f.read(packed, 1, size); mp_uint32 index = 0; mp_uint32 row = 0; while (index<size) { mp_ubyte pi = safeRead(packed, index, size); if (pi == 0) { row++; // one more safety net for incorrectly saved pattern sizes if (row >= 64) { int i = 0; i++; i--; break; } continue; } mp_uint32 chn = pi&31; if (chn>maxChannels && (pi & (32+64+128))) { maxChannels = chn; } mp_ubyte* slot = pattern+(row*32*5)+chn*5; if (pi & 32) { slot[0] = safeRead(packed, index, size, 0xFF); slot[1] = safeRead(packed, index, size); } if (pi & 64) { slot[2] = safeRead(packed, index, size, 0xFF); } if (pi & 128) { slot[3] = safeRead(packed, index, size, 0xFF); slot[4] = safeRead(packed, index, size); } } maxChannels++; if (maxChannels > header->channum) maxChannels = header->channum; delete[] packed; } if (maxChannels > songMaxChannels) songMaxChannels = maxChannels; } convertS3MPattern(&phead[i], pattern, maxChannels, i); } if (header->channum > songMaxChannels) header->channum = songMaxChannels; delete[] pattern; delete[] insParaPtrs; delete[] patParaPtrs; s = 0; for (i = 0; i < header->insnum; i++) { mp_uint32 smpOffs = samplePtrs[i]; if (smpOffs) { f.seekWithBaseOffset(smpOffs); if (!smp[s].samplen) continue; bool adpcm = (smp[s].res == 0xAD); mp_sint32 result = module->loadModuleSample(f, s, adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_UNSIGNED, adpcm ? (XModule::ST_16BIT | XModule::ST_PACKING_ADPCM) : (XModule::ST_16BIT | XModule::ST_UNSIGNED)); if (result != MP_OK) { delete[] samplePtrs; return result; } if (adpcm) // no longer needed smp[s].res = 0; s++; } } delete[] samplePtrs; header->smpnum = s; strcpy(header->tracker,"Screamtracker 3"); module->setDefaultPanning(); module->postProcessSamples(); return MP_OK; }
83839366626583868665259951755341094581
LoaderS3M.cpp
183144652101625968491560243513367539209
CWE-787
CVE-2019-14464
XMFile::read in XMFile.cpp in milkyplay in MilkyTracker 1.02.00 has a heap-based buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2019-14464
281,247
MilkyTracker
fd607a3439fcdd0992e5efded3c16fc79c804e34
https://github.com/milkytracker/MilkyTracker
https://github.com/milkytracker/MilkyTracker/commit/fd607a3439fcdd0992e5efded3c16fc79c804e34
Fix #184: Heap overflow in S3M loader
0
mp_sint32 LoaderS3M::load(XMFileBase& f, XModule* module) { module->cleanUp(); // this will make code much easier to read TXMHeader* header = &module->header; TXMInstrument* instr = module->instr; TXMSample* smp = module->smp; TXMPattern* phead = module->phead; // we're already out of memory here if (!phead || !instr || !smp) return MP_OUT_OF_MEMORY; f.read(&header->name,1,28); header->whythis1a = f.readByte(); if (f.readByte() != 16) return MP_LOADER_FAILED; // no ST3 module f.readByte(); // skip something f.readByte(); // skip something header->ordnum = f.readWord(); // number of positions in order list (songlength) mp_ubyte* orders = new mp_ubyte[header->ordnum]; if (orders == NULL) return MP_OUT_OF_MEMORY; header->insnum = f.readWord(); // number of instruments if (header->insnum > MP_MAXINS) return MP_LOADER_FAILED; header->patnum = f.readWord(); // number of patterns if (header->patnum > 256) return MP_LOADER_FAILED; mp_sint32 flags = f.readWord(); // st3 flags mp_sint32 Cvt = f.readWord(); header->flags = XModule::MODULE_ST3NEWINSTRUMENT | XModule::MODULE_ST3DUALCOMMANDS; if (Cvt == 0x1300 || (flags & 64)) header->flags |= module->MODULE_OLDS3MVOLSLIDES; header->flags |= module->MODULE_ST3NOTECUT; /*mp_uword Ffi = */f.readWord(); f.read(header->sig,1,4); header->mainvol = module->vol64to255(f.readByte()); // initial main volume header->tempo = f.readByte(); // tempo header->speed = f.readByte(); // speed f.readByte(); // global volume? skipped... f.readByte(); // ignore GUS click removal /*mp_ubyte dp = */f.readByte(); f.readDword(); // skip something f.readDword(); // skip something f.readWord(); // skip some more... mp_ubyte channelSettings[32]; f.read(channelSettings,1,32); mp_sint32 numChannels = 0; for (numChannels = 0; numChannels < 32; numChannels++) if (channelSettings[numChannels] == 255) break; header->channum = numChannels; // number of channels f.read(orders,1,header->ordnum); mp_sint32 j = 0, i = 0; for (i = 0; i < header->ordnum; i++) { if (orders[i] == 255) break; header->ord[j++] = orders[i]; } header->ordnum = j; // final songlength delete[] orders; mp_uword* insParaPtrs = new mp_uword[header->insnum]; if (insParaPtrs == NULL) return MP_OUT_OF_MEMORY; f.readWords(insParaPtrs,header->insnum); mp_uword* patParaPtrs = new mp_uword[header->patnum]; if (patParaPtrs == NULL) { delete[] insParaPtrs; return MP_OUT_OF_MEMORY; } f.readWords(patParaPtrs,header->patnum); //for (i = 0; i < header->insnum; i++) //{ // printf("%x\n",insParaPtrs[i]*16); //} ////////////////////// // read instruments // ////////////////////// mp_uint32* samplePtrs = new mp_uint32[header->insnum]; if (samplePtrs == NULL) { delete[] insParaPtrs; delete[] patParaPtrs; return MP_OUT_OF_MEMORY; } memset(samplePtrs,0,sizeof(mp_uint32)*header->insnum); mp_sint32 s = 0; for (i = 0; i < header->insnum; i++) { mp_uint32 insOffs = insParaPtrs[i]*16; if (insOffs) { f.seekWithBaseOffset(insOffs); // We can only read that if it's a sample mp_ubyte type = f.readByte(); if (type == 1) { f.read(smp[s].name,1,12); // read dos filename mp_ubyte bOffs = f.readByte(); mp_uword wOffs = f.readWord(); // stupid fileoffsets samplePtrs[i] = (((mp_uint32)bOffs<<16)+(mp_uint32)wOffs)*16; smp[s].flags = 1; smp[s].pan = 0x80; smp[s].samplen = f.readDword(); smp[s].loopstart = f.readDword(); mp_sint32 looplen = ((mp_sint32)f.readDword() - (mp_sint32)smp[s].loopstart); if (looplen < 0) looplen = 0; smp[s].looplen = looplen; smp[s].vol = module->vol64to255(f.readByte()); f.readByte(); // skip something smp[s].res = f.readByte() == 0x04 ? 0xAD : 0; // packing mp_ubyte flags = f.readByte(); // looping if (flags & 1) { smp[s].type = 1; } // 16 bit sample if (flags & 4) { smp[s].type |= 16; smp[s].samplen >>= 1; smp[s].loopstart >>= 1; smp[s].looplen >>= 1; } mp_uint32 c4spd = f.readDword(); XModule::convertc4spd(c4spd,&smp[s].finetune,&smp[s].relnote); #ifdef VERBOSE printf("%i, %i\n",c4spd,module->getc4spd(smp[s].relnote,smp[s].finetune)); #endif f.readDword(); // skip something f.readDword(); // skip two internal words f.readDword(); // skip internal dword f.read(instr[i].name,1,28); // instrument name f.readDword(); // skip signature if (samplePtrs[i] && smp[s].samplen) { instr[i].samp=1; for (j=0;j<120;j++) instr[i].snum[j] = s; s++; } } else if (type == 0) { samplePtrs[i] = 0; mp_ubyte buffer[12]; f.read(buffer,1,12); // read dos filename f.readByte(); f.readWord(); f.readDword(); f.readDword(); f.readDword(); f.readByte(); f.readByte(); // skip something f.readByte(); // skip packing f.readByte(); f.readDword(); f.readDword(); // skip something f.readDword(); // skip two internal words f.readDword(); // skip internal dword f.read(instr[i].name,1,28); // instrument name f.readDword(); // skip signature } else { samplePtrs[i] = 0; } } } ////////////////////// // read patterns // ////////////////////// mp_ubyte* pattern = new mp_ubyte[64*32*5]; if (pattern == NULL) { delete[] insParaPtrs; delete[] patParaPtrs; delete[] samplePtrs; return MP_OUT_OF_MEMORY; } mp_uint32 songMaxChannels = 1; for (i = 0; i < header->patnum; i++) { for (j = 0; j < 32*64; j++) { pattern[j*5] = 0xFF; pattern[j*5+1] = 0; pattern[j*5+2] = 0xFF; pattern[j*5+3] = 0xFF; pattern[j*5+4] = 0; } mp_uint32 patOffs = patParaPtrs[i]*16; mp_uint32 maxChannels = 1; if (patOffs) { f.seekWithBaseOffset(patOffs); mp_uint32 size = f.readWord(); if (size > 2) { size-=2; mp_ubyte* packed = new mp_ubyte[size+5]; if (packed == NULL) { delete[] insParaPtrs; delete[] patParaPtrs; delete[] samplePtrs; delete[] pattern; return MP_OUT_OF_MEMORY; } memset(packed, 0, size); f.read(packed, 1, size); mp_uint32 index = 0; mp_uint32 row = 0; while (index<size) { mp_ubyte pi = safeRead(packed, index, size); if (pi == 0) { row++; // one more safety net for incorrectly saved pattern sizes if (row >= 64) { int i = 0; i++; i--; break; } continue; } mp_uint32 chn = pi&31; if (chn>maxChannels && (pi & (32+64+128))) { maxChannels = chn; } mp_ubyte* slot = pattern+(row*32*5)+chn*5; if (pi & 32) { slot[0] = safeRead(packed, index, size, 0xFF); slot[1] = safeRead(packed, index, size); } if (pi & 64) { slot[2] = safeRead(packed, index, size, 0xFF); } if (pi & 128) { slot[3] = safeRead(packed, index, size, 0xFF); slot[4] = safeRead(packed, index, size); } } maxChannels++; if (maxChannels > header->channum) maxChannels = header->channum; delete[] packed; } if (maxChannels > songMaxChannels) songMaxChannels = maxChannels; } convertS3MPattern(&phead[i], pattern, maxChannels, i); } if (header->channum > songMaxChannels) header->channum = songMaxChannels; delete[] pattern; delete[] insParaPtrs; delete[] patParaPtrs; s = 0; for (i = 0; i < header->insnum; i++) { mp_uint32 smpOffs = samplePtrs[i]; if (smpOffs) { f.seekWithBaseOffset(smpOffs); if (!smp[s].samplen) continue; bool adpcm = (smp[s].res == 0xAD); mp_sint32 result = module->loadModuleSample(f, s, adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_UNSIGNED, adpcm ? (XModule::ST_16BIT | XModule::ST_PACKING_ADPCM) : (XModule::ST_16BIT | XModule::ST_UNSIGNED)); if (result != MP_OK) { delete[] samplePtrs; return result; } if (adpcm) // no longer needed smp[s].res = 0; s++; } } delete[] samplePtrs; header->smpnum = s; strcpy(header->tracker,"Screamtracker 3"); module->setDefaultPanning(); module->postProcessSamples(); return MP_OK; }
43770452708802506727115709874913360488
LoaderS3M.cpp
201031335875612039718425244532999180036
CWE-787
CVE-2019-14464
XMFile::read in XMFile.cpp in milkyplay in MilkyTracker 1.02.00 has a heap-based buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2019-14464
198,703
LibRaw
4606c28f494a750892c5c1ac7903e62dd1c6fdb5
https://github.com/LibRaw/LibRaw
https://github.com/LibRaw/LibRaw/commit/4606c28f494a750892c5c1ac7903e62dd1c6fdb5
0.16.1: fix for dcraw ljpeg_start() vulnerability
1
int CLASS ljpeg_start (struct jhead *jh, int info_only) { int c, tag, len; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; fread (data, 2, 1, ifp); if (data[1] != 0xd8) return 0; do { fread (data, 2, 2, ifp); tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc0: jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: if (info_only) break; for (dp = data; dp < data+len && (c = *dp++) < 4; ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (info_only) return 1; if (jh->clrs > 6 || !jh->huff[0]) return 0; FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; }
130689334179908551360949370308005940309
dcraw.c
16246307575535149063752681880088000458
CWE-189
CVE-2015-3885
Integer overflow in the ljpeg_start function in dcraw 7.00 and earlier allows remote attackers to cause a denial of service (crash) via a crafted image, which triggers a buffer overflow, related to the len variable.
https://nvd.nist.gov/vuln/detail/CVE-2015-3885
281,662
LibRaw
4606c28f494a750892c5c1ac7903e62dd1c6fdb5
https://github.com/LibRaw/LibRaw
https://github.com/LibRaw/LibRaw/commit/4606c28f494a750892c5c1ac7903e62dd1c6fdb5
0.16.1: fix for dcraw ljpeg_start() vulnerability
0
int CLASS ljpeg_start (struct jhead *jh, int info_only) { int c, tag; ushort len; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; fread (data, 2, 1, ifp); if (data[1] != 0xd8) return 0; do { fread (data, 2, 2, ifp); tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc0: jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: if (info_only) break; for (dp = data; dp < data+len && (c = *dp++) < 4; ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (info_only) return 1; if (jh->clrs > 6 || !jh->huff[0]) return 0; FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; }
72339835961882099009562800572208643918
None
CWE-189
CVE-2015-3885
Integer overflow in the ljpeg_start function in dcraw 7.00 and earlier allows remote attackers to cause a denial of service (crash) via a crafted image, which triggers a buffer overflow, related to the len variable.
https://nvd.nist.gov/vuln/detail/CVE-2015-3885
198,736
linux
d563131ef23cbc756026f839a82598c8445bc45f
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/d563131ef23cbc756026f839a82598c8445bc45f
rsi: release skb if rsi_prepare_beacon fails In rsi_send_beacon, if rsi_prepare_beacon fails the allocated skb should be released. Signed-off-by: Navid Emamdoost <[email protected]> Signed-off-by: Kalle Valo <[email protected]>
1
static int rsi_send_beacon(struct rsi_common *common) { struct sk_buff *skb = NULL; u8 dword_align_bytes = 0; skb = dev_alloc_skb(MAX_MGMT_PKT_SIZE); if (!skb) return -ENOMEM; memset(skb->data, 0, MAX_MGMT_PKT_SIZE); dword_align_bytes = ((unsigned long)skb->data & 0x3f); if (dword_align_bytes) skb_pull(skb, (64 - dword_align_bytes)); if (rsi_prepare_beacon(common, skb)) { rsi_dbg(ERR_ZONE, "Failed to prepare beacon\n"); return -EINVAL; } skb_queue_tail(&common->tx_queue[MGMT_BEACON_Q], skb); rsi_set_event(&common->tx_thread.event); rsi_dbg(DATA_TX_ZONE, "%s: Added to beacon queue\n", __func__); return 0; }
130931178778692254191224779038755080046
rsi_91x_mgmt.c
125660046646447806158908760119804627111
CWE-401
CVE-2019-19071
A memory leak in the rsi_send_beacon() function in drivers/net/wireless/rsi/rsi_91x_mgmt.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering rsi_prepare_beacon() failures, aka CID-d563131ef23c.
https://nvd.nist.gov/vuln/detail/CVE-2019-19071
282,862
linux
d563131ef23cbc756026f839a82598c8445bc45f
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/d563131ef23cbc756026f839a82598c8445bc45f
rsi: release skb if rsi_prepare_beacon fails In rsi_send_beacon, if rsi_prepare_beacon fails the allocated skb should be released. Signed-off-by: Navid Emamdoost <[email protected]> Signed-off-by: Kalle Valo <[email protected]>
0
static int rsi_send_beacon(struct rsi_common *common) { struct sk_buff *skb = NULL; u8 dword_align_bytes = 0; skb = dev_alloc_skb(MAX_MGMT_PKT_SIZE); if (!skb) return -ENOMEM; memset(skb->data, 0, MAX_MGMT_PKT_SIZE); dword_align_bytes = ((unsigned long)skb->data & 0x3f); if (dword_align_bytes) skb_pull(skb, (64 - dword_align_bytes)); if (rsi_prepare_beacon(common, skb)) { rsi_dbg(ERR_ZONE, "Failed to prepare beacon\n"); dev_kfree_skb(skb); return -EINVAL; } skb_queue_tail(&common->tx_queue[MGMT_BEACON_Q], skb); rsi_set_event(&common->tx_thread.event); rsi_dbg(DATA_TX_ZONE, "%s: Added to beacon queue\n", __func__); return 0; }
202315144827915003727836614095080991835
rsi_91x_mgmt.c
337039362328413232417752595040682703698
CWE-401
CVE-2019-19071
A memory leak in the rsi_send_beacon() function in drivers/net/wireless/rsi/rsi_91x_mgmt.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering rsi_prepare_beacon() failures, aka CID-d563131ef23c.
https://nvd.nist.gov/vuln/detail/CVE-2019-19071
198,743
LuaJIT
53f82e6e2e858a0a62fd1a2ff47e9866693382e6
https://github.com/LuaJIT/LuaJIT
https://github.com/LuaJIT/LuaJIT/commit/53f82e6e2e858a0a62fd1a2ff47e9866693382e6
Fix frame traversal for __gc handler frames. Reported by Changochen.
1
static ptrdiff_t finderrfunc(lua_State *L) { cTValue *frame = L->base-1, *bot = tvref(L->stack); void *cf = L->cframe; while (frame > bot && cf) { while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */ if (frame >= restorestack(L, -cframe_nres(cf))) break; if (cframe_errfunc(cf) >= 0) /* Error handler not inherited (-1)? */ return cframe_errfunc(cf); cf = cframe_prev(cf); /* Else unwind cframe and continue searching. */ if (cf == NULL) return 0; } switch (frame_typep(frame)) { case FRAME_LUA: case FRAME_LUAP: frame = frame_prevl(frame); break; case FRAME_C: cf = cframe_prev(cf); /* fallthrough */ case FRAME_VARG: frame = frame_prevd(frame); break; case FRAME_CONT: #if LJ_HASFFI if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK) cf = cframe_prev(cf); #endif frame = frame_prevd(frame); break; case FRAME_CP: if (cframe_canyield(cf)) return 0; if (cframe_errfunc(cf) >= 0) return cframe_errfunc(cf); frame = frame_prevd(frame); break; case FRAME_PCALL: case FRAME_PCALLH: if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue))) /* xpcall? */ return savestack(L, frame-1); /* Point to xpcall's errorfunc. */ return 0; default: lua_assert(0); return 0; } } return 0; }
309200300493568288549157158368440611870
lj_err.c
339549767514658029818043680727253046808
CWE-125
CVE-2020-15890
LuaJit through 2.1.0-beta3 has an out-of-bounds read because __gc handler frame traversal is mishandled.
https://nvd.nist.gov/vuln/detail/CVE-2020-15890
282,984
LuaJIT
53f82e6e2e858a0a62fd1a2ff47e9866693382e6
https://github.com/LuaJIT/LuaJIT
https://github.com/LuaJIT/LuaJIT/commit/53f82e6e2e858a0a62fd1a2ff47e9866693382e6
Fix frame traversal for __gc handler frames. Reported by Changochen.
0
static ptrdiff_t finderrfunc(lua_State *L) { cTValue *frame = L->base-1, *bot = tvref(L->stack); void *cf = L->cframe; while (frame > bot && cf) { while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */ if (frame >= restorestack(L, -cframe_nres(cf))) break; if (cframe_errfunc(cf) >= 0) /* Error handler not inherited (-1)? */ return cframe_errfunc(cf); cf = cframe_prev(cf); /* Else unwind cframe and continue searching. */ if (cf == NULL) return 0; } switch (frame_typep(frame)) { case FRAME_LUA: case FRAME_LUAP: frame = frame_prevl(frame); break; case FRAME_C: cf = cframe_prev(cf); /* fallthrough */ case FRAME_VARG: frame = frame_prevd(frame); break; case FRAME_CONT: #if LJ_HASFFI if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK) cf = cframe_prev(cf); #endif frame = frame_prevd(frame); break; case FRAME_CP: if (cframe_canyield(cf)) return 0; if (cframe_errfunc(cf) >= 0) return cframe_errfunc(cf); cf = cframe_prev(cf); frame = frame_prevd(frame); break; case FRAME_PCALL: case FRAME_PCALLH: if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue))) /* xpcall? */ return savestack(L, frame-1); /* Point to xpcall's errorfunc. */ return 0; default: lua_assert(0); return 0; } } return 0; }
135963737792819118980125175334737284274
lj_err.c
198203473898814036407466574660463075188
CWE-125
CVE-2020-15890
LuaJit through 2.1.0-beta3 has an out-of-bounds read because __gc handler frame traversal is mishandled.
https://nvd.nist.gov/vuln/detail/CVE-2020-15890
198,927
radare2
0a557045476a2969c7079aec9eeb29d02f2809c6
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/0a557045476a2969c7079aec9eeb29d02f2809c6
Fix oobread and unaligned casts in the NE entrypoint logic ##crash * Reported by @hmsec via huntr.dev * Reproducer: nepocaligns * BountyID: ec538fa4-06c6-4050-a141-f60153ddeaac
1
RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) { if (!bin->entry_table) { return NULL; } RList *entries = r_list_newf (free); if (!entries) { return NULL; } RList *segments = r_bin_ne_get_segments (bin); if (!segments) { r_list_free (entries); return NULL; } if (bin->ne_header->csEntryPoint) { RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } entry->bits = 16; ut32 entry_cs = bin->ne_header->csEntryPoint; RBinSection *s = r_list_get_n (segments, entry_cs - 1); entry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0); r_list_append (entries, entry); } int off = 0; size_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset; while (off < bin->ne_header->EntryTableLength) { if (tableat + off >= r_buf_size (bin->buf)) { break; } ut8 bundle_length = *(ut8 *)(bin->entry_table + off); if (!bundle_length) { break; } off++; ut8 bundle_type = *(ut8 *)(bin->entry_table + off); off++; int i; for (i = 0; i < bundle_length; i++) { if (tableat + off + 4 >= r_buf_size (bin->buf)) { break; } RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } off++; if (!bundle_type) { // Skip off--; free (entry); break; } else if (bundle_type == 0xff) { // moveable off += 2; ut8 segnum = *(bin->entry_table + off); off++; ut16 segoff = *(ut16 *)(bin->entry_table + off); if (segnum > 0) { entry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff; } } else { // Fixed if (bundle_type < bin->ne_header->SegCount) { entry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + *(ut16 *)(bin->entry_table + off); } } off += 2; r_list_append (entries, entry); } } r_list_free (segments); bin->entries = entries; return entries; }
128571297919304348712196386626162050665
ne.c
267767472176864232009512780125221207666
CWE-125
CVE-2022-1297
Out-of-bounds Read in r_bin_ne_get_entrypoints function in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability may allow attackers to read sensitive information or cause a crash.
https://nvd.nist.gov/vuln/detail/CVE-2022-1297
285,157
radare2
0a557045476a2969c7079aec9eeb29d02f2809c6
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/0a557045476a2969c7079aec9eeb29d02f2809c6
Fix oobread and unaligned casts in the NE entrypoint logic ##crash * Reported by @hmsec via huntr.dev * Reproducer: nepocaligns * BountyID: ec538fa4-06c6-4050-a141-f60153ddeaac
0
RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) { if (!bin->entry_table) { return NULL; } RList *entries = r_list_newf (free); if (!entries) { return NULL; } RList *segments = r_bin_ne_get_segments (bin); if (!segments) { r_list_free (entries); return NULL; } if (bin->ne_header->csEntryPoint) { RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } entry->bits = 16; ut32 entry_cs = bin->ne_header->csEntryPoint; RBinSection *s = r_list_get_n (segments, entry_cs - 1); entry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0); r_list_append (entries, entry); } int off = 0; size_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset; while (off < bin->ne_header->EntryTableLength) { if (tableat + off >= r_buf_size (bin->buf)) { break; } ut8 bundle_length = *(ut8 *)(bin->entry_table + off); if (!bundle_length) { break; } off++; ut8 bundle_type = *(ut8 *)(bin->entry_table + off); off++; int i; for (i = 0; i < bundle_length; i++) { if (tableat + off + 4 >= r_buf_size (bin->buf)) { break; } RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } off++; if (!bundle_type) { // Skip off--; free (entry); break; } else if (bundle_type == 0xff) { // moveable off += 2; ut8 segnum = *(bin->entry_table + off); off++; if (off > bin->ne_header->EntryTableLength) { break; } ut16 segoff = r_read_le16 (bin->entry_table + off); if (segnum > 0 && segnum < bin->ne_header->SegCount) { entry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff; } } else { // Fixed if (off + 2 >= bin->ne_header->EntryTableLength) { break; } ut16 delta = r_read_le16 (bin->entry_table + off); if (bundle_type < bin->ne_header->SegCount) { entry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + delta; } } off += 2; r_list_append (entries, entry); } } r_list_free (segments); bin->entries = entries; return entries; }
178596264562074967520508544999708304050
ne.c
100978875788089844508151411517959063917
CWE-125
CVE-2022-1297
Out-of-bounds Read in r_bin_ne_get_entrypoints function in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability may allow attackers to read sensitive information or cause a crash.
https://nvd.nist.gov/vuln/detail/CVE-2022-1297
198,983
swtpm
9f740868fc36761de27df3935513bdebf8852d19
https://github.com/stefanberger/swtpm
https://github.com/stefanberger/swtpm/commit/9f740868fc36761de27df3935513bdebf8852d19
swtpm: Check header size indicator against expected size (CID 375869) This fix addresses Coverity issue CID 375869. Check the header size indicated in the header of the state against the expected size and return an error code in case the header size indicator is different. There was only one header size so far since blobheader was introduced, so we don't need to deal with different sizes. Without this fix a specially craft header could have cause out-of-bounds accesses on the byte array containing the swtpm's state. Signed-off-by: Stefan Berger <[email protected]>
1
SWTPM_NVRAM_CheckHeader(unsigned char *data, uint32_t length, uint32_t *dataoffset, uint16_t *hdrflags, uint8_t *hdrversion, bool quiet) { blobheader *bh = (blobheader *)data; if (length < sizeof(bh)) { if (!quiet) logprintf(STDERR_FILENO, "not enough bytes for header: %u\n", length); return TPM_BAD_PARAMETER; } if (ntohl(bh->totlen) != length) { if (!quiet) logprintf(STDERR_FILENO, "broken header: bh->totlen %u != %u\n", htonl(bh->totlen), length); return TPM_BAD_PARAMETER; } if (bh->min_version > BLOB_HEADER_VERSION) { if (!quiet) logprintf(STDERR_FILENO, "Minimum required version for the blob is %d, we " "only support version %d\n", bh->min_version, BLOB_HEADER_VERSION); return TPM_BAD_VERSION; } *hdrversion = bh->version; *dataoffset = ntohs(bh->hdrsize); *hdrflags = ntohs(bh->flags); return TPM_SUCCESS; }
173394517357295307246184358296702159922
swtpm_nvfile.c
132354630792840361852785968580616241078
CWE-125
CVE-2022-23645
swtpm is a libtpms-based TPM emulator with socket, character device, and Linux CUSE interface. Versions prior to 0.5.3, 0.6.2, and 0.7.1 are vulnerable to out-of-bounds read. A specially crafted header of swtpm's state, where the blobheader's hdrsize indicator has an invalid value, may cause an out-of-bounds access when the byte array representing the state of the TPM is accessed. This will likely crash swtpm or prevent it from starting since the state cannot be understood. Users should upgrade to swtpm v0.5.3, v0.6.2, or v0.7.1 to receive a patch. There are currently no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2022-23645
286,739
swtpm
9f740868fc36761de27df3935513bdebf8852d19
https://github.com/stefanberger/swtpm
https://github.com/stefanberger/swtpm/commit/9f740868fc36761de27df3935513bdebf8852d19
swtpm: Check header size indicator against expected size (CID 375869) This fix addresses Coverity issue CID 375869. Check the header size indicated in the header of the state against the expected size and return an error code in case the header size indicator is different. There was only one header size so far since blobheader was introduced, so we don't need to deal with different sizes. Without this fix a specially craft header could have cause out-of-bounds accesses on the byte array containing the swtpm's state. Signed-off-by: Stefan Berger <[email protected]>
0
SWTPM_NVRAM_CheckHeader(unsigned char *data, uint32_t length, uint32_t *dataoffset, uint16_t *hdrflags, uint8_t *hdrversion, bool quiet) { blobheader *bh = (blobheader *)data; uint16_t hdrsize; if (length < sizeof(bh)) { if (!quiet) logprintf(STDERR_FILENO, "not enough bytes for header: %u\n", length); return TPM_BAD_PARAMETER; } if (ntohl(bh->totlen) != length) { if (!quiet) logprintf(STDERR_FILENO, "broken header: bh->totlen %u != %u\n", htonl(bh->totlen), length); return TPM_BAD_PARAMETER; } if (bh->min_version > BLOB_HEADER_VERSION) { if (!quiet) logprintf(STDERR_FILENO, "Minimum required version for the blob is %d, we " "only support version %d\n", bh->min_version, BLOB_HEADER_VERSION); return TPM_BAD_VERSION; } hdrsize = ntohs(bh->hdrsize); if (hdrsize != sizeof(blobheader)) { logprintf(STDERR_FILENO, "bad header size: %u != %zu\n", hdrsize, sizeof(blobheader)); return TPM_BAD_DATASIZE; } *hdrversion = bh->version; *dataoffset = hdrsize; *hdrflags = ntohs(bh->flags); return TPM_SUCCESS; }
285282572007511982258600873303228604021
swtpm_nvstore.c
83066481150728701283019472792244832496
CWE-125
CVE-2022-23645
swtpm is a libtpms-based TPM emulator with socket, character device, and Linux CUSE interface. Versions prior to 0.5.3, 0.6.2, and 0.7.1 are vulnerable to out-of-bounds read. A specially crafted header of swtpm's state, where the blobheader's hdrsize indicator has an invalid value, may cause an out-of-bounds access when the byte array representing the state of the TPM is accessed. This will likely crash swtpm or prevent it from starting since the state cannot be understood. Users should upgrade to swtpm v0.5.3, v0.6.2, or v0.7.1 to receive a patch. There are currently no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2022-23645
199,159
linux
8423f0b6d513b259fdab9c9bf4aaa6188d054c2d
https://github.com/torvalds/linux
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8423f0b6d513b259fdab9c9bf4aaa6188d054c2d
ALSA: pcm: oss: Fix race at SNDCTL_DSP_SYNC There is a small race window at snd_pcm_oss_sync() that is called from OSS PCM SNDCTL_DSP_SYNC ioctl; namely the function calls snd_pcm_oss_make_ready() at first, then takes the params_lock mutex for the rest. When the stream is set up again by another thread between them, it leads to inconsistency, and may result in unexpected results such as NULL dereference of OSS buffer as a fuzzer spotted recently. The fix is simply to cover snd_pcm_oss_make_ready() call into the same params_lock mutex with snd_pcm_oss_make_ready_locked() variant. Reported-and-tested-by: butt3rflyh4ck <[email protected]> Reviewed-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Link: https://lore.kernel.org/r/CAFcO6XN7JDM4xSXGhtusQfS2mSBcx50VJKwQpCq=WeLt57aaZA@mail.gmail.com Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Takashi Iwai <[email protected]>
1
static int snd_pcm_oss_sync(struct snd_pcm_oss_file *pcm_oss_file) { int err = 0; unsigned int saved_f_flags; struct snd_pcm_substream *substream; struct snd_pcm_runtime *runtime; snd_pcm_format_t format; unsigned long width; size_t size; substream = pcm_oss_file->streams[SNDRV_PCM_STREAM_PLAYBACK]; if (substream != NULL) { runtime = substream->runtime; if (atomic_read(&substream->mmap_count)) goto __direct; err = snd_pcm_oss_make_ready(substream); if (err < 0) return err; atomic_inc(&runtime->oss.rw_ref); if (mutex_lock_interruptible(&runtime->oss.params_lock)) { atomic_dec(&runtime->oss.rw_ref); return -ERESTARTSYS; } format = snd_pcm_oss_format_from(runtime->oss.format); width = snd_pcm_format_physical_width(format); if (runtime->oss.buffer_used > 0) { #ifdef OSS_DEBUG pcm_dbg(substream->pcm, "sync: buffer_used\n"); #endif size = (8 * (runtime->oss.period_bytes - runtime->oss.buffer_used) + 7) / width; snd_pcm_format_set_silence(format, runtime->oss.buffer + runtime->oss.buffer_used, size); err = snd_pcm_oss_sync1(substream, runtime->oss.period_bytes); if (err < 0) goto unlock; } else if (runtime->oss.period_ptr > 0) { #ifdef OSS_DEBUG pcm_dbg(substream->pcm, "sync: period_ptr\n"); #endif size = runtime->oss.period_bytes - runtime->oss.period_ptr; snd_pcm_format_set_silence(format, runtime->oss.buffer, size * 8 / width); err = snd_pcm_oss_sync1(substream, size); if (err < 0) goto unlock; } /* * The ALSA's period might be a bit large than OSS one. * Fill the remain portion of ALSA period with zeros. */ size = runtime->control->appl_ptr % runtime->period_size; if (size > 0) { size = runtime->period_size - size; if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED) snd_pcm_lib_write(substream, NULL, size); else if (runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED) snd_pcm_lib_writev(substream, NULL, size); } unlock: mutex_unlock(&runtime->oss.params_lock); atomic_dec(&runtime->oss.rw_ref); if (err < 0) return err; /* * finish sync: drain the buffer */ __direct: saved_f_flags = substream->f_flags; substream->f_flags &= ~O_NONBLOCK; err = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DRAIN, NULL); substream->f_flags = saved_f_flags; if (err < 0) return err; mutex_lock(&runtime->oss.params_lock); runtime->oss.prepare = 1; mutex_unlock(&runtime->oss.params_lock); } substream = pcm_oss_file->streams[SNDRV_PCM_STREAM_CAPTURE]; if (substream != NULL) { err = snd_pcm_oss_make_ready(substream); if (err < 0) return err; runtime = substream->runtime; err = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL); if (err < 0) return err; mutex_lock(&runtime->oss.params_lock); runtime->oss.buffer_used = 0; runtime->oss.prepare = 1; mutex_unlock(&runtime->oss.params_lock); } return 0; }
331549555245265175479800423924118181234
None
CWE-362
CVE-2022-3303
A race condition flaw was found in the Linux kernel sound subsystem due to improper locking. It could lead to a NULL pointer dereference while handling the SNDCTL_DSP_SYNC ioctl. A privileged local user (root or member of the audio group) could use this flaw to crash the system, resulting in a denial of service condition
https://nvd.nist.gov/vuln/detail/CVE-2022-3303
289,293
linux
8423f0b6d513b259fdab9c9bf4aaa6188d054c2d
https://github.com/torvalds/linux
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8423f0b6d513b259fdab9c9bf4aaa6188d054c2d
ALSA: pcm: oss: Fix race at SNDCTL_DSP_SYNC There is a small race window at snd_pcm_oss_sync() that is called from OSS PCM SNDCTL_DSP_SYNC ioctl; namely the function calls snd_pcm_oss_make_ready() at first, then takes the params_lock mutex for the rest. When the stream is set up again by another thread between them, it leads to inconsistency, and may result in unexpected results such as NULL dereference of OSS buffer as a fuzzer spotted recently. The fix is simply to cover snd_pcm_oss_make_ready() call into the same params_lock mutex with snd_pcm_oss_make_ready_locked() variant. Reported-and-tested-by: butt3rflyh4ck <[email protected]> Reviewed-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Link: https://lore.kernel.org/r/CAFcO6XN7JDM4xSXGhtusQfS2mSBcx50VJKwQpCq=WeLt57aaZA@mail.gmail.com Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Takashi Iwai <[email protected]>
0
static int snd_pcm_oss_sync(struct snd_pcm_oss_file *pcm_oss_file) { int err = 0; unsigned int saved_f_flags; struct snd_pcm_substream *substream; struct snd_pcm_runtime *runtime; snd_pcm_format_t format; unsigned long width; size_t size; substream = pcm_oss_file->streams[SNDRV_PCM_STREAM_PLAYBACK]; if (substream != NULL) { runtime = substream->runtime; if (atomic_read(&substream->mmap_count)) goto __direct; atomic_inc(&runtime->oss.rw_ref); if (mutex_lock_interruptible(&runtime->oss.params_lock)) { atomic_dec(&runtime->oss.rw_ref); return -ERESTARTSYS; } err = snd_pcm_oss_make_ready_locked(substream); if (err < 0) goto unlock; format = snd_pcm_oss_format_from(runtime->oss.format); width = snd_pcm_format_physical_width(format); if (runtime->oss.buffer_used > 0) { #ifdef OSS_DEBUG pcm_dbg(substream->pcm, "sync: buffer_used\n"); #endif size = (8 * (runtime->oss.period_bytes - runtime->oss.buffer_used) + 7) / width; snd_pcm_format_set_silence(format, runtime->oss.buffer + runtime->oss.buffer_used, size); err = snd_pcm_oss_sync1(substream, runtime->oss.period_bytes); if (err < 0) goto unlock; } else if (runtime->oss.period_ptr > 0) { #ifdef OSS_DEBUG pcm_dbg(substream->pcm, "sync: period_ptr\n"); #endif size = runtime->oss.period_bytes - runtime->oss.period_ptr; snd_pcm_format_set_silence(format, runtime->oss.buffer, size * 8 / width); err = snd_pcm_oss_sync1(substream, size); if (err < 0) goto unlock; } /* * The ALSA's period might be a bit large than OSS one. * Fill the remain portion of ALSA period with zeros. */ size = runtime->control->appl_ptr % runtime->period_size; if (size > 0) { size = runtime->period_size - size; if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED) snd_pcm_lib_write(substream, NULL, size); else if (runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED) snd_pcm_lib_writev(substream, NULL, size); } unlock: mutex_unlock(&runtime->oss.params_lock); atomic_dec(&runtime->oss.rw_ref); if (err < 0) return err; /* * finish sync: drain the buffer */ __direct: saved_f_flags = substream->f_flags; substream->f_flags &= ~O_NONBLOCK; err = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DRAIN, NULL); substream->f_flags = saved_f_flags; if (err < 0) return err; mutex_lock(&runtime->oss.params_lock); runtime->oss.prepare = 1; mutex_unlock(&runtime->oss.params_lock); } substream = pcm_oss_file->streams[SNDRV_PCM_STREAM_CAPTURE]; if (substream != NULL) { err = snd_pcm_oss_make_ready(substream); if (err < 0) return err; runtime = substream->runtime; err = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL); if (err < 0) return err; mutex_lock(&runtime->oss.params_lock); runtime->oss.buffer_used = 0; runtime->oss.prepare = 1; mutex_unlock(&runtime->oss.params_lock); } return 0; }
1326761650975653611382443550395595187
None
CWE-362
CVE-2022-3303
A race condition flaw was found in the Linux kernel sound subsystem due to improper locking. It could lead to a NULL pointer dereference while handling the SNDCTL_DSP_SYNC ioctl. A privileged local user (root or member of the audio group) could use this flaw to crash the system, resulting in a denial of service condition
https://nvd.nist.gov/vuln/detail/CVE-2022-3303
199,712
linux
8700af2cc18c919b2a83e74e0479038fd113c15d
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/8700af2cc18c919b2a83e74e0479038fd113c15d
RDMA/rtrs-clt: Fix possible double free in error case Callback function rtrs_clt_dev_release() for put_device() calls kfree(clt) to free memory. We shouldn't call kfree(clt) again, and we can't use the clt after kfree too. Replace device_register() with device_initialize() and device_add() so that dev_set_name can() be used appropriately. Move mutex_destroy() to the release function so it can be called in the alloc_clt err path. Fixes: eab098246625 ("RDMA/rtrs-clt: Refactor the failure cases in alloc_clt") Link: https://lore.kernel.org/r/[email protected] Reported-by: Miaoqian Lin <[email protected]> Signed-off-by: Md Haris Iqbal <[email protected]> Reviewed-by: Jack Wang <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]>
1
static void rtrs_clt_dev_release(struct device *dev) { struct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess, dev); kfree(clt); }
64652297556654438298355501352205556509
rtrs-clt.c
149775209474441169700962555059878991264
CWE-415
CVE-2022-29156
drivers/infiniband/ulp/rtrs/rtrs-clt.c in the Linux kernel before 5.16.12 has a double free related to rtrs_clt_dev_release.
https://nvd.nist.gov/vuln/detail/CVE-2022-29156
291,761
linux
8700af2cc18c919b2a83e74e0479038fd113c15d
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/8700af2cc18c919b2a83e74e0479038fd113c15d
RDMA/rtrs-clt: Fix possible double free in error case Callback function rtrs_clt_dev_release() for put_device() calls kfree(clt) to free memory. We shouldn't call kfree(clt) again, and we can't use the clt after kfree too. Replace device_register() with device_initialize() and device_add() so that dev_set_name can() be used appropriately. Move mutex_destroy() to the release function so it can be called in the alloc_clt err path. Fixes: eab098246625 ("RDMA/rtrs-clt: Refactor the failure cases in alloc_clt") Link: https://lore.kernel.org/r/[email protected] Reported-by: Miaoqian Lin <[email protected]> Signed-off-by: Md Haris Iqbal <[email protected]> Reviewed-by: Jack Wang <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]>
0
static void rtrs_clt_dev_release(struct device *dev) { struct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess, dev); mutex_destroy(&clt->paths_ev_mutex); mutex_destroy(&clt->paths_mutex); kfree(clt); }
280791422344483990445186805760516988921
rtrs-clt.c
123062054699569722257369072160789726422
CWE-415
CVE-2022-29156
drivers/infiniband/ulp/rtrs/rtrs-clt.c in the Linux kernel before 5.16.12 has a double free related to rtrs_clt_dev_release.
https://nvd.nist.gov/vuln/detail/CVE-2022-29156
199,767
hexchat
4e061a43b3453a9856d34250c3913175c45afe9d
https://github.com/hexchat/hexchat
https://github.com/hexchat/hexchat/commit/4e061a43b3453a9856d34250c3913175c45afe9d
Clean up handling CAP LS
1
inbound_cap_ls (server *serv, char *nick, char *extensions_str, const message_tags_data *tags_data) { char buffer[256]; /* buffer for requesting capabilities and emitting the signal */ guint32 want_cap; /* format the CAP REQ string based on previous capabilities being requested or not */ guint32 want_sasl; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */ char **extensions; int i; EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick, extensions_str, NULL, NULL, 0, tags_data->timestamp); want_cap = 0; want_sasl = 0; extensions = g_strsplit (extensions_str, " ", 0); strcpy (buffer, "CAP REQ :"); for (i=0; extensions[i]; i++) { const char *extension = extensions[i]; if (!strcmp (extension, "identify-msg")) { strcat (buffer, "identify-msg "); want_cap = 1; } if (!strcmp (extension, "multi-prefix")) { strcat (buffer, "multi-prefix "); want_cap = 1; } if (!strcmp (extension, "away-notify")) { strcat (buffer, "away-notify "); want_cap = 1; } if (!strcmp (extension, "account-notify")) { strcat (buffer, "account-notify "); want_cap = 1; } if (!strcmp (extension, "extended-join")) { strcat (buffer, "extended-join "); want_cap = 1; } if (!strcmp (extension, "userhost-in-names")) { strcat (buffer, "userhost-in-names "); want_cap = 1; } /* bouncers can prefix a name space to the extension so we should use. * znc <= 1.0 uses "znc.in/server-time" and newer use "znc.in/server-time-iso". */ if (!strcmp (extension, "znc.in/server-time-iso")) { strcat (buffer, "znc.in/server-time-iso "); want_cap = 1; } if (!strcmp (extension, "znc.in/server-time")) { strcat (buffer, "znc.in/server-time "); want_cap = 1; } if (prefs.hex_irc_cap_server_time && !strcmp (extension, "server-time")) { strcat (buffer, "server-time "); want_cap = 1; } /* if the SASL password is set AND auth mode is set to SASL, request SASL auth */ if (!strcmp (extension, "sasl") && ((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0) || (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert))) { strcat (buffer, "sasl "); want_cap = 1; want_sasl = 1; } } g_strfreev (extensions); if (want_cap) { /* buffer + 9 = emit buffer without "CAP REQ :" */ EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session, buffer + 9, NULL, NULL, NULL, 0, tags_data->timestamp); tcp_sendf (serv, "%s\r\n", g_strchomp (buffer)); } if (!want_sasl) { /* if we use SASL, CAP END is dealt via raw numerics */ serv->sent_capend = TRUE; tcp_send_len (serv, "CAP END\r\n", 9); } }
289376674180826741553106169575003472652
inbound.c
202497518967624726910452754426675896941
CWE-22
CVE-2016-2087
Directory traversal vulnerability in the client in HexChat 2.11.0 allows remote IRC servers to read or modify arbitrary files via a .. (dot dot) in the server name.
https://nvd.nist.gov/vuln/detail/CVE-2016-2087
292,205
hexchat
4e061a43b3453a9856d34250c3913175c45afe9d
https://github.com/hexchat/hexchat
https://github.com/hexchat/hexchat/commit/4e061a43b3453a9856d34250c3913175c45afe9d
Clean up handling CAP LS
0
inbound_cap_ls (server *serv, char *nick, char *extensions_str, const message_tags_data *tags_data) { char buffer[256]; /* buffer for requesting capabilities and emitting the signal */ gboolean want_cap = FALSE; /* format the CAP REQ string based on previous capabilities being requested or not */ gboolean want_sasl = FALSE; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */ char **extensions; int i; EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick, extensions_str, NULL, NULL, 0, tags_data->timestamp); extensions = g_strsplit (extensions_str, " ", 0); strcpy (buffer, "CAP REQ :"); for (i=0; extensions[i]; i++) { const char *extension = extensions[i]; gsize x; /* if the SASL password is set AND auth mode is set to SASL, request SASL auth */ if (!g_strcmp0 (extension, "sasl") && ((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0) || (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert))) { want_cap = TRUE; want_sasl = TRUE; g_strlcat (buffer, "sasl ", sizeof(buffer)); continue; } for (x = 0; x < G_N_ELEMENTS(supported_caps); ++x) { if (!g_strcmp0 (extension, supported_caps[x])) { g_strlcat (buffer, extension, sizeof(buffer)); g_strlcat (buffer, " ", sizeof(buffer)); want_cap = TRUE; } } } g_strfreev (extensions); if (want_cap) { /* buffer + 9 = emit buffer without "CAP REQ :" */ EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session, buffer + 9, NULL, NULL, NULL, 0, tags_data->timestamp); tcp_sendf (serv, "%s\r\n", g_strchomp (buffer)); } if (!want_sasl) { /* if we use SASL, CAP END is dealt via raw numerics */ serv->sent_capend = TRUE; tcp_send_len (serv, "CAP END\r\n", 9); } }
298030143557811243277605801674004119778
inbound.c
316287172279434102312310467592869221678
CWE-22
CVE-2016-2087
Directory traversal vulnerability in the client in HexChat 2.11.0 allows remote IRC servers to read or modify arbitrary files via a .. (dot dot) in the server name.
https://nvd.nist.gov/vuln/detail/CVE-2016-2087
199,778
puma
acdc3ae571dfae0e045cf09a295280127db65c7f
https://github.com/puma/puma
https://github.com/puma/puma/commit/acdc3ae571dfae0e045cf09a295280127db65c7f
Merge pull request from GHSA-48w2-rm65-62xx * Fix HTTP request smuggling vulnerability See GHSA-48w2-rm65-62xx or CVE-2021-41136 for more info. * 4.3.9 release note * 5.5.1 release note * 5.5.1
1
size_t puma_parser_execute(puma_parser *parser, const char *buffer, size_t len, size_t off) { const char *p, *pe; int cs = parser->cs; assert(off <= len && "offset past end of buffer"); p = buffer+off; pe = buffer+len; /* assert(*pe == '\0' && "pointer does not end on NUL"); */ assert((size_t) (pe - p) == len - off && "pointers aren't same distance"); #line 87 "ext/puma_http11/http11_parser.c" { if ( p == pe ) goto _test_eof; switch ( cs ) { case 1: switch( (*p) ) { case 36: goto tr0; case 95: goto tr0; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto tr0; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto tr0; } else goto tr0; goto st0; st0: cs = 0; goto _out; tr0: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st2; st2: if ( ++p == pe ) goto _test_eof2; case 2: #line 118 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr2; case 36: goto st27; case 95: goto st27; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st27; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st27; } else goto st27; goto st0; tr2: #line 50 "ext/puma_http11/http11_parser.rl" { parser->request_method(parser, PTR_TO(mark), LEN(mark, p)); } goto st3; st3: if ( ++p == pe ) goto _test_eof3; case 3: #line 143 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 42: goto tr4; case 43: goto tr5; case 47: goto tr6; case 58: goto tr7; } if ( (*p) < 65 ) { if ( 45 <= (*p) && (*p) <= 57 ) goto tr5; } else if ( (*p) > 90 ) { if ( 97 <= (*p) && (*p) <= 122 ) goto tr5; } else goto tr5; goto st0; tr4: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st4; st4: if ( ++p == pe ) goto _test_eof4; case 4: #line 167 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr8; case 35: goto tr9; } goto st0; tr8: #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr31: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } #line 56 "ext/puma_http11/http11_parser.rl" { parser->fragment(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr33: #line 56 "ext/puma_http11/http11_parser.rl" { parser->fragment(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr37: #line 69 "ext/puma_http11/http11_parser.rl" { parser->request_path(parser, PTR_TO(mark), LEN(mark,p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr41: #line 60 "ext/puma_http11/http11_parser.rl" { MARK(query_start, p); } #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr44: #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; st5: if ( ++p == pe ) goto _test_eof5; case 5: #line 229 "ext/puma_http11/http11_parser.c" if ( (*p) == 72 ) goto tr10; goto st0; tr10: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st6; st6: if ( ++p == pe ) goto _test_eof6; case 6: #line 241 "ext/puma_http11/http11_parser.c" if ( (*p) == 84 ) goto st7; goto st0; st7: if ( ++p == pe ) goto _test_eof7; case 7: if ( (*p) == 84 ) goto st8; goto st0; st8: if ( ++p == pe ) goto _test_eof8; case 8: if ( (*p) == 80 ) goto st9; goto st0; st9: if ( ++p == pe ) goto _test_eof9; case 9: if ( (*p) == 47 ) goto st10; goto st0; st10: if ( ++p == pe ) goto _test_eof10; case 10: if ( 48 <= (*p) && (*p) <= 57 ) goto st11; goto st0; st11: if ( ++p == pe ) goto _test_eof11; case 11: if ( (*p) == 46 ) goto st12; if ( 48 <= (*p) && (*p) <= 57 ) goto st11; goto st0; st12: if ( ++p == pe ) goto _test_eof12; case 12: if ( 48 <= (*p) && (*p) <= 57 ) goto st13; goto st0; st13: if ( ++p == pe ) goto _test_eof13; case 13: if ( (*p) == 13 ) goto tr18; if ( 48 <= (*p) && (*p) <= 57 ) goto st13; goto st0; tr18: #line 65 "ext/puma_http11/http11_parser.rl" { parser->http_version(parser, PTR_TO(mark), LEN(mark, p)); } goto st14; tr26: #line 46 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } #line 47 "ext/puma_http11/http11_parser.rl" { parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p)); } goto st14; tr29: #line 47 "ext/puma_http11/http11_parser.rl" { parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p)); } goto st14; st14: if ( ++p == pe ) goto _test_eof14; case 14: #line 322 "ext/puma_http11/http11_parser.c" if ( (*p) == 10 ) goto st15; goto st0; st15: if ( ++p == pe ) goto _test_eof15; case 15: switch( (*p) ) { case 13: goto st16; case 33: goto tr21; case 124: goto tr21; case 126: goto tr21; } if ( (*p) < 45 ) { if ( (*p) > 39 ) { if ( 42 <= (*p) && (*p) <= 43 ) goto tr21; } else if ( (*p) >= 35 ) goto tr21; } else if ( (*p) > 46 ) { if ( (*p) < 65 ) { if ( 48 <= (*p) && (*p) <= 57 ) goto tr21; } else if ( (*p) > 90 ) { if ( 94 <= (*p) && (*p) <= 122 ) goto tr21; } else goto tr21; } else goto tr21; goto st0; st16: if ( ++p == pe ) goto _test_eof16; case 16: if ( (*p) == 10 ) goto tr22; goto st0; tr22: #line 73 "ext/puma_http11/http11_parser.rl" { parser->body_start = p - buffer + 1; parser->header_done(parser, p + 1, pe - p - 1); {p++; cs = 46; goto _out;} } goto st46; st46: if ( ++p == pe ) goto _test_eof46; case 46: #line 373 "ext/puma_http11/http11_parser.c" goto st0; tr21: #line 40 "ext/puma_http11/http11_parser.rl" { MARK(field_start, p); } #line 41 "ext/puma_http11/http11_parser.rl" { snake_upcase_char((char *)p); } goto st17; tr23: #line 41 "ext/puma_http11/http11_parser.rl" { snake_upcase_char((char *)p); } goto st17; st17: if ( ++p == pe ) goto _test_eof17; case 17: #line 389 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 33: goto tr23; case 58: goto tr24; case 124: goto tr23; case 126: goto tr23; } if ( (*p) < 45 ) { if ( (*p) > 39 ) { if ( 42 <= (*p) && (*p) <= 43 ) goto tr23; } else if ( (*p) >= 35 ) goto tr23; } else if ( (*p) > 46 ) { if ( (*p) < 65 ) { if ( 48 <= (*p) && (*p) <= 57 ) goto tr23; } else if ( (*p) > 90 ) { if ( 94 <= (*p) && (*p) <= 122 ) goto tr23; } else goto tr23; } else goto tr23; goto st0; tr24: #line 42 "ext/puma_http11/http11_parser.rl" { parser->field_len = LEN(field_start, p); } goto st18; tr27: #line 46 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st18; st18: if ( ++p == pe ) goto _test_eof18; case 18: #line 428 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 13: goto tr26; case 32: goto tr27; } goto tr25; tr25: #line 46 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st19; st19: if ( ++p == pe ) goto _test_eof19; case 19: #line 442 "ext/puma_http11/http11_parser.c" if ( (*p) == 13 ) goto tr29; goto st19; tr9: #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; tr38: #line 69 "ext/puma_http11/http11_parser.rl" { parser->request_path(parser, PTR_TO(mark), LEN(mark,p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; tr42: #line 60 "ext/puma_http11/http11_parser.rl" { MARK(query_start, p); } #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; tr45: #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; st20: if ( ++p == pe ) goto _test_eof20; case 20: #line 488 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr31; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( (*p) > 31 ) { if ( 34 <= (*p) && (*p) <= 35 ) goto st0; } else if ( (*p) >= 0 ) goto st0; goto tr30; tr30: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st21; st21: if ( ++p == pe ) goto _test_eof21; case 21: #line 509 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr33; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( (*p) > 31 ) { if ( 34 <= (*p) && (*p) <= 35 ) goto st0; } else if ( (*p) >= 0 ) goto st0; goto st21; tr5: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st22; st22: if ( ++p == pe ) goto _test_eof22; case 22: #line 530 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 43: goto st22; case 58: goto st23; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st22; } else if ( (*p) > 57 ) { if ( (*p) > 90 ) { if ( 97 <= (*p) && (*p) <= 122 ) goto st22; } else if ( (*p) >= 65 ) goto st22; } else goto st22; goto st0; tr7: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st23; st23: if ( ++p == pe ) goto _test_eof23; case 23: #line 555 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr8; case 34: goto st0; case 35: goto tr9; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto st23; tr6: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st24; st24: if ( ++p == pe ) goto _test_eof24; case 24: #line 575 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr37; case 34: goto st0; case 35: goto tr38; case 60: goto st0; case 62: goto st0; case 63: goto tr39; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto st24; tr39: #line 69 "ext/puma_http11/http11_parser.rl" { parser->request_path(parser, PTR_TO(mark), LEN(mark,p)); } goto st25; st25: if ( ++p == pe ) goto _test_eof25; case 25: #line 598 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr41; case 34: goto st0; case 35: goto tr42; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto tr40; tr40: #line 60 "ext/puma_http11/http11_parser.rl" { MARK(query_start, p); } goto st26; st26: if ( ++p == pe ) goto _test_eof26; case 26: #line 618 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr44; case 34: goto st0; case 35: goto tr45; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto st26; st27: if ( ++p == pe ) goto _test_eof27; case 27: switch( (*p) ) { case 32: goto tr2; case 36: goto st28; case 95: goto st28; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st28; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st28; } else goto st28; goto st0; st28: if ( ++p == pe ) goto _test_eof28; case 28: switch( (*p) ) { case 32: goto tr2; case 36: goto st29; case 95: goto st29; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st29; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st29; } else goto st29; goto st0; st29: if ( ++p == pe ) goto _test_eof29; case 29: switch( (*p) ) { case 32: goto tr2; case 36: goto st30; case 95: goto st30; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st30; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st30; } else goto st30; goto st0; st30: if ( ++p == pe ) goto _test_eof30; case 30: switch( (*p) ) { case 32: goto tr2; case 36: goto st31; case 95: goto st31; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st31; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st31; } else goto st31; goto st0; st31: if ( ++p == pe ) goto _test_eof31; case 31: switch( (*p) ) { case 32: goto tr2; case 36: goto st32; case 95: goto st32; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st32; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st32; } else goto st32; goto st0; st32: if ( ++p == pe ) goto _test_eof32; case 32: switch( (*p) ) { case 32: goto tr2; case 36: goto st33; case 95: goto st33; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st33; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st33; } else goto st33; goto st0; st33: if ( ++p == pe ) goto _test_eof33; case 33: switch( (*p) ) { case 32: goto tr2; case 36: goto st34; case 95: goto st34; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st34; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st34; } else goto st34; goto st0; st34: if ( ++p == pe ) goto _test_eof34; case 34: switch( (*p) ) { case 32: goto tr2; case 36: goto st35; case 95: goto st35; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st35; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st35; } else goto st35; goto st0; st35: if ( ++p == pe ) goto _test_eof35; case 35: switch( (*p) ) { case 32: goto tr2; case 36: goto st36; case 95: goto st36; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st36; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st36; } else goto st36; goto st0; st36: if ( ++p == pe ) goto _test_eof36; case 36: switch( (*p) ) { case 32: goto tr2; case 36: goto st37; case 95: goto st37; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st37; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st37; } else goto st37; goto st0; st37: if ( ++p == pe ) goto _test_eof37; case 37: switch( (*p) ) { case 32: goto tr2; case 36: goto st38; case 95: goto st38; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st38; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st38; } else goto st38; goto st0; st38: if ( ++p == pe ) goto _test_eof38; case 38: switch( (*p) ) { case 32: goto tr2; case 36: goto st39; case 95: goto st39; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st39; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st39; } else goto st39; goto st0; st39: if ( ++p == pe ) goto _test_eof39; case 39: switch( (*p) ) { case 32: goto tr2; case 36: goto st40; case 95: goto st40; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st40; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st40; } else goto st40; goto st0; st40: if ( ++p == pe ) goto _test_eof40; case 40: switch( (*p) ) { case 32: goto tr2; case 36: goto st41; case 95: goto st41; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st41; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st41; } else goto st41; goto st0; st41: if ( ++p == pe ) goto _test_eof41; case 41: switch( (*p) ) { case 32: goto tr2; case 36: goto st42; case 95: goto st42; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st42; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st42; } else goto st42; goto st0; st42: if ( ++p == pe ) goto _test_eof42; case 42: switch( (*p) ) { case 32: goto tr2; case 36: goto st43; case 95: goto st43; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st43; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st43; } else goto st43; goto st0; st43: if ( ++p == pe ) goto _test_eof43; case 43: switch( (*p) ) { case 32: goto tr2; case 36: goto st44; case 95: goto st44; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st44; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st44; } else goto st44; goto st0; st44: if ( ++p == pe ) goto _test_eof44; case 44: switch( (*p) ) { case 32: goto tr2; case 36: goto st45; case 95: goto st45; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st45; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st45; } else goto st45; goto st0; st45: if ( ++p == pe ) goto _test_eof45; case 45: if ( (*p) == 32 ) goto tr2; goto st0; } _test_eof2: cs = 2; goto _test_eof; _test_eof3: cs = 3; goto _test_eof; _test_eof4: cs = 4; goto _test_eof; _test_eof5: cs = 5; goto _test_eof; _test_eof6: cs = 6; goto _test_eof; _test_eof7: cs = 7; goto _test_eof; _test_eof8: cs = 8; goto _test_eof; _test_eof9: cs = 9; goto _test_eof; _test_eof10: cs = 10; goto _test_eof; _test_eof11: cs = 11; goto _test_eof; _test_eof12: cs = 12; goto _test_eof; _test_eof13: cs = 13; goto _test_eof; _test_eof14: cs = 14; goto _test_eof; _test_eof15: cs = 15; goto _test_eof; _test_eof16: cs = 16; goto _test_eof; _test_eof46: cs = 46; goto _test_eof; _test_eof17: cs = 17; goto _test_eof; _test_eof18: cs = 18; goto _test_eof; _test_eof19: cs = 19; goto _test_eof; _test_eof20: cs = 20; goto _test_eof; _test_eof21: cs = 21; goto _test_eof; _test_eof22: cs = 22; goto _test_eof; _test_eof23: cs = 23; goto _test_eof; _test_eof24: cs = 24; goto _test_eof; _test_eof25: cs = 25; goto _test_eof; _test_eof26: cs = 26; goto _test_eof; _test_eof27: cs = 27; goto _test_eof; _test_eof28: cs = 28; goto _test_eof; _test_eof29: cs = 29; goto _test_eof; _test_eof30: cs = 30; goto _test_eof; _test_eof31: cs = 31; goto _test_eof; _test_eof32: cs = 32; goto _test_eof; _test_eof33: cs = 33; goto _test_eof; _test_eof34: cs = 34; goto _test_eof; _test_eof35: cs = 35; goto _test_eof; _test_eof36: cs = 36; goto _test_eof; _test_eof37: cs = 37; goto _test_eof; _test_eof38: cs = 38; goto _test_eof; _test_eof39: cs = 39; goto _test_eof; _test_eof40: cs = 40; goto _test_eof; _test_eof41: cs = 41; goto _test_eof; _test_eof42: cs = 42; goto _test_eof; _test_eof43: cs = 43; goto _test_eof; _test_eof44: cs = 44; goto _test_eof; _test_eof45: cs = 45; goto _test_eof; _test_eof: {} _out: {} } #line 117 "ext/puma_http11/http11_parser.rl" if (!puma_parser_has_error(parser)) parser->cs = cs; parser->nread += p - (buffer + off); assert(p <= pe && "buffer overflow after parsing execute"); assert(parser->nread <= len && "nread longer than length"); assert(parser->body_start <= len && "body starts after buffer end"); assert(parser->mark < len && "mark is after buffer end"); assert(parser->field_len <= len && "field has length longer than whole buffer"); assert(parser->field_start < len && "field starts after buffer end"); return(parser->nread); }
94439113710401505299900606066823977917
http11_parser.c
59830834973701402944362779116096200943
CWE-444
CVE-2021-41136
Puma is a HTTP 1.1 server for Ruby/Rack applications. Prior to versions 5.5.1 and 4.3.9, using `puma` with a proxy which forwards HTTP header values which contain the LF character could allow HTTP request smugggling. A client could smuggle a request through a proxy, causing the proxy to send a response back to another unknown client. The only proxy which has this behavior, as far as the Puma team is aware of, is Apache Traffic Server. If the proxy uses persistent connections and the client adds another request in via HTTP pipelining, the proxy may mistake it as the first request's body. Puma, however, would see it as two requests, and when processing the second request, send back a response that the proxy does not expect. If the proxy has reused the persistent connection to Puma to send another request for a different client, the second response from the first client will be sent to the second client. This vulnerability was patched in Puma 5.5.1 and 4.3.9. As a workaround, do not use Apache Traffic Server with `puma`.
https://nvd.nist.gov/vuln/detail/CVE-2021-41136
292,609
puma
acdc3ae571dfae0e045cf09a295280127db65c7f
https://github.com/puma/puma
https://github.com/puma/puma/commit/acdc3ae571dfae0e045cf09a295280127db65c7f
Merge pull request from GHSA-48w2-rm65-62xx * Fix HTTP request smuggling vulnerability See GHSA-48w2-rm65-62xx or CVE-2021-41136 for more info. * 4.3.9 release note * 5.5.1 release note * 5.5.1
0
size_t puma_parser_execute(puma_parser *parser, const char *buffer, size_t len, size_t off) { const char *p, *pe; int cs = parser->cs; assert(off <= len && "offset past end of buffer"); p = buffer+off; pe = buffer+len; /* assert(*pe == '\0' && "pointer does not end on NUL"); */ assert((size_t) (pe - p) == len - off && "pointers aren't same distance"); #line 87 "ext/puma_http11/http11_parser.c" { if ( p == pe ) goto _test_eof; switch ( cs ) { case 1: switch( (*p) ) { case 36: goto tr0; case 95: goto tr0; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto tr0; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto tr0; } else goto tr0; goto st0; st0: cs = 0; goto _out; tr0: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st2; st2: if ( ++p == pe ) goto _test_eof2; case 2: #line 118 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr2; case 36: goto st27; case 95: goto st27; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st27; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st27; } else goto st27; goto st0; tr2: #line 50 "ext/puma_http11/http11_parser.rl" { parser->request_method(parser, PTR_TO(mark), LEN(mark, p)); } goto st3; st3: if ( ++p == pe ) goto _test_eof3; case 3: #line 143 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 42: goto tr4; case 43: goto tr5; case 47: goto tr6; case 58: goto tr7; } if ( (*p) < 65 ) { if ( 45 <= (*p) && (*p) <= 57 ) goto tr5; } else if ( (*p) > 90 ) { if ( 97 <= (*p) && (*p) <= 122 ) goto tr5; } else goto tr5; goto st0; tr4: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st4; st4: if ( ++p == pe ) goto _test_eof4; case 4: #line 167 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr8; case 35: goto tr9; } goto st0; tr8: #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr31: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } #line 56 "ext/puma_http11/http11_parser.rl" { parser->fragment(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr33: #line 56 "ext/puma_http11/http11_parser.rl" { parser->fragment(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr37: #line 69 "ext/puma_http11/http11_parser.rl" { parser->request_path(parser, PTR_TO(mark), LEN(mark,p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr41: #line 60 "ext/puma_http11/http11_parser.rl" { MARK(query_start, p); } #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; tr44: #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st5; st5: if ( ++p == pe ) goto _test_eof5; case 5: #line 229 "ext/puma_http11/http11_parser.c" if ( (*p) == 72 ) goto tr10; goto st0; tr10: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st6; st6: if ( ++p == pe ) goto _test_eof6; case 6: #line 241 "ext/puma_http11/http11_parser.c" if ( (*p) == 84 ) goto st7; goto st0; st7: if ( ++p == pe ) goto _test_eof7; case 7: if ( (*p) == 84 ) goto st8; goto st0; st8: if ( ++p == pe ) goto _test_eof8; case 8: if ( (*p) == 80 ) goto st9; goto st0; st9: if ( ++p == pe ) goto _test_eof9; case 9: if ( (*p) == 47 ) goto st10; goto st0; st10: if ( ++p == pe ) goto _test_eof10; case 10: if ( 48 <= (*p) && (*p) <= 57 ) goto st11; goto st0; st11: if ( ++p == pe ) goto _test_eof11; case 11: if ( (*p) == 46 ) goto st12; if ( 48 <= (*p) && (*p) <= 57 ) goto st11; goto st0; st12: if ( ++p == pe ) goto _test_eof12; case 12: if ( 48 <= (*p) && (*p) <= 57 ) goto st13; goto st0; st13: if ( ++p == pe ) goto _test_eof13; case 13: if ( (*p) == 13 ) goto tr18; if ( 48 <= (*p) && (*p) <= 57 ) goto st13; goto st0; tr18: #line 65 "ext/puma_http11/http11_parser.rl" { parser->http_version(parser, PTR_TO(mark), LEN(mark, p)); } goto st14; tr26: #line 46 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } #line 47 "ext/puma_http11/http11_parser.rl" { parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p)); } goto st14; tr29: #line 47 "ext/puma_http11/http11_parser.rl" { parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p)); } goto st14; st14: if ( ++p == pe ) goto _test_eof14; case 14: #line 322 "ext/puma_http11/http11_parser.c" if ( (*p) == 10 ) goto st15; goto st0; st15: if ( ++p == pe ) goto _test_eof15; case 15: switch( (*p) ) { case 13: goto st16; case 33: goto tr21; case 124: goto tr21; case 126: goto tr21; } if ( (*p) < 45 ) { if ( (*p) > 39 ) { if ( 42 <= (*p) && (*p) <= 43 ) goto tr21; } else if ( (*p) >= 35 ) goto tr21; } else if ( (*p) > 46 ) { if ( (*p) < 65 ) { if ( 48 <= (*p) && (*p) <= 57 ) goto tr21; } else if ( (*p) > 90 ) { if ( 94 <= (*p) && (*p) <= 122 ) goto tr21; } else goto tr21; } else goto tr21; goto st0; st16: if ( ++p == pe ) goto _test_eof16; case 16: if ( (*p) == 10 ) goto tr22; goto st0; tr22: #line 73 "ext/puma_http11/http11_parser.rl" { parser->body_start = p - buffer + 1; parser->header_done(parser, p + 1, pe - p - 1); {p++; cs = 46; goto _out;} } goto st46; st46: if ( ++p == pe ) goto _test_eof46; case 46: #line 373 "ext/puma_http11/http11_parser.c" goto st0; tr21: #line 40 "ext/puma_http11/http11_parser.rl" { MARK(field_start, p); } #line 41 "ext/puma_http11/http11_parser.rl" { snake_upcase_char((char *)p); } goto st17; tr23: #line 41 "ext/puma_http11/http11_parser.rl" { snake_upcase_char((char *)p); } goto st17; st17: if ( ++p == pe ) goto _test_eof17; case 17: #line 389 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 33: goto tr23; case 58: goto tr24; case 124: goto tr23; case 126: goto tr23; } if ( (*p) < 45 ) { if ( (*p) > 39 ) { if ( 42 <= (*p) && (*p) <= 43 ) goto tr23; } else if ( (*p) >= 35 ) goto tr23; } else if ( (*p) > 46 ) { if ( (*p) < 65 ) { if ( 48 <= (*p) && (*p) <= 57 ) goto tr23; } else if ( (*p) > 90 ) { if ( 94 <= (*p) && (*p) <= 122 ) goto tr23; } else goto tr23; } else goto tr23; goto st0; tr24: #line 42 "ext/puma_http11/http11_parser.rl" { parser->field_len = LEN(field_start, p); } goto st18; tr27: #line 46 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st18; st18: if ( ++p == pe ) goto _test_eof18; case 18: #line 428 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 9: goto tr25; case 13: goto tr26; case 32: goto tr27; } if ( 33 <= (*p) && (*p) <= 126 ) goto tr25; goto st0; tr25: #line 46 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st19; st19: if ( ++p == pe ) goto _test_eof19; case 19: #line 445 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 9: goto st19; case 13: goto tr29; } if ( 32 <= (*p) && (*p) <= 126 ) goto st19; goto st0; tr9: #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; tr38: #line 69 "ext/puma_http11/http11_parser.rl" { parser->request_path(parser, PTR_TO(mark), LEN(mark,p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; tr42: #line 60 "ext/puma_http11/http11_parser.rl" { MARK(query_start, p); } #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; tr45: #line 61 "ext/puma_http11/http11_parser.rl" { parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p)); } #line 53 "ext/puma_http11/http11_parser.rl" { parser->request_uri(parser, PTR_TO(mark), LEN(mark, p)); } goto st20; st20: if ( ++p == pe ) goto _test_eof20; case 20: #line 495 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr31; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( (*p) > 31 ) { if ( 34 <= (*p) && (*p) <= 35 ) goto st0; } else if ( (*p) >= 0 ) goto st0; goto tr30; tr30: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st21; st21: if ( ++p == pe ) goto _test_eof21; case 21: #line 516 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr33; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( (*p) > 31 ) { if ( 34 <= (*p) && (*p) <= 35 ) goto st0; } else if ( (*p) >= 0 ) goto st0; goto st21; tr5: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st22; st22: if ( ++p == pe ) goto _test_eof22; case 22: #line 537 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 43: goto st22; case 58: goto st23; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st22; } else if ( (*p) > 57 ) { if ( (*p) > 90 ) { if ( 97 <= (*p) && (*p) <= 122 ) goto st22; } else if ( (*p) >= 65 ) goto st22; } else goto st22; goto st0; tr7: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st23; st23: if ( ++p == pe ) goto _test_eof23; case 23: #line 562 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr8; case 34: goto st0; case 35: goto tr9; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto st23; tr6: #line 37 "ext/puma_http11/http11_parser.rl" { MARK(mark, p); } goto st24; st24: if ( ++p == pe ) goto _test_eof24; case 24: #line 582 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr37; case 34: goto st0; case 35: goto tr38; case 60: goto st0; case 62: goto st0; case 63: goto tr39; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto st24; tr39: #line 69 "ext/puma_http11/http11_parser.rl" { parser->request_path(parser, PTR_TO(mark), LEN(mark,p)); } goto st25; st25: if ( ++p == pe ) goto _test_eof25; case 25: #line 605 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr41; case 34: goto st0; case 35: goto tr42; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto tr40; tr40: #line 60 "ext/puma_http11/http11_parser.rl" { MARK(query_start, p); } goto st26; st26: if ( ++p == pe ) goto _test_eof26; case 26: #line 625 "ext/puma_http11/http11_parser.c" switch( (*p) ) { case 32: goto tr44; case 34: goto st0; case 35: goto tr45; case 60: goto st0; case 62: goto st0; case 127: goto st0; } if ( 0 <= (*p) && (*p) <= 31 ) goto st0; goto st26; st27: if ( ++p == pe ) goto _test_eof27; case 27: switch( (*p) ) { case 32: goto tr2; case 36: goto st28; case 95: goto st28; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st28; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st28; } else goto st28; goto st0; st28: if ( ++p == pe ) goto _test_eof28; case 28: switch( (*p) ) { case 32: goto tr2; case 36: goto st29; case 95: goto st29; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st29; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st29; } else goto st29; goto st0; st29: if ( ++p == pe ) goto _test_eof29; case 29: switch( (*p) ) { case 32: goto tr2; case 36: goto st30; case 95: goto st30; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st30; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st30; } else goto st30; goto st0; st30: if ( ++p == pe ) goto _test_eof30; case 30: switch( (*p) ) { case 32: goto tr2; case 36: goto st31; case 95: goto st31; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st31; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st31; } else goto st31; goto st0; st31: if ( ++p == pe ) goto _test_eof31; case 31: switch( (*p) ) { case 32: goto tr2; case 36: goto st32; case 95: goto st32; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st32; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st32; } else goto st32; goto st0; st32: if ( ++p == pe ) goto _test_eof32; case 32: switch( (*p) ) { case 32: goto tr2; case 36: goto st33; case 95: goto st33; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st33; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st33; } else goto st33; goto st0; st33: if ( ++p == pe ) goto _test_eof33; case 33: switch( (*p) ) { case 32: goto tr2; case 36: goto st34; case 95: goto st34; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st34; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st34; } else goto st34; goto st0; st34: if ( ++p == pe ) goto _test_eof34; case 34: switch( (*p) ) { case 32: goto tr2; case 36: goto st35; case 95: goto st35; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st35; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st35; } else goto st35; goto st0; st35: if ( ++p == pe ) goto _test_eof35; case 35: switch( (*p) ) { case 32: goto tr2; case 36: goto st36; case 95: goto st36; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st36; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st36; } else goto st36; goto st0; st36: if ( ++p == pe ) goto _test_eof36; case 36: switch( (*p) ) { case 32: goto tr2; case 36: goto st37; case 95: goto st37; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st37; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st37; } else goto st37; goto st0; st37: if ( ++p == pe ) goto _test_eof37; case 37: switch( (*p) ) { case 32: goto tr2; case 36: goto st38; case 95: goto st38; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st38; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st38; } else goto st38; goto st0; st38: if ( ++p == pe ) goto _test_eof38; case 38: switch( (*p) ) { case 32: goto tr2; case 36: goto st39; case 95: goto st39; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st39; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st39; } else goto st39; goto st0; st39: if ( ++p == pe ) goto _test_eof39; case 39: switch( (*p) ) { case 32: goto tr2; case 36: goto st40; case 95: goto st40; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st40; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st40; } else goto st40; goto st0; st40: if ( ++p == pe ) goto _test_eof40; case 40: switch( (*p) ) { case 32: goto tr2; case 36: goto st41; case 95: goto st41; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st41; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st41; } else goto st41; goto st0; st41: if ( ++p == pe ) goto _test_eof41; case 41: switch( (*p) ) { case 32: goto tr2; case 36: goto st42; case 95: goto st42; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st42; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st42; } else goto st42; goto st0; st42: if ( ++p == pe ) goto _test_eof42; case 42: switch( (*p) ) { case 32: goto tr2; case 36: goto st43; case 95: goto st43; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st43; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st43; } else goto st43; goto st0; st43: if ( ++p == pe ) goto _test_eof43; case 43: switch( (*p) ) { case 32: goto tr2; case 36: goto st44; case 95: goto st44; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st44; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st44; } else goto st44; goto st0; st44: if ( ++p == pe ) goto _test_eof44; case 44: switch( (*p) ) { case 32: goto tr2; case 36: goto st45; case 95: goto st45; } if ( (*p) < 48 ) { if ( 45 <= (*p) && (*p) <= 46 ) goto st45; } else if ( (*p) > 57 ) { if ( 65 <= (*p) && (*p) <= 90 ) goto st45; } else goto st45; goto st0; st45: if ( ++p == pe ) goto _test_eof45; case 45: if ( (*p) == 32 ) goto tr2; goto st0; } _test_eof2: cs = 2; goto _test_eof; _test_eof3: cs = 3; goto _test_eof; _test_eof4: cs = 4; goto _test_eof; _test_eof5: cs = 5; goto _test_eof; _test_eof6: cs = 6; goto _test_eof; _test_eof7: cs = 7; goto _test_eof; _test_eof8: cs = 8; goto _test_eof; _test_eof9: cs = 9; goto _test_eof; _test_eof10: cs = 10; goto _test_eof; _test_eof11: cs = 11; goto _test_eof; _test_eof12: cs = 12; goto _test_eof; _test_eof13: cs = 13; goto _test_eof; _test_eof14: cs = 14; goto _test_eof; _test_eof15: cs = 15; goto _test_eof; _test_eof16: cs = 16; goto _test_eof; _test_eof46: cs = 46; goto _test_eof; _test_eof17: cs = 17; goto _test_eof; _test_eof18: cs = 18; goto _test_eof; _test_eof19: cs = 19; goto _test_eof; _test_eof20: cs = 20; goto _test_eof; _test_eof21: cs = 21; goto _test_eof; _test_eof22: cs = 22; goto _test_eof; _test_eof23: cs = 23; goto _test_eof; _test_eof24: cs = 24; goto _test_eof; _test_eof25: cs = 25; goto _test_eof; _test_eof26: cs = 26; goto _test_eof; _test_eof27: cs = 27; goto _test_eof; _test_eof28: cs = 28; goto _test_eof; _test_eof29: cs = 29; goto _test_eof; _test_eof30: cs = 30; goto _test_eof; _test_eof31: cs = 31; goto _test_eof; _test_eof32: cs = 32; goto _test_eof; _test_eof33: cs = 33; goto _test_eof; _test_eof34: cs = 34; goto _test_eof; _test_eof35: cs = 35; goto _test_eof; _test_eof36: cs = 36; goto _test_eof; _test_eof37: cs = 37; goto _test_eof; _test_eof38: cs = 38; goto _test_eof; _test_eof39: cs = 39; goto _test_eof; _test_eof40: cs = 40; goto _test_eof; _test_eof41: cs = 41; goto _test_eof; _test_eof42: cs = 42; goto _test_eof; _test_eof43: cs = 43; goto _test_eof; _test_eof44: cs = 44; goto _test_eof; _test_eof45: cs = 45; goto _test_eof; _test_eof: {} _out: {} } #line 117 "ext/puma_http11/http11_parser.rl" if (!puma_parser_has_error(parser)) parser->cs = cs; parser->nread += p - (buffer + off); assert(p <= pe && "buffer overflow after parsing execute"); assert(parser->nread <= len && "nread longer than length"); assert(parser->body_start <= len && "body starts after buffer end"); assert(parser->mark < len && "mark is after buffer end"); assert(parser->field_len <= len && "field has length longer than whole buffer"); assert(parser->field_start < len && "field starts after buffer end"); return(parser->nread); }
5609299839918997212046312730863248259
http11_parser.c
310028467856200472681435734448209650249
CWE-444
CVE-2021-41136
Puma is a HTTP 1.1 server for Ruby/Rack applications. Prior to versions 5.5.1 and 4.3.9, using `puma` with a proxy which forwards HTTP header values which contain the LF character could allow HTTP request smugggling. A client could smuggle a request through a proxy, causing the proxy to send a response back to another unknown client. The only proxy which has this behavior, as far as the Puma team is aware of, is Apache Traffic Server. If the proxy uses persistent connections and the client adds another request in via HTTP pipelining, the proxy may mistake it as the first request's body. Puma, however, would see it as two requests, and when processing the second request, send back a response that the proxy does not expect. If the proxy has reused the persistent connection to Puma to send another request for a different client, the second response from the first client will be sent to the second client. This vulnerability was patched in Puma 5.5.1 and 4.3.9. As a workaround, do not use Apache Traffic Server with `puma`.
https://nvd.nist.gov/vuln/detail/CVE-2021-41136
199,833
chafa
e4b777c7b7c144cd16a0ea96108267b1004fe6c9
https://github.com/hpjansson/chafa
https://github.com/hpjansson/chafa/commit/e4b777c7b7c144cd16a0ea96108267b1004fe6c9
libnsgif: Fix null pointer deref on frameless GIF input A crafted GIF file with no frame data could cause a null pointer dereference leading to denial of service (crash). Reported by @JieyongMa via huntr.dev.
1
gif_internal_decode_frame(gif_animation *gif, unsigned int frame, bool clear_image) { unsigned int index = 0; const unsigned char *gif_data, *gif_end; ssize_t gif_bytes; unsigned int width, height, offset_x, offset_y; unsigned int flags, colour_table_size, interlace; unsigned int *colour_table; unsigned int *frame_data = 0; // Set to 0 for no warnings unsigned int *frame_scanline; ssize_t save_buffer_position; unsigned int return_value = 0; unsigned int x, y, decode_y, burst_bytes; register unsigned char colour; /* Ensure this frame is supposed to be decoded */ if (gif->frames[frame].display == false) { return GIF_OK; } /* Ensure the frame is in range to decode */ if (frame > gif->frame_count_partial) { return GIF_INSUFFICIENT_DATA; } /* done if frame is already decoded */ if ((!clear_image) && ((int)frame == gif->decoded_frame)) { return GIF_OK; } /* Get the start of our frame data and the end of the GIF data */ gif_data = gif->gif_data + gif->frames[frame].frame_pointer; gif_end = gif->gif_data + gif->buffer_size; gif_bytes = (gif_end - gif_data); /* * Ensure there is a minimal amount of data to proceed. The shortest * block of data is a 10-byte image descriptor + 1-byte gif trailer */ if (gif_bytes < 12) { return GIF_INSUFFICIENT_FRAME_DATA; } /* Save the buffer position */ save_buffer_position = gif->buffer_position; gif->buffer_position = gif_data - gif->gif_data; /* Skip any extensions because they have allready been processed */ if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) { goto gif_decode_frame_exit; } gif_data = (gif->gif_data + gif->buffer_position); gif_bytes = (gif_end - gif_data); /* Ensure we have enough data for the 10-byte image descriptor + 1-byte * gif trailer */ if (gif_bytes < 12) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* 10-byte Image Descriptor is: * * +0 CHAR Image Separator (0x2c) * +1 SHORT Image Left Position * +3 SHORT Image Top Position * +5 SHORT Width * +7 SHORT Height * +9 CHAR __Packed Fields__ * 1BIT Local Colour Table Flag * 1BIT Interlace Flag * 1BIT Sort Flag * 2BITS Reserved * 3BITS Size of Local Colour Table */ if (gif_data[0] != GIF_IMAGE_SEPARATOR) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } offset_x = gif_data[1] | (gif_data[2] << 8); offset_y = gif_data[3] | (gif_data[4] << 8); width = gif_data[5] | (gif_data[6] << 8); height = gif_data[7] | (gif_data[8] << 8); /* Boundary checking - shouldn't ever happen except unless the data has * been modified since initialisation. */ if ((offset_x + width > gif->width) || (offset_y + height > gif->height)) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } /* Decode the flags */ flags = gif_data[9]; colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); interlace = flags & GIF_INTERLACE_MASK; /* Advance data pointer to next block either colour table or image * data. */ gif_data += 10; gif_bytes = (gif_end - gif_data); /* Set up the colour table */ if (flags & GIF_COLOUR_TABLE_MASK) { if (gif_bytes < (int)(3 * colour_table_size)) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } colour_table = gif->local_colour_table; if (!clear_image) { for (index = 0; index < colour_table_size; index++) { /* Gif colour map contents are r,g,b. * * We want to pack them bytewise into the * colour table, such that the red component * is in byte 0 and the alpha component is in * byte 3. */ unsigned char *entry = (unsigned char *) &colour_table[index]; entry[0] = gif_data[0]; /* r */ entry[1] = gif_data[1]; /* g */ entry[2] = gif_data[2]; /* b */ entry[3] = 0xff; /* a */ gif_data += 3; } } else { gif_data += 3 * colour_table_size; } gif_bytes = (gif_end - gif_data); } else { colour_table = gif->global_colour_table; } /* Ensure sufficient data remains */ if (gif_bytes < 1) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* check for an end marker */ if (gif_data[0] == GIF_TRAILER) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* Get the frame data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) { return GIF_INSUFFICIENT_MEMORY; } /* If we are clearing the image we just clear, if not decode */ if (!clear_image) { lzw_result res; const uint8_t *stack_base; const uint8_t *stack_pos; /* Ensure we have enough data for a 1-byte LZW code size + * 1-byte gif trailer */ if (gif_bytes < 2) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* If we only have a 1-byte LZW code size + 1-byte gif trailer, * we're finished */ if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* If the previous frame's disposal method requires we restore * the background colour or this is the first frame, clear * the frame data */ if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) { memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); gif->decoded_frame = frame; /* The line below would fill the image with its * background color, but because GIFs support * transparency we likely wouldn't want to do that. */ /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */ } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) { return_value = gif_internal_decode_frame(gif, (frame - 1), true); if (return_value != GIF_OK) { goto gif_decode_frame_exit; } } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) { /* * If the previous frame's disposal method requires we * restore the previous image, find the last image set * to "do not dispose" and get that frame data */ int last_undisposed_frame = frame - 2; while ((last_undisposed_frame >= 0) && (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) { last_undisposed_frame--; } /* If we don't find one, clear the frame data */ if (last_undisposed_frame == -1) { /* see notes above on transparency * vs. background color */ memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); } else { return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false); if (return_value != GIF_OK) { goto gif_decode_frame_exit; } /* Get this frame's data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) { return GIF_INSUFFICIENT_MEMORY; } } } gif->decoded_frame = frame; gif->buffer_position = (gif_data - gif->gif_data) + 1; /* Initialise the LZW decoding */ res = lzw_decode_init(gif->lzw_ctx, gif->gif_data, gif->buffer_size, gif->buffer_position, gif_data[0], &stack_base, &stack_pos); if (res != LZW_OK) { return gif_error_from_lzw(res); } /* Decompress the data */ for (y = 0; y < height; y++) { if (interlace) { decode_y = gif_interlaced_line(height, y) + offset_y; } else { decode_y = y + offset_y; } frame_scanline = frame_data + offset_x + (decode_y * gif->width); /* Rather than decoding pixel by pixel, we try to burst * out streams of data to remove the need for end-of * data checks every pixel. */ x = width; while (x > 0) { burst_bytes = (stack_pos - stack_base); if (burst_bytes > 0) { if (burst_bytes > x) { burst_bytes = x; } x -= burst_bytes; while (burst_bytes-- > 0) { colour = *--stack_pos; if (((gif->frames[frame].transparency) && (colour != gif->frames[frame].transparency_index)) || (!gif->frames[frame].transparency)) { *frame_scanline = colour_table[colour]; } frame_scanline++; } } else { res = lzw_decode(gif->lzw_ctx, &stack_pos); if (res != LZW_OK) { /* Unexpected end of frame, try to recover */ if (res == LZW_OK_EOD) { return_value = GIF_OK; } else { return_value = gif_error_from_lzw(res); } goto gif_decode_frame_exit; } } } } } else { /* Clear our frame */ if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) { for (y = 0; y < height; y++) { frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width); if (gif->frames[frame].transparency) { memset(frame_scanline, GIF_TRANSPARENT_COLOUR, width * 4); } else { memset(frame_scanline, colour_table[gif->background_index], width * 4); } } } } gif_decode_frame_exit: /* Check if we should test for optimisation */ if (gif->frames[frame].virgin) { if (gif->bitmap_callbacks.bitmap_test_opaque) { gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image); } else { gif->frames[frame].opaque = false; } gif->frames[frame].virgin = false; } if (gif->bitmap_callbacks.bitmap_set_opaque) { gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque); } if (gif->bitmap_callbacks.bitmap_modified) { gif->bitmap_callbacks.bitmap_modified(gif->frame_image); } /* Restore the buffer position */ gif->buffer_position = save_buffer_position; return return_value; }
44351140165833891890072470559672892000
libnsgif.c
198094748346353506643883012228634204471
CWE-476
CVE-2022-1507
chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file. in GitHub repository hpjansson/chafa prior to 1.10.2. chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file.
https://nvd.nist.gov/vuln/detail/CVE-2022-1507
293,496
chafa
e4b777c7b7c144cd16a0ea96108267b1004fe6c9
https://github.com/hpjansson/chafa
https://github.com/hpjansson/chafa/commit/e4b777c7b7c144cd16a0ea96108267b1004fe6c9
libnsgif: Fix null pointer deref on frameless GIF input A crafted GIF file with no frame data could cause a null pointer dereference leading to denial of service (crash). Reported by @JieyongMa via huntr.dev.
0
gif_internal_decode_frame(gif_animation *gif, unsigned int frame, bool clear_image) { unsigned int index = 0; const unsigned char *gif_data, *gif_end; ssize_t gif_bytes; unsigned int width, height, offset_x, offset_y; unsigned int flags, colour_table_size, interlace; unsigned int *colour_table; unsigned int *frame_data = 0; // Set to 0 for no warnings unsigned int *frame_scanline; ssize_t save_buffer_position; unsigned int return_value = 0; unsigned int x, y, decode_y, burst_bytes; register unsigned char colour; /* If the GIF has no frame data, frame holders will not be allocated in * gif_initialise() */ if (gif->frames == NULL) { return GIF_INSUFFICIENT_DATA; } /* Ensure this frame is supposed to be decoded */ if (gif->frames[frame].display == false) { return GIF_OK; } /* Ensure the frame is in range to decode */ if (frame > gif->frame_count_partial) { return GIF_INSUFFICIENT_DATA; } /* done if frame is already decoded */ if ((!clear_image) && ((int)frame == gif->decoded_frame)) { return GIF_OK; } /* Get the start of our frame data and the end of the GIF data */ gif_data = gif->gif_data + gif->frames[frame].frame_pointer; gif_end = gif->gif_data + gif->buffer_size; gif_bytes = (gif_end - gif_data); /* * Ensure there is a minimal amount of data to proceed. The shortest * block of data is a 10-byte image descriptor + 1-byte gif trailer */ if (gif_bytes < 12) { return GIF_INSUFFICIENT_FRAME_DATA; } /* Save the buffer position */ save_buffer_position = gif->buffer_position; gif->buffer_position = gif_data - gif->gif_data; /* Skip any extensions because they have allready been processed */ if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) { goto gif_decode_frame_exit; } gif_data = (gif->gif_data + gif->buffer_position); gif_bytes = (gif_end - gif_data); /* Ensure we have enough data for the 10-byte image descriptor + 1-byte * gif trailer */ if (gif_bytes < 12) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* 10-byte Image Descriptor is: * * +0 CHAR Image Separator (0x2c) * +1 SHORT Image Left Position * +3 SHORT Image Top Position * +5 SHORT Width * +7 SHORT Height * +9 CHAR __Packed Fields__ * 1BIT Local Colour Table Flag * 1BIT Interlace Flag * 1BIT Sort Flag * 2BITS Reserved * 3BITS Size of Local Colour Table */ if (gif_data[0] != GIF_IMAGE_SEPARATOR) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } offset_x = gif_data[1] | (gif_data[2] << 8); offset_y = gif_data[3] | (gif_data[4] << 8); width = gif_data[5] | (gif_data[6] << 8); height = gif_data[7] | (gif_data[8] << 8); /* Boundary checking - shouldn't ever happen except unless the data has * been modified since initialisation. */ if ((offset_x + width > gif->width) || (offset_y + height > gif->height)) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } /* Decode the flags */ flags = gif_data[9]; colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); interlace = flags & GIF_INTERLACE_MASK; /* Advance data pointer to next block either colour table or image * data. */ gif_data += 10; gif_bytes = (gif_end - gif_data); /* Set up the colour table */ if (flags & GIF_COLOUR_TABLE_MASK) { if (gif_bytes < (int)(3 * colour_table_size)) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } colour_table = gif->local_colour_table; if (!clear_image) { for (index = 0; index < colour_table_size; index++) { /* Gif colour map contents are r,g,b. * * We want to pack them bytewise into the * colour table, such that the red component * is in byte 0 and the alpha component is in * byte 3. */ unsigned char *entry = (unsigned char *) &colour_table[index]; entry[0] = gif_data[0]; /* r */ entry[1] = gif_data[1]; /* g */ entry[2] = gif_data[2]; /* b */ entry[3] = 0xff; /* a */ gif_data += 3; } } else { gif_data += 3 * colour_table_size; } gif_bytes = (gif_end - gif_data); } else { colour_table = gif->global_colour_table; } /* Ensure sufficient data remains */ if (gif_bytes < 1) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* check for an end marker */ if (gif_data[0] == GIF_TRAILER) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* Get the frame data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) { return GIF_INSUFFICIENT_MEMORY; } /* If we are clearing the image we just clear, if not decode */ if (!clear_image) { lzw_result res; const uint8_t *stack_base; const uint8_t *stack_pos; /* Ensure we have enough data for a 1-byte LZW code size + * 1-byte gif trailer */ if (gif_bytes < 2) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* If we only have a 1-byte LZW code size + 1-byte gif trailer, * we're finished */ if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* If the previous frame's disposal method requires we restore * the background colour or this is the first frame, clear * the frame data */ if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) { memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); gif->decoded_frame = frame; /* The line below would fill the image with its * background color, but because GIFs support * transparency we likely wouldn't want to do that. */ /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */ } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) { return_value = gif_internal_decode_frame(gif, (frame - 1), true); if (return_value != GIF_OK) { goto gif_decode_frame_exit; } } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) { /* * If the previous frame's disposal method requires we * restore the previous image, find the last image set * to "do not dispose" and get that frame data */ int last_undisposed_frame = frame - 2; while ((last_undisposed_frame >= 0) && (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) { last_undisposed_frame--; } /* If we don't find one, clear the frame data */ if (last_undisposed_frame == -1) { /* see notes above on transparency * vs. background color */ memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); } else { return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false); if (return_value != GIF_OK) { goto gif_decode_frame_exit; } /* Get this frame's data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) { return GIF_INSUFFICIENT_MEMORY; } } } gif->decoded_frame = frame; gif->buffer_position = (gif_data - gif->gif_data) + 1; /* Initialise the LZW decoding */ res = lzw_decode_init(gif->lzw_ctx, gif->gif_data, gif->buffer_size, gif->buffer_position, gif_data[0], &stack_base, &stack_pos); if (res != LZW_OK) { return gif_error_from_lzw(res); } /* Decompress the data */ for (y = 0; y < height; y++) { if (interlace) { decode_y = gif_interlaced_line(height, y) + offset_y; } else { decode_y = y + offset_y; } frame_scanline = frame_data + offset_x + (decode_y * gif->width); /* Rather than decoding pixel by pixel, we try to burst * out streams of data to remove the need for end-of * data checks every pixel. */ x = width; while (x > 0) { burst_bytes = (stack_pos - stack_base); if (burst_bytes > 0) { if (burst_bytes > x) { burst_bytes = x; } x -= burst_bytes; while (burst_bytes-- > 0) { colour = *--stack_pos; if (((gif->frames[frame].transparency) && (colour != gif->frames[frame].transparency_index)) || (!gif->frames[frame].transparency)) { *frame_scanline = colour_table[colour]; } frame_scanline++; } } else { res = lzw_decode(gif->lzw_ctx, &stack_pos); if (res != LZW_OK) { /* Unexpected end of frame, try to recover */ if (res == LZW_OK_EOD) { return_value = GIF_OK; } else { return_value = gif_error_from_lzw(res); } goto gif_decode_frame_exit; } } } } } else { /* Clear our frame */ if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) { for (y = 0; y < height; y++) { frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width); if (gif->frames[frame].transparency) { memset(frame_scanline, GIF_TRANSPARENT_COLOUR, width * 4); } else { memset(frame_scanline, colour_table[gif->background_index], width * 4); } } } } gif_decode_frame_exit: /* Check if we should test for optimisation */ if (gif->frames[frame].virgin) { if (gif->bitmap_callbacks.bitmap_test_opaque) { gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image); } else { gif->frames[frame].opaque = false; } gif->frames[frame].virgin = false; } if (gif->bitmap_callbacks.bitmap_set_opaque) { gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque); } if (gif->bitmap_callbacks.bitmap_modified) { gif->bitmap_callbacks.bitmap_modified(gif->frame_image); } /* Restore the buffer position */ gif->buffer_position = save_buffer_position; return return_value; }
289353344148943948893339832130354113499
libnsgif.c
172226271399464040769871629514764443605
CWE-476
CVE-2022-1507
chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file. in GitHub repository hpjansson/chafa prior to 1.10.2. chafa: NULL Pointer Dereference in function gif_internal_decode_frame at libnsgif.c:599 allows attackers to cause a denial of service (crash) via a crafted input file.
https://nvd.nist.gov/vuln/detail/CVE-2022-1507
199,836
pjproject
077b465c33f0aec05a49cd2ca456f9a1b112e896
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/077b465c33f0aec05a49cd2ca456f9a1b112e896
Merge pull request from GHSA-7fw8-54cv-r7pm
1
PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner ) { int chr = *scanner->curptr; if (!chr) { pj_scan_syntax_err(scanner); return 0; } ++scanner->curptr; if (PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) { pj_scan_skip_whitespace(scanner); } return chr; }
113292852369107945981597354542276439074
None
CWE-125
CVE-2022-21723
PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions 2.11.1 and prior, parsing an incoming SIP message that contains a malformed multipart can potentially cause out-of-bound read access. This issue affects all PJSIP users that accept SIP multipart. The patch is available as commit in the `master` branch. There are no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2022-21723
293,522
pjproject
077b465c33f0aec05a49cd2ca456f9a1b112e896
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/077b465c33f0aec05a49cd2ca456f9a1b112e896
Merge pull request from GHSA-7fw8-54cv-r7pm
0
PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner ) { register char *s = scanner->curptr; int chr; if (s >= scanner->end || !*s) { pj_scan_syntax_err(scanner); return 0; } chr = *s; ++s; scanner->curptr = s; if (PJ_SCAN_CHECK_EOF(s) && PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) { pj_scan_skip_whitespace(scanner); } return chr; }
311538047427415366173114134774711443657
None
CWE-125
CVE-2022-21723
PJSIP is a free and open source multimedia communication library written in C language implementing standard based protocols such as SIP, SDP, RTP, STUN, TURN, and ICE. In versions 2.11.1 and prior, parsing an incoming SIP message that contains a malformed multipart can potentially cause out-of-bound read access. This issue affects all PJSIP users that accept SIP multipart. The patch is available as commit in the `master` branch. There are no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2022-21723
199,841
radare2
feaa4e7f7399c51ee6f52deb84dc3f795b4035d6
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/feaa4e7f7399c51ee6f52deb84dc3f795b4035d6
Fix null deref in xnu.kernelcache ##crash * Reported by @xshad3 via huntr.dev
1
static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) { RBuffer *fbuf = r_buf_ref (buf); struct MACH0_(opts_t) opts; MACH0_(opts_set_default) (&opts, bf); struct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts); if (!main_mach0) { return false; } RRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0); RKernelCacheObj *obj = NULL; RPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0); if (!prelink_range) { goto beach; } obj = R_NEW0 (RKernelCacheObj); if (!obj) { R_FREE (prelink_range); goto beach; } RCFValueDict *prelink_info = NULL; if (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) { prelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset, prelink_range->range.size, R_CF_OPTION_SKIP_NSDATA); if (!prelink_info) { R_FREE (prelink_range); R_FREE (obj); goto beach; } } if (!pending_bin_files) { pending_bin_files = r_list_new (); if (!pending_bin_files) { R_FREE (prelink_range); R_FREE (obj); R_FREE (prelink_info); goto beach; } } obj->mach0 = main_mach0; obj->rebase_info = rebase_info; obj->prelink_info = prelink_info; obj->cache_buf = fbuf; obj->pa2va_exec = prelink_range->pa2va_exec; obj->pa2va_data = prelink_range->pa2va_data; R_FREE (prelink_range); *bin_obj = obj; r_list_push (pending_bin_files, bf); if (rebase_info || main_mach0->chained_starts) { RIO *io = bf->rbin->iob.io; swizzle_io_read (obj, io); } return true; beach: r_buf_free (fbuf); obj->cache_buf = NULL; MACH0_(mach0_free) (main_mach0); return false; }
233224811640274540394040555084759924603
bin_xnu_kernelcache.c
125322815790464606650182134413161579767
CWE-476
CVE-2022-0419
NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.0.
https://nvd.nist.gov/vuln/detail/CVE-2022-0419
293,750
radare2
feaa4e7f7399c51ee6f52deb84dc3f795b4035d6
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/feaa4e7f7399c51ee6f52deb84dc3f795b4035d6
Fix null deref in xnu.kernelcache ##crash * Reported by @xshad3 via huntr.dev
0
static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) { RBuffer *fbuf = r_buf_ref (buf); struct MACH0_(opts_t) opts; MACH0_(opts_set_default) (&opts, bf); struct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts); if (!main_mach0) { return false; } RRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0); RKernelCacheObj *obj = NULL; RPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0); if (!prelink_range) { goto beach; } obj = R_NEW0 (RKernelCacheObj); if (!obj) { R_FREE (prelink_range); goto beach; } RCFValueDict *prelink_info = NULL; if (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) { prelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset, prelink_range->range.size, R_CF_OPTION_SKIP_NSDATA); if (!prelink_info) { R_FREE (prelink_range); R_FREE (obj); goto beach; } } if (!pending_bin_files) { pending_bin_files = r_list_new (); if (!pending_bin_files) { R_FREE (prelink_range); R_FREE (obj); R_FREE (prelink_info); goto beach; } } obj->mach0 = main_mach0; obj->rebase_info = rebase_info; obj->prelink_info = prelink_info; obj->cache_buf = fbuf; obj->pa2va_exec = prelink_range->pa2va_exec; obj->pa2va_data = prelink_range->pa2va_data; R_FREE (prelink_range); *bin_obj = obj; r_list_push (pending_bin_files, bf); if (rebase_info || main_mach0->chained_starts) { RIO *io = bf->rbin->iob.io; swizzle_io_read (obj, io); } return true; beach: r_buf_free (fbuf); if (obj) { obj->cache_buf = NULL; } MACH0_(mach0_free) (main_mach0); return false; }
89284562812027856469144613822814889366
bin_xnu_kernelcache.c
321377781677570580244771377920228203962
CWE-476
CVE-2022-0419
NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.0.
https://nvd.nist.gov/vuln/detail/CVE-2022-0419
199,851
vim
6e28703a8e41f775f64e442c5d11ce1ff599aa3f
https://github.com/vim/vim
https://github.com/vim/vim/commit/6e28703a8e41f775f64e442c5d11ce1ff599aa3f
patch 8.2.4359: crash when repeatedly using :retab Problem: crash when repeatedly using :retab. Solution: Bail out when the line is getting too long.
1
ex_retab(exarg_T *eap) { linenr_T lnum; int got_tab = FALSE; long num_spaces = 0; long num_tabs; long len; long col; long vcol; long start_col = 0; // For start of white-space string long start_vcol = 0; // For start of white-space string long old_len; char_u *ptr; char_u *new_line = (char_u *)1; // init to non-NULL int did_undo; // called u_save for current line #ifdef FEAT_VARTABS int *new_vts_array = NULL; char_u *new_ts_str; // string value of tab argument #else int temp; int new_ts; #endif int save_list; linenr_T first_line = 0; // first changed line linenr_T last_line = 0; // last changed line save_list = curwin->w_p_list; curwin->w_p_list = 0; // don't want list mode here #ifdef FEAT_VARTABS new_ts_str = eap->arg; if (tabstop_set(eap->arg, &new_vts_array) == FAIL) return; while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',') ++(eap->arg); // This ensures that either new_vts_array and new_ts_str are freshly // allocated, or new_vts_array points to an existing array and new_ts_str // is null. if (new_vts_array == NULL) { new_vts_array = curbuf->b_p_vts_array; new_ts_str = NULL; } else new_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str); #else ptr = eap->arg; new_ts = getdigits(&ptr); if (new_ts < 0 && *eap->arg == '-') { emsg(_(e_argument_must_be_positive)); return; } if (new_ts < 0 || new_ts > TABSTOP_MAX) { semsg(_(e_invalid_argument_str), eap->arg); return; } if (new_ts == 0) new_ts = curbuf->b_p_ts; #endif for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum) { ptr = ml_get(lnum); col = 0; vcol = 0; did_undo = FALSE; for (;;) { if (VIM_ISWHITE(ptr[col])) { if (!got_tab && num_spaces == 0) { // First consecutive white-space start_vcol = vcol; start_col = col; } if (ptr[col] == ' ') num_spaces++; else got_tab = TRUE; } else { if (got_tab || (eap->forceit && num_spaces > 1)) { // Retabulate this string of white-space // len is virtual length of white string len = num_spaces = vcol - start_vcol; num_tabs = 0; if (!curbuf->b_p_et) { #ifdef FEAT_VARTABS int t, s; tabstop_fromto(start_vcol, vcol, curbuf->b_p_ts, new_vts_array, &t, &s); num_tabs = t; num_spaces = s; #else temp = new_ts - (start_vcol % new_ts); if (num_spaces >= temp) { num_spaces -= temp; num_tabs++; } num_tabs += num_spaces / new_ts; num_spaces -= (num_spaces / new_ts) * new_ts; #endif } if (curbuf->b_p_et || got_tab || (num_spaces + num_tabs < len)) { if (did_undo == FALSE) { did_undo = TRUE; if (u_save((linenr_T)(lnum - 1), (linenr_T)(lnum + 1)) == FAIL) { new_line = NULL; // flag out-of-memory break; } } // len is actual number of white characters used len = num_spaces + num_tabs; old_len = (long)STRLEN(ptr); new_line = alloc(old_len - col + start_col + len + 1); if (new_line == NULL) break; if (start_col > 0) mch_memmove(new_line, ptr, (size_t)start_col); mch_memmove(new_line + start_col + len, ptr + col, (size_t)(old_len - col + 1)); ptr = new_line + start_col; for (col = 0; col < len; col++) ptr[col] = (col < num_tabs) ? '\t' : ' '; if (ml_replace(lnum, new_line, FALSE) == OK) // "new_line" may have been copied new_line = curbuf->b_ml.ml_line_ptr; if (first_line == 0) first_line = lnum; last_line = lnum; ptr = new_line; col = start_col + len; } } got_tab = FALSE; num_spaces = 0; } if (ptr[col] == NUL) break; vcol += chartabsize(ptr + col, (colnr_T)vcol); if (has_mbyte) col += (*mb_ptr2len)(ptr + col); else ++col; } if (new_line == NULL) // out of memory break; line_breakcheck(); } if (got_int) emsg(_(e_interrupted)); #ifdef FEAT_VARTABS // If a single value was given then it can be considered equal to // either the value of 'tabstop' or the value of 'vartabstop'. if (tabstop_count(curbuf->b_p_vts_array) == 0 && tabstop_count(new_vts_array) == 1 && curbuf->b_p_ts == tabstop_first(new_vts_array)) ; // not changed else if (tabstop_count(curbuf->b_p_vts_array) > 0 && tabstop_eq(curbuf->b_p_vts_array, new_vts_array)) ; // not changed else redraw_curbuf_later(NOT_VALID); #else if (curbuf->b_p_ts != new_ts) redraw_curbuf_later(NOT_VALID); #endif if (first_line != 0) changed_lines(first_line, 0, last_line + 1, 0L); curwin->w_p_list = save_list; // restore 'list' #ifdef FEAT_VARTABS if (new_ts_str != NULL) // set the new tabstop { // If 'vartabstop' is in use or if the value given to retab has more // than one tabstop then update 'vartabstop'. int *old_vts_ary = curbuf->b_p_vts_array; if (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1) { set_string_option_direct((char_u *)"vts", -1, new_ts_str, OPT_FREE|OPT_LOCAL, 0); curbuf->b_p_vts_array = new_vts_array; vim_free(old_vts_ary); } else { // 'vartabstop' wasn't in use and a single value was given to // retab then update 'tabstop'. curbuf->b_p_ts = tabstop_first(new_vts_array); vim_free(new_vts_array); } vim_free(new_ts_str); } #else curbuf->b_p_ts = new_ts; #endif coladvance(curwin->w_curswant); u_clearline(); }
55704685563391152697895881333081984969
indent.c
264017227782989622614587099376842569247
CWE-787
CVE-2022-0572
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0572
293,939
vim
6e28703a8e41f775f64e442c5d11ce1ff599aa3f
https://github.com/vim/vim
https://github.com/vim/vim/commit/6e28703a8e41f775f64e442c5d11ce1ff599aa3f
patch 8.2.4359: crash when repeatedly using :retab Problem: crash when repeatedly using :retab. Solution: Bail out when the line is getting too long.
0
ex_retab(exarg_T *eap) { linenr_T lnum; int got_tab = FALSE; long num_spaces = 0; long num_tabs; long len; long col; long vcol; long start_col = 0; // For start of white-space string long start_vcol = 0; // For start of white-space string long old_len; char_u *ptr; char_u *new_line = (char_u *)1; // init to non-NULL int did_undo; // called u_save for current line #ifdef FEAT_VARTABS int *new_vts_array = NULL; char_u *new_ts_str; // string value of tab argument #else int temp; int new_ts; #endif int save_list; linenr_T first_line = 0; // first changed line linenr_T last_line = 0; // last changed line save_list = curwin->w_p_list; curwin->w_p_list = 0; // don't want list mode here #ifdef FEAT_VARTABS new_ts_str = eap->arg; if (tabstop_set(eap->arg, &new_vts_array) == FAIL) return; while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',') ++(eap->arg); // This ensures that either new_vts_array and new_ts_str are freshly // allocated, or new_vts_array points to an existing array and new_ts_str // is null. if (new_vts_array == NULL) { new_vts_array = curbuf->b_p_vts_array; new_ts_str = NULL; } else new_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str); #else ptr = eap->arg; new_ts = getdigits(&ptr); if (new_ts < 0 && *eap->arg == '-') { emsg(_(e_argument_must_be_positive)); return; } if (new_ts < 0 || new_ts > TABSTOP_MAX) { semsg(_(e_invalid_argument_str), eap->arg); return; } if (new_ts == 0) new_ts = curbuf->b_p_ts; #endif for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum) { ptr = ml_get(lnum); col = 0; vcol = 0; did_undo = FALSE; for (;;) { if (VIM_ISWHITE(ptr[col])) { if (!got_tab && num_spaces == 0) { // First consecutive white-space start_vcol = vcol; start_col = col; } if (ptr[col] == ' ') num_spaces++; else got_tab = TRUE; } else { if (got_tab || (eap->forceit && num_spaces > 1)) { // Retabulate this string of white-space // len is virtual length of white string len = num_spaces = vcol - start_vcol; num_tabs = 0; if (!curbuf->b_p_et) { #ifdef FEAT_VARTABS int t, s; tabstop_fromto(start_vcol, vcol, curbuf->b_p_ts, new_vts_array, &t, &s); num_tabs = t; num_spaces = s; #else temp = new_ts - (start_vcol % new_ts); if (num_spaces >= temp) { num_spaces -= temp; num_tabs++; } num_tabs += num_spaces / new_ts; num_spaces -= (num_spaces / new_ts) * new_ts; #endif } if (curbuf->b_p_et || got_tab || (num_spaces + num_tabs < len)) { if (did_undo == FALSE) { did_undo = TRUE; if (u_save((linenr_T)(lnum - 1), (linenr_T)(lnum + 1)) == FAIL) { new_line = NULL; // flag out-of-memory break; } } // len is actual number of white characters used len = num_spaces + num_tabs; old_len = (long)STRLEN(ptr); new_line = alloc(old_len - col + start_col + len + 1); if (new_line == NULL) break; if (start_col > 0) mch_memmove(new_line, ptr, (size_t)start_col); mch_memmove(new_line + start_col + len, ptr + col, (size_t)(old_len - col + 1)); ptr = new_line + start_col; for (col = 0; col < len; col++) ptr[col] = (col < num_tabs) ? '\t' : ' '; if (ml_replace(lnum, new_line, FALSE) == OK) // "new_line" may have been copied new_line = curbuf->b_ml.ml_line_ptr; if (first_line == 0) first_line = lnum; last_line = lnum; ptr = new_line; col = start_col + len; } } got_tab = FALSE; num_spaces = 0; } if (ptr[col] == NUL) break; vcol += chartabsize(ptr + col, (colnr_T)vcol); if (vcol >= MAXCOL) { emsg(_(e_resulting_text_too_long)); break; } if (has_mbyte) col += (*mb_ptr2len)(ptr + col); else ++col; } if (new_line == NULL) // out of memory break; line_breakcheck(); } if (got_int) emsg(_(e_interrupted)); #ifdef FEAT_VARTABS // If a single value was given then it can be considered equal to // either the value of 'tabstop' or the value of 'vartabstop'. if (tabstop_count(curbuf->b_p_vts_array) == 0 && tabstop_count(new_vts_array) == 1 && curbuf->b_p_ts == tabstop_first(new_vts_array)) ; // not changed else if (tabstop_count(curbuf->b_p_vts_array) > 0 && tabstop_eq(curbuf->b_p_vts_array, new_vts_array)) ; // not changed else redraw_curbuf_later(NOT_VALID); #else if (curbuf->b_p_ts != new_ts) redraw_curbuf_later(NOT_VALID); #endif if (first_line != 0) changed_lines(first_line, 0, last_line + 1, 0L); curwin->w_p_list = save_list; // restore 'list' #ifdef FEAT_VARTABS if (new_ts_str != NULL) // set the new tabstop { // If 'vartabstop' is in use or if the value given to retab has more // than one tabstop then update 'vartabstop'. int *old_vts_ary = curbuf->b_p_vts_array; if (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1) { set_string_option_direct((char_u *)"vts", -1, new_ts_str, OPT_FREE|OPT_LOCAL, 0); curbuf->b_p_vts_array = new_vts_array; vim_free(old_vts_ary); } else { // 'vartabstop' wasn't in use and a single value was given to // retab then update 'tabstop'. curbuf->b_p_ts = tabstop_first(new_vts_array); vim_free(new_vts_array); } vim_free(new_ts_str); } #else curbuf->b_p_ts = new_ts; #endif coladvance(curwin->w_curswant); u_clearline(); }
256003981723363048355423518421227047339
indent.c
225104819640164774379021828754456921804
CWE-787
CVE-2022-0572
Heap-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0572
199,952
MilkyTracker
3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b
https://github.com/milkytracker/MilkyTracker
https://github.com/milkytracker/MilkyTracker/commit/3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b
Fix possible stack corruption with XM instrument headers claiming a size of less than 4 Closes #275
1
mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module) { mp_ubyte insData[230]; mp_sint32 smpReloc[MP_MAXINSSAMPS]; mp_ubyte nbu[MP_MAXINSSAMPS]; mp_uint32 fileSize = 0; module->cleanUp(); // this will make code much easier to read TXMHeader* header = &module->header; TXMInstrument* instr = module->instr; TXMSample* smp = module->smp; TXMPattern* phead = module->phead; // we're already out of memory here if (!phead || !instr || !smp) return MP_OUT_OF_MEMORY; fileSize = f.sizeWithBaseOffset(); f.read(&header->sig,1,17); f.read(&header->name,1,20); f.read(&header->whythis1a,1,1); header->whythis1a=0; f.read(&header->tracker,1,20); f.readWords(&header->ver,1); if (header->ver != 0x102 && header->ver != 0x103 && // untested header->ver != 0x104) return MP_LOADER_FAILED; f.readDwords(&header->hdrsize,1); header->hdrsize-=4; mp_uint32 hdrSize = 0x110; if (header->hdrsize > hdrSize) hdrSize = header->hdrsize; mp_ubyte* hdrBuff = new mp_ubyte[hdrSize]; memset(hdrBuff, 0, hdrSize); f.read(hdrBuff, 1, header->hdrsize); header->ordnum = LittleEndian::GET_WORD(hdrBuff); header->restart = LittleEndian::GET_WORD(hdrBuff+2); header->channum = LittleEndian::GET_WORD(hdrBuff+4); header->patnum = LittleEndian::GET_WORD(hdrBuff+6); header->insnum = LittleEndian::GET_WORD(hdrBuff+8); header->freqtab = LittleEndian::GET_WORD(hdrBuff+10); header->tempo = LittleEndian::GET_WORD(hdrBuff+12); header->speed = LittleEndian::GET_WORD(hdrBuff+14); memcpy(header->ord, hdrBuff+16, 256); if(header->ordnum > MP_MAXORDERS) header->ordnum = MP_MAXORDERS; if(header->insnum > MP_MAXINS) return MP_LOADER_FAILED; delete[] hdrBuff; header->mainvol=255; header->flags = XModule::MODULE_XMNOTECLIPPING | XModule::MODULE_XMARPEGGIO | XModule::MODULE_XMPORTANOTEBUFFER | XModule::MODULE_XMVOLCOLUMNVIBRATO; header->uppernotebound = 119; mp_sint32 i,y,sc; for (i=0;i<32;i++) header->pan[i]=0x80; // old version? if (header->ver == 0x102 || header->ver == 0x103) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;y<header->insnum;y++) { f.readDwords(&instr[y].size,1); f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); mp_uword numSamples = 0; f.readWords(&numSamples,1); if(numSamples > MP_MAXINSSAMPS) return MP_LOADER_FAILED; instr[y].samp = numSamples; if (instr[y].size == 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); memset(insData, 0, 230); if (instr[y].size - 33 > 230) return MP_OUT_OF_MEMORY; f.read(insData, 1, instr[y].size - 33); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) { venv.env[l][1]<<=2; penv.env[l][1]<<=2; } if (!module->addVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;sc<instr[y].samp;sc++) { smp[g+s].flags=3; smp[g+s].venvnum=e+1; smp[g+s].penvnum=e+1; smp[g+s].vibtype=vibtype; smp[g+s].vibsweep=vibsweep; smp[g+s].vibdepth=vibdepth; smp[g+s].vibrate=vibrate; smp[g+s].volfade=volfade; // not sure why I did that, actually doesn't make sense //if (!(venv.type&1)) smp[g+s].volfade=0; f.readDwords(&smp[g+s].samplen,1); f.readDwords(&smp[g+s].loopstart,1); f.readDwords(&smp[g+s].looplen,1); smp[g+s].vol=XModule::vol64to255(f.readByte()); //f.read(&smp[g+s].vol,1,1); f.read(&smp[g+s].finetune,1,1); f.read(&smp[g+s].type,1,1); #ifdef VERBOSE printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16)); #endif f.read(&smp[g+s].pan,1,1); f.read(&smp[g+s].relnote,1,1); f.read(&smp[g+s].res,1,1); f.read(&smp[g+s].name,1,22); char line[30]; memset(line, 0, sizeof(line)); XModule::convertStr(line, smp[g+s].name, 23, false); if (line[0]) module->addSongMessageLine(line); // ignore empty samples #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16; #else s+=instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } for (y=0;y<header->patnum;y++) { if (header->ver == 0x104 || header->ver == 0x103) { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); f.readWords(&phead[y].rows,1); f.readWords(&phead[y].patdata,1); } else { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); phead[y].rows = (mp_uword)f.readByte()+1; f.readWords(&phead[y].patdata,1); } phead[y].effnum=2; phead[y].channum=(mp_ubyte)header->channum; phead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6]; // out of memory? if (phead[y].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[y].patternData,0,phead[y].rows*header->channum*6); if (phead[y].patdata) { mp_ubyte *buffer = new mp_ubyte[phead[y].patdata]; // out of memory? if (buffer == NULL) { return MP_OUT_OF_MEMORY; } f.read(buffer,1,phead[y].patdata); //printf("%i\n", phead[y].patdata); mp_sint32 pc = 0, bc = 0; for (mp_sint32 r=0;r<phead[y].rows;r++) { for (mp_sint32 c=0;c<header->channum;c++) { mp_ubyte slot[5]; memset(slot,0,5); if ((buffer[pc]&128)) { mp_ubyte pb = buffer[pc]; pc++; if ((pb&1)) { //phead[y].patternData[bc]=buffer[pc]; slot[0]=buffer[pc]; pc++; } if ((pb&2)) { //phead[y].patternData[bc+1]=buffer[pc]; slot[1]=buffer[pc]; pc++; } if ((pb&4)) { //phead[y].patternData[bc+2]=buffer[pc]; slot[2]=buffer[pc]; pc++; } if ((pb&8)) { //phead[y].patternData[bc+3]=buffer[pc]; slot[3]=buffer[pc]; pc++; } if ((pb&16)) { //phead[y].patternData[bc+4]=buffer[pc]; slot[4]=buffer[pc]; pc++; } } else { //memcpy(phead[y].patternData+bc,buffer+pc,5); memcpy(slot,buffer+pc,5); pc+=5; } char gl=0; for (mp_sint32 i=0;i<XModule::numValidXMEffects;i++) if (slot[3]==XModule::validXMEffects[i]) gl=1; if (!gl) slot[3]=slot[4]=0; if ((slot[3]==0xC)||(slot[3]==0x10)) { slot[4] = XModule::vol64to255(slot[4]); /*mp_sint32 bl = slot[4]; if (bl>64) bl=64; slot[4]=(bl*261120)>>16;*/ } if ((!slot[3])&&(slot[4])) slot[3]=0x20; if (slot[3]==0xE) { slot[3]=(slot[4]>>4)+0x30; slot[4]=slot[4]&0xf; } if (slot[3]==0x21) { slot[3]=(slot[4]>>4)+0x40; slot[4]=slot[4]&0xf; } if (slot[0]==97) slot[0]=XModule::NOTE_OFF; phead[y].patternData[bc]=slot[0]; phead[y].patternData[bc+1]=slot[1]; XModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]); phead[y].patternData[bc+4]=slot[3]; phead[y].patternData[bc+5]=slot[4]; /*if ((y==3)&&(c==2)) { for (mp_sint32 bl=0;bl<6;bl++) cprintf("%x ",phead[y].patternData[bc+bl]); cprintf("\r\n"); getch(); };*/ /*printf("Note : %i\r\n",phead[y].patternData[bc]); printf("Ins : %i\r\n",phead[y].patternData[bc+1]); printf("Vol : %i\r\n",phead[y].patternData[bc+2]); printf("Eff : %i\r\n",phead[y].patternData[bc+3]); printf("Effop: %i\r\n",phead[y].patternData[bc+4]); getch();*/ bc+=6; } // for c } // for r delete[] buffer; } } if (header->ver == 0x104) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;y<header->insnum;y++) { // fixes MOOH.XM loading problems // seems to store more instruments in the header than in the actual file if (f.posWithBaseOffset() >= fileSize) break; //TXMInstrument* ins = &instr[y]; f.readDwords(&instr[y].size,1); if (instr[y].size < 29) { mp_ubyte buffer[29]; memset(buffer, 0, sizeof(buffer)); f.read(buffer, 1, instr[y].size - 4); memcpy(instr[y].name, buffer, 22); instr[y].type = buffer[22]; instr[y].samp = LittleEndian::GET_WORD(buffer + 23); } else { f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); f.readWords(&instr[y].samp,1); } if (instr[y].samp > MP_MAXINSSAMPS) return MP_LOADER_FAILED; //printf("%i, %i\n", instr[y].size, instr[y].samp); if (instr[y].size <= 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); #ifdef VERBOSE printf("%i/%i: %i, %i, %i, %s\n",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name); #endif memset(insData, 0, 230); if (instr[y].size - 33 > 230) { //return -7; break; } f.read(insData, 1, instr[y].size - 33); /*printf("%i\r\n",instr[y].size); printf("%s\r\n",instr[y].name); printf("%i\r\n",instr[y].type); printf("%i\r\n",instr[y].samp); printf("%i\r\n",instr[y].shsize);*/ //getch(); memset(smpReloc, 0, sizeof(smpReloc)); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; //f.read(&nbu,1,96); memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; //f.readWords(&volfade,1); volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) { venv.env[l][1]<<=2; penv.env[l][1]<<=2; } if (!module->addVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;sc<instr[y].samp;sc++) { //TXMSample* smpl = &smp[g+s]; smp[g+s].flags=3; smp[g+s].venvnum=e+1; smp[g+s].penvnum=e+1; smp[g+s].vibtype=vibtype; smp[g+s].vibsweep=vibsweep; smp[g+s].vibdepth=vibdepth; smp[g+s].vibrate=vibrate; smp[g+s].volfade=volfade; // not sure why I did that, actually doesn't make sense //if (!(venv.type&1)) smp[g+s].volfade=0; f.readDwords(&smp[g+s].samplen,1); f.readDwords(&smp[g+s].loopstart,1); f.readDwords(&smp[g+s].looplen,1); smp[g+s].vol=XModule::vol64to255(f.readByte()); //f.read(&smp[g+s].vol,1,1); f.read(&smp[g+s].finetune,1,1); f.read(&smp[g+s].type,1,1); #ifdef VERBOSE printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16)); #endif f.read(&smp[g+s].pan,1,1); f.read(&smp[g+s].relnote,1,1); f.read(&smp[g+s].res,1,1); f.read(&smp[g+s].name,1,22); char line[30]; memset(line, 0, sizeof(line)); XModule::convertStr(line, smp[g+s].name, 23, false); if (line[0]) module->addSongMessageLine(line); #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } for (sc=0;sc<instr[y].samp;sc++) { if (smp[s].samplen) { bool adpcm = (smp[s].res == 0xAD); mp_uint32 oldSize = smp[s].samplen; if (smp[s].type&16) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA, adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT), oldSize); if (result != MP_OK) return result; if (adpcm) smp[s].res = 0; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } else { mp_sint32 s = 0; for (y=0;y<header->insnum;y++) { for (sc=0;sc<instr[y].samp;sc++) { if (smp[s].samplen) { mp_uint32 oldSize = smp[s].samplen; if (smp[s].type&16) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize); if (result != MP_OK) return result; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } } // convert modplug stereo samples for (mp_sint32 s = 0; s < header->smpnum; s++) { if (smp[s].type & 32) { // that's what's allowed, stupid modplug tracker smp[s].type &= 3+16; if (smp[s].sample == NULL) continue; if (!(smp[s].type&16)) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sbyte* sample = (mp_sbyte*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -128) s = -128; if (s > 127) s = 127; sample[i] = (mp_sbyte)s; } } else { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sword* sample = (mp_sword*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -32768) s = -32768; if (s > 32767) s = 32767; sample[i] = (mp_sword)s; } } } // correct loop type 0x03 (undefined) // will become ping pong loop // note that FT2 will refuse to load XM files with such a loop type if ((smp[s].type & 0x3) == 0x3) smp[s].type&=~1; } // correct number of patterns if necessary, otherwise the post processing will remove // the "invalid" patterns from the order list bool addPatterns = false; for (i = 0; i < header->ordnum; i++) if (header->ord[i]+1 > header->patnum) { header->patnum = header->ord[i]+1; addPatterns = true; } // if the pattern number has been adjusted, add some empty patterns if (addPatterns) { for (i = 0; i < header->patnum; i++) if (phead[i].patternData == NULL) { phead[i].rows = 64; phead[i].effnum = 2; phead[i].channum = (mp_ubyte)header->channum; phead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6]; // out of memory? if (phead[i].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[i].patternData,0,phead[i].rows*header->channum*6); } } // check for MODPLUG extensions if (f.posWithBaseOffset() + 8 <= fileSize) { char buffer[4]; f.read(buffer, 1, 4); if (memcmp(buffer, "text", 4) == 0) { mp_uint32 len = f.readDword(); module->allocateSongMessage(len+1); memset(module->message, 0, len+1); f.read(module->message, 1, len); } } module->postProcessSamples(); return MP_OK; }
297622282182467898464562664481031169978
None
CWE-787
CVE-2022-34927
MilkyTracker v1.03.00 was discovered to contain a stack overflow via the component LoaderXM::load. This vulnerability is triggered when the program is supplied a crafted XM module file.
https://nvd.nist.gov/vuln/detail/CVE-2022-34927
295,887
MilkyTracker
3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b
https://github.com/milkytracker/MilkyTracker
https://github.com/milkytracker/MilkyTracker/commit/3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b
Fix possible stack corruption with XM instrument headers claiming a size of less than 4 Closes #275
0
mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module) { mp_ubyte insData[230]; mp_sint32 smpReloc[MP_MAXINSSAMPS]; mp_ubyte nbu[MP_MAXINSSAMPS]; mp_uint32 fileSize = 0; module->cleanUp(); // this will make code much easier to read TXMHeader* header = &module->header; TXMInstrument* instr = module->instr; TXMSample* smp = module->smp; TXMPattern* phead = module->phead; // we're already out of memory here if (!phead || !instr || !smp) return MP_OUT_OF_MEMORY; fileSize = f.sizeWithBaseOffset(); f.read(&header->sig,1,17); f.read(&header->name,1,20); f.read(&header->whythis1a,1,1); header->whythis1a=0; f.read(&header->tracker,1,20); f.readWords(&header->ver,1); if (header->ver != 0x102 && header->ver != 0x103 && // untested header->ver != 0x104) return MP_LOADER_FAILED; f.readDwords(&header->hdrsize,1); header->hdrsize-=4; mp_uint32 hdrSize = 0x110; if (header->hdrsize > hdrSize) hdrSize = header->hdrsize; mp_ubyte* hdrBuff = new mp_ubyte[hdrSize]; memset(hdrBuff, 0, hdrSize); f.read(hdrBuff, 1, header->hdrsize); header->ordnum = LittleEndian::GET_WORD(hdrBuff); header->restart = LittleEndian::GET_WORD(hdrBuff+2); header->channum = LittleEndian::GET_WORD(hdrBuff+4); header->patnum = LittleEndian::GET_WORD(hdrBuff+6); header->insnum = LittleEndian::GET_WORD(hdrBuff+8); header->freqtab = LittleEndian::GET_WORD(hdrBuff+10); header->tempo = LittleEndian::GET_WORD(hdrBuff+12); header->speed = LittleEndian::GET_WORD(hdrBuff+14); memcpy(header->ord, hdrBuff+16, 256); if(header->ordnum > MP_MAXORDERS) header->ordnum = MP_MAXORDERS; if(header->insnum > MP_MAXINS) return MP_LOADER_FAILED; delete[] hdrBuff; header->mainvol=255; header->flags = XModule::MODULE_XMNOTECLIPPING | XModule::MODULE_XMARPEGGIO | XModule::MODULE_XMPORTANOTEBUFFER | XModule::MODULE_XMVOLCOLUMNVIBRATO; header->uppernotebound = 119; mp_sint32 i,y,sc; for (i=0;i<32;i++) header->pan[i]=0x80; // old version? if (header->ver == 0x102 || header->ver == 0x103) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;y<header->insnum;y++) { f.readDwords(&instr[y].size,1); f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); mp_uword numSamples = 0; f.readWords(&numSamples,1); if(numSamples > MP_MAXINSSAMPS) return MP_LOADER_FAILED; instr[y].samp = numSamples; if (instr[y].size == 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); memset(insData, 0, 230); if (instr[y].size - 33 > 230) return MP_OUT_OF_MEMORY; f.read(insData, 1, instr[y].size - 33); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) { venv.env[l][1]<<=2; penv.env[l][1]<<=2; } if (!module->addVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;sc<instr[y].samp;sc++) { smp[g+s].flags=3; smp[g+s].venvnum=e+1; smp[g+s].penvnum=e+1; smp[g+s].vibtype=vibtype; smp[g+s].vibsweep=vibsweep; smp[g+s].vibdepth=vibdepth; smp[g+s].vibrate=vibrate; smp[g+s].volfade=volfade; // not sure why I did that, actually doesn't make sense //if (!(venv.type&1)) smp[g+s].volfade=0; f.readDwords(&smp[g+s].samplen,1); f.readDwords(&smp[g+s].loopstart,1); f.readDwords(&smp[g+s].looplen,1); smp[g+s].vol=XModule::vol64to255(f.readByte()); //f.read(&smp[g+s].vol,1,1); f.read(&smp[g+s].finetune,1,1); f.read(&smp[g+s].type,1,1); #ifdef VERBOSE printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16)); #endif f.read(&smp[g+s].pan,1,1); f.read(&smp[g+s].relnote,1,1); f.read(&smp[g+s].res,1,1); f.read(&smp[g+s].name,1,22); char line[30]; memset(line, 0, sizeof(line)); XModule::convertStr(line, smp[g+s].name, 23, false); if (line[0]) module->addSongMessageLine(line); // ignore empty samples #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16; #else s+=instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } for (y=0;y<header->patnum;y++) { if (header->ver == 0x104 || header->ver == 0x103) { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); f.readWords(&phead[y].rows,1); f.readWords(&phead[y].patdata,1); } else { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); phead[y].rows = (mp_uword)f.readByte()+1; f.readWords(&phead[y].patdata,1); } phead[y].effnum=2; phead[y].channum=(mp_ubyte)header->channum; phead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6]; // out of memory? if (phead[y].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[y].patternData,0,phead[y].rows*header->channum*6); if (phead[y].patdata) { mp_ubyte *buffer = new mp_ubyte[phead[y].patdata]; // out of memory? if (buffer == NULL) { return MP_OUT_OF_MEMORY; } f.read(buffer,1,phead[y].patdata); //printf("%i\n", phead[y].patdata); mp_sint32 pc = 0, bc = 0; for (mp_sint32 r=0;r<phead[y].rows;r++) { for (mp_sint32 c=0;c<header->channum;c++) { mp_ubyte slot[5]; memset(slot,0,5); if ((buffer[pc]&128)) { mp_ubyte pb = buffer[pc]; pc++; if ((pb&1)) { //phead[y].patternData[bc]=buffer[pc]; slot[0]=buffer[pc]; pc++; } if ((pb&2)) { //phead[y].patternData[bc+1]=buffer[pc]; slot[1]=buffer[pc]; pc++; } if ((pb&4)) { //phead[y].patternData[bc+2]=buffer[pc]; slot[2]=buffer[pc]; pc++; } if ((pb&8)) { //phead[y].patternData[bc+3]=buffer[pc]; slot[3]=buffer[pc]; pc++; } if ((pb&16)) { //phead[y].patternData[bc+4]=buffer[pc]; slot[4]=buffer[pc]; pc++; } } else { //memcpy(phead[y].patternData+bc,buffer+pc,5); memcpy(slot,buffer+pc,5); pc+=5; } char gl=0; for (mp_sint32 i=0;i<XModule::numValidXMEffects;i++) if (slot[3]==XModule::validXMEffects[i]) gl=1; if (!gl) slot[3]=slot[4]=0; if ((slot[3]==0xC)||(slot[3]==0x10)) { slot[4] = XModule::vol64to255(slot[4]); /*mp_sint32 bl = slot[4]; if (bl>64) bl=64; slot[4]=(bl*261120)>>16;*/ } if ((!slot[3])&&(slot[4])) slot[3]=0x20; if (slot[3]==0xE) { slot[3]=(slot[4]>>4)+0x30; slot[4]=slot[4]&0xf; } if (slot[3]==0x21) { slot[3]=(slot[4]>>4)+0x40; slot[4]=slot[4]&0xf; } if (slot[0]==97) slot[0]=XModule::NOTE_OFF; phead[y].patternData[bc]=slot[0]; phead[y].patternData[bc+1]=slot[1]; XModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]); phead[y].patternData[bc+4]=slot[3]; phead[y].patternData[bc+5]=slot[4]; /*if ((y==3)&&(c==2)) { for (mp_sint32 bl=0;bl<6;bl++) cprintf("%x ",phead[y].patternData[bc+bl]); cprintf("\r\n"); getch(); };*/ /*printf("Note : %i\r\n",phead[y].patternData[bc]); printf("Ins : %i\r\n",phead[y].patternData[bc+1]); printf("Vol : %i\r\n",phead[y].patternData[bc+2]); printf("Eff : %i\r\n",phead[y].patternData[bc+3]); printf("Effop: %i\r\n",phead[y].patternData[bc+4]); getch();*/ bc+=6; } // for c } // for r delete[] buffer; } } if (header->ver == 0x104) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;y<header->insnum;y++) { // fixes MOOH.XM loading problems // seems to store more instruments in the header than in the actual file if (f.posWithBaseOffset() >= fileSize) break; //TXMInstrument* ins = &instr[y]; f.readDwords(&instr[y].size,1); if (instr[y].size >= 4 && instr[y].size < 29) { mp_ubyte buffer[29]; memset(buffer, 0, sizeof(buffer)); f.read(buffer, 1, instr[y].size - 4); memcpy(instr[y].name, buffer, 22); instr[y].type = buffer[22]; instr[y].samp = LittleEndian::GET_WORD(buffer + 23); } else { f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); f.readWords(&instr[y].samp,1); } if (instr[y].samp > MP_MAXINSSAMPS) return MP_LOADER_FAILED; //printf("%i, %i\n", instr[y].size, instr[y].samp); if (instr[y].size <= 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); #ifdef VERBOSE printf("%i/%i: %i, %i, %i, %s\n",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name); #endif memset(insData, 0, 230); if (instr[y].size - 33 > 230) { //return -7; break; } f.read(insData, 1, instr[y].size - 33); /*printf("%i\r\n",instr[y].size); printf("%s\r\n",instr[y].name); printf("%i\r\n",instr[y].type); printf("%i\r\n",instr[y].samp); printf("%i\r\n",instr[y].shsize);*/ //getch(); memset(smpReloc, 0, sizeof(smpReloc)); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; //f.read(&nbu,1,96); memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; //f.readWords(&volfade,1); volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) { venv.env[l][1]<<=2; penv.env[l][1]<<=2; } if (!module->addVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;sc<instr[y].samp;sc++) { //TXMSample* smpl = &smp[g+s]; smp[g+s].flags=3; smp[g+s].venvnum=e+1; smp[g+s].penvnum=e+1; smp[g+s].vibtype=vibtype; smp[g+s].vibsweep=vibsweep; smp[g+s].vibdepth=vibdepth; smp[g+s].vibrate=vibrate; smp[g+s].volfade=volfade; // not sure why I did that, actually doesn't make sense //if (!(venv.type&1)) smp[g+s].volfade=0; f.readDwords(&smp[g+s].samplen,1); f.readDwords(&smp[g+s].loopstart,1); f.readDwords(&smp[g+s].looplen,1); smp[g+s].vol=XModule::vol64to255(f.readByte()); //f.read(&smp[g+s].vol,1,1); f.read(&smp[g+s].finetune,1,1); f.read(&smp[g+s].type,1,1); #ifdef VERBOSE printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16)); #endif f.read(&smp[g+s].pan,1,1); f.read(&smp[g+s].relnote,1,1); f.read(&smp[g+s].res,1,1); f.read(&smp[g+s].name,1,22); char line[30]; memset(line, 0, sizeof(line)); XModule::convertStr(line, smp[g+s].name, 23, false); if (line[0]) module->addSongMessageLine(line); #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } for (sc=0;sc<instr[y].samp;sc++) { if (smp[s].samplen) { bool adpcm = (smp[s].res == 0xAD); mp_uint32 oldSize = smp[s].samplen; if (smp[s].type&16) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA, adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT), oldSize); if (result != MP_OK) return result; if (adpcm) smp[s].res = 0; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } else { mp_sint32 s = 0; for (y=0;y<header->insnum;y++) { for (sc=0;sc<instr[y].samp;sc++) { if (smp[s].samplen) { mp_uint32 oldSize = smp[s].samplen; if (smp[s].type&16) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize); if (result != MP_OK) return result; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } } // convert modplug stereo samples for (mp_sint32 s = 0; s < header->smpnum; s++) { if (smp[s].type & 32) { // that's what's allowed, stupid modplug tracker smp[s].type &= 3+16; if (smp[s].sample == NULL) continue; if (!(smp[s].type&16)) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sbyte* sample = (mp_sbyte*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -128) s = -128; if (s > 127) s = 127; sample[i] = (mp_sbyte)s; } } else { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sword* sample = (mp_sword*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -32768) s = -32768; if (s > 32767) s = 32767; sample[i] = (mp_sword)s; } } } // correct loop type 0x03 (undefined) // will become ping pong loop // note that FT2 will refuse to load XM files with such a loop type if ((smp[s].type & 0x3) == 0x3) smp[s].type&=~1; } // correct number of patterns if necessary, otherwise the post processing will remove // the "invalid" patterns from the order list bool addPatterns = false; for (i = 0; i < header->ordnum; i++) if (header->ord[i]+1 > header->patnum) { header->patnum = header->ord[i]+1; addPatterns = true; } // if the pattern number has been adjusted, add some empty patterns if (addPatterns) { for (i = 0; i < header->patnum; i++) if (phead[i].patternData == NULL) { phead[i].rows = 64; phead[i].effnum = 2; phead[i].channum = (mp_ubyte)header->channum; phead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6]; // out of memory? if (phead[i].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[i].patternData,0,phead[i].rows*header->channum*6); } } // check for MODPLUG extensions if (f.posWithBaseOffset() + 8 <= fileSize) { char buffer[4]; f.read(buffer, 1, 4); if (memcmp(buffer, "text", 4) == 0) { mp_uint32 len = f.readDword(); module->allocateSongMessage(len+1); memset(module->message, 0, len+1); f.read(module->message, 1, len); } } module->postProcessSamples(); return MP_OK; }
77426307026803583568821855740200554303
None
CWE-787
CVE-2022-34927
MilkyTracker v1.03.00 was discovered to contain a stack overflow via the component LoaderXM::load. This vulnerability is triggered when the program is supplied a crafted XM module file.
https://nvd.nist.gov/vuln/detail/CVE-2022-34927
199,984
vim
37f47958b8a2a44abc60614271d9537e7f14e51a
https://github.com/vim/vim
https://github.com/vim/vim/commit/37f47958b8a2a44abc60614271d9537e7f14e51a
patch 8.2.4253: using freed memory when substitute with function call Problem: Using freed memory when substitute uses a recursive function call. Solution: Make a copy of the substitute text.
1
ex_substitute(exarg_T *eap) { linenr_T lnum; long i = 0; regmmatch_T regmatch; static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, 0}; #ifdef FEAT_EVAL subflags_T subflags_save; #endif int save_do_all; // remember user specified 'g' flag int save_do_ask; // remember user specified 'c' flag char_u *pat = NULL, *sub = NULL; // init for GCC int delimiter; int sublen; int got_quit = FALSE; int got_match = FALSE; int temp; int which_pat; char_u *cmd; int save_State; linenr_T first_line = 0; // first changed line linenr_T last_line= 0; // below last changed line AFTER the // change linenr_T old_line_count = curbuf->b_ml.ml_line_count; linenr_T line2; long nmatch; // number of lines in match char_u *sub_firstline; // allocated copy of first sub line int endcolumn = FALSE; // cursor in last column when done pos_T old_cursor = curwin->w_cursor; int start_nsubs; #ifdef FEAT_EVAL int save_ma = 0; #endif cmd = eap->arg; if (!global_busy) { sub_nsubs = 0; sub_nlines = 0; } start_nsubs = sub_nsubs; if (eap->cmdidx == CMD_tilde) which_pat = RE_LAST; // use last used regexp else which_pat = RE_SUBST; // use last substitute regexp // new pattern and substitution if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd) && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL) { // don't accept alphanumeric for separator if (check_regexp_delim(*cmd) == FAIL) return; #ifdef FEAT_EVAL if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg) == FAIL) return; #endif /* * undocumented vi feature: * "\/sub/" and "\?sub?" use last used search pattern (almost like * //sub/r). "\&sub&" use last substitute pattern (like //sub/). */ if (*cmd == '\\') { ++cmd; if (vim_strchr((char_u *)"/?&", *cmd) == NULL) { emsg(_(e_backslash_should_be_followed_by)); return; } if (*cmd != '&') which_pat = RE_SEARCH; // use last '/' pattern pat = (char_u *)""; // empty search pattern delimiter = *cmd++; // remember delimiter character } else // find the end of the regexp { which_pat = RE_LAST; // use last used regexp delimiter = *cmd++; // remember delimiter character pat = cmd; // remember start of search pat cmd = skip_regexp_ex(cmd, delimiter, magic_isset(), &eap->arg, NULL, NULL); if (cmd[0] == delimiter) // end delimiter found *cmd++ = NUL; // replace it with a NUL } /* * Small incompatibility: vi sees '\n' as end of the command, but in * Vim we want to use '\n' to find/substitute a NUL. */ sub = cmd; // remember the start of the substitution cmd = skip_substitute(cmd, delimiter); if (!eap->skip) { // In POSIX vi ":s/pat/%/" uses the previous subst. string. if (STRCMP(sub, "%") == 0 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL) { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } sub = old_sub; } else { vim_free(old_sub); old_sub = vim_strsave(sub); } } } else if (!eap->skip) // use previous pattern and substitution { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } pat = NULL; // search_regcomp() will use previous pattern sub = old_sub; // Vi compatibility quirk: repeating with ":s" keeps the cursor in the // last column after using "$". endcolumn = (curwin->w_curswant == MAXCOL); } // Recognize ":%s/\n//" and turn it into a join command, which is much // more efficient. // TODO: find a generic solution to make line-joining operations more // efficient, avoid allocating a string that grows in size. if (pat != NULL && STRCMP(pat, "\\n") == 0 && *sub == NUL && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l' || *cmd == 'p' || *cmd == '#')))) { linenr_T joined_lines_count; if (eap->skip) return; curwin->w_cursor.lnum = eap->line1; if (*cmd == 'l') eap->flags = EXFLAG_LIST; else if (*cmd == '#') eap->flags = EXFLAG_NR; else if (*cmd == 'p') eap->flags = EXFLAG_PRINT; // The number of lines joined is the number of lines in the range plus // one. One less when the last line is included. joined_lines_count = eap->line2 - eap->line1 + 1; if (eap->line2 < curbuf->b_ml.ml_line_count) ++joined_lines_count; if (joined_lines_count > 1) { (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE); sub_nsubs = joined_lines_count - 1; sub_nlines = 1; (void)do_sub_msg(FALSE); ex_may_print(eap); } if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) save_re_pat(RE_SUBST, pat, magic_isset()); // put pattern in history add_to_history(HIST_SEARCH, pat, TRUE, NUL); return; } /* * Find trailing options. When '&' is used, keep old options. */ if (*cmd == '&') ++cmd; else { #ifdef FEAT_EVAL if (in_vim9script()) { // ignore 'gdefault' and 'edcompatible' subflags.do_all = FALSE; subflags.do_ask = FALSE; } else #endif if (!p_ed) { if (p_gd) // default is global on subflags.do_all = TRUE; else subflags.do_all = FALSE; subflags.do_ask = FALSE; } subflags.do_error = TRUE; subflags.do_print = FALSE; subflags.do_list = FALSE; subflags.do_count = FALSE; subflags.do_number = FALSE; subflags.do_ic = 0; } while (*cmd) { /* * Note that 'g' and 'c' are always inverted, also when p_ed is off. * 'r' is never inverted. */ if (*cmd == 'g') subflags.do_all = !subflags.do_all; else if (*cmd == 'c') subflags.do_ask = !subflags.do_ask; else if (*cmd == 'n') subflags.do_count = TRUE; else if (*cmd == 'e') subflags.do_error = !subflags.do_error; else if (*cmd == 'r') // use last used regexp which_pat = RE_LAST; else if (*cmd == 'p') subflags.do_print = TRUE; else if (*cmd == '#') { subflags.do_print = TRUE; subflags.do_number = TRUE; } else if (*cmd == 'l') { subflags.do_print = TRUE; subflags.do_list = TRUE; } else if (*cmd == 'i') // ignore case subflags.do_ic = 'i'; else if (*cmd == 'I') // don't ignore case subflags.do_ic = 'I'; else break; ++cmd; } if (subflags.do_count) subflags.do_ask = FALSE; save_do_all = subflags.do_all; save_do_ask = subflags.do_ask; /* * check for a trailing count */ cmd = skipwhite(cmd); if (VIM_ISDIGIT(*cmd)) { i = getdigits(&cmd); if (i <= 0 && !eap->skip && subflags.do_error) { emsg(_(e_positive_count_required)); return; } eap->line1 = eap->line2; eap->line2 += i - 1; if (eap->line2 > curbuf->b_ml.ml_line_count) eap->line2 = curbuf->b_ml.ml_line_count; } /* * check for trailing command or garbage */ cmd = skipwhite(cmd); if (*cmd && *cmd != '"') // if not end-of-line or comment { set_nextcmd(eap, cmd); if (eap->nextcmd == NULL) { semsg(_(e_trailing_characters_str), cmd); return; } } if (eap->skip) // not executing commands, only parsing return; if (!subflags.do_count && !curbuf->b_p_ma) { // Substitution is not allowed in non-'modifiable' buffer emsg(_(e_cannot_make_changes_modifiable_is_off)); return; } if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL) { if (subflags.do_error) emsg(_(e_invalid_command)); return; } // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' if (subflags.do_ic == 'i') regmatch.rmm_ic = TRUE; else if (subflags.do_ic == 'I') regmatch.rmm_ic = FALSE; sub_firstline = NULL; /* * ~ in the substitute pattern is replaced with the old pattern. * We do it here once to avoid it to be replaced over and over again. * But don't do it when it starts with "\=", then it's an expression. */ if (!(sub[0] == '\\' && sub[1] == '=')) sub = regtilde(sub, magic_isset()); /* * Check for a match on each line. */ line2 = eap->line2; for (lnum = eap->line1; lnum <= line2 && !(got_quit #if defined(FEAT_EVAL) || aborting() #endif ); ++lnum) { nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0, NULL, NULL); if (nmatch) { colnr_T copycol; colnr_T matchcol; colnr_T prev_matchcol = MAXCOL; char_u *new_end, *new_start = NULL; unsigned new_start_len = 0; char_u *p1; int did_sub = FALSE; int lastone; int len, copy_len, needed_len; long nmatch_tl = 0; // nr of lines matched below lnum int do_again; // do it again after joining lines int skip_match = FALSE; linenr_T sub_firstlnum; // nr of first sub line #ifdef FEAT_PROP_POPUP int apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE; colnr_T total_added = 0; #endif /* * The new text is build up step by step, to avoid too much * copying. There are these pieces: * sub_firstline The old text, unmodified. * copycol Column in the old text where we started * looking for a match; from here old text still * needs to be copied to the new text. * matchcol Column number of the old text where to look * for the next match. It's just after the * previous match or one further. * prev_matchcol Column just after the previous match (if any). * Mostly equal to matchcol, except for the first * match and after skipping an empty match. * regmatch.*pos Where the pattern matched in the old text. * new_start The new text, all that has been produced so * far. * new_end The new text, where to append new text. * * lnum The line number where we found the start of * the match. Can be below the line we searched * when there is a \n before a \zs in the * pattern. * sub_firstlnum The line number in the buffer where to look * for a match. Can be different from "lnum" * when the pattern or substitute string contains * line breaks. * * Special situations: * - When the substitute string contains a line break, the part up * to the line break is inserted in the text, but the copy of * the original line is kept. "sub_firstlnum" is adjusted for * the inserted lines. * - When the matched pattern contains a line break, the old line * is taken from the line at the end of the pattern. The lines * in the match are deleted later, "sub_firstlnum" is adjusted * accordingly. * * The new text is built up in new_start[]. It has some extra * room to avoid using alloc()/free() too often. new_start_len is * the length of the allocated memory at new_start. * * Make a copy of the old line, so it won't be taken away when * updating the screen or handling a multi-line match. The "old_" * pointers point into this copy. */ sub_firstlnum = lnum; copycol = 0; matchcol = 0; // At first match, remember current cursor position. if (!got_match) { setpcmark(); got_match = TRUE; } /* * Loop until nothing more to replace in this line. * 1. Handle match with empty string. * 2. If do_ask is set, ask for confirmation. * 3. substitute the string. * 4. if do_all is set, find next match * 5. break if there isn't another match in this line */ for (;;) { // Advance "lnum" to the line where the match starts. The // match does not start in the first line when there is a line // break before \zs. if (regmatch.startpos[0].lnum > 0) { lnum += regmatch.startpos[0].lnum; sub_firstlnum += regmatch.startpos[0].lnum; nmatch -= regmatch.startpos[0].lnum; VIM_CLEAR(sub_firstline); } // Match might be after the last line for "\n\zs" matching at // the end of the last line. if (lnum > curbuf->b_ml.ml_line_count) break; if (sub_firstline == NULL) { sub_firstline = vim_strsave(ml_get(sub_firstlnum)); if (sub_firstline == NULL) { vim_free(new_start); goto outofmem; } } // Save the line number of the last change for the final // cursor position (just like Vi). curwin->w_cursor.lnum = lnum; do_again = FALSE; /* * 1. Match empty string does not count, except for first * match. This reproduces the strange vi behaviour. * This also catches endless loops. */ if (matchcol == prev_matchcol && regmatch.endpos[0].lnum == 0 && matchcol == regmatch.endpos[0].col) { if (sub_firstline[matchcol] == NUL) // We already were at the end of the line. Don't look // for a match in this line again. skip_match = TRUE; else { // search for a match at next column if (has_mbyte) matchcol += mb_ptr2len(sub_firstline + matchcol); else ++matchcol; } goto skip; } // Normally we continue searching for a match just after the // previous match. matchcol = regmatch.endpos[0].col; prev_matchcol = matchcol; /* * 2. If do_count is set only increase the counter. * If do_ask is set, ask for confirmation. */ if (subflags.do_count) { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":s/\nB\@=//gc" get stuck. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); nmatch = 1; skip_match = TRUE; } sub_nsubs++; did_sub = TRUE; #ifdef FEAT_EVAL // Skip the substitution, unless an expression is used, // then it is evaluated in the sandbox. if (!(sub[0] == '\\' && sub[1] == '=')) #endif goto skip; } if (subflags.do_ask) { int typed = 0; // change State to CONFIRM, so that the mouse works // properly save_State = State; State = CONFIRM; setmouse(); // disable mouse in xterm curwin->w_cursor.col = regmatch.startpos[0].col; if (curwin->w_p_crb) do_check_cursorbind(); // When 'cpoptions' contains "u" don't sync undo when // asking for confirmation. if (vim_strchr(p_cpo, CPO_UNDO) != NULL) ++no_u_sync; /* * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. */ while (subflags.do_ask) { if (exmode_active) { char_u *resp; colnr_T sc, ec; print_line_no_prefix(lnum, subflags.do_number, subflags.do_list); getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL); curwin->w_cursor.col = regmatch.endpos[0].col - 1; if (curwin->w_cursor.col < 0) curwin->w_cursor.col = 0; getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec); curwin->w_cursor.col = regmatch.startpos[0].col; if (subflags.do_number || curwin->w_p_nu) { int numw = number_width(curwin) + 1; sc += numw; ec += numw; } msg_start(); for (i = 0; i < (long)sc; ++i) msg_putchar(' '); for ( ; i <= (long)ec; ++i) msg_putchar('^'); resp = getexmodeline('?', NULL, 0, TRUE); if (resp != NULL) { typed = *resp; vim_free(resp); } } else { char_u *orig_line = NULL; int len_change = 0; int save_p_lz = p_lz; #ifdef FEAT_FOLDING int save_p_fen = curwin->w_p_fen; curwin->w_p_fen = FALSE; #endif // Invert the matched string. // Remove the inversion afterwards. temp = RedrawingDisabled; RedrawingDisabled = 0; // avoid calling update_screen() in vgetorpeek() p_lz = FALSE; if (new_start != NULL) { // There already was a substitution, we would // like to show this to the user. We cannot // really update the line, it would change // what matches. Temporarily replace the line // and change it back afterwards. orig_line = vim_strsave(ml_get(lnum)); if (orig_line != NULL) { char_u *new_line = concat_str(new_start, sub_firstline + copycol); if (new_line == NULL) VIM_CLEAR(orig_line); else { // Position the cursor relative to the // end of the line, the previous // substitute may have inserted or // deleted characters before the // cursor. len_change = (int)STRLEN(new_line) - (int)STRLEN(orig_line); curwin->w_cursor.col += len_change; ml_replace(lnum, new_line, FALSE); } } } search_match_lines = regmatch.endpos[0].lnum - regmatch.startpos[0].lnum; search_match_endcol = regmatch.endpos[0].col + len_change; highlight_match = TRUE; update_topline(); validate_cursor(); update_screen(SOME_VALID); highlight_match = FALSE; redraw_later(SOME_VALID); #ifdef FEAT_FOLDING curwin->w_p_fen = save_p_fen; #endif if (msg_row == Rows - 1) msg_didout = FALSE; // avoid a scroll-up msg_starthere(); i = msg_scroll; msg_scroll = 0; // truncate msg when // needed msg_no_more = TRUE; // write message same highlighting as for // wait_return smsg_attr(HL_ATTR(HLF_R), _("replace with %s (y/n/a/q/l/^E/^Y)?"), sub); msg_no_more = FALSE; msg_scroll = i; showruler(TRUE); windgoto(msg_row, msg_col); RedrawingDisabled = temp; #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif ++no_mapping; // don't map this key ++allow_keys; // allow special keys typed = plain_vgetc(); --allow_keys; --no_mapping; // clear the question msg_didout = FALSE; // don't scroll up msg_col = 0; gotocmdline(TRUE); p_lz = save_p_lz; // restore the line if (orig_line != NULL) ml_replace(lnum, orig_line, FALSE); } need_wait_return = FALSE; // no hit-return prompt if (typed == 'q' || typed == ESC || typed == Ctrl_C #ifdef UNIX || typed == intr_char #endif ) { got_quit = TRUE; break; } if (typed == 'n') break; if (typed == 'y') break; if (typed == 'l') { // last: replace and then stop subflags.do_all = FALSE; line2 = lnum; break; } if (typed == 'a') { subflags.do_ask = FALSE; break; } if (typed == Ctrl_E) scrollup_clamp(); else if (typed == Ctrl_Y) scrolldown_clamp(); } State = save_State; setmouse(); if (vim_strchr(p_cpo, CPO_UNDO) != NULL) --no_u_sync; if (typed == 'n') { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc" // get stuck when pressing 'n'. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); skip_match = TRUE; } goto skip; } if (got_quit) goto skip; } // Move the cursor to the start of the match, so that we can // use "\=col("."). curwin->w_cursor.col = regmatch.startpos[0].col; /* * 3. substitute the string. */ #ifdef FEAT_EVAL save_ma = curbuf->b_p_ma; if (subflags.do_count) { // prevent accidentally changing the buffer by a function curbuf->b_p_ma = FALSE; sandbox++; } // Save flags for recursion. They can change for e.g. // :s/^/\=execute("s#^##gn") subflags_save = subflags; #endif // get length of substitution part sublen = vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, sub_firstline, FALSE, magic_isset(), TRUE); #ifdef FEAT_EVAL // If getting the substitute string caused an error, don't do // the replacement. // Don't keep flags set by a recursive call. subflags = subflags_save; if (aborting() || subflags.do_count) { curbuf->b_p_ma = save_ma; if (sandbox > 0) sandbox--; goto skip; } #endif // When the match included the "$" of the last line it may // go beyond the last line of the buffer. if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1) { nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1; skip_match = TRUE; } // Need room for: // - result so far in new_start (not for first sub in line) // - original text up to match // - length of substituted part // - original text after match // Adjust text properties here, since we have all information // needed. if (nmatch == 1) { p1 = sub_firstline; #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { int bytes_added = sublen - 1 - (regmatch.endpos[0].col - regmatch.startpos[0].col); // When text properties are changed, need to save for // undo first, unless done already. if (adjust_prop_columns(lnum, total_added + regmatch.startpos[0].col, bytes_added, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; // Offset for column byte number of the text property // in the resulting buffer afterwards. total_added += bytes_added; } #endif } else { p1 = ml_get(sub_firstlnum + nmatch - 1); nmatch_tl += nmatch - 1; } copy_len = regmatch.startpos[0].col - copycol; needed_len = copy_len + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col) + sublen + 1; if (new_start == NULL) { /* * Get some space for a temporary buffer to do the * substitution into (and some extra space to avoid * too many calls to alloc()/free()). */ new_start_len = needed_len + 50; if ((new_start = alloc(new_start_len)) == NULL) goto outofmem; *new_start = NUL; new_end = new_start; } else { /* * Check if the temporary buffer is long enough to do the * substitution into. If not, make it larger (with a bit * extra to avoid too many calls to alloc()/free()). */ len = (unsigned)STRLEN(new_start); needed_len += len; if (needed_len > (int)new_start_len) { new_start_len = needed_len + 50; if ((p1 = alloc(new_start_len)) == NULL) { vim_free(new_start); goto outofmem; } mch_memmove(p1, new_start, (size_t)(len + 1)); vim_free(new_start); new_start = p1; } new_end = new_start + len; } /* * copy the text up to the part that matched */ mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len); new_end += copy_len; (void)vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, new_end, TRUE, magic_isset(), TRUE); sub_nsubs++; did_sub = TRUE; // Move the cursor to the start of the line, to avoid that it // is beyond the end of the line after the substitution. curwin->w_cursor.col = 0; // For a multi-line match, make a copy of the last matched // line and continue in that one. if (nmatch > 1) { sub_firstlnum += nmatch - 1; vim_free(sub_firstline); sub_firstline = vim_strsave(ml_get(sub_firstlnum)); // When going beyond the last line, stop substituting. if (sub_firstlnum <= line2) do_again = TRUE; else subflags.do_all = FALSE; } // Remember next character to be copied. copycol = regmatch.endpos[0].col; if (skip_match) { // Already hit end of the buffer, sub_firstlnum is one // less than what it ought to be. vim_free(sub_firstline); sub_firstline = vim_strsave((char_u *)""); copycol = 0; } /* * Now the trick is to replace CTRL-M chars with a real line * break. This would make it impossible to insert a CTRL-M in * the text. The line break can be avoided by preceding the * CTRL-M with a backslash. To be able to insert a backslash, * they must be doubled in the string and are halved here. * That is Vi compatible. */ for (p1 = new_end; *p1; ++p1) { if (p1[0] == '\\' && p1[1] != NUL) // remove backslash { STRMOVE(p1, p1 + 1); #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { // When text properties are changed, need to save // for undo first, unless done already. if (adjust_prop_columns(lnum, (colnr_T)(p1 - new_start), -1, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; } #endif } else if (*p1 == CAR) { if (u_inssub(lnum) == OK) // prepare for undo { colnr_T plen = (colnr_T)(p1 - new_start + 1); *p1 = NUL; // truncate up to the CR ml_append(lnum - 1, new_start, plen, FALSE); mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L); if (subflags.do_ask) appended_lines(lnum - 1, 1L); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } #ifdef FEAT_PROP_POPUP adjust_props_for_split(lnum + 1, lnum, plen, 1); #endif // all line numbers increase ++sub_firstlnum; ++lnum; ++line2; // move the cursor to the new line, like Vi ++curwin->w_cursor.lnum; // copy the rest STRMOVE(new_start, p1 + 1); p1 = new_start - 1; } } else if (has_mbyte) p1 += (*mb_ptr2len)(p1) - 1; } /* * 4. If do_all is set, find next match. * Prevent endless loop with patterns that match empty * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g. * But ":s/\n/#/" is OK. */ skip: // We already know that we did the last subst when we are at // the end of the line, except that a pattern like // "bar\|\nfoo" may match at the NUL. "lnum" can be below // "line2" when there is a \zs in the pattern after a line // break. lastone = (skip_match || got_int || got_quit || lnum > line2 || !(subflags.do_all || do_again) || (sub_firstline[matchcol] == NUL && nmatch <= 1 && !re_multiline(regmatch.regprog))); nmatch = -1; /* * Replace the line in the buffer when needed. This is * skipped when there are more matches. * The check for nmatch_tl is needed for when multi-line * matching must replace the lines before trying to do another * match, otherwise "\@<=" won't work. * When the match starts below where we start searching also * need to replace the line first (using \zs after \n). */ if (lastone || nmatch_tl > 0 || (nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL)) == 0 || regmatch.startpos[0].lnum > 0) { if (new_start != NULL) { /* * Copy the rest of the line, that didn't match. * "matchcol" has to be adjusted, we use the end of * the line as reference, because the substitute may * have changed the number of characters. Same for * "prev_matchcol". */ STRCAT(new_start, sub_firstline + copycol); matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; if (u_savesub(lnum) != OK) break; ml_replace(lnum, new_start, TRUE); if (nmatch_tl > 0) { /* * Matched lines have now been substituted and are * useless, delete them. The part after the match * has been appended to new_start, we don't need * it in the buffer. */ ++lnum; if (u_savedel(lnum, nmatch_tl) != OK) break; for (i = 0; i < nmatch_tl; ++i) ml_delete(lnum); mark_adjust(lnum, lnum + nmatch_tl - 1, (long)MAXLNUM, -nmatch_tl); if (subflags.do_ask) deleted_lines(lnum, nmatch_tl); --lnum; line2 -= nmatch_tl; // nr of lines decreases nmatch_tl = 0; } // When asking, undo is saved each time, must also set // changed flag each time. if (subflags.do_ask) changed_bytes(lnum, 0); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } sub_firstlnum = lnum; vim_free(sub_firstline); // free the temp buffer sub_firstline = new_start; new_start = NULL; matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; copycol = 0; } if (nmatch == -1 && !lastone) nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL); /* * 5. break if there isn't another match in this line */ if (nmatch <= 0) { // If the match found didn't start where we were // searching, do the next search in the line where we // found the match. if (nmatch == -1) lnum -= regmatch.startpos[0].lnum; break; } } line_breakcheck(); } if (did_sub) ++sub_nlines; vim_free(new_start); // for when substitute was cancelled VIM_CLEAR(sub_firstline); // free the copy of the original line } line_breakcheck(); } if (first_line != 0) { // Need to subtract the number of added lines from "last_line" to get // the line number before the change (same as adding the number of // deleted lines). i = curbuf->b_ml.ml_line_count - old_line_count; changed_lines(first_line, 0, last_line - i, i); } outofmem: vim_free(sub_firstline); // may have to free allocated copy of the line // ":s/pat//n" doesn't move the cursor if (subflags.do_count) curwin->w_cursor = old_cursor; if (sub_nsubs > start_nsubs) { if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '[ and '] marks. curbuf->b_op_start.lnum = eap->line1; curbuf->b_op_end.lnum = line2; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } if (!global_busy) { // when interactive leave cursor on the match if (!subflags.do_ask) { if (endcolumn) coladvance((colnr_T)MAXCOL); else beginline(BL_WHITE | BL_FIX); } if (!do_sub_msg(subflags.do_count) && subflags.do_ask) msg(""); } else global_need_beginline = TRUE; if (subflags.do_print) print_line(curwin->w_cursor.lnum, subflags.do_number, subflags.do_list); } else if (!global_busy) { if (got_int) // interrupted emsg(_(e_interrupted)); else if (got_match) // did find something but nothing substituted msg(""); else if (subflags.do_error) // nothing found semsg(_(e_pattern_not_found_str), get_search_pat()); } #ifdef FEAT_FOLDING if (subflags.do_ask && hasAnyFolding(curwin)) // Cursor position may require updating changed_window_setting(); #endif vim_regfree(regmatch.regprog); // Restore the flag values, they can be used for ":&&". subflags.do_all = save_do_all; subflags.do_ask = save_do_ask; }
259196751787508005925510441148614080583
ex_cmds.c
59965875084146466287270368497703800580
CWE-416
CVE-2022-0413
Use After Free in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0413
296,226
vim
37f47958b8a2a44abc60614271d9537e7f14e51a
https://github.com/vim/vim
https://github.com/vim/vim/commit/37f47958b8a2a44abc60614271d9537e7f14e51a
patch 8.2.4253: using freed memory when substitute with function call Problem: Using freed memory when substitute uses a recursive function call. Solution: Make a copy of the substitute text.
0
ex_substitute(exarg_T *eap) { linenr_T lnum; long i = 0; regmmatch_T regmatch; static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, 0}; #ifdef FEAT_EVAL subflags_T subflags_save; #endif int save_do_all; // remember user specified 'g' flag int save_do_ask; // remember user specified 'c' flag char_u *pat = NULL, *sub = NULL; // init for GCC char_u *sub_copy = NULL; int delimiter; int sublen; int got_quit = FALSE; int got_match = FALSE; int temp; int which_pat; char_u *cmd; int save_State; linenr_T first_line = 0; // first changed line linenr_T last_line= 0; // below last changed line AFTER the // change linenr_T old_line_count = curbuf->b_ml.ml_line_count; linenr_T line2; long nmatch; // number of lines in match char_u *sub_firstline; // allocated copy of first sub line int endcolumn = FALSE; // cursor in last column when done pos_T old_cursor = curwin->w_cursor; int start_nsubs; #ifdef FEAT_EVAL int save_ma = 0; #endif cmd = eap->arg; if (!global_busy) { sub_nsubs = 0; sub_nlines = 0; } start_nsubs = sub_nsubs; if (eap->cmdidx == CMD_tilde) which_pat = RE_LAST; // use last used regexp else which_pat = RE_SUBST; // use last substitute regexp // new pattern and substitution if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd) && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL) { // don't accept alphanumeric for separator if (check_regexp_delim(*cmd) == FAIL) return; #ifdef FEAT_EVAL if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg) == FAIL) return; #endif /* * undocumented vi feature: * "\/sub/" and "\?sub?" use last used search pattern (almost like * //sub/r). "\&sub&" use last substitute pattern (like //sub/). */ if (*cmd == '\\') { ++cmd; if (vim_strchr((char_u *)"/?&", *cmd) == NULL) { emsg(_(e_backslash_should_be_followed_by)); return; } if (*cmd != '&') which_pat = RE_SEARCH; // use last '/' pattern pat = (char_u *)""; // empty search pattern delimiter = *cmd++; // remember delimiter character } else // find the end of the regexp { which_pat = RE_LAST; // use last used regexp delimiter = *cmd++; // remember delimiter character pat = cmd; // remember start of search pat cmd = skip_regexp_ex(cmd, delimiter, magic_isset(), &eap->arg, NULL, NULL); if (cmd[0] == delimiter) // end delimiter found *cmd++ = NUL; // replace it with a NUL } /* * Small incompatibility: vi sees '\n' as end of the command, but in * Vim we want to use '\n' to find/substitute a NUL. */ sub = cmd; // remember the start of the substitution cmd = skip_substitute(cmd, delimiter); if (!eap->skip) { // In POSIX vi ":s/pat/%/" uses the previous subst. string. if (STRCMP(sub, "%") == 0 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL) { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } sub = old_sub; } else { vim_free(old_sub); old_sub = vim_strsave(sub); } } } else if (!eap->skip) // use previous pattern and substitution { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } pat = NULL; // search_regcomp() will use previous pattern sub = old_sub; // Vi compatibility quirk: repeating with ":s" keeps the cursor in the // last column after using "$". endcolumn = (curwin->w_curswant == MAXCOL); } // Recognize ":%s/\n//" and turn it into a join command, which is much // more efficient. // TODO: find a generic solution to make line-joining operations more // efficient, avoid allocating a string that grows in size. if (pat != NULL && STRCMP(pat, "\\n") == 0 && *sub == NUL && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l' || *cmd == 'p' || *cmd == '#')))) { linenr_T joined_lines_count; if (eap->skip) return; curwin->w_cursor.lnum = eap->line1; if (*cmd == 'l') eap->flags = EXFLAG_LIST; else if (*cmd == '#') eap->flags = EXFLAG_NR; else if (*cmd == 'p') eap->flags = EXFLAG_PRINT; // The number of lines joined is the number of lines in the range plus // one. One less when the last line is included. joined_lines_count = eap->line2 - eap->line1 + 1; if (eap->line2 < curbuf->b_ml.ml_line_count) ++joined_lines_count; if (joined_lines_count > 1) { (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE); sub_nsubs = joined_lines_count - 1; sub_nlines = 1; (void)do_sub_msg(FALSE); ex_may_print(eap); } if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) save_re_pat(RE_SUBST, pat, magic_isset()); // put pattern in history add_to_history(HIST_SEARCH, pat, TRUE, NUL); return; } /* * Find trailing options. When '&' is used, keep old options. */ if (*cmd == '&') ++cmd; else { #ifdef FEAT_EVAL if (in_vim9script()) { // ignore 'gdefault' and 'edcompatible' subflags.do_all = FALSE; subflags.do_ask = FALSE; } else #endif if (!p_ed) { if (p_gd) // default is global on subflags.do_all = TRUE; else subflags.do_all = FALSE; subflags.do_ask = FALSE; } subflags.do_error = TRUE; subflags.do_print = FALSE; subflags.do_list = FALSE; subflags.do_count = FALSE; subflags.do_number = FALSE; subflags.do_ic = 0; } while (*cmd) { /* * Note that 'g' and 'c' are always inverted, also when p_ed is off. * 'r' is never inverted. */ if (*cmd == 'g') subflags.do_all = !subflags.do_all; else if (*cmd == 'c') subflags.do_ask = !subflags.do_ask; else if (*cmd == 'n') subflags.do_count = TRUE; else if (*cmd == 'e') subflags.do_error = !subflags.do_error; else if (*cmd == 'r') // use last used regexp which_pat = RE_LAST; else if (*cmd == 'p') subflags.do_print = TRUE; else if (*cmd == '#') { subflags.do_print = TRUE; subflags.do_number = TRUE; } else if (*cmd == 'l') { subflags.do_print = TRUE; subflags.do_list = TRUE; } else if (*cmd == 'i') // ignore case subflags.do_ic = 'i'; else if (*cmd == 'I') // don't ignore case subflags.do_ic = 'I'; else break; ++cmd; } if (subflags.do_count) subflags.do_ask = FALSE; save_do_all = subflags.do_all; save_do_ask = subflags.do_ask; /* * check for a trailing count */ cmd = skipwhite(cmd); if (VIM_ISDIGIT(*cmd)) { i = getdigits(&cmd); if (i <= 0 && !eap->skip && subflags.do_error) { emsg(_(e_positive_count_required)); return; } eap->line1 = eap->line2; eap->line2 += i - 1; if (eap->line2 > curbuf->b_ml.ml_line_count) eap->line2 = curbuf->b_ml.ml_line_count; } /* * check for trailing command or garbage */ cmd = skipwhite(cmd); if (*cmd && *cmd != '"') // if not end-of-line or comment { set_nextcmd(eap, cmd); if (eap->nextcmd == NULL) { semsg(_(e_trailing_characters_str), cmd); return; } } if (eap->skip) // not executing commands, only parsing return; if (!subflags.do_count && !curbuf->b_p_ma) { // Substitution is not allowed in non-'modifiable' buffer emsg(_(e_cannot_make_changes_modifiable_is_off)); return; } if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL) { if (subflags.do_error) emsg(_(e_invalid_command)); return; } // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' if (subflags.do_ic == 'i') regmatch.rmm_ic = TRUE; else if (subflags.do_ic == 'I') regmatch.rmm_ic = FALSE; sub_firstline = NULL; /* * If the substitute pattern starts with "\=" then it's an expression. * Make a copy, a recursive function may free it. * Otherwise, '~' in the substitute pattern is replaced with the old * pattern. We do it here once to avoid it to be replaced over and over * again. */ if (sub[0] == '\\' && sub[1] == '=') { sub = vim_strsave(sub); if (sub == NULL) return; sub_copy = sub; } else sub = regtilde(sub, magic_isset()); /* * Check for a match on each line. */ line2 = eap->line2; for (lnum = eap->line1; lnum <= line2 && !(got_quit #if defined(FEAT_EVAL) || aborting() #endif ); ++lnum) { nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0, NULL, NULL); if (nmatch) { colnr_T copycol; colnr_T matchcol; colnr_T prev_matchcol = MAXCOL; char_u *new_end, *new_start = NULL; unsigned new_start_len = 0; char_u *p1; int did_sub = FALSE; int lastone; int len, copy_len, needed_len; long nmatch_tl = 0; // nr of lines matched below lnum int do_again; // do it again after joining lines int skip_match = FALSE; linenr_T sub_firstlnum; // nr of first sub line #ifdef FEAT_PROP_POPUP int apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE; colnr_T total_added = 0; #endif /* * The new text is build up step by step, to avoid too much * copying. There are these pieces: * sub_firstline The old text, unmodified. * copycol Column in the old text where we started * looking for a match; from here old text still * needs to be copied to the new text. * matchcol Column number of the old text where to look * for the next match. It's just after the * previous match or one further. * prev_matchcol Column just after the previous match (if any). * Mostly equal to matchcol, except for the first * match and after skipping an empty match. * regmatch.*pos Where the pattern matched in the old text. * new_start The new text, all that has been produced so * far. * new_end The new text, where to append new text. * * lnum The line number where we found the start of * the match. Can be below the line we searched * when there is a \n before a \zs in the * pattern. * sub_firstlnum The line number in the buffer where to look * for a match. Can be different from "lnum" * when the pattern or substitute string contains * line breaks. * * Special situations: * - When the substitute string contains a line break, the part up * to the line break is inserted in the text, but the copy of * the original line is kept. "sub_firstlnum" is adjusted for * the inserted lines. * - When the matched pattern contains a line break, the old line * is taken from the line at the end of the pattern. The lines * in the match are deleted later, "sub_firstlnum" is adjusted * accordingly. * * The new text is built up in new_start[]. It has some extra * room to avoid using alloc()/free() too often. new_start_len is * the length of the allocated memory at new_start. * * Make a copy of the old line, so it won't be taken away when * updating the screen or handling a multi-line match. The "old_" * pointers point into this copy. */ sub_firstlnum = lnum; copycol = 0; matchcol = 0; // At first match, remember current cursor position. if (!got_match) { setpcmark(); got_match = TRUE; } /* * Loop until nothing more to replace in this line. * 1. Handle match with empty string. * 2. If do_ask is set, ask for confirmation. * 3. substitute the string. * 4. if do_all is set, find next match * 5. break if there isn't another match in this line */ for (;;) { // Advance "lnum" to the line where the match starts. The // match does not start in the first line when there is a line // break before \zs. if (regmatch.startpos[0].lnum > 0) { lnum += regmatch.startpos[0].lnum; sub_firstlnum += regmatch.startpos[0].lnum; nmatch -= regmatch.startpos[0].lnum; VIM_CLEAR(sub_firstline); } // Match might be after the last line for "\n\zs" matching at // the end of the last line. if (lnum > curbuf->b_ml.ml_line_count) break; if (sub_firstline == NULL) { sub_firstline = vim_strsave(ml_get(sub_firstlnum)); if (sub_firstline == NULL) { vim_free(new_start); goto outofmem; } } // Save the line number of the last change for the final // cursor position (just like Vi). curwin->w_cursor.lnum = lnum; do_again = FALSE; /* * 1. Match empty string does not count, except for first * match. This reproduces the strange vi behaviour. * This also catches endless loops. */ if (matchcol == prev_matchcol && regmatch.endpos[0].lnum == 0 && matchcol == regmatch.endpos[0].col) { if (sub_firstline[matchcol] == NUL) // We already were at the end of the line. Don't look // for a match in this line again. skip_match = TRUE; else { // search for a match at next column if (has_mbyte) matchcol += mb_ptr2len(sub_firstline + matchcol); else ++matchcol; } goto skip; } // Normally we continue searching for a match just after the // previous match. matchcol = regmatch.endpos[0].col; prev_matchcol = matchcol; /* * 2. If do_count is set only increase the counter. * If do_ask is set, ask for confirmation. */ if (subflags.do_count) { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":s/\nB\@=//gc" get stuck. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); nmatch = 1; skip_match = TRUE; } sub_nsubs++; did_sub = TRUE; #ifdef FEAT_EVAL // Skip the substitution, unless an expression is used, // then it is evaluated in the sandbox. if (!(sub[0] == '\\' && sub[1] == '=')) #endif goto skip; } if (subflags.do_ask) { int typed = 0; // change State to CONFIRM, so that the mouse works // properly save_State = State; State = CONFIRM; setmouse(); // disable mouse in xterm curwin->w_cursor.col = regmatch.startpos[0].col; if (curwin->w_p_crb) do_check_cursorbind(); // When 'cpoptions' contains "u" don't sync undo when // asking for confirmation. if (vim_strchr(p_cpo, CPO_UNDO) != NULL) ++no_u_sync; /* * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. */ while (subflags.do_ask) { if (exmode_active) { char_u *resp; colnr_T sc, ec; print_line_no_prefix(lnum, subflags.do_number, subflags.do_list); getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL); curwin->w_cursor.col = regmatch.endpos[0].col - 1; if (curwin->w_cursor.col < 0) curwin->w_cursor.col = 0; getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec); curwin->w_cursor.col = regmatch.startpos[0].col; if (subflags.do_number || curwin->w_p_nu) { int numw = number_width(curwin) + 1; sc += numw; ec += numw; } msg_start(); for (i = 0; i < (long)sc; ++i) msg_putchar(' '); for ( ; i <= (long)ec; ++i) msg_putchar('^'); resp = getexmodeline('?', NULL, 0, TRUE); if (resp != NULL) { typed = *resp; vim_free(resp); } } else { char_u *orig_line = NULL; int len_change = 0; int save_p_lz = p_lz; #ifdef FEAT_FOLDING int save_p_fen = curwin->w_p_fen; curwin->w_p_fen = FALSE; #endif // Invert the matched string. // Remove the inversion afterwards. temp = RedrawingDisabled; RedrawingDisabled = 0; // avoid calling update_screen() in vgetorpeek() p_lz = FALSE; if (new_start != NULL) { // There already was a substitution, we would // like to show this to the user. We cannot // really update the line, it would change // what matches. Temporarily replace the line // and change it back afterwards. orig_line = vim_strsave(ml_get(lnum)); if (orig_line != NULL) { char_u *new_line = concat_str(new_start, sub_firstline + copycol); if (new_line == NULL) VIM_CLEAR(orig_line); else { // Position the cursor relative to the // end of the line, the previous // substitute may have inserted or // deleted characters before the // cursor. len_change = (int)STRLEN(new_line) - (int)STRLEN(orig_line); curwin->w_cursor.col += len_change; ml_replace(lnum, new_line, FALSE); } } } search_match_lines = regmatch.endpos[0].lnum - regmatch.startpos[0].lnum; search_match_endcol = regmatch.endpos[0].col + len_change; highlight_match = TRUE; update_topline(); validate_cursor(); update_screen(SOME_VALID); highlight_match = FALSE; redraw_later(SOME_VALID); #ifdef FEAT_FOLDING curwin->w_p_fen = save_p_fen; #endif if (msg_row == Rows - 1) msg_didout = FALSE; // avoid a scroll-up msg_starthere(); i = msg_scroll; msg_scroll = 0; // truncate msg when // needed msg_no_more = TRUE; // write message same highlighting as for // wait_return smsg_attr(HL_ATTR(HLF_R), _("replace with %s (y/n/a/q/l/^E/^Y)?"), sub); msg_no_more = FALSE; msg_scroll = i; showruler(TRUE); windgoto(msg_row, msg_col); RedrawingDisabled = temp; #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif ++no_mapping; // don't map this key ++allow_keys; // allow special keys typed = plain_vgetc(); --allow_keys; --no_mapping; // clear the question msg_didout = FALSE; // don't scroll up msg_col = 0; gotocmdline(TRUE); p_lz = save_p_lz; // restore the line if (orig_line != NULL) ml_replace(lnum, orig_line, FALSE); } need_wait_return = FALSE; // no hit-return prompt if (typed == 'q' || typed == ESC || typed == Ctrl_C #ifdef UNIX || typed == intr_char #endif ) { got_quit = TRUE; break; } if (typed == 'n') break; if (typed == 'y') break; if (typed == 'l') { // last: replace and then stop subflags.do_all = FALSE; line2 = lnum; break; } if (typed == 'a') { subflags.do_ask = FALSE; break; } if (typed == Ctrl_E) scrollup_clamp(); else if (typed == Ctrl_Y) scrolldown_clamp(); } State = save_State; setmouse(); if (vim_strchr(p_cpo, CPO_UNDO) != NULL) --no_u_sync; if (typed == 'n') { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc" // get stuck when pressing 'n'. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); skip_match = TRUE; } goto skip; } if (got_quit) goto skip; } // Move the cursor to the start of the match, so that we can // use "\=col("."). curwin->w_cursor.col = regmatch.startpos[0].col; /* * 3. substitute the string. */ #ifdef FEAT_EVAL save_ma = curbuf->b_p_ma; if (subflags.do_count) { // prevent accidentally changing the buffer by a function curbuf->b_p_ma = FALSE; sandbox++; } // Save flags for recursion. They can change for e.g. // :s/^/\=execute("s#^##gn") subflags_save = subflags; #endif // get length of substitution part sublen = vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, sub_firstline, FALSE, magic_isset(), TRUE); #ifdef FEAT_EVAL // If getting the substitute string caused an error, don't do // the replacement. // Don't keep flags set by a recursive call. subflags = subflags_save; if (aborting() || subflags.do_count) { curbuf->b_p_ma = save_ma; if (sandbox > 0) sandbox--; goto skip; } #endif // When the match included the "$" of the last line it may // go beyond the last line of the buffer. if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1) { nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1; skip_match = TRUE; } // Need room for: // - result so far in new_start (not for first sub in line) // - original text up to match // - length of substituted part // - original text after match // Adjust text properties here, since we have all information // needed. if (nmatch == 1) { p1 = sub_firstline; #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { int bytes_added = sublen - 1 - (regmatch.endpos[0].col - regmatch.startpos[0].col); // When text properties are changed, need to save for // undo first, unless done already. if (adjust_prop_columns(lnum, total_added + regmatch.startpos[0].col, bytes_added, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; // Offset for column byte number of the text property // in the resulting buffer afterwards. total_added += bytes_added; } #endif } else { p1 = ml_get(sub_firstlnum + nmatch - 1); nmatch_tl += nmatch - 1; } copy_len = regmatch.startpos[0].col - copycol; needed_len = copy_len + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col) + sublen + 1; if (new_start == NULL) { /* * Get some space for a temporary buffer to do the * substitution into (and some extra space to avoid * too many calls to alloc()/free()). */ new_start_len = needed_len + 50; if ((new_start = alloc(new_start_len)) == NULL) goto outofmem; *new_start = NUL; new_end = new_start; } else { /* * Check if the temporary buffer is long enough to do the * substitution into. If not, make it larger (with a bit * extra to avoid too many calls to alloc()/free()). */ len = (unsigned)STRLEN(new_start); needed_len += len; if (needed_len > (int)new_start_len) { new_start_len = needed_len + 50; if ((p1 = alloc(new_start_len)) == NULL) { vim_free(new_start); goto outofmem; } mch_memmove(p1, new_start, (size_t)(len + 1)); vim_free(new_start); new_start = p1; } new_end = new_start + len; } /* * copy the text up to the part that matched */ mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len); new_end += copy_len; (void)vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, new_end, TRUE, magic_isset(), TRUE); sub_nsubs++; did_sub = TRUE; // Move the cursor to the start of the line, to avoid that it // is beyond the end of the line after the substitution. curwin->w_cursor.col = 0; // For a multi-line match, make a copy of the last matched // line and continue in that one. if (nmatch > 1) { sub_firstlnum += nmatch - 1; vim_free(sub_firstline); sub_firstline = vim_strsave(ml_get(sub_firstlnum)); // When going beyond the last line, stop substituting. if (sub_firstlnum <= line2) do_again = TRUE; else subflags.do_all = FALSE; } // Remember next character to be copied. copycol = regmatch.endpos[0].col; if (skip_match) { // Already hit end of the buffer, sub_firstlnum is one // less than what it ought to be. vim_free(sub_firstline); sub_firstline = vim_strsave((char_u *)""); copycol = 0; } /* * Now the trick is to replace CTRL-M chars with a real line * break. This would make it impossible to insert a CTRL-M in * the text. The line break can be avoided by preceding the * CTRL-M with a backslash. To be able to insert a backslash, * they must be doubled in the string and are halved here. * That is Vi compatible. */ for (p1 = new_end; *p1; ++p1) { if (p1[0] == '\\' && p1[1] != NUL) // remove backslash { STRMOVE(p1, p1 + 1); #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { // When text properties are changed, need to save // for undo first, unless done already. if (adjust_prop_columns(lnum, (colnr_T)(p1 - new_start), -1, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; } #endif } else if (*p1 == CAR) { if (u_inssub(lnum) == OK) // prepare for undo { colnr_T plen = (colnr_T)(p1 - new_start + 1); *p1 = NUL; // truncate up to the CR ml_append(lnum - 1, new_start, plen, FALSE); mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L); if (subflags.do_ask) appended_lines(lnum - 1, 1L); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } #ifdef FEAT_PROP_POPUP adjust_props_for_split(lnum + 1, lnum, plen, 1); #endif // all line numbers increase ++sub_firstlnum; ++lnum; ++line2; // move the cursor to the new line, like Vi ++curwin->w_cursor.lnum; // copy the rest STRMOVE(new_start, p1 + 1); p1 = new_start - 1; } } else if (has_mbyte) p1 += (*mb_ptr2len)(p1) - 1; } /* * 4. If do_all is set, find next match. * Prevent endless loop with patterns that match empty * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g. * But ":s/\n/#/" is OK. */ skip: // We already know that we did the last subst when we are at // the end of the line, except that a pattern like // "bar\|\nfoo" may match at the NUL. "lnum" can be below // "line2" when there is a \zs in the pattern after a line // break. lastone = (skip_match || got_int || got_quit || lnum > line2 || !(subflags.do_all || do_again) || (sub_firstline[matchcol] == NUL && nmatch <= 1 && !re_multiline(regmatch.regprog))); nmatch = -1; /* * Replace the line in the buffer when needed. This is * skipped when there are more matches. * The check for nmatch_tl is needed for when multi-line * matching must replace the lines before trying to do another * match, otherwise "\@<=" won't work. * When the match starts below where we start searching also * need to replace the line first (using \zs after \n). */ if (lastone || nmatch_tl > 0 || (nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL)) == 0 || regmatch.startpos[0].lnum > 0) { if (new_start != NULL) { /* * Copy the rest of the line, that didn't match. * "matchcol" has to be adjusted, we use the end of * the line as reference, because the substitute may * have changed the number of characters. Same for * "prev_matchcol". */ STRCAT(new_start, sub_firstline + copycol); matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; if (u_savesub(lnum) != OK) break; ml_replace(lnum, new_start, TRUE); if (nmatch_tl > 0) { /* * Matched lines have now been substituted and are * useless, delete them. The part after the match * has been appended to new_start, we don't need * it in the buffer. */ ++lnum; if (u_savedel(lnum, nmatch_tl) != OK) break; for (i = 0; i < nmatch_tl; ++i) ml_delete(lnum); mark_adjust(lnum, lnum + nmatch_tl - 1, (long)MAXLNUM, -nmatch_tl); if (subflags.do_ask) deleted_lines(lnum, nmatch_tl); --lnum; line2 -= nmatch_tl; // nr of lines decreases nmatch_tl = 0; } // When asking, undo is saved each time, must also set // changed flag each time. if (subflags.do_ask) changed_bytes(lnum, 0); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } sub_firstlnum = lnum; vim_free(sub_firstline); // free the temp buffer sub_firstline = new_start; new_start = NULL; matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; copycol = 0; } if (nmatch == -1 && !lastone) nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL); /* * 5. break if there isn't another match in this line */ if (nmatch <= 0) { // If the match found didn't start where we were // searching, do the next search in the line where we // found the match. if (nmatch == -1) lnum -= regmatch.startpos[0].lnum; break; } } line_breakcheck(); } if (did_sub) ++sub_nlines; vim_free(new_start); // for when substitute was cancelled VIM_CLEAR(sub_firstline); // free the copy of the original line } line_breakcheck(); } if (first_line != 0) { // Need to subtract the number of added lines from "last_line" to get // the line number before the change (same as adding the number of // deleted lines). i = curbuf->b_ml.ml_line_count - old_line_count; changed_lines(first_line, 0, last_line - i, i); } outofmem: vim_free(sub_firstline); // may have to free allocated copy of the line // ":s/pat//n" doesn't move the cursor if (subflags.do_count) curwin->w_cursor = old_cursor; if (sub_nsubs > start_nsubs) { if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '[ and '] marks. curbuf->b_op_start.lnum = eap->line1; curbuf->b_op_end.lnum = line2; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } if (!global_busy) { // when interactive leave cursor on the match if (!subflags.do_ask) { if (endcolumn) coladvance((colnr_T)MAXCOL); else beginline(BL_WHITE | BL_FIX); } if (!do_sub_msg(subflags.do_count) && subflags.do_ask) msg(""); } else global_need_beginline = TRUE; if (subflags.do_print) print_line(curwin->w_cursor.lnum, subflags.do_number, subflags.do_list); } else if (!global_busy) { if (got_int) // interrupted emsg(_(e_interrupted)); else if (got_match) // did find something but nothing substituted msg(""); else if (subflags.do_error) // nothing found semsg(_(e_pattern_not_found_str), get_search_pat()); } #ifdef FEAT_FOLDING if (subflags.do_ask && hasAnyFolding(curwin)) // Cursor position may require updating changed_window_setting(); #endif vim_regfree(regmatch.regprog); vim_free(sub_copy); // Restore the flag values, they can be used for ":&&". subflags.do_all = save_do_all; subflags.do_ask = save_do_ask; }
291806400828750764975961626021835315123
ex_cmds.c
316790051330868655972553819181856040285
CWE-416
CVE-2022-0413
Use After Free in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0413
200,113
ImageMagick
389ecc365a7c61404ba078a72c3fa5a3cf1b4101
https://github.com/ImageMagick/ImageMagick
https://github.com/ImageMagick/ImageMagick/commit/389ecc365a7c61404ba078a72c3fa5a3cf1b4101
https://github.com/ImageMagick/ImageMagick/issues/1221
1
static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotated_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; quantum_info=(QuantumInfo *) NULL; (void) SeekBlob(image,0,SEEK_SET); while (EOFBlob(image) == MagickFalse) { /* Object parser loop. */ ldblk=ReadBlobLSBLong(image); if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf != 0) && (HDR.imagf != 1)) break; if (HDR.nameLen > 0xFFFF) return(DestroyImageList(image)); for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; if ((image->columns == 0) || (image->rows == 0)) return(DestroyImageList(image)); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); if(HDR.imagf==1) ldblk *= 2; SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR); if ((image->columns == 0) || (image->rows == 0)) return(image->previous == (Image *) NULL ? DestroyImageList(image) : image); goto skip_reading_current; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(DestroyImageList(image)); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(image,q,(int) image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception); else InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception); } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } rotated_image=RotateImage(image,90.0,exception); if (rotated_image != (Image *) NULL) { rotated_image->page.x=0; rotated_image->page.y=0; rotated_image->colors = image->colors; DestroyBlob(rotated_image); rotated_image->blob=ReferenceBlob(image->blob); AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ skip_reading_current: AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
285338942932126464684406061663699404409
mat.c
152895055268444149031499537279657208937
CWE-787
CVE-2018-14551
The ReadMATImageV4 function in coders/mat.c in ImageMagick 7.0.8-7 uses an uninitialized variable, leading to memory corruption.
https://nvd.nist.gov/vuln/detail/CVE-2018-14551
299,319
ImageMagick
389ecc365a7c61404ba078a72c3fa5a3cf1b4101
https://github.com/ImageMagick/ImageMagick
https://github.com/ImageMagick/ImageMagick/commit/389ecc365a7c61404ba078a72c3fa5a3cf1b4101
https://github.com/ImageMagick/ImageMagick/issues/1221
0
static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotated_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; quantum_info=(QuantumInfo *) NULL; (void) SeekBlob(image,0,SEEK_SET); status=MagickTrue; while (EOFBlob(image) == MagickFalse) { /* Object parser loop. */ ldblk=ReadBlobLSBLong(image); if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf != 0) && (HDR.imagf != 1)) break; if (HDR.nameLen > 0xFFFF) return(DestroyImageList(image)); for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; if ((image->columns == 0) || (image->rows == 0)) return(DestroyImageList(image)); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); if(HDR.imagf==1) ldblk *= 2; SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR); if ((image->columns == 0) || (image->rows == 0)) return(image->previous == (Image *) NULL ? DestroyImageList(image) : image); goto skip_reading_current; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(DestroyImageList(image)); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(image,q,(int) image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception); else InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception); } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } rotated_image=RotateImage(image,90.0,exception); if (rotated_image != (Image *) NULL) { rotated_image->page.x=0; rotated_image->page.y=0; rotated_image->colors = image->colors; DestroyBlob(rotated_image); rotated_image->blob=ReferenceBlob(image->blob); AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ skip_reading_current: AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
27945736353263207032658277682673712117
mat.c
197422043282011428208750932279920042610
CWE-787
CVE-2018-14551
The ReadMATImageV4 function in coders/mat.c in ImageMagick 7.0.8-7 uses an uninitialized variable, leading to memory corruption.
https://nvd.nist.gov/vuln/detail/CVE-2018-14551
200,157
exim
e2f5dc151e2e79058e93924e6d35510557f0535d
https://github.com/Exim/exim
http://git.exim.org/exim.git/commit/e2f5dc151e2e79058e93924e6d35510557f0535d
Check configure file permissions even for non-default files if still privileged (Bug 1044, CVE-2010-4345)
1
readconf_main(void) { int sep = 0; struct stat statbuf; uschar *s, *filename; uschar *list = config_main_filelist; /* Loop through the possible file names */ while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)) != NULL) { /* Cut out all the fancy processing unless specifically wanted */ #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID) uschar *suffix = filename + Ustrlen(filename); /* Try for the node-specific file if a node name exists */ #ifdef CONFIGURE_FILE_USE_NODE struct utsname uts; if (uname(&uts) >= 0) { #ifdef CONFIGURE_FILE_USE_EUID sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename); config_file = Ufopen(filename, "rb"); if (config_file == NULL) #endif /* CONFIGURE_FILE_USE_EUID */ { sprintf(CS suffix, ".%.256s", uts.nodename); config_file = Ufopen(filename, "rb"); } } #endif /* CONFIGURE_FILE_USE_NODE */ /* Otherwise, try the generic name, possibly with the euid added */ #ifdef CONFIGURE_FILE_USE_EUID if (config_file == NULL) { sprintf(CS suffix, ".%ld", (long int)original_euid); config_file = Ufopen(filename, "rb"); } #endif /* CONFIGURE_FILE_USE_EUID */ /* Finally, try the unadorned name */ if (config_file == NULL) { *suffix = 0; config_file = Ufopen(filename, "rb"); } #else /* if neither defined */ /* This is the common case when the fancy processing is not included. */ config_file = Ufopen(filename, "rb"); #endif /* If the file does not exist, continue to try any others. For any other error, break out (and die). */ if (config_file != NULL || errno != ENOENT) break; } /* On success, save the name for verification; config_filename is used when logging configuration errors (it changes for .included files) whereas config_main_filename is the name shown by -bP. Failure to open a configuration file is a serious disaster. */ if (config_file != NULL) { config_filename = config_main_filename = string_copy(filename); } else { if (filename == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): " "%s", config_main_filelist); else log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno, "configuration file %s", filename)); } /* Check the status of the file we have opened, unless it was specified on the command line, in which case privilege was given away at the start. */ if (!config_changed) { if (fstat(fileno(config_file), &statbuf) != 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s", big_buffer); if ((statbuf.st_uid != root_uid /* owner not root */ #ifdef CONFIGURE_OWNER && statbuf.st_uid != config_uid /* owner not the special one */ #endif ) || /* or */ (statbuf.st_gid != root_gid /* group not root & */ #ifdef CONFIGURE_GROUP && statbuf.st_gid != config_gid /* group not the special one */ #endif && (statbuf.st_mode & 020) != 0) || /* group writeable */ /* or */ ((statbuf.st_mode & 2) != 0)) /* world writeable */ log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the " "wrong owner, group, or mode", big_buffer); } /* Process the main configuration settings. They all begin with a lower case letter. If we see something starting with an upper case letter, it is taken as a macro definition. */ while ((s = get_config_line()) != NULL) { if (isupper(s[0])) read_macro_assignment(s); else if (Ustrncmp(s, "domainlist", 10) == 0) read_named_list(&domainlist_anchor, &domainlist_count, MAX_NAMED_LIST, s+10, US"domain list"); else if (Ustrncmp(s, "hostlist", 8) == 0) read_named_list(&hostlist_anchor, &hostlist_count, MAX_NAMED_LIST, s+8, US"host list"); else if (Ustrncmp(s, US"addresslist", 11) == 0) read_named_list(&addresslist_anchor, &addresslist_count, MAX_NAMED_LIST, s+11, US"address list"); else if (Ustrncmp(s, US"localpartlist", 13) == 0) read_named_list(&localpartlist_anchor, &localpartlist_count, MAX_NAMED_LIST, s+13, US"local part list"); else (void) readconf_handle_option(s, optionlist_config, optionlist_config_size, NULL, US"main option \"%s\" unknown"); } /* If local_sender_retain is set, local_from_check must be unset. */ if (local_sender_retain && local_from_check) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and " "local_sender_retain are set; this combination is not allowed"); /* If the timezone string is empty, set it to NULL, implying no TZ variable wanted. */ if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL; /* The max retry interval must not be greater than 24 hours. */ if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60; /* remote_max_parallel must be > 0 */ if (remote_max_parallel <= 0) remote_max_parallel = 1; /* Save the configured setting of freeze_tell, so we can re-instate it at the start of a new SMTP message. */ freeze_tell_config = freeze_tell; /* The primary host name may be required for expansion of spool_directory and log_file_path, so make sure it is set asap. It is obtained from uname(), but if that yields an unqualified value, make a FQDN by using gethostbyname to canonize it. Some people like upper case letters in their host names, so we don't force the case. */ if (primary_hostname == NULL) { uschar *hostname; struct utsname uts; if (uname(&uts) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name"); hostname = US uts.nodename; if (Ustrchr(hostname, '.') == NULL) { int af = AF_INET; struct hostent *hostdata; #if HAVE_IPV6 if (!disable_ipv6 && (dns_ipv4_lookup == NULL || match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN, TRUE, NULL) != OK)) af = AF_INET6; #else af = AF_INET; #endif for (;;) { #if HAVE_IPV6 #if HAVE_GETIPNODEBYNAME int error_num; hostdata = getipnodebyname(CS hostname, af, 0, &error_num); #else hostdata = gethostbyname2(CS hostname, af); #endif #else hostdata = gethostbyname(CS hostname); #endif if (hostdata != NULL) { hostname = US hostdata->h_name; break; } if (af == AF_INET) break; af = AF_INET; } } primary_hostname = string_copy(hostname); } /* Set up default value for smtp_active_hostname */ smtp_active_hostname = primary_hostname; /* If spool_directory wasn't set in the build-time configuration, it must have got set above. Of course, writing to the log may not work if log_file_path is not set, but it will at least get to syslog or somewhere, with any luck. */ if (*spool_directory == 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot " "proceed"); /* Expand the spool directory name; it may, for example, contain the primary host name. Same comment about failure. */ s = expand_string(spool_directory); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory " "\"%s\": %s", spool_directory, expand_string_message); spool_directory = s; /* Expand log_file_path, which must contain "%s" in any component that isn't the null string or "syslog". It is also allowed to contain one instance of %D. However, it must NOT contain % followed by anything else. */ if (*log_file_path != 0) { uschar *ss, *sss; int sep = ':'; /* Fixed for log file path */ s = expand_string(log_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path " "\"%s\": %s", log_file_path, expand_string_message); ss = s; while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL) { uschar *t; if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue; t = Ustrstr(sss, "%s"); if (t == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not " "contain \"%%s\"", sss); *t = 'X'; t = Ustrchr(sss, '%'); if (t != NULL) { if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains " "unexpected \"%%\" character", s); } } log_file_path = s; } /* Interpret syslog_facility into an integer argument for 'ident' param to openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the leading "log_". */ if (syslog_facility_str != NULL) { int i; uschar *s = syslog_facility_str; if ((Ustrlen(syslog_facility_str) >= 4) && (strncmpic(syslog_facility_str, US"log_", 4) == 0)) s += 4; for (i = 0; i < syslog_list_size; i++) { if (strcmpic(s, syslog_list[i].name) == 0) { syslog_facility = syslog_list[i].value; break; } } if (i >= syslog_list_size) { log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "failed to interpret syslog_facility \"%s\"", syslog_facility_str); } } /* Expand pid_file_path */ if (*pid_file_path != 0) { s = expand_string(pid_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path " "\"%s\": %s", pid_file_path, expand_string_message); pid_file_path = s; } /* Compile the regex for matching a UUCP-style "From_" line in an incoming message. */ regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE); /* Unpick the SMTP rate limiting options, if set */ if (smtp_ratelimit_mail != NULL) { unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold, &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit); } if (smtp_ratelimit_rcpt != NULL) { unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold, &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit); } /* The qualify domains default to the primary host name */ if (qualify_domain_sender == NULL) qualify_domain_sender = primary_hostname; if (qualify_domain_recipient == NULL) qualify_domain_recipient = qualify_domain_sender; /* Setting system_filter_user in the configuration sets the gid as well if a name is given, but a numerical value does not. */ if (system_filter_uid_set && !system_filter_gid_set) { struct passwd *pw = getpwuid(system_filter_uid); if (pw == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld", (long int)system_filter_uid); system_filter_gid = pw->pw_gid; system_filter_gid_set = TRUE; } /* If the errors_reply_to field is set, check that it is syntactically valid and ensure it contains a domain. */ if (errors_reply_to != NULL) { uschar *errmess; int start, end, domain; uschar *recipient = parse_extract_address(errors_reply_to, &errmess, &start, &end, &domain, FALSE); if (recipient == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "error in errors_reply_to (%s): %s", errors_reply_to, errmess); if (domain == 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "errors_reply_to (%s) does not contain a domain", errors_reply_to); } /* If smtp_accept_queue or smtp_accept_max_per_host is set, then smtp_accept_max must also be set. */ if (smtp_accept_max == 0 && (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL)) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "smtp_accept_max must be set if smtp_accept_queue or " "smtp_accept_max_per_host is set"); /* Set up the host number if anything is specified. It is an expanded string so that it can be computed from the host name, for example. We do this last so as to ensure that everything else is set up before the expansion. */ if (host_number_string != NULL) { uschar *end; uschar *s = expand_string(host_number_string); long int n = Ustrtol(s, &end, 0); while (isspace(*end)) end++; if (*end != 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number value is not a number: %s", s); if (n > LOCALHOST_MAX) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number is greater than the maximum allowed value (%d)", LOCALHOST_MAX); host_number = n; } #ifdef SUPPORT_TLS /* If tls_verify_hosts is set, tls_verify_certificates must also be set */ if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) && tls_verify_certificates == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "tls_%sverify_hosts is set, but tls_verify_certificates is not set", (tls_verify_hosts != NULL)? "" : "try_"); /* If openssl_options is set, validate it */ if (openssl_options != NULL) { # ifdef USE_GNUTLS log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options is set but we're using GnuTLS"); # else long dummy; if (!(tls_openssl_options_parse(openssl_options, &dummy))) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options parse error: %s", openssl_options); # endif } #endif }
74987850300315727501245353003929658606
readconf.c
217124537327695199621061480517955399637
CWE-264
CVE-2010-4345
Exim 4.72 and earlier allows local users to gain privileges by leveraging the ability of the exim user account to specify an alternate configuration file with a directive that contains arbitrary commands, as demonstrated by the spool_directory directive.
https://nvd.nist.gov/vuln/detail/CVE-2010-4345
299,905
exim
e2f5dc151e2e79058e93924e6d35510557f0535d
https://github.com/Exim/exim
http://git.exim.org/exim.git/commit/e2f5dc151e2e79058e93924e6d35510557f0535d
Check configure file permissions even for non-default files if still privileged (Bug 1044, CVE-2010-4345)
0
readconf_main(void) { int sep = 0; struct stat statbuf; uschar *s, *filename; uschar *list = config_main_filelist; /* Loop through the possible file names */ while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)) != NULL) { /* Cut out all the fancy processing unless specifically wanted */ #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID) uschar *suffix = filename + Ustrlen(filename); /* Try for the node-specific file if a node name exists */ #ifdef CONFIGURE_FILE_USE_NODE struct utsname uts; if (uname(&uts) >= 0) { #ifdef CONFIGURE_FILE_USE_EUID sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename); config_file = Ufopen(filename, "rb"); if (config_file == NULL) #endif /* CONFIGURE_FILE_USE_EUID */ { sprintf(CS suffix, ".%.256s", uts.nodename); config_file = Ufopen(filename, "rb"); } } #endif /* CONFIGURE_FILE_USE_NODE */ /* Otherwise, try the generic name, possibly with the euid added */ #ifdef CONFIGURE_FILE_USE_EUID if (config_file == NULL) { sprintf(CS suffix, ".%ld", (long int)original_euid); config_file = Ufopen(filename, "rb"); } #endif /* CONFIGURE_FILE_USE_EUID */ /* Finally, try the unadorned name */ if (config_file == NULL) { *suffix = 0; config_file = Ufopen(filename, "rb"); } #else /* if neither defined */ /* This is the common case when the fancy processing is not included. */ config_file = Ufopen(filename, "rb"); #endif /* If the file does not exist, continue to try any others. For any other error, break out (and die). */ if (config_file != NULL || errno != ENOENT) break; } /* On success, save the name for verification; config_filename is used when logging configuration errors (it changes for .included files) whereas config_main_filename is the name shown by -bP. Failure to open a configuration file is a serious disaster. */ if (config_file != NULL) { config_filename = config_main_filename = string_copy(filename); } else { if (filename == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): " "%s", config_main_filelist); else log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno, "configuration file %s", filename)); } /* Check the status of the file we have opened, if we have retained root privileges. */ if (trusted_config) { if (fstat(fileno(config_file), &statbuf) != 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s", big_buffer); if ((statbuf.st_uid != root_uid /* owner not root */ #ifdef CONFIGURE_OWNER && statbuf.st_uid != config_uid /* owner not the special one */ #endif ) || /* or */ (statbuf.st_gid != root_gid /* group not root & */ #ifdef CONFIGURE_GROUP && statbuf.st_gid != config_gid /* group not the special one */ #endif && (statbuf.st_mode & 020) != 0) || /* group writeable */ /* or */ ((statbuf.st_mode & 2) != 0)) /* world writeable */ log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the " "wrong owner, group, or mode", big_buffer); } /* Process the main configuration settings. They all begin with a lower case letter. If we see something starting with an upper case letter, it is taken as a macro definition. */ while ((s = get_config_line()) != NULL) { if (isupper(s[0])) read_macro_assignment(s); else if (Ustrncmp(s, "domainlist", 10) == 0) read_named_list(&domainlist_anchor, &domainlist_count, MAX_NAMED_LIST, s+10, US"domain list"); else if (Ustrncmp(s, "hostlist", 8) == 0) read_named_list(&hostlist_anchor, &hostlist_count, MAX_NAMED_LIST, s+8, US"host list"); else if (Ustrncmp(s, US"addresslist", 11) == 0) read_named_list(&addresslist_anchor, &addresslist_count, MAX_NAMED_LIST, s+11, US"address list"); else if (Ustrncmp(s, US"localpartlist", 13) == 0) read_named_list(&localpartlist_anchor, &localpartlist_count, MAX_NAMED_LIST, s+13, US"local part list"); else (void) readconf_handle_option(s, optionlist_config, optionlist_config_size, NULL, US"main option \"%s\" unknown"); } /* If local_sender_retain is set, local_from_check must be unset. */ if (local_sender_retain && local_from_check) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and " "local_sender_retain are set; this combination is not allowed"); /* If the timezone string is empty, set it to NULL, implying no TZ variable wanted. */ if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL; /* The max retry interval must not be greater than 24 hours. */ if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60; /* remote_max_parallel must be > 0 */ if (remote_max_parallel <= 0) remote_max_parallel = 1; /* Save the configured setting of freeze_tell, so we can re-instate it at the start of a new SMTP message. */ freeze_tell_config = freeze_tell; /* The primary host name may be required for expansion of spool_directory and log_file_path, so make sure it is set asap. It is obtained from uname(), but if that yields an unqualified value, make a FQDN by using gethostbyname to canonize it. Some people like upper case letters in their host names, so we don't force the case. */ if (primary_hostname == NULL) { uschar *hostname; struct utsname uts; if (uname(&uts) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name"); hostname = US uts.nodename; if (Ustrchr(hostname, '.') == NULL) { int af = AF_INET; struct hostent *hostdata; #if HAVE_IPV6 if (!disable_ipv6 && (dns_ipv4_lookup == NULL || match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN, TRUE, NULL) != OK)) af = AF_INET6; #else af = AF_INET; #endif for (;;) { #if HAVE_IPV6 #if HAVE_GETIPNODEBYNAME int error_num; hostdata = getipnodebyname(CS hostname, af, 0, &error_num); #else hostdata = gethostbyname2(CS hostname, af); #endif #else hostdata = gethostbyname(CS hostname); #endif if (hostdata != NULL) { hostname = US hostdata->h_name; break; } if (af == AF_INET) break; af = AF_INET; } } primary_hostname = string_copy(hostname); } /* Set up default value for smtp_active_hostname */ smtp_active_hostname = primary_hostname; /* If spool_directory wasn't set in the build-time configuration, it must have got set above. Of course, writing to the log may not work if log_file_path is not set, but it will at least get to syslog or somewhere, with any luck. */ if (*spool_directory == 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot " "proceed"); /* Expand the spool directory name; it may, for example, contain the primary host name. Same comment about failure. */ s = expand_string(spool_directory); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory " "\"%s\": %s", spool_directory, expand_string_message); spool_directory = s; /* Expand log_file_path, which must contain "%s" in any component that isn't the null string or "syslog". It is also allowed to contain one instance of %D. However, it must NOT contain % followed by anything else. */ if (*log_file_path != 0) { uschar *ss, *sss; int sep = ':'; /* Fixed for log file path */ s = expand_string(log_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path " "\"%s\": %s", log_file_path, expand_string_message); ss = s; while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL) { uschar *t; if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue; t = Ustrstr(sss, "%s"); if (t == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not " "contain \"%%s\"", sss); *t = 'X'; t = Ustrchr(sss, '%'); if (t != NULL) { if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains " "unexpected \"%%\" character", s); } } log_file_path = s; } /* Interpret syslog_facility into an integer argument for 'ident' param to openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the leading "log_". */ if (syslog_facility_str != NULL) { int i; uschar *s = syslog_facility_str; if ((Ustrlen(syslog_facility_str) >= 4) && (strncmpic(syslog_facility_str, US"log_", 4) == 0)) s += 4; for (i = 0; i < syslog_list_size; i++) { if (strcmpic(s, syslog_list[i].name) == 0) { syslog_facility = syslog_list[i].value; break; } } if (i >= syslog_list_size) { log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "failed to interpret syslog_facility \"%s\"", syslog_facility_str); } } /* Expand pid_file_path */ if (*pid_file_path != 0) { s = expand_string(pid_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path " "\"%s\": %s", pid_file_path, expand_string_message); pid_file_path = s; } /* Compile the regex for matching a UUCP-style "From_" line in an incoming message. */ regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE); /* Unpick the SMTP rate limiting options, if set */ if (smtp_ratelimit_mail != NULL) { unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold, &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit); } if (smtp_ratelimit_rcpt != NULL) { unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold, &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit); } /* The qualify domains default to the primary host name */ if (qualify_domain_sender == NULL) qualify_domain_sender = primary_hostname; if (qualify_domain_recipient == NULL) qualify_domain_recipient = qualify_domain_sender; /* Setting system_filter_user in the configuration sets the gid as well if a name is given, but a numerical value does not. */ if (system_filter_uid_set && !system_filter_gid_set) { struct passwd *pw = getpwuid(system_filter_uid); if (pw == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld", (long int)system_filter_uid); system_filter_gid = pw->pw_gid; system_filter_gid_set = TRUE; } /* If the errors_reply_to field is set, check that it is syntactically valid and ensure it contains a domain. */ if (errors_reply_to != NULL) { uschar *errmess; int start, end, domain; uschar *recipient = parse_extract_address(errors_reply_to, &errmess, &start, &end, &domain, FALSE); if (recipient == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "error in errors_reply_to (%s): %s", errors_reply_to, errmess); if (domain == 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "errors_reply_to (%s) does not contain a domain", errors_reply_to); } /* If smtp_accept_queue or smtp_accept_max_per_host is set, then smtp_accept_max must also be set. */ if (smtp_accept_max == 0 && (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL)) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "smtp_accept_max must be set if smtp_accept_queue or " "smtp_accept_max_per_host is set"); /* Set up the host number if anything is specified. It is an expanded string so that it can be computed from the host name, for example. We do this last so as to ensure that everything else is set up before the expansion. */ if (host_number_string != NULL) { uschar *end; uschar *s = expand_string(host_number_string); long int n = Ustrtol(s, &end, 0); while (isspace(*end)) end++; if (*end != 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number value is not a number: %s", s); if (n > LOCALHOST_MAX) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number is greater than the maximum allowed value (%d)", LOCALHOST_MAX); host_number = n; } #ifdef SUPPORT_TLS /* If tls_verify_hosts is set, tls_verify_certificates must also be set */ if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) && tls_verify_certificates == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "tls_%sverify_hosts is set, but tls_verify_certificates is not set", (tls_verify_hosts != NULL)? "" : "try_"); /* If openssl_options is set, validate it */ if (openssl_options != NULL) { # ifdef USE_GNUTLS log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options is set but we're using GnuTLS"); # else long dummy; if (!(tls_openssl_options_parse(openssl_options, &dummy))) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options parse error: %s", openssl_options); # endif } #endif }
301428151374859174448691319049213421591
readconf.c
241387030736703229400830956134687102289
CWE-264
CVE-2010-4345
Exim 4.72 and earlier allows local users to gain privileges by leveraging the ability of the exim user account to specify an alternate configuration file with a directive that contains arbitrary commands, as demonstrated by the spool_directory directive.
https://nvd.nist.gov/vuln/detail/CVE-2010-4345
200,163
linux
817b8b9c5396d2b2d92311b46719aad5d3339dbe
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/817b8b9c5396d2b2d92311b46719aad5d3339dbe
HID: elo: fix memory leak in elo_probe When hid_parse() in elo_probe() fails, it forgets to call usb_put_dev to decrease the refcount. Fix this by adding usb_put_dev() in the error handling code of elo_probe(). Fixes: fbf42729d0e9 ("HID: elo: update the reference count of the usb device structure") Reported-by: syzkaller <[email protected]> Signed-off-by: Dongliang Mu <[email protected]> Signed-off-by: Jiri Kosina <[email protected]>
1
static int elo_probe(struct hid_device *hdev, const struct hid_device_id *id) { struct elo_priv *priv; int ret; struct usb_device *udev; if (!hid_is_usb(hdev)) return -EINVAL; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; INIT_DELAYED_WORK(&priv->work, elo_work); udev = interface_to_usbdev(to_usb_interface(hdev->dev.parent)); priv->usbdev = usb_get_dev(udev); hid_set_drvdata(hdev, priv); ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); goto err_free; } ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); if (ret) { hid_err(hdev, "hw start failed\n"); goto err_free; } if (elo_broken_firmware(priv->usbdev)) { hid_info(hdev, "broken firmware found, installing workaround\n"); queue_delayed_work(wq, &priv->work, ELO_PERIODIC_READ_INTERVAL); } return 0; err_free: kfree(priv); return ret; }
119771214080354607700352502150468808097
hid-elo.c
34235452733984026251117954935462979934
CWE-200
CVE-2022-27950
In drivers/hid/hid-elo.c in the Linux kernel before 5.16.11, a memory leak exists for a certain hid_parse error condition.
https://nvd.nist.gov/vuln/detail/CVE-2022-27950
299,976
linux
817b8b9c5396d2b2d92311b46719aad5d3339dbe
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/817b8b9c5396d2b2d92311b46719aad5d3339dbe
HID: elo: fix memory leak in elo_probe When hid_parse() in elo_probe() fails, it forgets to call usb_put_dev to decrease the refcount. Fix this by adding usb_put_dev() in the error handling code of elo_probe(). Fixes: fbf42729d0e9 ("HID: elo: update the reference count of the usb device structure") Reported-by: syzkaller <[email protected]> Signed-off-by: Dongliang Mu <[email protected]> Signed-off-by: Jiri Kosina <[email protected]>
0
static int elo_probe(struct hid_device *hdev, const struct hid_device_id *id) { struct elo_priv *priv; int ret; struct usb_device *udev; if (!hid_is_usb(hdev)) return -EINVAL; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; INIT_DELAYED_WORK(&priv->work, elo_work); udev = interface_to_usbdev(to_usb_interface(hdev->dev.parent)); priv->usbdev = usb_get_dev(udev); hid_set_drvdata(hdev, priv); ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); goto err_free; } ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); if (ret) { hid_err(hdev, "hw start failed\n"); goto err_free; } if (elo_broken_firmware(priv->usbdev)) { hid_info(hdev, "broken firmware found, installing workaround\n"); queue_delayed_work(wq, &priv->work, ELO_PERIODIC_READ_INTERVAL); } return 0; err_free: usb_put_dev(udev); kfree(priv); return ret; }
135198268803525127724468857463616363456
hid-elo.c
128667147531145854584279442153105575626
CWE-200
CVE-2022-27950
In drivers/hid/hid-elo.c in the Linux kernel before 5.16.11, a memory leak exists for a certain hid_parse error condition.
https://nvd.nist.gov/vuln/detail/CVE-2022-27950
200,287
linux
d6d86830705f173fca6087a3e67ceaf68db80523
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/d6d86830705f173fca6087a3e67ceaf68db80523
net ticp:fix a kernel-infoleak in __tipc_sendmsg() struct tipc_socket_addr.ref has a 4-byte hole,and __tipc_getname() currently copying it to user space,causing kernel-infoleak. BUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] BUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33 BUG: KMSAN: kernel-infoleak in _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33 instrument_copy_to_user include/linux/instrumented.h:121 [inline] instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33 _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33 copy_to_user include/linux/uaccess.h:209 [inline] copy_to_user include/linux/uaccess.h:209 [inline] net/socket.c:287 move_addr_to_user+0x3f6/0x600 net/socket.c:287 net/socket.c:287 __sys_getpeername+0x470/0x6b0 net/socket.c:1987 net/socket.c:1987 __do_sys_getpeername net/socket.c:1997 [inline] __se_sys_getpeername net/socket.c:1994 [inline] __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994 __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994 __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994 do_syscall_x64 arch/x86/entry/common.c:51 [inline] do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82 do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82 entry_SYSCALL_64_after_hwframe+0x44/0xae Uninit was stored to memory at: tipc_getname+0x575/0x5e0 net/tipc/socket.c:757 net/tipc/socket.c:757 __sys_getpeername+0x3b3/0x6b0 net/socket.c:1984 net/socket.c:1984 __do_sys_getpeername net/socket.c:1997 [inline] __se_sys_getpeername net/socket.c:1994 [inline] __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994 __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994 __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994 do_syscall_x64 arch/x86/entry/common.c:51 [inline] do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82 do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82 entry_SYSCALL_64_after_hwframe+0x44/0xae Uninit was stored to memory at: msg_set_word net/tipc/msg.h:212 [inline] msg_set_destport net/tipc/msg.h:619 [inline] msg_set_word net/tipc/msg.h:212 [inline] net/tipc/socket.c:1486 msg_set_destport net/tipc/msg.h:619 [inline] net/tipc/socket.c:1486 __tipc_sendmsg+0x44fa/0x5890 net/tipc/socket.c:1486 net/tipc/socket.c:1486 tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402 sock_sendmsg_nosec net/socket.c:704 [inline] sock_sendmsg net/socket.c:724 [inline] sock_sendmsg_nosec net/socket.c:704 [inline] net/socket.c:2409 sock_sendmsg net/socket.c:724 [inline] net/socket.c:2409 ____sys_sendmsg+0xe11/0x12c0 net/socket.c:2409 net/socket.c:2409 ___sys_sendmsg net/socket.c:2463 [inline] ___sys_sendmsg net/socket.c:2463 [inline] net/socket.c:2492 __sys_sendmsg+0x704/0x840 net/socket.c:2492 net/socket.c:2492 __do_sys_sendmsg net/socket.c:2501 [inline] __se_sys_sendmsg net/socket.c:2499 [inline] __do_sys_sendmsg net/socket.c:2501 [inline] net/socket.c:2499 __se_sys_sendmsg net/socket.c:2499 [inline] net/socket.c:2499 __x64_sys_sendmsg+0xe2/0x120 net/socket.c:2499 net/socket.c:2499 do_syscall_x64 arch/x86/entry/common.c:51 [inline] do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82 do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82 entry_SYSCALL_64_after_hwframe+0x44/0xae Local variable skaddr created at: __tipc_sendmsg+0x2d0/0x5890 net/tipc/socket.c:1419 net/tipc/socket.c:1419 tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402 Bytes 4-7 of 16 are uninitialized Memory access of size 16 starts at ffff888113753e00 Data copied to user address 0000000020000280 Reported-by: [email protected] Signed-off-by: Haimin Zhang <[email protected]> Acked-by: Jon Maloy <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jakub Kicinski <[email protected]>
1
static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct tipc_sock *tsk = tipc_sk(sk); struct tipc_uaddr *ua = (struct tipc_uaddr *)m->msg_name; long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT); struct list_head *clinks = &tsk->cong_links; bool syn = !tipc_sk_type_connectionless(sk); struct tipc_group *grp = tsk->group; struct tipc_msg *hdr = &tsk->phdr; struct tipc_socket_addr skaddr; struct sk_buff_head pkts; int atype, mtu, rc; if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE)) return -EMSGSIZE; if (ua) { if (!tipc_uaddr_valid(ua, m->msg_namelen)) return -EINVAL; atype = ua->addrtype; } /* If socket belongs to a communication group follow other paths */ if (grp) { if (!ua) return tipc_send_group_bcast(sock, m, dlen, timeout); if (atype == TIPC_SERVICE_ADDR) return tipc_send_group_anycast(sock, m, dlen, timeout); if (atype == TIPC_SOCKET_ADDR) return tipc_send_group_unicast(sock, m, dlen, timeout); if (atype == TIPC_SERVICE_RANGE) return tipc_send_group_mcast(sock, m, dlen, timeout); return -EINVAL; } if (!ua) { ua = (struct tipc_uaddr *)&tsk->peer; if (!syn && ua->family != AF_TIPC) return -EDESTADDRREQ; atype = ua->addrtype; } if (unlikely(syn)) { if (sk->sk_state == TIPC_LISTEN) return -EPIPE; if (sk->sk_state != TIPC_OPEN) return -EISCONN; if (tsk->published) return -EOPNOTSUPP; if (atype == TIPC_SERVICE_ADDR) tsk->conn_addrtype = atype; msg_set_syn(hdr, 1); } /* Determine destination */ if (atype == TIPC_SERVICE_RANGE) { return tipc_sendmcast(sock, ua, m, dlen, timeout); } else if (atype == TIPC_SERVICE_ADDR) { skaddr.node = ua->lookup_node; ua->scope = tipc_node2scope(skaddr.node); if (!tipc_nametbl_lookup_anycast(net, ua, &skaddr)) return -EHOSTUNREACH; } else if (atype == TIPC_SOCKET_ADDR) { skaddr = ua->sk; } else { return -EINVAL; } /* Block or return if destination link is congested */ rc = tipc_wait_for_cond(sock, &timeout, !tipc_dest_find(clinks, skaddr.node, 0)); if (unlikely(rc)) return rc; /* Finally build message header */ msg_set_destnode(hdr, skaddr.node); msg_set_destport(hdr, skaddr.ref); if (atype == TIPC_SERVICE_ADDR) { msg_set_type(hdr, TIPC_NAMED_MSG); msg_set_hdr_sz(hdr, NAMED_H_SIZE); msg_set_nametype(hdr, ua->sa.type); msg_set_nameinst(hdr, ua->sa.instance); msg_set_lookup_scope(hdr, ua->scope); } else { /* TIPC_SOCKET_ADDR */ msg_set_type(hdr, TIPC_DIRECT_MSG); msg_set_lookup_scope(hdr, 0); msg_set_hdr_sz(hdr, BASIC_H_SIZE); } /* Add message body */ __skb_queue_head_init(&pkts); mtu = tipc_node_get_mtu(net, skaddr.node, tsk->portid, true); rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts); if (unlikely(rc != dlen)) return rc; if (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) { __skb_queue_purge(&pkts); return -ENOMEM; } /* Send message */ trace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, " "); rc = tipc_node_xmit(net, &pkts, skaddr.node, tsk->portid); if (unlikely(rc == -ELINKCONG)) { tipc_dest_push(clinks, skaddr.node, 0); tsk->cong_link_cnt++; rc = 0; } if (unlikely(syn && !rc)) { tipc_set_sk_state(sk, TIPC_CONNECTING); if (dlen && timeout) { timeout = msecs_to_jiffies(timeout); tipc_wait_for_connect(sock, &timeout); } } return rc ? rc : dlen; }
187316583908925875095721276140565552990
socket.c
211909288028562459580061336771266741769
CWE-200
CVE-2022-0382
An information leak flaw was found due to uninitialized memory in the Linux kernel's TIPC protocol subsystem, in the way a user sends a TIPC datagram to one or more destinations. This flaw allows a local user to read some kernel memory. This issue is limited to no more than 7 bytes, and the user cannot control what is read. This flaw affects the Linux kernel versions prior to 5.17-rc1.
https://nvd.nist.gov/vuln/detail/CVE-2022-0382
300,731
linux
d6d86830705f173fca6087a3e67ceaf68db80523
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/d6d86830705f173fca6087a3e67ceaf68db80523
net ticp:fix a kernel-infoleak in __tipc_sendmsg() struct tipc_socket_addr.ref has a 4-byte hole,and __tipc_getname() currently copying it to user space,causing kernel-infoleak. BUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] BUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33 BUG: KMSAN: kernel-infoleak in _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33 instrument_copy_to_user include/linux/instrumented.h:121 [inline] instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33 _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33 copy_to_user include/linux/uaccess.h:209 [inline] copy_to_user include/linux/uaccess.h:209 [inline] net/socket.c:287 move_addr_to_user+0x3f6/0x600 net/socket.c:287 net/socket.c:287 __sys_getpeername+0x470/0x6b0 net/socket.c:1987 net/socket.c:1987 __do_sys_getpeername net/socket.c:1997 [inline] __se_sys_getpeername net/socket.c:1994 [inline] __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994 __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994 __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994 do_syscall_x64 arch/x86/entry/common.c:51 [inline] do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82 do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82 entry_SYSCALL_64_after_hwframe+0x44/0xae Uninit was stored to memory at: tipc_getname+0x575/0x5e0 net/tipc/socket.c:757 net/tipc/socket.c:757 __sys_getpeername+0x3b3/0x6b0 net/socket.c:1984 net/socket.c:1984 __do_sys_getpeername net/socket.c:1997 [inline] __se_sys_getpeername net/socket.c:1994 [inline] __do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994 __se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994 __x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994 do_syscall_x64 arch/x86/entry/common.c:51 [inline] do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82 do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82 entry_SYSCALL_64_after_hwframe+0x44/0xae Uninit was stored to memory at: msg_set_word net/tipc/msg.h:212 [inline] msg_set_destport net/tipc/msg.h:619 [inline] msg_set_word net/tipc/msg.h:212 [inline] net/tipc/socket.c:1486 msg_set_destport net/tipc/msg.h:619 [inline] net/tipc/socket.c:1486 __tipc_sendmsg+0x44fa/0x5890 net/tipc/socket.c:1486 net/tipc/socket.c:1486 tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402 sock_sendmsg_nosec net/socket.c:704 [inline] sock_sendmsg net/socket.c:724 [inline] sock_sendmsg_nosec net/socket.c:704 [inline] net/socket.c:2409 sock_sendmsg net/socket.c:724 [inline] net/socket.c:2409 ____sys_sendmsg+0xe11/0x12c0 net/socket.c:2409 net/socket.c:2409 ___sys_sendmsg net/socket.c:2463 [inline] ___sys_sendmsg net/socket.c:2463 [inline] net/socket.c:2492 __sys_sendmsg+0x704/0x840 net/socket.c:2492 net/socket.c:2492 __do_sys_sendmsg net/socket.c:2501 [inline] __se_sys_sendmsg net/socket.c:2499 [inline] __do_sys_sendmsg net/socket.c:2501 [inline] net/socket.c:2499 __se_sys_sendmsg net/socket.c:2499 [inline] net/socket.c:2499 __x64_sys_sendmsg+0xe2/0x120 net/socket.c:2499 net/socket.c:2499 do_syscall_x64 arch/x86/entry/common.c:51 [inline] do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82 do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82 entry_SYSCALL_64_after_hwframe+0x44/0xae Local variable skaddr created at: __tipc_sendmsg+0x2d0/0x5890 net/tipc/socket.c:1419 net/tipc/socket.c:1419 tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402 Bytes 4-7 of 16 are uninitialized Memory access of size 16 starts at ffff888113753e00 Data copied to user address 0000000020000280 Reported-by: [email protected] Signed-off-by: Haimin Zhang <[email protected]> Acked-by: Jon Maloy <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jakub Kicinski <[email protected]>
0
static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct tipc_sock *tsk = tipc_sk(sk); struct tipc_uaddr *ua = (struct tipc_uaddr *)m->msg_name; long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT); struct list_head *clinks = &tsk->cong_links; bool syn = !tipc_sk_type_connectionless(sk); struct tipc_group *grp = tsk->group; struct tipc_msg *hdr = &tsk->phdr; struct tipc_socket_addr skaddr; struct sk_buff_head pkts; int atype, mtu, rc; if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE)) return -EMSGSIZE; if (ua) { if (!tipc_uaddr_valid(ua, m->msg_namelen)) return -EINVAL; atype = ua->addrtype; } /* If socket belongs to a communication group follow other paths */ if (grp) { if (!ua) return tipc_send_group_bcast(sock, m, dlen, timeout); if (atype == TIPC_SERVICE_ADDR) return tipc_send_group_anycast(sock, m, dlen, timeout); if (atype == TIPC_SOCKET_ADDR) return tipc_send_group_unicast(sock, m, dlen, timeout); if (atype == TIPC_SERVICE_RANGE) return tipc_send_group_mcast(sock, m, dlen, timeout); return -EINVAL; } if (!ua) { ua = (struct tipc_uaddr *)&tsk->peer; if (!syn && ua->family != AF_TIPC) return -EDESTADDRREQ; atype = ua->addrtype; } if (unlikely(syn)) { if (sk->sk_state == TIPC_LISTEN) return -EPIPE; if (sk->sk_state != TIPC_OPEN) return -EISCONN; if (tsk->published) return -EOPNOTSUPP; if (atype == TIPC_SERVICE_ADDR) tsk->conn_addrtype = atype; msg_set_syn(hdr, 1); } memset(&skaddr, 0, sizeof(skaddr)); /* Determine destination */ if (atype == TIPC_SERVICE_RANGE) { return tipc_sendmcast(sock, ua, m, dlen, timeout); } else if (atype == TIPC_SERVICE_ADDR) { skaddr.node = ua->lookup_node; ua->scope = tipc_node2scope(skaddr.node); if (!tipc_nametbl_lookup_anycast(net, ua, &skaddr)) return -EHOSTUNREACH; } else if (atype == TIPC_SOCKET_ADDR) { skaddr = ua->sk; } else { return -EINVAL; } /* Block or return if destination link is congested */ rc = tipc_wait_for_cond(sock, &timeout, !tipc_dest_find(clinks, skaddr.node, 0)); if (unlikely(rc)) return rc; /* Finally build message header */ msg_set_destnode(hdr, skaddr.node); msg_set_destport(hdr, skaddr.ref); if (atype == TIPC_SERVICE_ADDR) { msg_set_type(hdr, TIPC_NAMED_MSG); msg_set_hdr_sz(hdr, NAMED_H_SIZE); msg_set_nametype(hdr, ua->sa.type); msg_set_nameinst(hdr, ua->sa.instance); msg_set_lookup_scope(hdr, ua->scope); } else { /* TIPC_SOCKET_ADDR */ msg_set_type(hdr, TIPC_DIRECT_MSG); msg_set_lookup_scope(hdr, 0); msg_set_hdr_sz(hdr, BASIC_H_SIZE); } /* Add message body */ __skb_queue_head_init(&pkts); mtu = tipc_node_get_mtu(net, skaddr.node, tsk->portid, true); rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts); if (unlikely(rc != dlen)) return rc; if (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) { __skb_queue_purge(&pkts); return -ENOMEM; } /* Send message */ trace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, " "); rc = tipc_node_xmit(net, &pkts, skaddr.node, tsk->portid); if (unlikely(rc == -ELINKCONG)) { tipc_dest_push(clinks, skaddr.node, 0); tsk->cong_link_cnt++; rc = 0; } if (unlikely(syn && !rc)) { tipc_set_sk_state(sk, TIPC_CONNECTING); if (dlen && timeout) { timeout = msecs_to_jiffies(timeout); tipc_wait_for_connect(sock, &timeout); } } return rc ? rc : dlen; }
227702131307400151351141402297304867494
socket.c
232810698779802669165593435483275736628
CWE-200
CVE-2022-0382
An information leak flaw was found due to uninitialized memory in the Linux kernel's TIPC protocol subsystem, in the way a user sends a TIPC datagram to one or more destinations. This flaw allows a local user to read some kernel memory. This issue is limited to no more than 7 bytes, and the user cannot control what is read. This flaw affects the Linux kernel versions prior to 5.17-rc1.
https://nvd.nist.gov/vuln/detail/CVE-2022-0382
200,305
ghostpdl
2793769ff107d8d22dadd30c6e68cd781b569550
https://github.com/ArtifexSoftware/ghostpdl
https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=2793769ff107d8d22dadd30c6e68cd781b569550
Bug 701819: fixed ordering in if expression to avoid out-of-bounds access. Fixes: ./sanbin/gs -dBATCH -dNOPAUSE -r965 -sOutputFile=tmp -sDEVICE=pcx16 ../bug-701819.pdf
1
pcx_write_rle(const byte * from, const byte * end, int step, gp_file * file) { /* * The PCX format theoretically allows encoding runs of 63 * identical bytes, but some readers can't handle repetition * counts greater than 15. */ #define MAX_RUN_COUNT 15 int max_run = step * MAX_RUN_COUNT; while (from < end) { byte data = *from; from += step; if (data != *from || from == end) { if (data >= 0xc0) gp_fputc(0xc1, file); } else { const byte *start = from; while ((from < end) && (*from == data)) from += step; /* Now (from - start) / step + 1 is the run length. */ while (from - start >= max_run) { gp_fputc(0xc0 + MAX_RUN_COUNT, file); gp_fputc(data, file); start += max_run; } if (from > start || data >= 0xc0) gp_fputc((from - start) / step + 0xc1, file); } gp_fputc(data, file); } #undef MAX_RUN_COUNT }
302156343438902913796919673468889397004
gdevpcx.c
193192744323180393354892924891696445092
CWE-787
CVE-2020-16305
A buffer overflow vulnerability in pcx_write_rle() in contrib/japanese/gdev10v.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.
https://nvd.nist.gov/vuln/detail/CVE-2020-16305
301,016
ghostpdl
2793769ff107d8d22dadd30c6e68cd781b569550
https://github.com/ArtifexSoftware/ghostpdl
https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=2793769ff107d8d22dadd30c6e68cd781b569550
Bug 701819: fixed ordering in if expression to avoid out-of-bounds access. Fixes: ./sanbin/gs -dBATCH -dNOPAUSE -r965 -sOutputFile=tmp -sDEVICE=pcx16 ../bug-701819.pdf
0
pcx_write_rle(const byte * from, const byte * end, int step, gp_file * file) { /* * The PCX format theoretically allows encoding runs of 63 * identical bytes, but some readers can't handle repetition * counts greater than 15. */ #define MAX_RUN_COUNT 15 int max_run = step * MAX_RUN_COUNT; while (from < end) { byte data = *from; from += step; if (from >= end || data != *from) { if (data >= 0xc0) gp_fputc(0xc1, file); } else { const byte *start = from; while ((from < end) && (*from == data)) from += step; /* Now (from - start) / step + 1 is the run length. */ while (from - start >= max_run) { gp_fputc(0xc0 + MAX_RUN_COUNT, file); gp_fputc(data, file); start += max_run; } if (from > start || data >= 0xc0) gp_fputc((from - start) / step + 0xc1, file); } gp_fputc(data, file); } #undef MAX_RUN_COUNT }
242406925449442075366182864127739162962
gdevpcx.c
146911482994709759285318949799638474400
CWE-787
CVE-2020-16305
A buffer overflow vulnerability in pcx_write_rle() in contrib/japanese/gdev10v.c of Artifex Software GhostScript v9.50 allows a remote attacker to cause a denial of service via a crafted PDF file. This is fixed in v9.51.
https://nvd.nist.gov/vuln/detail/CVE-2020-16305
200,320
samba
eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696
https://github.com/samba-team/samba
http://git.samba.org/?p=samba.git;a=commitdiff;h=eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696
FSCTL_GET_SHADOW_COPY_DATA: Don't return 4 extra bytes at end labels_data_count already accounts for the unicode null character at the end of the array. There is no need in adding space for it again. Signed-off-by: Christof Schmitt <[email protected]> Reviewed-by: Jeremy Allison <[email protected]> Reviewed-by: Simo Sorce <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Tue Aug 6 04:03:17 CEST 2013 on sn-devel-104
1
static NTSTATUS vfswrap_fsctl(struct vfs_handle_struct *handle, struct files_struct *fsp, TALLOC_CTX *ctx, uint32_t function, uint16_t req_flags, /* Needed for UNICODE ... */ const uint8_t *_in_data, uint32_t in_len, uint8_t **_out_data, uint32_t max_out_len, uint32_t *out_len) { const char *in_data = (const char *)_in_data; char **out_data = (char **)_out_data; switch (function) { case FSCTL_SET_SPARSE: { bool set_sparse = true; NTSTATUS status; if (in_len >= 1 && in_data[0] == 0) { set_sparse = false; } status = file_set_sparse(handle->conn, fsp, set_sparse); DEBUG(NT_STATUS_IS_OK(status) ? 10 : 9, ("FSCTL_SET_SPARSE: fname[%s] set[%u] - %s\n", smb_fname_str_dbg(fsp->fsp_name), set_sparse, nt_errstr(status))); return status; } case FSCTL_CREATE_OR_GET_OBJECT_ID: { unsigned char objid[16]; char *return_data = NULL; /* This should return the object-id on this file. * I think I'll make this be the inode+dev. JRA. */ DEBUG(10,("FSCTL_CREATE_OR_GET_OBJECT_ID: called on %s\n", fsp_fnum_dbg(fsp))); *out_len = (max_out_len >= 64) ? 64 : max_out_len; /* Hmmm, will this cause problems if less data asked for? */ return_data = talloc_array(ctx, char, 64); if (return_data == NULL) { return NT_STATUS_NO_MEMORY; } /* For backwards compatibility only store the dev/inode. */ push_file_id_16(return_data, &fsp->file_id); memcpy(return_data+16,create_volume_objectid(fsp->conn,objid),16); push_file_id_16(return_data+32, &fsp->file_id); *out_data = return_data; return NT_STATUS_OK; } case FSCTL_GET_REPARSE_POINT: { /* Fail it with STATUS_NOT_A_REPARSE_POINT */ DEBUG(10, ("FSCTL_GET_REPARSE_POINT: called on %s. " "Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp))); return NT_STATUS_NOT_A_REPARSE_POINT; } case FSCTL_SET_REPARSE_POINT: { /* Fail it with STATUS_NOT_A_REPARSE_POINT */ DEBUG(10, ("FSCTL_SET_REPARSE_POINT: called on %s. " "Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp))); return NT_STATUS_NOT_A_REPARSE_POINT; } case FSCTL_GET_SHADOW_COPY_DATA: { /* * This is called to retrieve the number of Shadow Copies (a.k.a. snapshots) * and return their volume names. If max_data_count is 16, then it is just * asking for the number of volumes and length of the combined names. * * pdata is the data allocated by our caller, but that uses * total_data_count (which is 0 in our case) rather than max_data_count. * Allocate the correct amount and return the pointer to let * it be deallocated when we return. */ struct shadow_copy_data *shadow_data = NULL; bool labels = False; uint32 labels_data_count = 0; uint32 i; char *cur_pdata = NULL; if (max_out_len < 16) { DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) < 16 is invalid!\n", max_out_len)); return NT_STATUS_INVALID_PARAMETER; } if (max_out_len > 16) { labels = True; } shadow_data = talloc_zero(ctx, struct shadow_copy_data); if (shadow_data == NULL) { DEBUG(0,("TALLOC_ZERO() failed!\n")); return NT_STATUS_NO_MEMORY; } /* * Call the VFS routine to actually do the work. */ if (SMB_VFS_GET_SHADOW_COPY_DATA(fsp, shadow_data, labels)!=0) { TALLOC_FREE(shadow_data); if (errno == ENOSYS) { DEBUG(5,("FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, not supported.\n", fsp->conn->connectpath)); return NT_STATUS_NOT_SUPPORTED; } else { DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, failed.\n", fsp->conn->connectpath)); return NT_STATUS_UNSUCCESSFUL; } } labels_data_count = (shadow_data->num_volumes * 2 * sizeof(SHADOW_COPY_LABEL)) + 2; if (!labels) { *out_len = 16; } else { *out_len = 12 + labels_data_count + 4; } if (max_out_len < *out_len) { DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) too small (%u) bytes needed!\n", max_out_len, *out_len)); TALLOC_FREE(shadow_data); return NT_STATUS_BUFFER_TOO_SMALL; } cur_pdata = talloc_zero_array(ctx, char, *out_len); if (cur_pdata == NULL) { TALLOC_FREE(shadow_data); return NT_STATUS_NO_MEMORY; } *out_data = cur_pdata; /* num_volumes 4 bytes */ SIVAL(cur_pdata, 0, shadow_data->num_volumes); if (labels) { /* num_labels 4 bytes */ SIVAL(cur_pdata, 4, shadow_data->num_volumes); } /* needed_data_count 4 bytes */ SIVAL(cur_pdata, 8, labels_data_count + 4); cur_pdata += 12; DEBUG(10,("FSCTL_GET_SHADOW_COPY_DATA: %u volumes for path[%s].\n", shadow_data->num_volumes, fsp_str_dbg(fsp))); if (labels && shadow_data->labels) { for (i=0; i<shadow_data->num_volumes; i++) { srvstr_push(cur_pdata, req_flags, cur_pdata, shadow_data->labels[i], 2 * sizeof(SHADOW_COPY_LABEL), STR_UNICODE|STR_TERMINATE); cur_pdata += 2 * sizeof(SHADOW_COPY_LABEL); DEBUGADD(10,("Label[%u]: '%s'\n",i,shadow_data->labels[i])); } } TALLOC_FREE(shadow_data); return NT_STATUS_OK; } case FSCTL_FIND_FILES_BY_SID: { /* pretend this succeeded - * * we have to send back a list with all files owned by this SID * * but I have to check that --metze */ struct dom_sid sid; uid_t uid; size_t sid_len; DEBUG(10, ("FSCTL_FIND_FILES_BY_SID: called on %s\n", fsp_fnum_dbg(fsp))); if (in_len < 8) { /* NT_STATUS_BUFFER_TOO_SMALL maybe? */ return NT_STATUS_INVALID_PARAMETER; } sid_len = MIN(in_len - 4,SID_MAX_SIZE); /* unknown 4 bytes: this is not the length of the sid :-( */ /*unknown = IVAL(pdata,0);*/ if (!sid_parse(in_data + 4, sid_len, &sid)) { return NT_STATUS_INVALID_PARAMETER; } DEBUGADD(10, ("for SID: %s\n", sid_string_dbg(&sid))); if (!sid_to_uid(&sid, &uid)) { DEBUG(0,("sid_to_uid: failed, sid[%s] sid_len[%lu]\n", sid_string_dbg(&sid), (unsigned long)sid_len)); uid = (-1); } /* we can take a look at the find source :-) * * find ./ -uid $uid -name '*' is what we need here * * * and send 4bytes len and then NULL terminated unicode strings * for each file * * but I don't know how to deal with the paged results * (maybe we can hang the result anywhere in the fsp struct) * * but I don't know how to deal with the paged results * (maybe we can hang the result anywhere in the fsp struct) * * we don't send all files at once * and at the next we should *not* start from the beginning, * so we have to cache the result * * --metze */ /* this works for now... */ return NT_STATUS_OK; } case FSCTL_QUERY_ALLOCATED_RANGES: { /* FIXME: This is just a dummy reply, telling that all of the * file is allocated. MKS cp needs that. * Adding the real allocated ranges via FIEMAP on Linux * and SEEK_DATA/SEEK_HOLE on Solaris is needed to make * this FSCTL correct for sparse files. */ NTSTATUS status; uint64_t offset, length; char *out_data_tmp = NULL; if (in_len != 16) { DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: data_count(%u) != 16 is invalid!\n", in_len)); return NT_STATUS_INVALID_PARAMETER; } if (max_out_len < 16) { DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: max_out_len (%u) < 16 is invalid!\n", max_out_len)); return NT_STATUS_INVALID_PARAMETER; } offset = BVAL(in_data,0); length = BVAL(in_data,8); if (offset + length < offset) { /* No 64-bit integer wrap. */ return NT_STATUS_INVALID_PARAMETER; } /* Shouldn't this be SMB_VFS_STAT ... ? */ status = vfs_stat_fsp(fsp); if (!NT_STATUS_IS_OK(status)) { return status; } *out_len = 16; out_data_tmp = talloc_array(ctx, char, *out_len); if (out_data_tmp == NULL) { DEBUG(10, ("unable to allocate memory for response\n")); return NT_STATUS_NO_MEMORY; } if (offset > fsp->fsp_name->st.st_ex_size || fsp->fsp_name->st.st_ex_size == 0 || length == 0) { memset(out_data_tmp, 0, *out_len); } else { uint64_t end = offset + length; end = MIN(end, fsp->fsp_name->st.st_ex_size); SBVAL(out_data_tmp, 0, 0); SBVAL(out_data_tmp, 8, end); } *out_data = out_data_tmp; return NT_STATUS_OK; } case FSCTL_IS_VOLUME_DIRTY: { DEBUG(10,("FSCTL_IS_VOLUME_DIRTY: called on %s " "(but remotely not supported)\n", fsp_fnum_dbg(fsp))); /* * http://msdn.microsoft.com/en-us/library/cc232128%28PROT.10%29.aspx * says we have to respond with NT_STATUS_INVALID_PARAMETER */ return NT_STATUS_INVALID_PARAMETER; } default: /* * Only print once ... unfortunately there could be lots of * different FSCTLs that are called. */ if (!vfswrap_logged_ioctl_message) { vfswrap_logged_ioctl_message = true; DEBUG(2, ("%s (0x%x): Currently not implemented.\n", __func__, function)); } } return NT_STATUS_NOT_SUPPORTED; }
216855121268945563940656517843611340199
vfs_default.c
120656139704674873497493645428059774528
CWE-665
CVE-2014-0178
Samba 3.6.6 through 3.6.23, 4.0.x before 4.0.18, and 4.1.x before 4.1.8, when a certain vfs shadow copy configuration is enabled, does not properly initialize the SRV_SNAPSHOT_ARRAY response field, which allows remote authenticated users to obtain potentially sensitive information from process memory via a (1) FSCTL_GET_SHADOW_COPY_DATA or (2) FSCTL_SRV_ENUMERATE_SNAPSHOTS request.
https://nvd.nist.gov/vuln/detail/CVE-2014-0178
301,429
samba
eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696
https://github.com/samba-team/samba
http://git.samba.org/?p=samba.git;a=commitdiff;h=eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696
FSCTL_GET_SHADOW_COPY_DATA: Don't return 4 extra bytes at end labels_data_count already accounts for the unicode null character at the end of the array. There is no need in adding space for it again. Signed-off-by: Christof Schmitt <[email protected]> Reviewed-by: Jeremy Allison <[email protected]> Reviewed-by: Simo Sorce <[email protected]> Autobuild-User(master): Jeremy Allison <[email protected]> Autobuild-Date(master): Tue Aug 6 04:03:17 CEST 2013 on sn-devel-104
0
static NTSTATUS vfswrap_fsctl(struct vfs_handle_struct *handle, struct files_struct *fsp, TALLOC_CTX *ctx, uint32_t function, uint16_t req_flags, /* Needed for UNICODE ... */ const uint8_t *_in_data, uint32_t in_len, uint8_t **_out_data, uint32_t max_out_len, uint32_t *out_len) { const char *in_data = (const char *)_in_data; char **out_data = (char **)_out_data; switch (function) { case FSCTL_SET_SPARSE: { bool set_sparse = true; NTSTATUS status; if (in_len >= 1 && in_data[0] == 0) { set_sparse = false; } status = file_set_sparse(handle->conn, fsp, set_sparse); DEBUG(NT_STATUS_IS_OK(status) ? 10 : 9, ("FSCTL_SET_SPARSE: fname[%s] set[%u] - %s\n", smb_fname_str_dbg(fsp->fsp_name), set_sparse, nt_errstr(status))); return status; } case FSCTL_CREATE_OR_GET_OBJECT_ID: { unsigned char objid[16]; char *return_data = NULL; /* This should return the object-id on this file. * I think I'll make this be the inode+dev. JRA. */ DEBUG(10,("FSCTL_CREATE_OR_GET_OBJECT_ID: called on %s\n", fsp_fnum_dbg(fsp))); *out_len = (max_out_len >= 64) ? 64 : max_out_len; /* Hmmm, will this cause problems if less data asked for? */ return_data = talloc_array(ctx, char, 64); if (return_data == NULL) { return NT_STATUS_NO_MEMORY; } /* For backwards compatibility only store the dev/inode. */ push_file_id_16(return_data, &fsp->file_id); memcpy(return_data+16,create_volume_objectid(fsp->conn,objid),16); push_file_id_16(return_data+32, &fsp->file_id); *out_data = return_data; return NT_STATUS_OK; } case FSCTL_GET_REPARSE_POINT: { /* Fail it with STATUS_NOT_A_REPARSE_POINT */ DEBUG(10, ("FSCTL_GET_REPARSE_POINT: called on %s. " "Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp))); return NT_STATUS_NOT_A_REPARSE_POINT; } case FSCTL_SET_REPARSE_POINT: { /* Fail it with STATUS_NOT_A_REPARSE_POINT */ DEBUG(10, ("FSCTL_SET_REPARSE_POINT: called on %s. " "Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp))); return NT_STATUS_NOT_A_REPARSE_POINT; } case FSCTL_GET_SHADOW_COPY_DATA: { /* * This is called to retrieve the number of Shadow Copies (a.k.a. snapshots) * and return their volume names. If max_data_count is 16, then it is just * asking for the number of volumes and length of the combined names. * * pdata is the data allocated by our caller, but that uses * total_data_count (which is 0 in our case) rather than max_data_count. * Allocate the correct amount and return the pointer to let * it be deallocated when we return. */ struct shadow_copy_data *shadow_data = NULL; bool labels = False; uint32 labels_data_count = 0; uint32 i; char *cur_pdata = NULL; if (max_out_len < 16) { DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) < 16 is invalid!\n", max_out_len)); return NT_STATUS_INVALID_PARAMETER; } if (max_out_len > 16) { labels = True; } shadow_data = talloc_zero(ctx, struct shadow_copy_data); if (shadow_data == NULL) { DEBUG(0,("TALLOC_ZERO() failed!\n")); return NT_STATUS_NO_MEMORY; } /* * Call the VFS routine to actually do the work. */ if (SMB_VFS_GET_SHADOW_COPY_DATA(fsp, shadow_data, labels)!=0) { TALLOC_FREE(shadow_data); if (errno == ENOSYS) { DEBUG(5,("FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, not supported.\n", fsp->conn->connectpath)); return NT_STATUS_NOT_SUPPORTED; } else { DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, failed.\n", fsp->conn->connectpath)); return NT_STATUS_UNSUCCESSFUL; } } labels_data_count = (shadow_data->num_volumes * 2 * sizeof(SHADOW_COPY_LABEL)) + 2; if (!labels) { *out_len = 16; } else { *out_len = 12 + labels_data_count; } if (max_out_len < *out_len) { DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) too small (%u) bytes needed!\n", max_out_len, *out_len)); TALLOC_FREE(shadow_data); return NT_STATUS_BUFFER_TOO_SMALL; } cur_pdata = talloc_zero_array(ctx, char, *out_len); if (cur_pdata == NULL) { TALLOC_FREE(shadow_data); return NT_STATUS_NO_MEMORY; } *out_data = cur_pdata; /* num_volumes 4 bytes */ SIVAL(cur_pdata, 0, shadow_data->num_volumes); if (labels) { /* num_labels 4 bytes */ SIVAL(cur_pdata, 4, shadow_data->num_volumes); } /* needed_data_count 4 bytes */ SIVAL(cur_pdata, 8, labels_data_count); cur_pdata += 12; DEBUG(10,("FSCTL_GET_SHADOW_COPY_DATA: %u volumes for path[%s].\n", shadow_data->num_volumes, fsp_str_dbg(fsp))); if (labels && shadow_data->labels) { for (i=0; i<shadow_data->num_volumes; i++) { srvstr_push(cur_pdata, req_flags, cur_pdata, shadow_data->labels[i], 2 * sizeof(SHADOW_COPY_LABEL), STR_UNICODE|STR_TERMINATE); cur_pdata += 2 * sizeof(SHADOW_COPY_LABEL); DEBUGADD(10,("Label[%u]: '%s'\n",i,shadow_data->labels[i])); } } TALLOC_FREE(shadow_data); return NT_STATUS_OK; } case FSCTL_FIND_FILES_BY_SID: { /* pretend this succeeded - * * we have to send back a list with all files owned by this SID * * but I have to check that --metze */ struct dom_sid sid; uid_t uid; size_t sid_len; DEBUG(10, ("FSCTL_FIND_FILES_BY_SID: called on %s\n", fsp_fnum_dbg(fsp))); if (in_len < 8) { /* NT_STATUS_BUFFER_TOO_SMALL maybe? */ return NT_STATUS_INVALID_PARAMETER; } sid_len = MIN(in_len - 4,SID_MAX_SIZE); /* unknown 4 bytes: this is not the length of the sid :-( */ /*unknown = IVAL(pdata,0);*/ if (!sid_parse(in_data + 4, sid_len, &sid)) { return NT_STATUS_INVALID_PARAMETER; } DEBUGADD(10, ("for SID: %s\n", sid_string_dbg(&sid))); if (!sid_to_uid(&sid, &uid)) { DEBUG(0,("sid_to_uid: failed, sid[%s] sid_len[%lu]\n", sid_string_dbg(&sid), (unsigned long)sid_len)); uid = (-1); } /* we can take a look at the find source :-) * * find ./ -uid $uid -name '*' is what we need here * * * and send 4bytes len and then NULL terminated unicode strings * for each file * * but I don't know how to deal with the paged results * (maybe we can hang the result anywhere in the fsp struct) * * but I don't know how to deal with the paged results * (maybe we can hang the result anywhere in the fsp struct) * * we don't send all files at once * and at the next we should *not* start from the beginning, * so we have to cache the result * * --metze */ /* this works for now... */ return NT_STATUS_OK; } case FSCTL_QUERY_ALLOCATED_RANGES: { /* FIXME: This is just a dummy reply, telling that all of the * file is allocated. MKS cp needs that. * Adding the real allocated ranges via FIEMAP on Linux * and SEEK_DATA/SEEK_HOLE on Solaris is needed to make * this FSCTL correct for sparse files. */ NTSTATUS status; uint64_t offset, length; char *out_data_tmp = NULL; if (in_len != 16) { DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: data_count(%u) != 16 is invalid!\n", in_len)); return NT_STATUS_INVALID_PARAMETER; } if (max_out_len < 16) { DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: max_out_len (%u) < 16 is invalid!\n", max_out_len)); return NT_STATUS_INVALID_PARAMETER; } offset = BVAL(in_data,0); length = BVAL(in_data,8); if (offset + length < offset) { /* No 64-bit integer wrap. */ return NT_STATUS_INVALID_PARAMETER; } /* Shouldn't this be SMB_VFS_STAT ... ? */ status = vfs_stat_fsp(fsp); if (!NT_STATUS_IS_OK(status)) { return status; } *out_len = 16; out_data_tmp = talloc_array(ctx, char, *out_len); if (out_data_tmp == NULL) { DEBUG(10, ("unable to allocate memory for response\n")); return NT_STATUS_NO_MEMORY; } if (offset > fsp->fsp_name->st.st_ex_size || fsp->fsp_name->st.st_ex_size == 0 || length == 0) { memset(out_data_tmp, 0, *out_len); } else { uint64_t end = offset + length; end = MIN(end, fsp->fsp_name->st.st_ex_size); SBVAL(out_data_tmp, 0, 0); SBVAL(out_data_tmp, 8, end); } *out_data = out_data_tmp; return NT_STATUS_OK; } case FSCTL_IS_VOLUME_DIRTY: { DEBUG(10,("FSCTL_IS_VOLUME_DIRTY: called on %s " "(but remotely not supported)\n", fsp_fnum_dbg(fsp))); /* * http://msdn.microsoft.com/en-us/library/cc232128%28PROT.10%29.aspx * says we have to respond with NT_STATUS_INVALID_PARAMETER */ return NT_STATUS_INVALID_PARAMETER; } default: /* * Only print once ... unfortunately there could be lots of * different FSCTLs that are called. */ if (!vfswrap_logged_ioctl_message) { vfswrap_logged_ioctl_message = true; DEBUG(2, ("%s (0x%x): Currently not implemented.\n", __func__, function)); } } return NT_STATUS_NOT_SUPPORTED; }
132063817933322219914210218512719915905
None
CWE-665
CVE-2014-0178
Samba 3.6.6 through 3.6.23, 4.0.x before 4.0.18, and 4.1.x before 4.1.8, when a certain vfs shadow copy configuration is enabled, does not properly initialize the SRV_SNAPSHOT_ARRAY response field, which allows remote authenticated users to obtain potentially sensitive information from process memory via a (1) FSCTL_GET_SHADOW_COPY_DATA or (2) FSCTL_SRV_ENUMERATE_SNAPSHOTS request.
https://nvd.nist.gov/vuln/detail/CVE-2014-0178
200,323
vim
156d3911952d73b03d7420dc3540215247db0fe8
https://github.com/vim/vim
https://github.com/vim/vim/commit/156d3911952d73b03d7420dc3540215247db0fe8
patch 8.2.5123: using invalid index when looking for spell suggestions Problem: Using invalid index when looking for spell suggestions. Solution: Do not decrement the index when it is zero.
1
suggest_trie_walk( suginfo_T *su, langp_T *lp, char_u *fword, int soundfold) { char_u tword[MAXWLEN]; // good word collected so far trystate_T stack[MAXWLEN]; char_u preword[MAXWLEN * 3]; // word found with proper case; // concatenation of prefix compound // words and split word. NUL terminated // when going deeper but not when coming // back. char_u compflags[MAXWLEN]; // compound flags, one for each word trystate_T *sp; int newscore; int score; char_u *byts, *fbyts, *pbyts; idx_T *idxs, *fidxs, *pidxs; int depth; int c, c2, c3; int n = 0; int flags; garray_T *gap; idx_T arridx; int len; char_u *p; fromto_T *ftp; int fl = 0, tl; int repextra = 0; // extra bytes in fword[] from REP item slang_T *slang = lp->lp_slang; int fword_ends; int goodword_ends; #ifdef DEBUG_TRIEWALK // Stores the name of the change made at each level. char_u changename[MAXWLEN][80]; #endif int breakcheckcount = 1000; #ifdef FEAT_RELTIME proftime_T time_limit; #endif int compound_ok; // Go through the whole case-fold tree, try changes at each node. // "tword[]" contains the word collected from nodes in the tree. // "fword[]" the word we are trying to match with (initially the bad // word). depth = 0; sp = &stack[0]; CLEAR_POINTER(sp); sp->ts_curi = 1; if (soundfold) { // Going through the soundfold tree. byts = fbyts = slang->sl_sbyts; idxs = fidxs = slang->sl_sidxs; pbyts = NULL; pidxs = NULL; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } else { // When there are postponed prefixes we need to use these first. At // the end of the prefix we continue in the case-fold tree. fbyts = slang->sl_fbyts; fidxs = slang->sl_fidxs; pbyts = slang->sl_pbyts; pidxs = slang->sl_pidxs; if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; sp->ts_state = STATE_NOPREFIX; // try without prefix first } else { byts = fbyts; idxs = fidxs; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } } #ifdef FEAT_RELTIME // The loop may take an indefinite amount of time. Break out after some // time. if (spell_suggest_timeout > 0) profile_setlimit(spell_suggest_timeout, &time_limit); #endif // Loop to find all suggestions. At each round we either: // - For the current state try one operation, advance "ts_curi", // increase "depth". // - When a state is done go to the next, set "ts_state". // - When all states are tried decrease "depth". while (depth >= 0 && !got_int) { sp = &stack[depth]; switch (sp->ts_state) { case STATE_START: case STATE_NOPREFIX: // Start of node: Deal with NUL bytes, which means // tword[] may end here. arridx = sp->ts_arridx; // current node in the tree len = byts[arridx]; // bytes in this node arridx += sp->ts_curi; // index of current byte if (sp->ts_prefixdepth == PFD_PREFIXTREE) { // Skip over the NUL bytes, we use them later. for (n = 0; n < len && byts[arridx + n] == 0; ++n) ; sp->ts_curi += n; // Always past NUL bytes now. n = (int)sp->ts_state; PROF_STORE(sp->ts_state) sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; // At end of a prefix or at start of prefixtree: check for // following word. if (depth < MAXWLEN - 1 && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)) { // Set su->su_badflags to the caps type at this position. // Use the caps type until here for the prefix itself. if (has_mbyte) n = nofold_len(fword, sp->ts_fidx, su->su_badptr); else n = sp->ts_fidx; flags = badword_captype(su->su_badptr, su->su_badptr + n); su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "prefix"); #endif go_deeper(stack, depth, 0); ++depth; sp = &stack[depth]; sp->ts_prefixdepth = depth - 1; byts = fbyts; idxs = fidxs; sp->ts_arridx = 0; // Move the prefix to preword[] with the right case // and make find_keepcap_word() works. tword[sp->ts_twordlen] = NUL; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, flags); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; } break; } if (sp->ts_curi > len || byts[arridx] != 0) { // Past bytes in node and/or past NUL bytes. PROF_STORE(sp->ts_state) sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; break; } // End of word in tree. ++sp->ts_curi; // eat one NUL byte flags = (int)idxs[arridx]; // Skip words with the NOSUGGEST flag. if (flags & WF_NOSUGGEST) break; fword_ends = (fword[sp->ts_fidx] == NUL || (soundfold ? VIM_ISWHITE(fword[sp->ts_fidx]) : !spell_iswordp(fword + sp->ts_fidx, curwin))); tword[sp->ts_twordlen] = NUL; if (sp->ts_prefixdepth <= PFD_NOTSPECIAL && (sp->ts_flags & TSF_PREFIXOK) == 0 && pbyts != NULL) { // There was a prefix before the word. Check that the prefix // can be used with this word. // Count the length of the NULs in the prefix. If there are // none this must be the first try without a prefix. n = stack[sp->ts_prefixdepth].ts_arridx; len = pbyts[n++]; for (c = 0; c < len && pbyts[n + c] == 0; ++c) ; if (c > 0) { c = valid_word_prefix(c, n, flags, tword + sp->ts_splitoff, slang, FALSE); if (c == 0) break; // Use the WF_RARE flag for a rare prefix. if (c & WF_RAREPFX) flags |= WF_RARE; // Tricky: when checking for both prefix and compounding // we run into the prefix flag first. // Remember that it's OK, so that we accept the prefix // when arriving at a compound flag. sp->ts_flags |= TSF_PREFIXOK; } } // Check NEEDCOMPOUND: can't use word without compounding. Do try // appending another compound word below. if (sp->ts_complen == sp->ts_compsplit && fword_ends && (flags & WF_NEEDCOMP)) goodword_ends = FALSE; else goodword_ends = TRUE; p = NULL; compound_ok = TRUE; if (sp->ts_complen > sp->ts_compsplit) { if (slang->sl_nobreak) { // There was a word before this word. When there was no // change in this word (it was correct) add the first word // as a suggestion. If this word was corrected too, we // need to check if a correct word follows. if (sp->ts_fidx - sp->ts_splitfidx == sp->ts_twordlen - sp->ts_splitoff && STRNCMP(fword + sp->ts_splitfidx, tword + sp->ts_splitoff, sp->ts_fidx - sp->ts_splitfidx) == 0) { preword[sp->ts_prewordlen] = NUL; newscore = score_wordcount_adj(slang, sp->ts_score, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (newscore <= su->su_maxscore) add_suggestion(su, &su->su_ga, preword, sp->ts_splitfidx - repextra, newscore, 0, FALSE, lp->lp_sallang, FALSE); break; } } else { // There was a compound word before this word. If this // word does not support compounding then give up // (splitting is tried for the word without compound // flag). if (((unsigned)flags >> 24) == 0 || sp->ts_twordlen - sp->ts_splitoff < slang->sl_compminlen) break; // For multi-byte chars check character length against // COMPOUNDMIN. if (has_mbyte && slang->sl_compminlen > 0 && mb_charlen(tword + sp->ts_splitoff) < slang->sl_compminlen) break; compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; vim_strncpy(preword + sp->ts_prewordlen, tword + sp->ts_splitoff, sp->ts_twordlen - sp->ts_splitoff); // Verify CHECKCOMPOUNDPATTERN rules. if (match_checkcompoundpattern(preword, sp->ts_prewordlen, &slang->sl_comppat)) compound_ok = FALSE; if (compound_ok) { p = preword; while (*skiptowhite(p) != NUL) p = skipwhite(skiptowhite(p)); if (fword_ends && !can_compound(slang, p, compflags + sp->ts_compsplit)) // Compound is not allowed. But it may still be // possible if we add another (short) word. compound_ok = FALSE; } // Get pointer to last char of previous word. p = preword + sp->ts_prewordlen; MB_PTR_BACK(preword, p); } } // Form the word with proper case in preword. // If there is a word from a previous split, append. // For the soundfold tree don't change the case, simply append. if (soundfold) STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff); else if (flags & WF_KEEPCAP) // Must find the word in the keep-case tree. find_keepcap_word(slang, tword + sp->ts_splitoff, preword + sp->ts_prewordlen); else { // Include badflags: If the badword is onecap or allcap // use that for the goodword too. But if the badword is // allcap and it's only one char long use onecap. c = su->su_badflags; if ((c & WF_ALLCAP) && su->su_badlen == (*mb_ptr2len)(su->su_badptr)) c = WF_ONECAP; c |= flags; // When appending a compound word after a word character don't // use Onecap. if (p != NULL && spell_iswordp_nmw(p, curwin)) c &= ~WF_ONECAP; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c); } if (!soundfold) { // Don't use a banned word. It may appear again as a good // word, thus remember it. if (flags & WF_BANNED) { add_banned(su, preword + sp->ts_prewordlen); break; } if ((sp->ts_complen == sp->ts_compsplit && WAS_BANNED(su, preword + sp->ts_prewordlen)) || WAS_BANNED(su, preword)) { if (slang->sl_compprog == NULL) break; // the word so far was banned but we may try compounding goodword_ends = FALSE; } } newscore = 0; if (!soundfold) // soundfold words don't have flags { if ((flags & WF_REGION) && (((unsigned)flags >> 16) & lp->lp_region) == 0) newscore += SCORE_REGION; if (flags & WF_RARE) newscore += SCORE_RARE; if (!spell_valid_case(su->su_badflags, captype(preword + sp->ts_prewordlen, NULL))) newscore += SCORE_ICASE; } // TODO: how about splitting in the soundfold tree? if (fword_ends && goodword_ends && sp->ts_fidx >= sp->ts_fidxtry && compound_ok) { // The badword also ends: add suggestions. #ifdef DEBUG_TRIEWALK if (soundfold && STRCMP(preword, "smwrd") == 0) { int j; // print the stack of changes that brought us here smsg("------ %s -------", fword); for (j = 0; j < depth; ++j) smsg("%s", changename[j]); } #endif if (soundfold) { // For soundfolded words we need to find the original // words, the edit distance and then add them. add_sound_suggest(su, preword, sp->ts_score, lp); } else if (sp->ts_fidx > 0) { // Give a penalty when changing non-word char to word // char, e.g., "thes," -> "these". p = fword + sp->ts_fidx; MB_PTR_BACK(fword, p); if (!spell_iswordp(p, curwin) && *preword != NUL) { p = preword + STRLEN(preword); MB_PTR_BACK(preword, p); if (spell_iswordp(p, curwin)) newscore += SCORE_NONWORD; } // Give a bonus to words seen before. score = score_wordcount_adj(slang, sp->ts_score + newscore, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (score <= su->su_maxscore) { add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score, 0, FALSE, lp->lp_sallang, FALSE); if (su->su_badflags & WF_MIXCAP) { // We really don't know if the word should be // upper or lower case, add both. c = captype(preword, NULL); if (c == 0 || c == WF_ALLCAP) { make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c == 0 ? WF_ALLCAP : 0); add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score + SCORE_ICASE, 0, FALSE, lp->lp_sallang, FALSE); } } } } } // Try word split and/or compounding. if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends) // Don't split halfway a character. && (!has_mbyte || sp->ts_tcharlen == 0)) { int try_compound; int try_split; // If past the end of the bad word don't try a split. // Otherwise try changing the next word. E.g., find // suggestions for "the the" where the second "the" is // different. It's done like a split. // TODO: word split for soundfold words try_split = (sp->ts_fidx - repextra < su->su_badlen) && !soundfold; // Get here in several situations: // 1. The word in the tree ends: // If the word allows compounding try that. Otherwise try // a split by inserting a space. For both check that a // valid words starts at fword[sp->ts_fidx]. // For NOBREAK do like compounding to be able to check if // the next word is valid. // 2. The badword does end, but it was due to a change (e.g., // a swap). No need to split, but do check that the // following word is valid. // 3. The badword and the word in the tree end. It may still // be possible to compound another (short) word. try_compound = FALSE; if (!soundfold && !slang->sl_nocompoundsugs && slang->sl_compprog != NULL && ((unsigned)flags >> 24) != 0 && sp->ts_twordlen - sp->ts_splitoff >= slang->sl_compminlen && (!has_mbyte || slang->sl_compminlen == 0 || mb_charlen(tword + sp->ts_splitoff) >= slang->sl_compminlen) && (slang->sl_compsylmax < MAXWLEN || sp->ts_complen + 1 - sp->ts_compsplit < slang->sl_compmax) && (can_be_compound(sp, slang, compflags, ((unsigned)flags >> 24)))) { try_compound = TRUE; compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; } // For NOBREAK we never try splitting, it won't make any word // valid. if (slang->sl_nobreak && !slang->sl_nocompoundsugs) try_compound = TRUE; // If we could add a compound word, and it's also possible to // split at this point, do the split first and set // TSF_DIDSPLIT to avoid doing it again. else if (!fword_ends && try_compound && (sp->ts_flags & TSF_DIDSPLIT) == 0) { try_compound = FALSE; sp->ts_flags |= TSF_DIDSPLIT; --sp->ts_curi; // do the same NUL again compflags[sp->ts_complen] = NUL; } else sp->ts_flags &= ~TSF_DIDSPLIT; if (try_split || try_compound) { if (!try_compound && (!fword_ends || !goodword_ends)) { // If we're going to split need to check that the // words so far are valid for compounding. If there // is only one word it must not have the NEEDCOMPOUND // flag. if (sp->ts_complen == sp->ts_compsplit && (flags & WF_NEEDCOMP)) break; p = preword; while (*skiptowhite(p) != NUL) p = skipwhite(skiptowhite(p)); if (sp->ts_complen > sp->ts_compsplit && !can_compound(slang, p, compflags + sp->ts_compsplit)) break; if (slang->sl_nosplitsugs) newscore += SCORE_SPLIT_NO; else newscore += SCORE_SPLIT; // Give a bonus to words seen before. newscore = score_wordcount_adj(slang, newscore, preword + sp->ts_prewordlen, TRUE); } if (TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (!try_compound && !fword_ends) sprintf(changename[depth], "%.*s-%s: split", sp->ts_twordlen, tword, fword + sp->ts_fidx); else sprintf(changename[depth], "%.*s-%s: compound", sp->ts_twordlen, tword, fword + sp->ts_fidx); #endif // Save things to be restored at STATE_SPLITUNDO. sp->ts_save_badflags = su->su_badflags; PROF_STORE(sp->ts_state) sp->ts_state = STATE_SPLITUNDO; ++depth; sp = &stack[depth]; // Append a space to preword when splitting. if (!try_compound && !fword_ends) STRCAT(preword, " "); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; sp->ts_splitfidx = sp->ts_fidx; // If the badword has a non-word character at this // position skip it. That means replacing the // non-word character with a space. Always skip a // character when the word ends. But only when the // good word can end. if (((!try_compound && !spell_iswordp_nmw(fword + sp->ts_fidx, curwin)) || fword_ends) && fword[sp->ts_fidx] != NUL && goodword_ends) { int l; l = mb_ptr2len(fword + sp->ts_fidx); if (fword_ends) { // Copy the skipped character to preword. mch_memmove(preword + sp->ts_prewordlen, fword + sp->ts_fidx, l); sp->ts_prewordlen += l; preword[sp->ts_prewordlen] = NUL; } else sp->ts_score -= SCORE_SPLIT - SCORE_SUBST; sp->ts_fidx += l; } // When compounding include compound flag in // compflags[] (already set above). When splitting we // may start compounding over again. if (try_compound) ++sp->ts_complen; else sp->ts_compsplit = sp->ts_complen; sp->ts_prefixdepth = PFD_NOPREFIX; // set su->su_badflags to the caps type at this // position if (has_mbyte) n = nofold_len(fword, sp->ts_fidx, su->su_badptr); else n = sp->ts_fidx; su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); // Restart at top of the tree. sp->ts_arridx = 0; // If there are postponed prefixes, try these too. if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; PROF_STORE(sp->ts_state) sp->ts_state = STATE_NOPREFIX; } } } } break; case STATE_SPLITUNDO: // Undo the changes done for word split or compound word. su->su_badflags = sp->ts_save_badflags; // Continue looking for NUL bytes. PROF_STORE(sp->ts_state) sp->ts_state = STATE_START; // In case we went into the prefix tree. byts = fbyts; idxs = fidxs; break; case STATE_ENDNUL: // Past the NUL bytes in the node. su->su_badflags = sp->ts_save_badflags; if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0) { // The badword ends, can't use STATE_PLAIN. PROF_STORE(sp->ts_state) sp->ts_state = STATE_DEL; break; } PROF_STORE(sp->ts_state) sp->ts_state = STATE_PLAIN; // FALLTHROUGH case STATE_PLAIN: // Go over all possible bytes at this node, add each to tword[] // and use child node. "ts_curi" is the index. arridx = sp->ts_arridx; if (sp->ts_curi > byts[arridx]) { // Done all bytes at this node, do next state. When still at // already changed bytes skip the other tricks. PROF_STORE(sp->ts_state) if (sp->ts_fidx >= sp->ts_fidxtry) sp->ts_state = STATE_DEL; else sp->ts_state = STATE_FINAL; } else { arridx += sp->ts_curi++; c = byts[arridx]; // Normal byte, go one level deeper. If it's not equal to the // byte in the bad word adjust the score. But don't even try // when the byte was already changed. And don't try when we // just deleted this byte, accepting it is always cheaper than // delete + substitute. if (c == fword[sp->ts_fidx] || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE)) newscore = 0; else newscore = SCORE_SUBST; if ((newscore == 0 || (sp->ts_fidx >= sp->ts_fidxtry && ((sp->ts_flags & TSF_DIDDEL) == 0 || c != fword[sp->ts_delidx]))) && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (newscore > 0) sprintf(changename[depth], "%.*s-%s: subst %c to %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx], c); else sprintf(changename[depth], "%.*s-%s: accept %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; sp = &stack[depth]; if (fword[sp->ts_fidx] != NUL) ++sp->ts_fidx; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[arridx]; if (newscore == SCORE_SUBST) sp->ts_isdiff = DIFF_YES; if (has_mbyte) { // Multi-byte characters are a bit complicated to // handle: They differ when any of the bytes differ // and then their length may also differ. if (sp->ts_tcharlen == 0) { // First byte. sp->ts_tcharidx = 0; sp->ts_tcharlen = MB_BYTE2LEN(c); sp->ts_fcharstart = sp->ts_fidx - 1; sp->ts_isdiff = (newscore != 0) ? DIFF_YES : DIFF_NONE; } else if (sp->ts_isdiff == DIFF_INSERT) // When inserting trail bytes don't advance in the // bad word. --sp->ts_fidx; if (++sp->ts_tcharidx == sp->ts_tcharlen) { // Last byte of character. if (sp->ts_isdiff == DIFF_YES) { // Correct ts_fidx for the byte length of the // character (we didn't check that before). sp->ts_fidx = sp->ts_fcharstart + mb_ptr2len( fword + sp->ts_fcharstart); // For changing a composing character adjust // the score from SCORE_SUBST to // SCORE_SUBCOMP. if (enc_utf8 && utf_iscomposing( utf_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen)) && utf_iscomposing( utf_ptr2char(fword + sp->ts_fcharstart))) sp->ts_score -= SCORE_SUBST - SCORE_SUBCOMP; // For a similar character adjust score from // SCORE_SUBST to SCORE_SIMILAR. else if (!soundfold && slang->sl_has_map && similar_chars(slang, mb_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen), mb_ptr2char(fword + sp->ts_fcharstart))) sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } else if (sp->ts_isdiff == DIFF_INSERT && sp->ts_twordlen > sp->ts_tcharlen) { p = tword + sp->ts_twordlen - sp->ts_tcharlen; c = mb_ptr2char(p); if (enc_utf8 && utf_iscomposing(c)) { // Inserting a composing char doesn't // count that much. sp->ts_score -= SCORE_INS - SCORE_INSCOMP; } else { // If the previous character was the same, // thus doubling a character, give a bonus // to the score. Also for the soundfold // tree (might seem illogical but does // give better scores). MB_PTR_BACK(tword, p); if (c == mb_ptr2char(p)) sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } // Starting a new char, reset the length. sp->ts_tcharlen = 0; } } else { // If we found a similar char adjust the score. // We do this after calling go_deeper() because // it's slow. if (newscore != 0 && !soundfold && slang->sl_has_map && similar_chars(slang, c, fword[sp->ts_fidx - 1])) sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } } } break; case STATE_DEL: // When past the first byte of a multi-byte char don't try // delete/insert/swap a character. if (has_mbyte && sp->ts_tcharlen > 0) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Try skipping one character in the bad word (delete it). PROF_STORE(sp->ts_state) sp->ts_state = STATE_INS_PREP; sp->ts_curi = 1; if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*') // Deleting a vowel at the start of a word counts less, see // soundalike_score(). newscore = 2 * SCORE_DEL / 3; else newscore = SCORE_DEL; if (fword[sp->ts_fidx] != NUL && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: delete %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; // Remember what character we deleted, so that we can avoid // inserting it again. stack[depth].ts_flags |= TSF_DIDDEL; stack[depth].ts_delidx = sp->ts_fidx; // Advance over the character in fword[]. Give a bonus to the // score if the same character is following "nn" -> "n". It's // a bit illogical for soundfold tree but it does give better // results. if (has_mbyte) { c = mb_ptr2char(fword + sp->ts_fidx); stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx); if (enc_utf8 && utf_iscomposing(c)) stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP; else if (c == mb_ptr2char(fword + stack[depth].ts_fidx)) stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } else { ++stack[depth].ts_fidx; if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1]) stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } break; } // FALLTHROUGH case STATE_INS_PREP: if (sp->ts_flags & TSF_DIDDEL) { // If we just deleted a byte then inserting won't make sense, // a substitute is always cheaper. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } // skip over NUL bytes n = sp->ts_arridx; for (;;) { if (sp->ts_curi > byts[n]) { // Only NUL bytes at this node, go to next state. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } if (byts[n + sp->ts_curi] != NUL) { // Found a byte to insert. PROF_STORE(sp->ts_state) sp->ts_state = STATE_INS; break; } ++sp->ts_curi; } break; // FALLTHROUGH case STATE_INS: // Insert one byte. Repeat this for each possible byte at this // node. n = sp->ts_arridx; if (sp->ts_curi > byts[n]) { // Done all bytes at this node, go to next state. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } // Do one more byte at this node, but: // - Skip NUL bytes. // - Skip the byte if it's equal to the byte in the word, // accepting that byte is always better. n += sp->ts_curi++; c = byts[n]; if (soundfold && sp->ts_twordlen == 0 && c == '*') // Inserting a vowel at the start of a word counts less, // see soundalike_score(). newscore = 2 * SCORE_INS / 3; else newscore = SCORE_INS; if (c != fword[sp->ts_fidx] && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: insert %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c); #endif ++depth; sp = &stack[depth]; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[n]; if (has_mbyte) { fl = MB_BYTE2LEN(c); if (fl > 1) { // There are following bytes for the same character. // We must find all bytes before trying // delete/insert/swap/etc. sp->ts_tcharlen = fl; sp->ts_tcharidx = 1; sp->ts_isdiff = DIFF_INSERT; } } else fl = 1; if (fl == 1) { // If the previous character was the same, thus doubling a // character, give a bonus to the score. Also for // soundfold words (illogical but does give a better // score). if (sp->ts_twordlen >= 2 && tword[sp->ts_twordlen - 2] == c) sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } break; case STATE_SWAP: // Swap two bytes in the bad word: "12" -> "21". // We change "fword" here, it's changed back afterwards at // STATE_UNSWAP. p = fword + sp->ts_fidx; c = *p; if (c == NUL) { // End of word, can't swap or replace. PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Don't swap if the first character is not a word character. // SWAP3 etc. also don't make sense then. if (!soundfold && !spell_iswordp(p, curwin)) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } if (has_mbyte) { n = MB_CPTR2LEN(p); c = mb_ptr2char(p); if (p[n] == NUL) c2 = NUL; else if (!soundfold && !spell_iswordp(p + n, curwin)) c2 = c; // don't swap non-word char else c2 = mb_ptr2char(p + n); } else { if (p[1] == NUL) c2 = NUL; else if (!soundfold && !spell_iswordp(p + 1, curwin)) c2 = c; // don't swap non-word char else c2 = p[1]; } // When the second character is NUL we can't swap. if (c2 == NUL) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } // When characters are identical, swap won't do anything. // Also get here if the second char is not a word character. if (c == c2) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP3; break; } if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP)) { go_deeper(stack, depth, SCORE_SWAP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c2); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNSWAP; ++depth; if (has_mbyte) { fl = mb_char2len(c2); mch_memmove(p, p + n, fl); mb_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else { p[0] = c2; p[1] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 2; } } else { // If this swap doesn't work then SWAP3 won't either. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNSWAP: // Undo the STATE_SWAP swap: "21" -> "12". p = fword + sp->ts_fidx; if (has_mbyte) { n = mb_ptr2len(p); c = mb_ptr2char(p + n); mch_memmove(p + mb_ptr2len(p + n), p, n); mb_char2bytes(c, p); } else { c = *p; *p = p[1]; p[1] = c; } // FALLTHROUGH case STATE_SWAP3: // Swap two bytes, skipping one: "123" -> "321". We change // "fword" here, it's changed back afterwards at STATE_UNSWAP3. p = fword + sp->ts_fidx; if (has_mbyte) { n = MB_CPTR2LEN(p); c = mb_ptr2char(p); fl = MB_CPTR2LEN(p + n); c2 = mb_ptr2char(p + n); if (!soundfold && !spell_iswordp(p + n + fl, curwin)) c3 = c; // don't swap non-word char else c3 = mb_ptr2char(p + n + fl); } else { c = *p; c2 = p[1]; if (!soundfold && !spell_iswordp(p + 2, curwin)) c3 = c; // don't swap non-word char else c3 = p[2]; } // When characters are identical: "121" then SWAP3 result is // identical, ROT3L result is same as SWAP: "211", ROT3L result is // same as SWAP on next char: "112". Thus skip all swapping. // Also skip when c3 is NUL. // Also get here when the third character is not a word character. // Second character may any char: "a.b" -> "b.a" if (c == c3 || c3 == NUL) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap3 %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c3); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNSWAP3; ++depth; if (has_mbyte) { tl = mb_char2len(c3); mch_memmove(p, p + n + fl, tl); mb_char2bytes(c2, p + tl); mb_char2bytes(c, p + fl + tl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl; } else { p[0] = p[2]; p[2] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNSWAP3: // Undo STATE_SWAP3: "321" -> "123" p = fword + sp->ts_fidx; if (has_mbyte) { n = mb_ptr2len(p); c2 = mb_ptr2char(p + n); fl = mb_ptr2len(p + n); c = mb_ptr2char(p + n + fl); tl = mb_ptr2len(p + n + fl); mch_memmove(p + fl + tl, p, n); mb_char2bytes(c, p); mb_char2bytes(c2, p + tl); p = p + tl; } else { c = *p; *p = p[2]; p[2] = c; ++p; } if (!soundfold && !spell_iswordp(p, curwin)) { // Middle char is not a word char, skip the rotate. First and // third char were already checked at swap and swap3. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } // Rotate three characters left: "123" -> "231". We change // "fword" here, it's changed back afterwards at STATE_UNROT3L. if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNROT3L; ++depth; p = fword + sp->ts_fidx; if (has_mbyte) { n = MB_CPTR2LEN(p); c = mb_ptr2char(p); fl = MB_CPTR2LEN(p + n); fl += MB_CPTR2LEN(p + n + fl); mch_memmove(p, p + n, fl); mb_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else { c = *p; *p = p[1]; p[1] = p[2]; p[2] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNROT3L: // Undo ROT3L: "231" -> "123" p = fword + sp->ts_fidx; if (has_mbyte) { n = mb_ptr2len(p); n += mb_ptr2len(p + n); c = mb_ptr2char(p + n); tl = mb_ptr2len(p + n); mch_memmove(p + tl, p, n); mb_char2bytes(c, p); } else { c = p[2]; p[2] = p[1]; p[1] = *p; *p = c; } // Rotate three bytes right: "123" -> "312". We change "fword" // here, it's changed back afterwards at STATE_UNROT3R. if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNROT3R; ++depth; p = fword + sp->ts_fidx; if (has_mbyte) { n = MB_CPTR2LEN(p); n += MB_CPTR2LEN(p + n); c = mb_ptr2char(p + n); tl = MB_CPTR2LEN(p + n); mch_memmove(p + tl, p, n); mb_char2bytes(c, p); stack[depth].ts_fidxtry = sp->ts_fidx + n + tl; } else { c = p[2]; p[2] = p[1]; p[1] = *p; *p = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNROT3R: // Undo ROT3R: "312" -> "123" p = fword + sp->ts_fidx; if (has_mbyte) { c = mb_ptr2char(p); tl = mb_ptr2len(p); n = mb_ptr2len(p + tl); n += mb_ptr2len(p + tl + n); mch_memmove(p, p + tl, n); mb_char2bytes(c, p + n); } else { c = *p; *p = p[1]; p[1] = p[2]; p[2] = c; } // FALLTHROUGH case STATE_REP_INI: // Check if matching with REP items from the .aff file would work. // Quickly skip if: // - there are no REP items and we are not in the soundfold trie // - the score is going to be too high anyway // - already applied a REP item or swapped here if ((lp->lp_replang == NULL && !soundfold) || sp->ts_score + SCORE_REP >= su->su_maxscore || sp->ts_fidx < sp->ts_fidxtry) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Use the first byte to quickly find the first entry that may // match. If the index is -1 there is none. if (soundfold) sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]]; else sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]]; if (sp->ts_curi < 0) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP; // FALLTHROUGH case STATE_REP: // Try matching with REP items from the .aff file. For each match // replace the characters and check if the resulting word is // valid. p = fword + sp->ts_fidx; if (soundfold) gap = &slang->sl_repsal; else gap = &lp->lp_replang->sl_rep; while (sp->ts_curi < gap->ga_len) { ftp = (fromto_T *)gap->ga_data + sp->ts_curi++; if (*ftp->ft_from != *p) { // past possible matching entries sp->ts_curi = gap->ga_len; break; } if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0 && TRY_DEEPER(su, stack, depth, SCORE_REP)) { go_deeper(stack, depth, SCORE_REP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: replace %s with %s", sp->ts_twordlen, tword, fword + sp->ts_fidx, ftp->ft_from, ftp->ft_to); #endif // Need to undo this afterwards. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_UNDO; // Change the "from" to the "to" string. ++depth; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); if (fl != tl) { STRMOVE(p + tl, p + fl); repextra += tl - fl; } mch_memmove(p, ftp->ft_to, tl); stack[depth].ts_fidxtry = sp->ts_fidx + tl; stack[depth].ts_tcharlen = 0; break; } } if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP) { // No (more) matches. PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; } break; case STATE_REP_UNDO: // Undo a REP replacement and continue with the next one. if (soundfold) gap = &slang->sl_repsal; else gap = &lp->lp_replang->sl_rep; ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); p = fword + sp->ts_fidx; if (fl != tl) { STRMOVE(p + fl, p + tl); repextra -= tl - fl; } mch_memmove(p, ftp->ft_from, fl); PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP; break; default: // Did all possible states at this level, go up one level. --depth; if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE) { // Continue in or go back to the prefix tree. byts = pbyts; idxs = pidxs; } // Don't check for CTRL-C too often, it takes time. if (--breakcheckcount == 0) { ui_breakcheck(); breakcheckcount = 1000; #ifdef FEAT_RELTIME if (spell_suggest_timeout > 0 && profile_passed_limit(&time_limit)) got_int = TRUE; #endif } } } }
86190004113264578506184029642372711349
spellsuggest.c
224942464208559430024115846607965193151
CWE-787
CVE-2022-2126
Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-2126
301,481
vim
156d3911952d73b03d7420dc3540215247db0fe8
https://github.com/vim/vim
https://github.com/vim/vim/commit/156d3911952d73b03d7420dc3540215247db0fe8
patch 8.2.5123: using invalid index when looking for spell suggestions Problem: Using invalid index when looking for spell suggestions. Solution: Do not decrement the index when it is zero.
0
suggest_trie_walk( suginfo_T *su, langp_T *lp, char_u *fword, int soundfold) { char_u tword[MAXWLEN]; // good word collected so far trystate_T stack[MAXWLEN]; char_u preword[MAXWLEN * 3]; // word found with proper case; // concatenation of prefix compound // words and split word. NUL terminated // when going deeper but not when coming // back. char_u compflags[MAXWLEN]; // compound flags, one for each word trystate_T *sp; int newscore; int score; char_u *byts, *fbyts, *pbyts; idx_T *idxs, *fidxs, *pidxs; int depth; int c, c2, c3; int n = 0; int flags; garray_T *gap; idx_T arridx; int len; char_u *p; fromto_T *ftp; int fl = 0, tl; int repextra = 0; // extra bytes in fword[] from REP item slang_T *slang = lp->lp_slang; int fword_ends; int goodword_ends; #ifdef DEBUG_TRIEWALK // Stores the name of the change made at each level. char_u changename[MAXWLEN][80]; #endif int breakcheckcount = 1000; #ifdef FEAT_RELTIME proftime_T time_limit; #endif int compound_ok; // Go through the whole case-fold tree, try changes at each node. // "tword[]" contains the word collected from nodes in the tree. // "fword[]" the word we are trying to match with (initially the bad // word). depth = 0; sp = &stack[0]; CLEAR_POINTER(sp); sp->ts_curi = 1; if (soundfold) { // Going through the soundfold tree. byts = fbyts = slang->sl_sbyts; idxs = fidxs = slang->sl_sidxs; pbyts = NULL; pidxs = NULL; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } else { // When there are postponed prefixes we need to use these first. At // the end of the prefix we continue in the case-fold tree. fbyts = slang->sl_fbyts; fidxs = slang->sl_fidxs; pbyts = slang->sl_pbyts; pidxs = slang->sl_pidxs; if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; sp->ts_state = STATE_NOPREFIX; // try without prefix first } else { byts = fbyts; idxs = fidxs; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } } #ifdef FEAT_RELTIME // The loop may take an indefinite amount of time. Break out after some // time. if (spell_suggest_timeout > 0) profile_setlimit(spell_suggest_timeout, &time_limit); #endif // Loop to find all suggestions. At each round we either: // - For the current state try one operation, advance "ts_curi", // increase "depth". // - When a state is done go to the next, set "ts_state". // - When all states are tried decrease "depth". while (depth >= 0 && !got_int) { sp = &stack[depth]; switch (sp->ts_state) { case STATE_START: case STATE_NOPREFIX: // Start of node: Deal with NUL bytes, which means // tword[] may end here. arridx = sp->ts_arridx; // current node in the tree len = byts[arridx]; // bytes in this node arridx += sp->ts_curi; // index of current byte if (sp->ts_prefixdepth == PFD_PREFIXTREE) { // Skip over the NUL bytes, we use them later. for (n = 0; n < len && byts[arridx + n] == 0; ++n) ; sp->ts_curi += n; // Always past NUL bytes now. n = (int)sp->ts_state; PROF_STORE(sp->ts_state) sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; // At end of a prefix or at start of prefixtree: check for // following word. if (depth < MAXWLEN - 1 && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)) { // Set su->su_badflags to the caps type at this position. // Use the caps type until here for the prefix itself. if (has_mbyte) n = nofold_len(fword, sp->ts_fidx, su->su_badptr); else n = sp->ts_fidx; flags = badword_captype(su->su_badptr, su->su_badptr + n); su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "prefix"); #endif go_deeper(stack, depth, 0); ++depth; sp = &stack[depth]; sp->ts_prefixdepth = depth - 1; byts = fbyts; idxs = fidxs; sp->ts_arridx = 0; // Move the prefix to preword[] with the right case // and make find_keepcap_word() works. tword[sp->ts_twordlen] = NUL; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, flags); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; } break; } if (sp->ts_curi > len || byts[arridx] != 0) { // Past bytes in node and/or past NUL bytes. PROF_STORE(sp->ts_state) sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; break; } // End of word in tree. ++sp->ts_curi; // eat one NUL byte flags = (int)idxs[arridx]; // Skip words with the NOSUGGEST flag. if (flags & WF_NOSUGGEST) break; fword_ends = (fword[sp->ts_fidx] == NUL || (soundfold ? VIM_ISWHITE(fword[sp->ts_fidx]) : !spell_iswordp(fword + sp->ts_fidx, curwin))); tword[sp->ts_twordlen] = NUL; if (sp->ts_prefixdepth <= PFD_NOTSPECIAL && (sp->ts_flags & TSF_PREFIXOK) == 0 && pbyts != NULL) { // There was a prefix before the word. Check that the prefix // can be used with this word. // Count the length of the NULs in the prefix. If there are // none this must be the first try without a prefix. n = stack[sp->ts_prefixdepth].ts_arridx; len = pbyts[n++]; for (c = 0; c < len && pbyts[n + c] == 0; ++c) ; if (c > 0) { c = valid_word_prefix(c, n, flags, tword + sp->ts_splitoff, slang, FALSE); if (c == 0) break; // Use the WF_RARE flag for a rare prefix. if (c & WF_RAREPFX) flags |= WF_RARE; // Tricky: when checking for both prefix and compounding // we run into the prefix flag first. // Remember that it's OK, so that we accept the prefix // when arriving at a compound flag. sp->ts_flags |= TSF_PREFIXOK; } } // Check NEEDCOMPOUND: can't use word without compounding. Do try // appending another compound word below. if (sp->ts_complen == sp->ts_compsplit && fword_ends && (flags & WF_NEEDCOMP)) goodword_ends = FALSE; else goodword_ends = TRUE; p = NULL; compound_ok = TRUE; if (sp->ts_complen > sp->ts_compsplit) { if (slang->sl_nobreak) { // There was a word before this word. When there was no // change in this word (it was correct) add the first word // as a suggestion. If this word was corrected too, we // need to check if a correct word follows. if (sp->ts_fidx - sp->ts_splitfidx == sp->ts_twordlen - sp->ts_splitoff && STRNCMP(fword + sp->ts_splitfidx, tword + sp->ts_splitoff, sp->ts_fidx - sp->ts_splitfidx) == 0) { preword[sp->ts_prewordlen] = NUL; newscore = score_wordcount_adj(slang, sp->ts_score, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (newscore <= su->su_maxscore) add_suggestion(su, &su->su_ga, preword, sp->ts_splitfidx - repextra, newscore, 0, FALSE, lp->lp_sallang, FALSE); break; } } else { // There was a compound word before this word. If this // word does not support compounding then give up // (splitting is tried for the word without compound // flag). if (((unsigned)flags >> 24) == 0 || sp->ts_twordlen - sp->ts_splitoff < slang->sl_compminlen) break; // For multi-byte chars check character length against // COMPOUNDMIN. if (has_mbyte && slang->sl_compminlen > 0 && mb_charlen(tword + sp->ts_splitoff) < slang->sl_compminlen) break; compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; vim_strncpy(preword + sp->ts_prewordlen, tword + sp->ts_splitoff, sp->ts_twordlen - sp->ts_splitoff); // Verify CHECKCOMPOUNDPATTERN rules. if (match_checkcompoundpattern(preword, sp->ts_prewordlen, &slang->sl_comppat)) compound_ok = FALSE; if (compound_ok) { p = preword; while (*skiptowhite(p) != NUL) p = skipwhite(skiptowhite(p)); if (fword_ends && !can_compound(slang, p, compflags + sp->ts_compsplit)) // Compound is not allowed. But it may still be // possible if we add another (short) word. compound_ok = FALSE; } // Get pointer to last char of previous word. p = preword + sp->ts_prewordlen; MB_PTR_BACK(preword, p); } } // Form the word with proper case in preword. // If there is a word from a previous split, append. // For the soundfold tree don't change the case, simply append. if (soundfold) STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff); else if (flags & WF_KEEPCAP) // Must find the word in the keep-case tree. find_keepcap_word(slang, tword + sp->ts_splitoff, preword + sp->ts_prewordlen); else { // Include badflags: If the badword is onecap or allcap // use that for the goodword too. But if the badword is // allcap and it's only one char long use onecap. c = su->su_badflags; if ((c & WF_ALLCAP) && su->su_badlen == (*mb_ptr2len)(su->su_badptr)) c = WF_ONECAP; c |= flags; // When appending a compound word after a word character don't // use Onecap. if (p != NULL && spell_iswordp_nmw(p, curwin)) c &= ~WF_ONECAP; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c); } if (!soundfold) { // Don't use a banned word. It may appear again as a good // word, thus remember it. if (flags & WF_BANNED) { add_banned(su, preword + sp->ts_prewordlen); break; } if ((sp->ts_complen == sp->ts_compsplit && WAS_BANNED(su, preword + sp->ts_prewordlen)) || WAS_BANNED(su, preword)) { if (slang->sl_compprog == NULL) break; // the word so far was banned but we may try compounding goodword_ends = FALSE; } } newscore = 0; if (!soundfold) // soundfold words don't have flags { if ((flags & WF_REGION) && (((unsigned)flags >> 16) & lp->lp_region) == 0) newscore += SCORE_REGION; if (flags & WF_RARE) newscore += SCORE_RARE; if (!spell_valid_case(su->su_badflags, captype(preword + sp->ts_prewordlen, NULL))) newscore += SCORE_ICASE; } // TODO: how about splitting in the soundfold tree? if (fword_ends && goodword_ends && sp->ts_fidx >= sp->ts_fidxtry && compound_ok) { // The badword also ends: add suggestions. #ifdef DEBUG_TRIEWALK if (soundfold && STRCMP(preword, "smwrd") == 0) { int j; // print the stack of changes that brought us here smsg("------ %s -------", fword); for (j = 0; j < depth; ++j) smsg("%s", changename[j]); } #endif if (soundfold) { // For soundfolded words we need to find the original // words, the edit distance and then add them. add_sound_suggest(su, preword, sp->ts_score, lp); } else if (sp->ts_fidx > 0) { // Give a penalty when changing non-word char to word // char, e.g., "thes," -> "these". p = fword + sp->ts_fidx; MB_PTR_BACK(fword, p); if (!spell_iswordp(p, curwin) && *preword != NUL) { p = preword + STRLEN(preword); MB_PTR_BACK(preword, p); if (spell_iswordp(p, curwin)) newscore += SCORE_NONWORD; } // Give a bonus to words seen before. score = score_wordcount_adj(slang, sp->ts_score + newscore, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (score <= su->su_maxscore) { add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score, 0, FALSE, lp->lp_sallang, FALSE); if (su->su_badflags & WF_MIXCAP) { // We really don't know if the word should be // upper or lower case, add both. c = captype(preword, NULL); if (c == 0 || c == WF_ALLCAP) { make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c == 0 ? WF_ALLCAP : 0); add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score + SCORE_ICASE, 0, FALSE, lp->lp_sallang, FALSE); } } } } } // Try word split and/or compounding. if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends) // Don't split halfway a character. && (!has_mbyte || sp->ts_tcharlen == 0)) { int try_compound; int try_split; // If past the end of the bad word don't try a split. // Otherwise try changing the next word. E.g., find // suggestions for "the the" where the second "the" is // different. It's done like a split. // TODO: word split for soundfold words try_split = (sp->ts_fidx - repextra < su->su_badlen) && !soundfold; // Get here in several situations: // 1. The word in the tree ends: // If the word allows compounding try that. Otherwise try // a split by inserting a space. For both check that a // valid words starts at fword[sp->ts_fidx]. // For NOBREAK do like compounding to be able to check if // the next word is valid. // 2. The badword does end, but it was due to a change (e.g., // a swap). No need to split, but do check that the // following word is valid. // 3. The badword and the word in the tree end. It may still // be possible to compound another (short) word. try_compound = FALSE; if (!soundfold && !slang->sl_nocompoundsugs && slang->sl_compprog != NULL && ((unsigned)flags >> 24) != 0 && sp->ts_twordlen - sp->ts_splitoff >= slang->sl_compminlen && (!has_mbyte || slang->sl_compminlen == 0 || mb_charlen(tword + sp->ts_splitoff) >= slang->sl_compminlen) && (slang->sl_compsylmax < MAXWLEN || sp->ts_complen + 1 - sp->ts_compsplit < slang->sl_compmax) && (can_be_compound(sp, slang, compflags, ((unsigned)flags >> 24)))) { try_compound = TRUE; compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; } // For NOBREAK we never try splitting, it won't make any word // valid. if (slang->sl_nobreak && !slang->sl_nocompoundsugs) try_compound = TRUE; // If we could add a compound word, and it's also possible to // split at this point, do the split first and set // TSF_DIDSPLIT to avoid doing it again. else if (!fword_ends && try_compound && (sp->ts_flags & TSF_DIDSPLIT) == 0) { try_compound = FALSE; sp->ts_flags |= TSF_DIDSPLIT; --sp->ts_curi; // do the same NUL again compflags[sp->ts_complen] = NUL; } else sp->ts_flags &= ~TSF_DIDSPLIT; if (try_split || try_compound) { if (!try_compound && (!fword_ends || !goodword_ends)) { // If we're going to split need to check that the // words so far are valid for compounding. If there // is only one word it must not have the NEEDCOMPOUND // flag. if (sp->ts_complen == sp->ts_compsplit && (flags & WF_NEEDCOMP)) break; p = preword; while (*skiptowhite(p) != NUL) p = skipwhite(skiptowhite(p)); if (sp->ts_complen > sp->ts_compsplit && !can_compound(slang, p, compflags + sp->ts_compsplit)) break; if (slang->sl_nosplitsugs) newscore += SCORE_SPLIT_NO; else newscore += SCORE_SPLIT; // Give a bonus to words seen before. newscore = score_wordcount_adj(slang, newscore, preword + sp->ts_prewordlen, TRUE); } if (TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (!try_compound && !fword_ends) sprintf(changename[depth], "%.*s-%s: split", sp->ts_twordlen, tword, fword + sp->ts_fidx); else sprintf(changename[depth], "%.*s-%s: compound", sp->ts_twordlen, tword, fword + sp->ts_fidx); #endif // Save things to be restored at STATE_SPLITUNDO. sp->ts_save_badflags = su->su_badflags; PROF_STORE(sp->ts_state) sp->ts_state = STATE_SPLITUNDO; ++depth; sp = &stack[depth]; // Append a space to preword when splitting. if (!try_compound && !fword_ends) STRCAT(preword, " "); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; sp->ts_splitfidx = sp->ts_fidx; // If the badword has a non-word character at this // position skip it. That means replacing the // non-word character with a space. Always skip a // character when the word ends. But only when the // good word can end. if (((!try_compound && !spell_iswordp_nmw(fword + sp->ts_fidx, curwin)) || fword_ends) && fword[sp->ts_fidx] != NUL && goodword_ends) { int l; l = mb_ptr2len(fword + sp->ts_fidx); if (fword_ends) { // Copy the skipped character to preword. mch_memmove(preword + sp->ts_prewordlen, fword + sp->ts_fidx, l); sp->ts_prewordlen += l; preword[sp->ts_prewordlen] = NUL; } else sp->ts_score -= SCORE_SPLIT - SCORE_SUBST; sp->ts_fidx += l; } // When compounding include compound flag in // compflags[] (already set above). When splitting we // may start compounding over again. if (try_compound) ++sp->ts_complen; else sp->ts_compsplit = sp->ts_complen; sp->ts_prefixdepth = PFD_NOPREFIX; // set su->su_badflags to the caps type at this // position if (has_mbyte) n = nofold_len(fword, sp->ts_fidx, su->su_badptr); else n = sp->ts_fidx; su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); // Restart at top of the tree. sp->ts_arridx = 0; // If there are postponed prefixes, try these too. if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; PROF_STORE(sp->ts_state) sp->ts_state = STATE_NOPREFIX; } } } } break; case STATE_SPLITUNDO: // Undo the changes done for word split or compound word. su->su_badflags = sp->ts_save_badflags; // Continue looking for NUL bytes. PROF_STORE(sp->ts_state) sp->ts_state = STATE_START; // In case we went into the prefix tree. byts = fbyts; idxs = fidxs; break; case STATE_ENDNUL: // Past the NUL bytes in the node. su->su_badflags = sp->ts_save_badflags; if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0) { // The badword ends, can't use STATE_PLAIN. PROF_STORE(sp->ts_state) sp->ts_state = STATE_DEL; break; } PROF_STORE(sp->ts_state) sp->ts_state = STATE_PLAIN; // FALLTHROUGH case STATE_PLAIN: // Go over all possible bytes at this node, add each to tword[] // and use child node. "ts_curi" is the index. arridx = sp->ts_arridx; if (sp->ts_curi > byts[arridx]) { // Done all bytes at this node, do next state. When still at // already changed bytes skip the other tricks. PROF_STORE(sp->ts_state) if (sp->ts_fidx >= sp->ts_fidxtry) sp->ts_state = STATE_DEL; else sp->ts_state = STATE_FINAL; } else { arridx += sp->ts_curi++; c = byts[arridx]; // Normal byte, go one level deeper. If it's not equal to the // byte in the bad word adjust the score. But don't even try // when the byte was already changed. And don't try when we // just deleted this byte, accepting it is always cheaper than // delete + substitute. if (c == fword[sp->ts_fidx] || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE)) newscore = 0; else newscore = SCORE_SUBST; if ((newscore == 0 || (sp->ts_fidx >= sp->ts_fidxtry && ((sp->ts_flags & TSF_DIDDEL) == 0 || c != fword[sp->ts_delidx]))) && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (newscore > 0) sprintf(changename[depth], "%.*s-%s: subst %c to %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx], c); else sprintf(changename[depth], "%.*s-%s: accept %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; sp = &stack[depth]; if (fword[sp->ts_fidx] != NUL) ++sp->ts_fidx; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[arridx]; if (newscore == SCORE_SUBST) sp->ts_isdiff = DIFF_YES; if (has_mbyte) { // Multi-byte characters are a bit complicated to // handle: They differ when any of the bytes differ // and then their length may also differ. if (sp->ts_tcharlen == 0) { // First byte. sp->ts_tcharidx = 0; sp->ts_tcharlen = MB_BYTE2LEN(c); sp->ts_fcharstart = sp->ts_fidx - 1; sp->ts_isdiff = (newscore != 0) ? DIFF_YES : DIFF_NONE; } else if (sp->ts_isdiff == DIFF_INSERT && sp->ts_fidx > 0) // When inserting trail bytes don't advance in the // bad word. --sp->ts_fidx; if (++sp->ts_tcharidx == sp->ts_tcharlen) { // Last byte of character. if (sp->ts_isdiff == DIFF_YES) { // Correct ts_fidx for the byte length of the // character (we didn't check that before). sp->ts_fidx = sp->ts_fcharstart + mb_ptr2len( fword + sp->ts_fcharstart); // For changing a composing character adjust // the score from SCORE_SUBST to // SCORE_SUBCOMP. if (enc_utf8 && utf_iscomposing( utf_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen)) && utf_iscomposing( utf_ptr2char(fword + sp->ts_fcharstart))) sp->ts_score -= SCORE_SUBST - SCORE_SUBCOMP; // For a similar character adjust score from // SCORE_SUBST to SCORE_SIMILAR. else if (!soundfold && slang->sl_has_map && similar_chars(slang, mb_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen), mb_ptr2char(fword + sp->ts_fcharstart))) sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } else if (sp->ts_isdiff == DIFF_INSERT && sp->ts_twordlen > sp->ts_tcharlen) { p = tword + sp->ts_twordlen - sp->ts_tcharlen; c = mb_ptr2char(p); if (enc_utf8 && utf_iscomposing(c)) { // Inserting a composing char doesn't // count that much. sp->ts_score -= SCORE_INS - SCORE_INSCOMP; } else { // If the previous character was the same, // thus doubling a character, give a bonus // to the score. Also for the soundfold // tree (might seem illogical but does // give better scores). MB_PTR_BACK(tword, p); if (c == mb_ptr2char(p)) sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } // Starting a new char, reset the length. sp->ts_tcharlen = 0; } } else { // If we found a similar char adjust the score. // We do this after calling go_deeper() because // it's slow. if (newscore != 0 && !soundfold && slang->sl_has_map && similar_chars(slang, c, fword[sp->ts_fidx - 1])) sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } } } break; case STATE_DEL: // When past the first byte of a multi-byte char don't try // delete/insert/swap a character. if (has_mbyte && sp->ts_tcharlen > 0) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Try skipping one character in the bad word (delete it). PROF_STORE(sp->ts_state) sp->ts_state = STATE_INS_PREP; sp->ts_curi = 1; if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*') // Deleting a vowel at the start of a word counts less, see // soundalike_score(). newscore = 2 * SCORE_DEL / 3; else newscore = SCORE_DEL; if (fword[sp->ts_fidx] != NUL && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: delete %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; // Remember what character we deleted, so that we can avoid // inserting it again. stack[depth].ts_flags |= TSF_DIDDEL; stack[depth].ts_delidx = sp->ts_fidx; // Advance over the character in fword[]. Give a bonus to the // score if the same character is following "nn" -> "n". It's // a bit illogical for soundfold tree but it does give better // results. if (has_mbyte) { c = mb_ptr2char(fword + sp->ts_fidx); stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx); if (enc_utf8 && utf_iscomposing(c)) stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP; else if (c == mb_ptr2char(fword + stack[depth].ts_fidx)) stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } else { ++stack[depth].ts_fidx; if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1]) stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } break; } // FALLTHROUGH case STATE_INS_PREP: if (sp->ts_flags & TSF_DIDDEL) { // If we just deleted a byte then inserting won't make sense, // a substitute is always cheaper. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } // skip over NUL bytes n = sp->ts_arridx; for (;;) { if (sp->ts_curi > byts[n]) { // Only NUL bytes at this node, go to next state. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } if (byts[n + sp->ts_curi] != NUL) { // Found a byte to insert. PROF_STORE(sp->ts_state) sp->ts_state = STATE_INS; break; } ++sp->ts_curi; } break; // FALLTHROUGH case STATE_INS: // Insert one byte. Repeat this for each possible byte at this // node. n = sp->ts_arridx; if (sp->ts_curi > byts[n]) { // Done all bytes at this node, go to next state. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } // Do one more byte at this node, but: // - Skip NUL bytes. // - Skip the byte if it's equal to the byte in the word, // accepting that byte is always better. n += sp->ts_curi++; c = byts[n]; if (soundfold && sp->ts_twordlen == 0 && c == '*') // Inserting a vowel at the start of a word counts less, // see soundalike_score(). newscore = 2 * SCORE_INS / 3; else newscore = SCORE_INS; if (c != fword[sp->ts_fidx] && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: insert %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c); #endif ++depth; sp = &stack[depth]; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[n]; if (has_mbyte) { fl = MB_BYTE2LEN(c); if (fl > 1) { // There are following bytes for the same character. // We must find all bytes before trying // delete/insert/swap/etc. sp->ts_tcharlen = fl; sp->ts_tcharidx = 1; sp->ts_isdiff = DIFF_INSERT; } } else fl = 1; if (fl == 1) { // If the previous character was the same, thus doubling a // character, give a bonus to the score. Also for // soundfold words (illogical but does give a better // score). if (sp->ts_twordlen >= 2 && tword[sp->ts_twordlen - 2] == c) sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } break; case STATE_SWAP: // Swap two bytes in the bad word: "12" -> "21". // We change "fword" here, it's changed back afterwards at // STATE_UNSWAP. p = fword + sp->ts_fidx; c = *p; if (c == NUL) { // End of word, can't swap or replace. PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Don't swap if the first character is not a word character. // SWAP3 etc. also don't make sense then. if (!soundfold && !spell_iswordp(p, curwin)) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } if (has_mbyte) { n = MB_CPTR2LEN(p); c = mb_ptr2char(p); if (p[n] == NUL) c2 = NUL; else if (!soundfold && !spell_iswordp(p + n, curwin)) c2 = c; // don't swap non-word char else c2 = mb_ptr2char(p + n); } else { if (p[1] == NUL) c2 = NUL; else if (!soundfold && !spell_iswordp(p + 1, curwin)) c2 = c; // don't swap non-word char else c2 = p[1]; } // When the second character is NUL we can't swap. if (c2 == NUL) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } // When characters are identical, swap won't do anything. // Also get here if the second char is not a word character. if (c == c2) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP3; break; } if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP)) { go_deeper(stack, depth, SCORE_SWAP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c2); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNSWAP; ++depth; if (has_mbyte) { fl = mb_char2len(c2); mch_memmove(p, p + n, fl); mb_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else { p[0] = c2; p[1] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 2; } } else { // If this swap doesn't work then SWAP3 won't either. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNSWAP: // Undo the STATE_SWAP swap: "21" -> "12". p = fword + sp->ts_fidx; if (has_mbyte) { n = mb_ptr2len(p); c = mb_ptr2char(p + n); mch_memmove(p + mb_ptr2len(p + n), p, n); mb_char2bytes(c, p); } else { c = *p; *p = p[1]; p[1] = c; } // FALLTHROUGH case STATE_SWAP3: // Swap two bytes, skipping one: "123" -> "321". We change // "fword" here, it's changed back afterwards at STATE_UNSWAP3. p = fword + sp->ts_fidx; if (has_mbyte) { n = MB_CPTR2LEN(p); c = mb_ptr2char(p); fl = MB_CPTR2LEN(p + n); c2 = mb_ptr2char(p + n); if (!soundfold && !spell_iswordp(p + n + fl, curwin)) c3 = c; // don't swap non-word char else c3 = mb_ptr2char(p + n + fl); } else { c = *p; c2 = p[1]; if (!soundfold && !spell_iswordp(p + 2, curwin)) c3 = c; // don't swap non-word char else c3 = p[2]; } // When characters are identical: "121" then SWAP3 result is // identical, ROT3L result is same as SWAP: "211", ROT3L result is // same as SWAP on next char: "112". Thus skip all swapping. // Also skip when c3 is NUL. // Also get here when the third character is not a word character. // Second character may any char: "a.b" -> "b.a" if (c == c3 || c3 == NUL) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap3 %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c3); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNSWAP3; ++depth; if (has_mbyte) { tl = mb_char2len(c3); mch_memmove(p, p + n + fl, tl); mb_char2bytes(c2, p + tl); mb_char2bytes(c, p + fl + tl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl; } else { p[0] = p[2]; p[2] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNSWAP3: // Undo STATE_SWAP3: "321" -> "123" p = fword + sp->ts_fidx; if (has_mbyte) { n = mb_ptr2len(p); c2 = mb_ptr2char(p + n); fl = mb_ptr2len(p + n); c = mb_ptr2char(p + n + fl); tl = mb_ptr2len(p + n + fl); mch_memmove(p + fl + tl, p, n); mb_char2bytes(c, p); mb_char2bytes(c2, p + tl); p = p + tl; } else { c = *p; *p = p[2]; p[2] = c; ++p; } if (!soundfold && !spell_iswordp(p, curwin)) { // Middle char is not a word char, skip the rotate. First and // third char were already checked at swap and swap3. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } // Rotate three characters left: "123" -> "231". We change // "fword" here, it's changed back afterwards at STATE_UNROT3L. if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNROT3L; ++depth; p = fword + sp->ts_fidx; if (has_mbyte) { n = MB_CPTR2LEN(p); c = mb_ptr2char(p); fl = MB_CPTR2LEN(p + n); fl += MB_CPTR2LEN(p + n + fl); mch_memmove(p, p + n, fl); mb_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else { c = *p; *p = p[1]; p[1] = p[2]; p[2] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNROT3L: // Undo ROT3L: "231" -> "123" p = fword + sp->ts_fidx; if (has_mbyte) { n = mb_ptr2len(p); n += mb_ptr2len(p + n); c = mb_ptr2char(p + n); tl = mb_ptr2len(p + n); mch_memmove(p + tl, p, n); mb_char2bytes(c, p); } else { c = p[2]; p[2] = p[1]; p[1] = *p; *p = c; } // Rotate three bytes right: "123" -> "312". We change "fword" // here, it's changed back afterwards at STATE_UNROT3R. if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNROT3R; ++depth; p = fword + sp->ts_fidx; if (has_mbyte) { n = MB_CPTR2LEN(p); n += MB_CPTR2LEN(p + n); c = mb_ptr2char(p + n); tl = MB_CPTR2LEN(p + n); mch_memmove(p + tl, p, n); mb_char2bytes(c, p); stack[depth].ts_fidxtry = sp->ts_fidx + n + tl; } else { c = p[2]; p[2] = p[1]; p[1] = *p; *p = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNROT3R: // Undo ROT3R: "312" -> "123" p = fword + sp->ts_fidx; if (has_mbyte) { c = mb_ptr2char(p); tl = mb_ptr2len(p); n = mb_ptr2len(p + tl); n += mb_ptr2len(p + tl + n); mch_memmove(p, p + tl, n); mb_char2bytes(c, p + n); } else { c = *p; *p = p[1]; p[1] = p[2]; p[2] = c; } // FALLTHROUGH case STATE_REP_INI: // Check if matching with REP items from the .aff file would work. // Quickly skip if: // - there are no REP items and we are not in the soundfold trie // - the score is going to be too high anyway // - already applied a REP item or swapped here if ((lp->lp_replang == NULL && !soundfold) || sp->ts_score + SCORE_REP >= su->su_maxscore || sp->ts_fidx < sp->ts_fidxtry) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Use the first byte to quickly find the first entry that may // match. If the index is -1 there is none. if (soundfold) sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]]; else sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]]; if (sp->ts_curi < 0) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP; // FALLTHROUGH case STATE_REP: // Try matching with REP items from the .aff file. For each match // replace the characters and check if the resulting word is // valid. p = fword + sp->ts_fidx; if (soundfold) gap = &slang->sl_repsal; else gap = &lp->lp_replang->sl_rep; while (sp->ts_curi < gap->ga_len) { ftp = (fromto_T *)gap->ga_data + sp->ts_curi++; if (*ftp->ft_from != *p) { // past possible matching entries sp->ts_curi = gap->ga_len; break; } if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0 && TRY_DEEPER(su, stack, depth, SCORE_REP)) { go_deeper(stack, depth, SCORE_REP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: replace %s with %s", sp->ts_twordlen, tword, fword + sp->ts_fidx, ftp->ft_from, ftp->ft_to); #endif // Need to undo this afterwards. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_UNDO; // Change the "from" to the "to" string. ++depth; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); if (fl != tl) { STRMOVE(p + tl, p + fl); repextra += tl - fl; } mch_memmove(p, ftp->ft_to, tl); stack[depth].ts_fidxtry = sp->ts_fidx + tl; stack[depth].ts_tcharlen = 0; break; } } if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP) { // No (more) matches. PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; } break; case STATE_REP_UNDO: // Undo a REP replacement and continue with the next one. if (soundfold) gap = &slang->sl_repsal; else gap = &lp->lp_replang->sl_rep; ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); p = fword + sp->ts_fidx; if (fl != tl) { STRMOVE(p + fl, p + tl); repextra -= tl - fl; } mch_memmove(p, ftp->ft_from, fl); PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP; break; default: // Did all possible states at this level, go up one level. --depth; if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE) { // Continue in or go back to the prefix tree. byts = pbyts; idxs = pidxs; } // Don't check for CTRL-C too often, it takes time. if (--breakcheckcount == 0) { ui_breakcheck(); breakcheckcount = 1000; #ifdef FEAT_RELTIME if (spell_suggest_timeout > 0 && profile_passed_limit(&time_limit)) got_int = TRUE; #endif } } } }
165297537933585359474732803706192755392
spellsuggest.c
24915610722049363928699434605775326954
CWE-787
CVE-2022-2126
Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-2126
200,379
radare2
48f0ea79f99174fb0a62cb2354e13496ce5b7c44
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/48f0ea79f99174fb0a62cb2354e13496ce5b7c44
Fix null deref in ne parser ##crash * Reported by @cnitlrt via huntr.dev * BountyID: d8b6d239-6d7b-4783-b26b-5be848c01aa1/ * Reproducer: nenull
1
RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) { int i; if (!bin) { return NULL; } RList *segments = r_list_newf (free); for (i = 0; i < bin->ne_header->SegCount; i++) { RBinSection *bs = R_NEW0 (RBinSection); if (!bs) { return segments; } NE_image_segment_entry *se = &bin->segment_entries[i]; bs->size = se->length; bs->vsize = se->minAllocSz ? se->minAllocSz : 64000; bs->bits = R_SYS_BITS_16; bs->is_data = se->flags & IS_DATA; bs->perm = __translate_perms (se->flags); bs->paddr = (ut64)se->offset * bin->alignment; bs->name = r_str_newf ("%s.%" PFMT64d, se->flags & IS_MOVEABLE ? "MOVEABLE" : "FIXED", bs->paddr); bs->is_segment = true; r_list_append (segments, bs); } bin->segments = segments; return segments; }
32265811031369210493685487313253460681
ne.c
158187364999589473605822811150926540610
CWE-476
CVE-2022-1382
NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of making the radare2 crash, thus affecting the availability of the system.
https://nvd.nist.gov/vuln/detail/CVE-2022-1382
302,095
radare2
48f0ea79f99174fb0a62cb2354e13496ce5b7c44
https://github.com/radare/radare2
https://github.com/radareorg/radare2/commit/48f0ea79f99174fb0a62cb2354e13496ce5b7c44
Fix null deref in ne parser ##crash * Reported by @cnitlrt via huntr.dev * BountyID: d8b6d239-6d7b-4783-b26b-5be848c01aa1/ * Reproducer: nenull
0
RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) { int i; if (!bin || !bin->segment_entries) { return NULL; } RList *segments = r_list_newf (free); for (i = 0; i < bin->ne_header->SegCount; i++) { RBinSection *bs = R_NEW0 (RBinSection); if (!bs) { return segments; } NE_image_segment_entry *se = &bin->segment_entries[i]; bs->size = se->length; bs->vsize = se->minAllocSz ? se->minAllocSz : 64000; bs->bits = R_SYS_BITS_16; bs->is_data = se->flags & IS_DATA; bs->perm = __translate_perms (se->flags); bs->paddr = (ut64)se->offset * bin->alignment; bs->name = r_str_newf ("%s.%" PFMT64d, se->flags & IS_MOVEABLE ? "MOVEABLE" : "FIXED", bs->paddr); bs->is_segment = true; r_list_append (segments, bs); } bin->segments = segments; return segments; }
16263805032815021006718433120091850858
None
CWE-476
CVE-2022-1382
NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.8. This vulnerability is capable of making the radare2 crash, thus affecting the availability of the system.
https://nvd.nist.gov/vuln/detail/CVE-2022-1382
200,695
linux
fc739a058d99c9297ef6bfd923b809d85855b9a9
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/fc739a058d99c9297ef6bfd923b809d85855b9a9
misc: fastrpc: prevent memory leak in fastrpc_dma_buf_attach In fastrpc_dma_buf_attach if dma_get_sgtable fails the allocated memory for a should be released. Signed-off-by: Navid Emamdoost <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
1
static int fastrpc_dma_buf_attach(struct dma_buf *dmabuf, struct dma_buf_attachment *attachment) { struct fastrpc_dma_buf_attachment *a; struct fastrpc_buf *buffer = dmabuf->priv; int ret; a = kzalloc(sizeof(*a), GFP_KERNEL); if (!a) return -ENOMEM; ret = dma_get_sgtable(buffer->dev, &a->sgt, buffer->virt, FASTRPC_PHYS(buffer->phys), buffer->size); if (ret < 0) { dev_err(buffer->dev, "failed to get scatterlist from DMA API\n"); return -EINVAL; } a->dev = attachment->dev; INIT_LIST_HEAD(&a->node); attachment->priv = a; mutex_lock(&buffer->lock); list_add(&a->node, &buffer->attachments); mutex_unlock(&buffer->lock); return 0; }
226882745088672382788622327400287132857
fastrpc.c
22170772729445349597675548574301219151
CWE-401
CVE-2019-19069
A memory leak in the fastrpc_dma_buf_attach() function in drivers/misc/fastrpc.c in the Linux kernel before 5.3.9 allows attackers to cause a denial of service (memory consumption) by triggering dma_get_sgtable() failures, aka CID-fc739a058d99.
https://nvd.nist.gov/vuln/detail/CVE-2019-19069
308,163
linux
fc739a058d99c9297ef6bfd923b809d85855b9a9
https://github.com/torvalds/linux
https://github.com/torvalds/linux/commit/fc739a058d99c9297ef6bfd923b809d85855b9a9
misc: fastrpc: prevent memory leak in fastrpc_dma_buf_attach In fastrpc_dma_buf_attach if dma_get_sgtable fails the allocated memory for a should be released. Signed-off-by: Navid Emamdoost <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
0
static int fastrpc_dma_buf_attach(struct dma_buf *dmabuf, struct dma_buf_attachment *attachment) { struct fastrpc_dma_buf_attachment *a; struct fastrpc_buf *buffer = dmabuf->priv; int ret; a = kzalloc(sizeof(*a), GFP_KERNEL); if (!a) return -ENOMEM; ret = dma_get_sgtable(buffer->dev, &a->sgt, buffer->virt, FASTRPC_PHYS(buffer->phys), buffer->size); if (ret < 0) { dev_err(buffer->dev, "failed to get scatterlist from DMA API\n"); kfree(a); return -EINVAL; } a->dev = attachment->dev; INIT_LIST_HEAD(&a->node); attachment->priv = a; mutex_lock(&buffer->lock); list_add(&a->node, &buffer->attachments); mutex_unlock(&buffer->lock); return 0; }
207220312586035988811790061557628451284
fastrpc.c
163997548888586618383929907046515889539
CWE-401
CVE-2019-19069
A memory leak in the fastrpc_dma_buf_attach() function in drivers/misc/fastrpc.c in the Linux kernel before 5.3.9 allows attackers to cause a denial of service (memory consumption) by triggering dma_get_sgtable() failures, aka CID-fc739a058d99.
https://nvd.nist.gov/vuln/detail/CVE-2019-19069
200,781
ncurses
790a85dbd4a81d5f5d8dd02a44d84f01512ef443
https://github.com/mirror/ncurses
https://github.com/mirror/ncurses/commit/790a85dbd4a81d5f5d8dd02a44d84f01512ef443#diff-7e95c7bc5f213e9be438e69a9d5d0f261a14952bcbd692f7b9014217b8047340
ncurses 6.2 - patch 20200531 + correct configure version-check/warnng for g++ to allow for 10.x + re-enable "bel" in konsole-base (report by Nia Huang) + add linux-s entry (patch by Alexandre Montaron). + drop long-obsolete convert_configure.pl + add test/test_parm.c, for checking tparm changes. + improve parameter-checking for tparm, adding function _nc_tiparm() to handle the most-used case, which accepts only numeric parameters (report/testcase by "puppet-meteor"). + use a more conservative estimate of the buffer-size in lib_tparm.c's save_text() and save_number(), in case the sprintf() function passes-through unexpected characters from a format specifier (report/testcase by "puppet-meteor"). + add a check for end-of-string in cvtchar to handle a malformed string in infotocap (report/testcase by "puppet-meteor").
1
cvtchar(register const char *sp) /* convert a character to a terminfo push */ { unsigned char c = 0; int len; switch (*sp) { case '\\': switch (*++sp) { case '\'': case '$': case '\\': case '%': c = UChar(*sp); len = 2; break; case '\0': c = '\\'; len = 1; break; case '0': case '1': case '2': case '3': len = 1; while (isdigit(UChar(*sp))) { c = UChar(8 * c + (*sp++ - '0')); len++; } break; default: c = UChar(*sp); len = (c != '\0') ? 2 : 1; break; } break; case '^': c = UChar(*++sp); if (c == '?') c = 127; else c &= 0x1f; len = 2; break; default: c = UChar(*sp); len = (c != '\0') ? 1 : 0; } if (isgraph(c) && c != ',' && c != '\'' && c != '\\' && c != ':') { dp = save_string(dp, "%\'"); dp = save_char(dp, c); dp = save_char(dp, '\''); } else if (c != '\0') { dp = save_string(dp, "%{"); if (c > 99) dp = save_char(dp, c / 100 + '0'); if (c > 9) dp = save_char(dp, ((int) (c / 10)) % 10 + '0'); dp = save_char(dp, c % 10 + '0'); dp = save_char(dp, '}'); } return len; }
56621931750240830327732003181202918311
None
CWE-787
CVE-2021-39537
An issue was discovered in ncurses through v6.2-1. _nc_captoinfo in captoinfo.c has a heap-based buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2021-39537
309,831
ncurses
790a85dbd4a81d5f5d8dd02a44d84f01512ef443
https://github.com/mirror/ncurses
https://github.com/mirror/ncurses/commit/790a85dbd4a81d5f5d8dd02a44d84f01512ef443#diff-7e95c7bc5f213e9be438e69a9d5d0f261a14952bcbd692f7b9014217b8047340
ncurses 6.2 - patch 20200531 + correct configure version-check/warnng for g++ to allow for 10.x + re-enable "bel" in konsole-base (report by Nia Huang) + add linux-s entry (patch by Alexandre Montaron). + drop long-obsolete convert_configure.pl + add test/test_parm.c, for checking tparm changes. + improve parameter-checking for tparm, adding function _nc_tiparm() to handle the most-used case, which accepts only numeric parameters (report/testcase by "puppet-meteor"). + use a more conservative estimate of the buffer-size in lib_tparm.c's save_text() and save_number(), in case the sprintf() function passes-through unexpected characters from a format specifier (report/testcase by "puppet-meteor"). + add a check for end-of-string in cvtchar to handle a malformed string in infotocap (report/testcase by "puppet-meteor").
0
cvtchar(register const char *sp) /* convert a character to a terminfo push */ { unsigned char c = 0; int len; switch (*sp) { case '\\': switch (*++sp) { case '\'': case '$': case '\\': case '%': c = UChar(*sp); len = 2; break; case '\0': c = '\\'; len = 1; break; case '0': case '1': case '2': case '3': len = 1; while (isdigit(UChar(*sp))) { c = UChar(8 * c + (*sp++ - '0')); len++; } break; default: c = UChar(*sp); len = (c != '\0') ? 2 : 1; break; } break; case '^': len = 2; c = UChar(*++sp); if (c == '?') { c = 127; } else if (c == '\0') { len = 1; } else { c &= 0x1f; } break; default: c = UChar(*sp); len = (c != '\0') ? 1 : 0; } if (isgraph(c) && c != ',' && c != '\'' && c != '\\' && c != ':') { dp = save_string(dp, "%\'"); dp = save_char(dp, c); dp = save_char(dp, '\''); } else if (c != '\0') { dp = save_string(dp, "%{"); if (c > 99) dp = save_char(dp, c / 100 + '0'); if (c > 9) dp = save_char(dp, ((int) (c / 10)) % 10 + '0'); dp = save_char(dp, c % 10 + '0'); dp = save_char(dp, '}'); } return len; }
173803971118928045075700643623936984208
None
CWE-787
CVE-2021-39537
An issue was discovered in ncurses through v6.2-1. _nc_captoinfo in captoinfo.c has a heap-based buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2021-39537
200,895
vim
d6c67629ed05aae436164eec474832daf8ba7420
https://github.com/vim/vim
https://github.com/vim/vim/commit/d6c67629ed05aae436164eec474832daf8ba7420
patch 9.0.0260: using freed memory when using 'quickfixtextfunc' recursively Problem: Using freed memory when using 'quickfixtextfunc' recursively. Solution: Do not allow for recursion.
1
call_qftf_func(qf_list_T *qfl, int qf_winid, long start_idx, long end_idx) { callback_T *cb = &qftf_cb; list_T *qftf_list = NULL; // If 'quickfixtextfunc' is set, then use the user-supplied function to get // the text to display. Use the local value of 'quickfixtextfunc' if it is // set. if (qfl->qf_qftf_cb.cb_name != NULL) cb = &qfl->qf_qftf_cb; if (cb->cb_name != NULL) { typval_T args[1]; dict_T *d; typval_T rettv; // create the dict argument if ((d = dict_alloc_lock(VAR_FIXED)) == NULL) return NULL; dict_add_number(d, "quickfix", (long)IS_QF_LIST(qfl)); dict_add_number(d, "winid", (long)qf_winid); dict_add_number(d, "id", (long)qfl->qf_id); dict_add_number(d, "start_idx", start_idx); dict_add_number(d, "end_idx", end_idx); ++d->dv_refcount; args[0].v_type = VAR_DICT; args[0].vval.v_dict = d; qftf_list = NULL; if (call_callback(cb, 0, &rettv, 1, args) != FAIL) { if (rettv.v_type == VAR_LIST) { qftf_list = rettv.vval.v_list; qftf_list->lv_refcount++; } clear_tv(&rettv); } dict_unref(d); } return qftf_list; }
339333086271181560510428879683096773754
None
CWE-703
CVE-2022-2982
Use After Free in GitHub repository vim/vim prior to 9.0.0260.
https://nvd.nist.gov/vuln/detail/CVE-2022-2982
312,399
vim
d6c67629ed05aae436164eec474832daf8ba7420
https://github.com/vim/vim
https://github.com/vim/vim/commit/d6c67629ed05aae436164eec474832daf8ba7420
patch 9.0.0260: using freed memory when using 'quickfixtextfunc' recursively Problem: Using freed memory when using 'quickfixtextfunc' recursively. Solution: Do not allow for recursion.
0
call_qftf_func(qf_list_T *qfl, int qf_winid, long start_idx, long end_idx) { callback_T *cb = &qftf_cb; list_T *qftf_list = NULL; static int recursive = FALSE; if (recursive) return NULL; // this doesn't work properly recursively recursive = TRUE; // If 'quickfixtextfunc' is set, then use the user-supplied function to get // the text to display. Use the local value of 'quickfixtextfunc' if it is // set. if (qfl->qf_qftf_cb.cb_name != NULL) cb = &qfl->qf_qftf_cb; if (cb->cb_name != NULL) { typval_T args[1]; dict_T *d; typval_T rettv; // create the dict argument if ((d = dict_alloc_lock(VAR_FIXED)) == NULL) { recursive = FALSE; return NULL; } dict_add_number(d, "quickfix", (long)IS_QF_LIST(qfl)); dict_add_number(d, "winid", (long)qf_winid); dict_add_number(d, "id", (long)qfl->qf_id); dict_add_number(d, "start_idx", start_idx); dict_add_number(d, "end_idx", end_idx); ++d->dv_refcount; args[0].v_type = VAR_DICT; args[0].vval.v_dict = d; qftf_list = NULL; if (call_callback(cb, 0, &rettv, 1, args) != FAIL) { if (rettv.v_type == VAR_LIST) { qftf_list = rettv.vval.v_list; qftf_list->lv_refcount++; } clear_tv(&rettv); } dict_unref(d); } recursive = FALSE; return qftf_list; }
274532016932228792070981910727654880739
quickfix.c
221790887990910120742119728344121157301
CWE-703
CVE-2022-2982
Use After Free in GitHub repository vim/vim prior to 9.0.0260.
https://nvd.nist.gov/vuln/detail/CVE-2022-2982
200,934
libvirt
524de6cc35d3b222f0e940bb0fd027f5482572c5
https://github.com/libvirt/libvirt
https://github.com/libvirt/libvirt/commit/524de6cc35d3b222f0e940bb0fd027f5482572c5
virstoragetest: testBackingParse: Use VIR_DOMAIN_DEF_FORMAT_SECURE when formatting xml We want to format even the secure information in tests. Signed-off-by: Peter Krempa <[email protected]> Reviewed-by: Erik Skultety <[email protected]>
1
testBackingParse(const void *args) { const struct testBackingParseData *data = args; g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER; g_autofree char *xml = NULL; g_autoptr(virStorageSource) src = NULL; int rc; int erc = data->rv; /* expect failure return code with NULL expected data */ if (!data->expect) erc = -1; if ((rc = virStorageSourceNewFromBackingAbsolute(data->backing, &src)) != erc) { fprintf(stderr, "expected return value '%d' actual '%d'\n", erc, rc); return -1; } if (!src) return 0; if (src && !data->expect) { fprintf(stderr, "parsing of backing store string '%s' should " "have failed\n", data->backing); return -1; } if (virDomainDiskSourceFormat(&buf, src, "source", 0, false, 0, true, NULL) < 0 || !(xml = virBufferContentAndReset(&buf))) { fprintf(stderr, "failed to format disk source xml\n"); return -1; } if (STRNEQ(xml, data->expect)) { fprintf(stderr, "\n backing store string '%s'\n" "expected storage source xml:\n%s\n" "actual storage source xml:\n%s\n", data->backing, data->expect, xml); return -1; } return 0; }
11097234962036893945341293376039418410
virstoragetest.c
229136922246575533938843249875631381172
CWE-212
CVE-2020-14301
An information disclosure vulnerability was found in libvirt in versions before 6.3.0. HTTP cookies used to access network-based disks were saved in the XML dump of the guest domain. This flaw allows an attacker to access potentially sensitive information in the domain configuration via the `dumpxml` command.
https://nvd.nist.gov/vuln/detail/CVE-2020-14301
313,134
libvirt
524de6cc35d3b222f0e940bb0fd027f5482572c5
https://github.com/libvirt/libvirt
https://github.com/libvirt/libvirt/commit/524de6cc35d3b222f0e940bb0fd027f5482572c5
virstoragetest: testBackingParse: Use VIR_DOMAIN_DEF_FORMAT_SECURE when formatting xml We want to format even the secure information in tests. Signed-off-by: Peter Krempa <[email protected]> Reviewed-by: Erik Skultety <[email protected]>
0
testBackingParse(const void *args) { const struct testBackingParseData *data = args; g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER; g_autofree char *xml = NULL; g_autoptr(virStorageSource) src = NULL; int rc; int erc = data->rv; unsigned int xmlformatflags = VIR_DOMAIN_DEF_FORMAT_SECURE; /* expect failure return code with NULL expected data */ if (!data->expect) erc = -1; if ((rc = virStorageSourceNewFromBackingAbsolute(data->backing, &src)) != erc) { fprintf(stderr, "expected return value '%d' actual '%d'\n", erc, rc); return -1; } if (!src) return 0; if (src && !data->expect) { fprintf(stderr, "parsing of backing store string '%s' should " "have failed\n", data->backing); return -1; } if (virDomainDiskSourceFormat(&buf, src, "source", 0, false, xmlformatflags, true, NULL) < 0 || !(xml = virBufferContentAndReset(&buf))) { fprintf(stderr, "failed to format disk source xml\n"); return -1; } if (STRNEQ(xml, data->expect)) { fprintf(stderr, "\n backing store string '%s'\n" "expected storage source xml:\n%s\n" "actual storage source xml:\n%s\n", data->backing, data->expect, xml); return -1; } return 0; }
323157311431778658152105206238946839547
virstoragetest.c
268394034841003390499099830389942989362
CWE-212
CVE-2020-14301
An information disclosure vulnerability was found in libvirt in versions before 6.3.0. HTTP cookies used to access network-based disks were saved in the XML dump of the guest domain. This flaw allows an attacker to access potentially sensitive information in the domain configuration via the `dumpxml` command.
https://nvd.nist.gov/vuln/detail/CVE-2020-14301
200,976
vim
395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c
https://github.com/vim/vim
https://github.com/vim/vim/commit/395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c
patch 8.2.4956: reading past end of line with "gf" in Visual block mode Problem: Reading past end of line with "gf" in Visual block mode. Solution: Do not include the NUL in the length.
1
get_visual_text( cmdarg_T *cap, char_u **pp, // return: start of selected text int *lenp) // return: length of selected text { if (VIsual_mode != 'V') unadjust_for_sel(); if (VIsual.lnum != curwin->w_cursor.lnum) { if (cap != NULL) clearopbeep(cap->oap); return FAIL; } if (VIsual_mode == 'V') { *pp = ml_get_curline(); *lenp = (int)STRLEN(*pp); } else { if (LT_POS(curwin->w_cursor, VIsual)) { *pp = ml_get_pos(&curwin->w_cursor); *lenp = VIsual.col - curwin->w_cursor.col + 1; } else { *pp = ml_get_pos(&VIsual); *lenp = curwin->w_cursor.col - VIsual.col + 1; } if (**pp == NUL) *lenp = 0; if (has_mbyte && *lenp > 0) // Correct the length to include all bytes of the last character. *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1; } reset_VIsual_and_resel(); return OK; }
284497166738290361019440448049627151253
None
CWE-787
CVE-2022-1720
Buffer Over-read in function grab_file_name in GitHub repository vim/vim prior to 8.2.4956. This vulnerability is capable of crashing the software, memory modification, and possible remote execution.
https://nvd.nist.gov/vuln/detail/CVE-2022-1720
313,850
vim
395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c
https://github.com/vim/vim
https://github.com/vim/vim/commit/395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c
patch 8.2.4956: reading past end of line with "gf" in Visual block mode Problem: Reading past end of line with "gf" in Visual block mode. Solution: Do not include the NUL in the length.
0
get_visual_text( cmdarg_T *cap, char_u **pp, // return: start of selected text int *lenp) // return: length of selected text { if (VIsual_mode != 'V') unadjust_for_sel(); if (VIsual.lnum != curwin->w_cursor.lnum) { if (cap != NULL) clearopbeep(cap->oap); return FAIL; } if (VIsual_mode == 'V') { *pp = ml_get_curline(); *lenp = (int)STRLEN(*pp); } else { if (LT_POS(curwin->w_cursor, VIsual)) { *pp = ml_get_pos(&curwin->w_cursor); *lenp = VIsual.col - curwin->w_cursor.col + 1; } else { *pp = ml_get_pos(&VIsual); *lenp = curwin->w_cursor.col - VIsual.col + 1; } if (**pp == NUL) *lenp = 0; if (*lenp > 0) { if (has_mbyte) // Correct the length to include all bytes of the last // character. *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1; else if ((*pp)[*lenp - 1] == NUL) // Do not include a trailing NUL. *lenp -= 1; } } reset_VIsual_and_resel(); return OK; }
15864851933404674407235198527938236742
normal.c
69342701404952166153136910551883160678
CWE-787
CVE-2022-1720
Buffer Over-read in function grab_file_name in GitHub repository vim/vim prior to 8.2.4956. This vulnerability is capable of crashing the software, memory modification, and possible remote execution.
https://nvd.nist.gov/vuln/detail/CVE-2022-1720
201,007
pjproject
560a1346f87aabe126509bb24930106dea292b00
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/560a1346f87aabe126509bb24930106dea292b00
Merge pull request from GHSA-f5qg-pqcg-765m
1
static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len) { char *p = buf; char *end = buf+len; unsigned i; int printed; /* check length for the "m=" line. */ if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) { return -1; } *p++ = 'm'; /* m= */ *p++ = '='; pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen); p += m->desc.media.slen; *p++ = ' '; printed = pj_utoa(m->desc.port, p); p += printed; if (m->desc.port_count > 1) { *p++ = '/'; printed = pj_utoa(m->desc.port_count, p); p += printed; } *p++ = ' '; pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen); p += m->desc.transport.slen; for (i=0; i<m->desc.fmt_count; ++i) { *p++ = ' '; pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen); p += m->desc.fmt[i].slen; } *p++ = '\r'; *p++ = '\n'; /* print connection info, if present. */ if (m->conn) { printed = print_connection_info(m->conn, p, (int)(end-p)); if (printed < 0) { return -1; } p += printed; } /* print optional bandwidth info. */ for (i=0; i<m->bandw_count; ++i) { printed = (int)print_bandw(m->bandw[i], p, end-p); if (printed < 0) { return -1; } p += printed; } /* print attributes. */ for (i=0; i<m->attr_count; ++i) { printed = (int)print_attr(m->attr[i], p, end-p); if (printed < 0) { return -1; } p += printed; } return (int)(p-buf); }
243109353869436532488614405590479215364
sdp.c
204440288713003047579803744169338279171
CWE-787
CVE-2022-24764
PJSIP is a free and open source multimedia communication library written in C. Versions 2.12 and prior contain a stack buffer overflow vulnerability that affects PJSUA2 users or users that call the API `pjmedia_sdp_print(), pjmedia_sdp_media_print()`. Applications that do not use PJSUA2 and do not directly call `pjmedia_sdp_print()` or `pjmedia_sdp_media_print()` should not be affected. A patch is available on the `master` branch of the `pjsip/pjproject` GitHub repository. There are currently no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2022-24764
314,536
pjproject
560a1346f87aabe126509bb24930106dea292b00
https://github.com/pjsip/pjproject
https://github.com/pjsip/pjproject/commit/560a1346f87aabe126509bb24930106dea292b00
Merge pull request from GHSA-f5qg-pqcg-765m
0
static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len) { char *p = buf; char *end = buf+len; unsigned i; int printed; /* check length for the "m=" line. */ if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) { return -1; } *p++ = 'm'; /* m= */ *p++ = '='; pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen); p += m->desc.media.slen; *p++ = ' '; printed = pj_utoa(m->desc.port, p); p += printed; if (m->desc.port_count > 1) { *p++ = '/'; printed = pj_utoa(m->desc.port_count, p); p += printed; } *p++ = ' '; pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen); p += m->desc.transport.slen; for (i=0; i<m->desc.fmt_count; ++i) { if (end-p > m->desc.fmt[i].slen) { *p++ = ' '; pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen); p += m->desc.fmt[i].slen; } else { return -1; } } if (end-p >= 2) { *p++ = '\r'; *p++ = '\n'; } else { return -1; } /* print connection info, if present. */ if (m->conn) { printed = print_connection_info(m->conn, p, (int)(end-p)); if (printed < 0) { return -1; } p += printed; } /* print optional bandwidth info. */ for (i=0; i<m->bandw_count; ++i) { printed = (int)print_bandw(m->bandw[i], p, end-p); if (printed < 0) { return -1; } p += printed; } /* print attributes. */ for (i=0; i<m->attr_count; ++i) { printed = (int)print_attr(m->attr[i], p, end-p); if (printed < 0) { return -1; } p += printed; } return (int)(p-buf); }
281187495727100348867210742014490000849
sdp.c
260444738794842919556316298921063524881
CWE-787
CVE-2022-24764
PJSIP is a free and open source multimedia communication library written in C. Versions 2.12 and prior contain a stack buffer overflow vulnerability that affects PJSUA2 users or users that call the API `pjmedia_sdp_print(), pjmedia_sdp_media_print()`. Applications that do not use PJSUA2 and do not directly call `pjmedia_sdp_print()` or `pjmedia_sdp_media_print()` should not be affected. A patch is available on the `master` branch of the `pjsip/pjproject` GitHub repository. There are currently no known workarounds.
https://nvd.nist.gov/vuln/detail/CVE-2022-24764
201,343
linux
a3727a8bac0a9e77c70820655fd8715523ba3db7
https://github.com/torvalds/linux
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a3727a8bac0a9e77c70820655fd8715523ba3db7
selinux,smack: fix subjective/objective credential use mixups Jann Horn reported a problem with commit eb1231f73c4d ("selinux: clarify task subjective and objective credentials") where some LSM hooks were attempting to access the subjective credentials of a task other than the current task. Generally speaking, it is not safe to access another task's subjective credentials and doing so can cause a number of problems. Further, while looking into the problem, I realized that Smack was suffering from a similar problem brought about by a similar commit 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials"). This patch addresses this problem by restoring the use of the task's objective credentials in those cases where the task is other than the current executing task. Not only does this resolve the problem reported by Jann, it is arguably the correct thing to do in these cases. Cc: [email protected] Fixes: eb1231f73c4d ("selinux: clarify task subjective and objective credentials") Fixes: 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials") Reported-by: Jann Horn <[email protected]> Acked-by: Eric W. Biederman <[email protected]> Acked-by: Casey Schaufler <[email protected]> Signed-off-by: Paul Moore <[email protected]>
1
static int selinux_ptrace_traceme(struct task_struct *parent) { return avc_has_perm(&selinux_state, task_sid_subj(parent), task_sid_obj(current), SECCLASS_PROCESS, PROCESS__PTRACE, NULL); }
244235637020461368565337014513482216980
None
CWE-416
CVE-2021-43057
An issue was discovered in the Linux kernel before 5.14.8. A use-after-free in selinux_ptrace_traceme (aka the SELinux handler for PTRACE_TRACEME) could be used by local attackers to cause memory corruption and escalate privileges, aka CID-a3727a8bac0a. This occurs because of an attempt to access the subjective credentials of another task.
https://nvd.nist.gov/vuln/detail/CVE-2021-43057
317,271
linux
a3727a8bac0a9e77c70820655fd8715523ba3db7
https://github.com/torvalds/linux
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a3727a8bac0a9e77c70820655fd8715523ba3db7
selinux,smack: fix subjective/objective credential use mixups Jann Horn reported a problem with commit eb1231f73c4d ("selinux: clarify task subjective and objective credentials") where some LSM hooks were attempting to access the subjective credentials of a task other than the current task. Generally speaking, it is not safe to access another task's subjective credentials and doing so can cause a number of problems. Further, while looking into the problem, I realized that Smack was suffering from a similar problem brought about by a similar commit 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials"). This patch addresses this problem by restoring the use of the task's objective credentials in those cases where the task is other than the current executing task. Not only does this resolve the problem reported by Jann, it is arguably the correct thing to do in these cases. Cc: [email protected] Fixes: eb1231f73c4d ("selinux: clarify task subjective and objective credentials") Fixes: 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials") Reported-by: Jann Horn <[email protected]> Acked-by: Eric W. Biederman <[email protected]> Acked-by: Casey Schaufler <[email protected]> Signed-off-by: Paul Moore <[email protected]>
0
static int selinux_ptrace_traceme(struct task_struct *parent) { return avc_has_perm(&selinux_state, task_sid_obj(parent), task_sid_obj(current), SECCLASS_PROCESS, PROCESS__PTRACE, NULL); }
139750086657330219714927956175340059557
None
CWE-416
CVE-2021-43057
An issue was discovered in the Linux kernel before 5.14.8. A use-after-free in selinux_ptrace_traceme (aka the SELinux handler for PTRACE_TRACEME) could be used by local attackers to cause memory corruption and escalate privileges, aka CID-a3727a8bac0a. This occurs because of an attempt to access the subjective credentials of another task.
https://nvd.nist.gov/vuln/detail/CVE-2021-43057
201,353
wireless-drivers
8b51dc7291473093c821195c4b6af85fadedbc2f
https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers
https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers.git/commit/?id=8b51dc7291473093c821195c4b6af85fadedbc2f
rsi: fix a double free bug in rsi_91x_deinit() `dev` (struct rsi_91x_usbdev *) field of adapter (struct rsi_91x_usbdev *) is allocated and initialized in `rsi_init_usb_interface`. If any error is detected in information read from the device side, `rsi_init_usb_interface` will be freed. However, in the higher level error handling code in `rsi_probe`, if error is detected, `rsi_91x_deinit` is called again, in which `dev` will be freed again, resulting double free. This patch fixes the double free by removing the free operation on `dev` in `rsi_init_usb_interface`, because `rsi_91x_deinit` is also used in `rsi_disconnect`, in that code path, the `dev` field is not (and thus needs to be) freed. This bug was found in v4.19, but is also present in the latest version of kernel. Fixes CVE-2019-15504. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Signed-off-by: Hui Peng <[email protected]> Reviewed-by: Guenter Roeck <[email protected]> Signed-off-by: Kalle Valo <[email protected]>
1
static int rsi_init_usb_interface(struct rsi_hw *adapter, struct usb_interface *pfunction) { struct rsi_91x_usbdev *rsi_dev; int status; rsi_dev = kzalloc(sizeof(*rsi_dev), GFP_KERNEL); if (!rsi_dev) return -ENOMEM; adapter->rsi_dev = rsi_dev; rsi_dev->usbdev = interface_to_usbdev(pfunction); rsi_dev->priv = (void *)adapter; if (rsi_find_bulk_in_and_out_endpoints(pfunction, adapter)) { status = -EINVAL; goto fail_eps; } adapter->device = &pfunction->dev; usb_set_intfdata(pfunction, adapter); rsi_dev->tx_buffer = kmalloc(2048, GFP_KERNEL); if (!rsi_dev->tx_buffer) { status = -ENOMEM; goto fail_eps; } if (rsi_usb_init_rx(adapter)) { rsi_dbg(ERR_ZONE, "Failed to init RX handle\n"); status = -ENOMEM; goto fail_rx; } rsi_dev->tx_blk_size = 252; adapter->block_size = rsi_dev->tx_blk_size; /* Initializing function callbacks */ adapter->check_hw_queue_status = rsi_usb_check_queue_status; adapter->determine_event_timeout = rsi_usb_event_timeout; adapter->rsi_host_intf = RSI_HOST_INTF_USB; adapter->host_intf_ops = &usb_host_intf_ops; #ifdef CONFIG_RSI_DEBUGFS /* In USB, one less than the MAX_DEBUGFS_ENTRIES entries is required */ adapter->num_debugfs_entries = (MAX_DEBUGFS_ENTRIES - 1); #endif rsi_dbg(INIT_ZONE, "%s: Enabled the interface\n", __func__); return 0; fail_rx: kfree(rsi_dev->tx_buffer); fail_eps: kfree(rsi_dev); return status; }
38914523915054214786919182237560230029
rsi_91x_usb.c
337775591275050809530599688018008269692
CWE-415
CVE-2019-15504
drivers/net/wireless/rsi/rsi_91x_usb.c in the Linux kernel through 5.2.9 has a Double Free via crafted USB device traffic (which may be remote via usbip or usbredir).
https://nvd.nist.gov/vuln/detail/CVE-2019-15504
318,099
wireless-drivers
8b51dc7291473093c821195c4b6af85fadedbc2f
https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers
https://git.kernel.org/pub/scm/linux/kernel/git/kvalo/wireless-drivers.git/commit/?id=8b51dc7291473093c821195c4b6af85fadedbc2f
rsi: fix a double free bug in rsi_91x_deinit() `dev` (struct rsi_91x_usbdev *) field of adapter (struct rsi_91x_usbdev *) is allocated and initialized in `rsi_init_usb_interface`. If any error is detected in information read from the device side, `rsi_init_usb_interface` will be freed. However, in the higher level error handling code in `rsi_probe`, if error is detected, `rsi_91x_deinit` is called again, in which `dev` will be freed again, resulting double free. This patch fixes the double free by removing the free operation on `dev` in `rsi_init_usb_interface`, because `rsi_91x_deinit` is also used in `rsi_disconnect`, in that code path, the `dev` field is not (and thus needs to be) freed. This bug was found in v4.19, but is also present in the latest version of kernel. Fixes CVE-2019-15504. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Signed-off-by: Hui Peng <[email protected]> Reviewed-by: Guenter Roeck <[email protected]> Signed-off-by: Kalle Valo <[email protected]>
0
static int rsi_init_usb_interface(struct rsi_hw *adapter, struct usb_interface *pfunction) { struct rsi_91x_usbdev *rsi_dev; int status; rsi_dev = kzalloc(sizeof(*rsi_dev), GFP_KERNEL); if (!rsi_dev) return -ENOMEM; adapter->rsi_dev = rsi_dev; rsi_dev->usbdev = interface_to_usbdev(pfunction); rsi_dev->priv = (void *)adapter; if (rsi_find_bulk_in_and_out_endpoints(pfunction, adapter)) { status = -EINVAL; goto fail_eps; } adapter->device = &pfunction->dev; usb_set_intfdata(pfunction, adapter); rsi_dev->tx_buffer = kmalloc(2048, GFP_KERNEL); if (!rsi_dev->tx_buffer) { status = -ENOMEM; goto fail_eps; } if (rsi_usb_init_rx(adapter)) { rsi_dbg(ERR_ZONE, "Failed to init RX handle\n"); status = -ENOMEM; goto fail_rx; } rsi_dev->tx_blk_size = 252; adapter->block_size = rsi_dev->tx_blk_size; /* Initializing function callbacks */ adapter->check_hw_queue_status = rsi_usb_check_queue_status; adapter->determine_event_timeout = rsi_usb_event_timeout; adapter->rsi_host_intf = RSI_HOST_INTF_USB; adapter->host_intf_ops = &usb_host_intf_ops; #ifdef CONFIG_RSI_DEBUGFS /* In USB, one less than the MAX_DEBUGFS_ENTRIES entries is required */ adapter->num_debugfs_entries = (MAX_DEBUGFS_ENTRIES - 1); #endif rsi_dbg(INIT_ZONE, "%s: Enabled the interface\n", __func__); return 0; fail_rx: kfree(rsi_dev->tx_buffer); fail_eps: return status; }
146493112175404963554656325384374694285
rsi_91x_usb.c
273043712433748171090882476377434422928
CWE-415
CVE-2019-15504
drivers/net/wireless/rsi/rsi_91x_usb.c in the Linux kernel through 5.2.9 has a Double Free via crafted USB device traffic (which may be remote via usbip or usbredir).
https://nvd.nist.gov/vuln/detail/CVE-2019-15504
201,382
gerbv
672214abb47a802fc000125996e6e0a46c623a4e
https://github.com/gerbv/gerbv
https://github.com/gerbv/gerbv/commit/672214abb47a802fc000125996e6e0a46c623a4e
Add test to demonstrate buffer overrun
1
drill_parse_T_code(gerb_file_t *fd, drill_state_t *state, gerbv_image_t *image, ssize_t file_line) { int tool_num; gboolean done = FALSE; int temp; double size; gerbv_drill_stats_t *stats = image->drill_stats; gerbv_aperture_t *apert; gchar *tmps; gchar *string; dprintf("---> entering %s()...\n", __FUNCTION__); /* Sneak a peek at what's hiding after the 'T'. Ugly fix for broken headers from Orcad, which is crap */ temp = gerb_fgetc(fd); dprintf(" Found a char '%s' (0x%02x) after the T\n", gerbv_escape_char(temp), temp); /* might be a tool tool change stop switch on/off*/ if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){ if(gerb_fgetc(fd) == 'S'){ if (gerb_fgetc(fd) == 'T' ){ fd->ptr -= 4; tmps = get_line(fd++); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1, _("Tool change stop switch found \"%s\" " "at line %ld in file \"%s\""), tmps, file_line, fd->filename); g_free (tmps); return -1; } gerb_ungetc(fd); } gerb_ungetc(fd); } if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) { if(temp != EOF) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("OrCAD bug: Junk text found in place of tool definition")); tmps = get_line(fd); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Junk text \"%s\" " "at line %ld in file \"%s\""), tmps, file_line, fd->filename); g_free (tmps); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Ignoring junk text")); } return -1; } gerb_ungetc(fd); tool_num = (int) gerb_fgetint(fd, NULL); dprintf (" Handling tool T%d at line %ld\n", tool_num, file_line); if (tool_num == 0) return tool_num; /* T00 is a command to unload the drill */ if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Out of bounds drill number %d " "at line %ld in file \"%s\""), tool_num, file_line, fd->filename); } /* Set the current tool to the correct one */ state->current_tool = tool_num; apert = image->aperture[tool_num]; /* Check for a size definition */ temp = gerb_fgetc(fd); /* This bit of code looks for a tool definition by scanning for strings * of form TxxC, TxxF, TxxS. */ while (!done) { switch((char)temp) { case 'C': size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals); dprintf (" Read a size of %g\n", size); if (state->unit == GERBV_UNIT_MM) { size /= 25.4; } else if(size >= 4.0) { /* If the drill size is >= 4 inches, assume that this must be wrong and that the units are mils. The limit being 4 inches is because the smallest drill I've ever seen used is 0,3mm(about 12mil). Half of that seemed a bit too small a margin, so a third it is */ gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Read a drill of diameter %g inches " "at line %ld in file \"%s\""), size, file_line, fd->filename); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Assuming units are mils")); size /= 1000.0; } if (size <= 0. || size >= 10000.) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Unreasonable drill size %g found for drill %d " "at line %ld in file \"%s\""), size, tool_num, file_line, fd->filename); } else { if (apert != NULL) { /* allow a redefine of a tool only if the new definition is exactly the same. * This avoid lots of spurious complaints with the output of some cad * tools while keeping complaints if there is a true problem */ if (apert->parameter[0] != size || apert->type != GERBV_APTYPE_CIRCLE || apert->nuf_parameters != 1 || apert->unit != GERBV_UNIT_INCH) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Found redefinition of drill %d " "at line %ld in file \"%s\""), tool_num, file_line, fd->filename); } } else { apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1); if (apert == NULL) GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__); /* There's really no way of knowing what unit the tools are defined in without sneaking a peek in the rest of the file first. That's done in drill_guess_format() */ apert->parameter[0] = size; apert->type = GERBV_APTYPE_CIRCLE; apert->nuf_parameters = 1; apert->unit = GERBV_UNIT_INCH; } } /* Add the tool whose definition we just found into the list * of tools for this layer used to generate statistics. */ stats = image->drill_stats; string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch"))); drill_stats_add_to_drill_list(stats->drill_list, tool_num, state->unit == GERBV_UNIT_MM ? size*25.4 : size, string); g_free(string); break; case 'F': case 'S' : /* Silently ignored. They're not important. */ gerb_fgetint(fd, NULL); break; default: /* Stop when finding anything but what's expected (and put it back) */ gerb_ungetc(fd); done = TRUE; break; } /* switch((char)temp) */ temp = gerb_fgetc(fd); if (EOF == temp) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF encountered in header of " "drill file \"%s\""), fd->filename); /* Restore new line character for processing */ if ('\n' == temp || '\r' == temp) gerb_ungetc(fd); } } /* while(!done) */ /* Done looking at tool definitions */ /* Catch the tools that aren't defined. This isn't strictly a good thing, but at least something is shown */ if (apert == NULL) { double dia; apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1); if (apert == NULL) GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__); /* See if we have the tool table */ dia = gerbv_get_tool_diameter(tool_num); if (dia <= 0) { /* * There is no tool. So go out and make some. * This size calculation is, of course, totally bogus. */ dia = (double)(16 + 8 * tool_num) / 1000; /* * Oooh, this is sooo ugly. But some CAD systems seem to always * use T00 at the end of the file while others that don't have * tool definitions inside the file never seem to use T00 at all. */ if (tool_num != 0) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Tool %02d used without being defined " "at line %ld in file \"%s\""), tool_num, file_line, fd->filename); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Setting a default size of %g\""), dia); } } apert->type = GERBV_APTYPE_CIRCLE; apert->nuf_parameters = 1; apert->parameter[0] = dia; /* Add the tool whose definition we just found into the list * of tools for this layer used to generate statistics. */ if (tool_num != 0) { /* Only add non-zero tool nums. * Zero = unload command. */ stats = image->drill_stats; string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch"))); drill_stats_add_to_drill_list(stats->drill_list, tool_num, state->unit == GERBV_UNIT_MM ? dia*25.4 : dia, string); g_free(string); } } /* if(image->aperture[tool_num] == NULL) */ dprintf("<---- ...leaving %s()\n", __FUNCTION__); return tool_num; } /* drill_parse_T_code() */
185752158214328372341115505036759500651
drill.c
62463866492734341751893387181625909179
CWE-787
CVE-2021-40391
An out-of-bounds write vulnerability exists in the drill format T-code tool number functionality of Gerbv 2.7.0, dev (commit b5f1eacd), and the forked version of Gerbv (commit 71493260). A specially-crafted drill file can lead to code execution. An attacker can provide a malicious file to trigger this vulnerability.
https://nvd.nist.gov/vuln/detail/CVE-2021-40391
318,781
gerbv
672214abb47a802fc000125996e6e0a46c623a4e
https://github.com/gerbv/gerbv
https://github.com/gerbv/gerbv/commit/672214abb47a802fc000125996e6e0a46c623a4e
Add test to demonstrate buffer overrun
0
drill_parse_T_code(gerb_file_t *fd, drill_state_t *state, gerbv_image_t *image, ssize_t file_line) { int tool_num; gboolean done = FALSE; int temp; double size; gerbv_drill_stats_t *stats = image->drill_stats; gerbv_aperture_t *apert; gchar *tmps; gchar *string; dprintf("---> entering %s()...\n", __FUNCTION__); /* Sneak a peek at what's hiding after the 'T'. Ugly fix for broken headers from Orcad, which is crap */ temp = gerb_fgetc(fd); dprintf(" Found a char '%s' (0x%02x) after the T\n", gerbv_escape_char(temp), temp); /* might be a tool tool change stop switch on/off*/ if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){ if(gerb_fgetc(fd) == 'S'){ if (gerb_fgetc(fd) == 'T' ){ fd->ptr -= 4; tmps = get_line(fd++); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1, _("Tool change stop switch found \"%s\" " "at line %ld in file \"%s\""), tmps, file_line, fd->filename); g_free (tmps); return -1; } gerb_ungetc(fd); } gerb_ungetc(fd); } if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) { if(temp != EOF) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("OrCAD bug: Junk text found in place of tool definition")); tmps = get_line(fd); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Junk text \"%s\" " "at line %ld in file \"%s\""), tmps, file_line, fd->filename); g_free (tmps); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Ignoring junk text")); } return -1; } gerb_ungetc(fd); tool_num = (int) gerb_fgetint(fd, NULL); dprintf (" Handling tool T%d at line %ld\n", tool_num, file_line); if (tool_num == 0) return tool_num; /* T00 is a command to unload the drill */ if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Out of bounds drill number %d " "at line %ld in file \"%s\""), tool_num, file_line, fd->filename); return -1; } /* Set the current tool to the correct one */ state->current_tool = tool_num; apert = image->aperture[tool_num]; /* Check for a size definition */ temp = gerb_fgetc(fd); /* This bit of code looks for a tool definition by scanning for strings * of form TxxC, TxxF, TxxS. */ while (!done) { switch((char)temp) { case 'C': size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals); dprintf (" Read a size of %g\n", size); if (state->unit == GERBV_UNIT_MM) { size /= 25.4; } else if(size >= 4.0) { /* If the drill size is >= 4 inches, assume that this must be wrong and that the units are mils. The limit being 4 inches is because the smallest drill I've ever seen used is 0,3mm(about 12mil). Half of that seemed a bit too small a margin, so a third it is */ gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Read a drill of diameter %g inches " "at line %ld in file \"%s\""), size, file_line, fd->filename); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Assuming units are mils")); size /= 1000.0; } if (size <= 0. || size >= 10000.) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Unreasonable drill size %g found for drill %d " "at line %ld in file \"%s\""), size, tool_num, file_line, fd->filename); } else { if (apert != NULL) { /* allow a redefine of a tool only if the new definition is exactly the same. * This avoid lots of spurious complaints with the output of some cad * tools while keeping complaints if there is a true problem */ if (apert->parameter[0] != size || apert->type != GERBV_APTYPE_CIRCLE || apert->nuf_parameters != 1 || apert->unit != GERBV_UNIT_INCH) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Found redefinition of drill %d " "at line %ld in file \"%s\""), tool_num, file_line, fd->filename); } } else { apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1); if (apert == NULL) GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__); /* There's really no way of knowing what unit the tools are defined in without sneaking a peek in the rest of the file first. That's done in drill_guess_format() */ apert->parameter[0] = size; apert->type = GERBV_APTYPE_CIRCLE; apert->nuf_parameters = 1; apert->unit = GERBV_UNIT_INCH; } } /* Add the tool whose definition we just found into the list * of tools for this layer used to generate statistics. */ stats = image->drill_stats; string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch"))); drill_stats_add_to_drill_list(stats->drill_list, tool_num, state->unit == GERBV_UNIT_MM ? size*25.4 : size, string); g_free(string); break; case 'F': case 'S' : /* Silently ignored. They're not important. */ gerb_fgetint(fd, NULL); break; default: /* Stop when finding anything but what's expected (and put it back) */ gerb_ungetc(fd); done = TRUE; break; } /* switch((char)temp) */ temp = gerb_fgetc(fd); if (EOF == temp) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF encountered in header of " "drill file \"%s\""), fd->filename); /* Restore new line character for processing */ if ('\n' == temp || '\r' == temp) gerb_ungetc(fd); } } /* while(!done) */ /* Done looking at tool definitions */ /* Catch the tools that aren't defined. This isn't strictly a good thing, but at least something is shown */ if (apert == NULL) { double dia; apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1); if (apert == NULL) GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__); /* See if we have the tool table */ dia = gerbv_get_tool_diameter(tool_num); if (dia <= 0) { /* * There is no tool. So go out and make some. * This size calculation is, of course, totally bogus. */ dia = (double)(16 + 8 * tool_num) / 1000; /* * Oooh, this is sooo ugly. But some CAD systems seem to always * use T00 at the end of the file while others that don't have * tool definitions inside the file never seem to use T00 at all. */ if (tool_num != 0) { gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Tool %02d used without being defined " "at line %ld in file \"%s\""), tool_num, file_line, fd->filename); gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Setting a default size of %g\""), dia); } } apert->type = GERBV_APTYPE_CIRCLE; apert->nuf_parameters = 1; apert->parameter[0] = dia; /* Add the tool whose definition we just found into the list * of tools for this layer used to generate statistics. */ if (tool_num != 0) { /* Only add non-zero tool nums. * Zero = unload command. */ stats = image->drill_stats; string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch"))); drill_stats_add_to_drill_list(stats->drill_list, tool_num, state->unit == GERBV_UNIT_MM ? dia*25.4 : dia, string); g_free(string); } } /* if(image->aperture[tool_num] == NULL) */ dprintf("<---- ...leaving %s()\n", __FUNCTION__); return tool_num; } /* drill_parse_T_code() */
295658284034771468073191411727984025582
drill.c
33522367220484611799947615316913326815
CWE-787
CVE-2021-40391
An out-of-bounds write vulnerability exists in the drill format T-code tool number functionality of Gerbv 2.7.0, dev (commit b5f1eacd), and the forked version of Gerbv (commit 71493260). A specially-crafted drill file can lead to code execution. An attacker can provide a malicious file to trigger this vulnerability.
https://nvd.nist.gov/vuln/detail/CVE-2021-40391
201,384
vim
34f8117dec685ace52cd9e578e2729db278163fc
https://github.com/vim/vim
https://github.com/vim/vim/commit/34f8117dec685ace52cd9e578e2729db278163fc
patch 8.2.4397: crash when using many composing characters in error message Problem: Crash when using many composing characters in error message. Solution: Use mb_cptr2char_adv() instead of mb_ptr2char_adv().
1
ga_concat_shorten_esc(garray_T *gap, char_u *str) { char_u *p; char_u *s; int c; int clen; char_u buf[NUMBUFLEN]; int same_len; if (str == NULL) { ga_concat(gap, (char_u *)"NULL"); return; } for (p = str; *p != NUL; ++p) { same_len = 1; s = p; c = mb_ptr2char_adv(&s); clen = s - p; while (*s != NUL && c == mb_ptr2char(s)) { ++same_len; s += clen; } if (same_len > 20) { ga_concat(gap, (char_u *)"\\["); ga_concat_esc(gap, p, clen); ga_concat(gap, (char_u *)" occurs "); vim_snprintf((char *)buf, NUMBUFLEN, "%d", same_len); ga_concat(gap, buf); ga_concat(gap, (char_u *)" times]"); p = s - 1; } else ga_concat_esc(gap, p, clen); } }
50963215449221402235184881814854547880
None
CWE-787
CVE-2022-0629
Stack-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0629
318,962
vim
34f8117dec685ace52cd9e578e2729db278163fc
https://github.com/vim/vim
https://github.com/vim/vim/commit/34f8117dec685ace52cd9e578e2729db278163fc
patch 8.2.4397: crash when using many composing characters in error message Problem: Crash when using many composing characters in error message. Solution: Use mb_cptr2char_adv() instead of mb_ptr2char_adv().
0
ga_concat_shorten_esc(garray_T *gap, char_u *str) { char_u *p; char_u *s; int c; int clen; char_u buf[NUMBUFLEN]; int same_len; if (str == NULL) { ga_concat(gap, (char_u *)"NULL"); return; } for (p = str; *p != NUL; ++p) { same_len = 1; s = p; c = mb_cptr2char_adv(&s); clen = s - p; while (*s != NUL && c == mb_ptr2char(s)) { ++same_len; s += clen; } if (same_len > 20) { ga_concat(gap, (char_u *)"\\["); ga_concat_esc(gap, p, clen); ga_concat(gap, (char_u *)" occurs "); vim_snprintf((char *)buf, NUMBUFLEN, "%d", same_len); ga_concat(gap, buf); ga_concat(gap, (char_u *)" times]"); p = s - 1; } else ga_concat_esc(gap, p, clen); } }
80466370940770826127245028745875582474
testing.c
163762640026672977997843160219561641403
CWE-787
CVE-2022-0629
Stack-based Buffer Overflow in GitHub repository vim/vim prior to 8.2.
https://nvd.nist.gov/vuln/detail/CVE-2022-0629
201,451
ImageMagick6
e6ea5876e0228165ee3abc6e959aa174cee06680
https://github.com/ImageMagick/ImageMagick6
https://github.com/ImageMagick/ImageMagick6/commit/e6ea5876e0228165ee3abc6e959aa174cee06680
https://github.com/ImageMagick/ImageMagick/issues/4988
1
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MaxTextExtent]; CINInfo cin; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; ssize_t i; PixelPacket *q; size_t extent, length; ssize_t count, y; unsigned char magick[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,"dpx:file.version",property); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,"dpx:file.filename",property); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,"dpx:file.create_date",property); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,"dpx:file.create_time",property); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,"dpx:image.orientation","%d", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,"dpx:image.label",property); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,"dpx:origination.filename",property); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,"dpx:origination.create_date",property); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,"dpx:origination.create_time",property); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,"dpx:origination.device",property); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,"dpx:origination.model",property); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,"dpx:origination.serial",property); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.offset","%d", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format, sizeof(cin.film.format)); (void) SetImageProperty(image,"dpx:film.format",property); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,"dpx:film.frame_position","%.20g", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.frame_rate","%g", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,"dpx:film.frame_id",property); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,"dpx:film.slate_info",property); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL,cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,"dpx:user.data",profile); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,MagickFalse); quantum_type=RGBQuantum; extent=GetQuantumExtent(image,quantum_info,quantum_type); (void) extent; length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } status=SetQuantumPad(image,quantum_info,0); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { const void *stream; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; stream=ReadBlobStream(image,length,pixels,&count); if (count != (ssize_t) length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,(unsigned char *) stream,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); SetImageColorspace(image,LogColorspace); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
230911711267539175049972905344313345647
cin.c
249228869233078232834553857521337694406
CWE-787
CVE-2022-28463
ImageMagick 7.1.0-27 is vulnerable to Buffer Overflow.
https://nvd.nist.gov/vuln/detail/CVE-2022-28463
319,422
ImageMagick6
e6ea5876e0228165ee3abc6e959aa174cee06680
https://github.com/ImageMagick/ImageMagick6
https://github.com/ImageMagick/ImageMagick6/commit/e6ea5876e0228165ee3abc6e959aa174cee06680
https://github.com/ImageMagick/ImageMagick/issues/4988
0
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MaxTextExtent]; CINInfo cin; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; ssize_t i; PixelPacket *q; size_t extent, length; ssize_t count, y; unsigned char magick[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); if (cin.file.image_offset < 712) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,"dpx:file.version",property); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,"dpx:file.filename",property); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,"dpx:file.create_date",property); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,"dpx:file.create_time",property); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,"dpx:image.orientation","%d", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,"dpx:image.label",property); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,"dpx:origination.filename",property); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,"dpx:origination.create_date",property); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,"dpx:origination.create_time",property); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,"dpx:origination.device",property); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,"dpx:origination.model",property); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,"dpx:origination.serial",property); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.offset","%d", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format, sizeof(cin.film.format)); (void) SetImageProperty(image,"dpx:film.format",property); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,"dpx:film.frame_position","%.20g", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.frame_rate","%g", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,"dpx:film.frame_id",property); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,"dpx:film.slate_info",property); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL,cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,"dpx:user.data",profile); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,MagickFalse); quantum_type=RGBQuantum; extent=GetQuantumExtent(image,quantum_info,quantum_type); (void) extent; length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } status=SetQuantumPad(image,quantum_info,0); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { const void *stream; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; stream=ReadBlobStream(image,length,pixels,&count); if (count != (ssize_t) length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,(unsigned char *) stream,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); SetImageColorspace(image,LogColorspace); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
125198761122342315192980410159814316224
cin.c
162029268319562364339376626172641683991
CWE-787
CVE-2022-28463
ImageMagick 7.1.0-27 is vulnerable to Buffer Overflow.
https://nvd.nist.gov/vuln/detail/CVE-2022-28463
201,872
gnutls
20a98e817713764b9df5306286091df1b61190d9
http://git.savannah.gnu.org/cgit/gnutls
https://gitlab.com/gnutls/gnutls/commit/20a98e817713764b9df5306286091df1b61190d9
handshake: check inappropriate fallback against the configured max version That allows to operate on a server which is explicitly configured to utilize earlier than TLS 1.2 versions.
1
_gnutls_server_select_suite(gnutls_session_t session, uint8_t * data, unsigned int datalen) { int ret; unsigned int i, j, cipher_suites_size; size_t pk_algos_size; uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE]; int retval; gnutls_pk_algorithm_t pk_algos[MAX_ALGOS]; /* will hold the pk algorithms * supported by the peer. */ for (i = 0; i < datalen; i += 2) { /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */ if (session->internals.priorities.sr != SR_DISABLED && data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR && data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) { _gnutls_handshake_log ("HSK[%p]: Received safe renegotiation CS\n", session); retval = _gnutls_ext_sr_recv_cs(session); if (retval < 0) { gnutls_assert(); return retval; } } /* TLS_FALLBACK_SCSV */ if (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR && data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) { _gnutls_handshake_log ("HSK[%p]: Received fallback CS\n", session); if (gnutls_protocol_get_version(session) != GNUTLS_TLS_VERSION_MAX) return GNUTLS_E_INAPPROPRIATE_FALLBACK; } } pk_algos_size = MAX_ALGOS; ret = server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos, &pk_algos_size); if (ret < 0) return gnutls_assert_val(ret); ret = _gnutls_supported_ciphersuites(session, cipher_suites, sizeof(cipher_suites)); if (ret < 0) return gnutls_assert_val(ret); cipher_suites_size = ret; /* Here we remove any ciphersuite that does not conform * the certificate requested, or to the * authentication requested (e.g. SRP). */ ret = _gnutls_remove_unwanted_ciphersuites(session, cipher_suites, cipher_suites_size, pk_algos, pk_algos_size); if (ret <= 0) { gnutls_assert(); if (ret < 0) return ret; else return GNUTLS_E_UNKNOWN_CIPHER_SUITE; } cipher_suites_size = ret; /* Data length should be zero mod 2 since * every ciphersuite is 2 bytes. (this check is needed * see below). */ if (datalen % 2 != 0) { gnutls_assert(); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } memset(session->security_parameters.cipher_suite, 0, 2); retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE; _gnutls_handshake_log ("HSK[%p]: Requested cipher suites[size: %d]: \n", session, (int) datalen); if (session->internals.priorities.server_precedence == 0) { for (j = 0; j < datalen; j += 2) { _gnutls_handshake_log("\t0x%.2x, 0x%.2x %s\n", data[j], data[j + 1], _gnutls_cipher_suite_get_name (&data[j])); for (i = 0; i < cipher_suites_size; i += 2) { if (memcmp(&cipher_suites[i], &data[j], 2) == 0) { _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session, _gnutls_cipher_suite_get_name (&data[j])); memcpy(session-> security_parameters. cipher_suite, &cipher_suites[i], 2); _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT, session->security_parameters. cipher_suite); retval = 0; goto finish; } } } } else { /* server selects */ for (i = 0; i < cipher_suites_size; i += 2) { for (j = 0; j < datalen; j += 2) { if (memcmp(&cipher_suites[i], &data[j], 2) == 0) { _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session, _gnutls_cipher_suite_get_name (&data[j])); memcpy(session-> security_parameters. cipher_suite, &cipher_suites[i], 2); _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT, session->security_parameters. cipher_suite); retval = 0; goto finish; } } } } finish: if (retval != 0) { gnutls_assert(); return retval; } /* check if the credentials (username, public key etc.) are ok */ if (_gnutls_get_kx_cred (session, _gnutls_cipher_suite_get_kx_algo(session->security_parameters. cipher_suite)) == NULL) { gnutls_assert(); return GNUTLS_E_INSUFFICIENT_CREDENTIALS; } /* set the mod_auth_st to the appropriate struct * according to the KX algorithm. This is needed since all the * handshake functions are read from there; */ session->internals.auth_struct = _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo (session->security_parameters. cipher_suite)); if (session->internals.auth_struct == NULL) { _gnutls_handshake_log ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n", session); gnutls_assert(); return GNUTLS_E_INTERNAL_ERROR; } return 0; }
43939075651028590089831343195417108850
gnutls_handshake.c
33222600436004333309471609542396279978
CWE-310
CVE-2014-3566
The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other products, uses nondeterministic CBC padding, which makes it easier for man-in-the-middle attackers to obtain cleartext data via a padding-oracle attack, aka the "POODLE" issue.
https://nvd.nist.gov/vuln/detail/CVE-2014-3566
325,821
gnutls
20a98e817713764b9df5306286091df1b61190d9
http://git.savannah.gnu.org/cgit/gnutls
https://gitlab.com/gnutls/gnutls/commit/20a98e817713764b9df5306286091df1b61190d9
handshake: check inappropriate fallback against the configured max version That allows to operate on a server which is explicitly configured to utilize earlier than TLS 1.2 versions.
0
_gnutls_server_select_suite(gnutls_session_t session, uint8_t * data, unsigned int datalen) { int ret; unsigned int i, j, cipher_suites_size; size_t pk_algos_size; uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE]; int retval; gnutls_pk_algorithm_t pk_algos[MAX_ALGOS]; /* will hold the pk algorithms * supported by the peer. */ for (i = 0; i < datalen; i += 2) { /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */ if (session->internals.priorities.sr != SR_DISABLED && data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR && data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) { _gnutls_handshake_log ("HSK[%p]: Received safe renegotiation CS\n", session); retval = _gnutls_ext_sr_recv_cs(session); if (retval < 0) { gnutls_assert(); return retval; } } /* TLS_FALLBACK_SCSV */ if (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR && data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) { unsigned max = _gnutls_version_max(session); _gnutls_handshake_log ("HSK[%p]: Received fallback CS\n", session); if (gnutls_protocol_get_version(session) != max) return gnutls_assert_val(GNUTLS_E_INAPPROPRIATE_FALLBACK); } } pk_algos_size = MAX_ALGOS; ret = server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos, &pk_algos_size); if (ret < 0) return gnutls_assert_val(ret); ret = _gnutls_supported_ciphersuites(session, cipher_suites, sizeof(cipher_suites)); if (ret < 0) return gnutls_assert_val(ret); cipher_suites_size = ret; /* Here we remove any ciphersuite that does not conform * the certificate requested, or to the * authentication requested (e.g. SRP). */ ret = _gnutls_remove_unwanted_ciphersuites(session, cipher_suites, cipher_suites_size, pk_algos, pk_algos_size); if (ret <= 0) { gnutls_assert(); if (ret < 0) return ret; else return GNUTLS_E_UNKNOWN_CIPHER_SUITE; } cipher_suites_size = ret; /* Data length should be zero mod 2 since * every ciphersuite is 2 bytes. (this check is needed * see below). */ if (datalen % 2 != 0) { gnutls_assert(); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } memset(session->security_parameters.cipher_suite, 0, 2); retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE; _gnutls_handshake_log ("HSK[%p]: Requested cipher suites[size: %d]: \n", session, (int) datalen); if (session->internals.priorities.server_precedence == 0) { for (j = 0; j < datalen; j += 2) { _gnutls_handshake_log("\t0x%.2x, 0x%.2x %s\n", data[j], data[j + 1], _gnutls_cipher_suite_get_name (&data[j])); for (i = 0; i < cipher_suites_size; i += 2) { if (memcmp(&cipher_suites[i], &data[j], 2) == 0) { _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session, _gnutls_cipher_suite_get_name (&data[j])); memcpy(session-> security_parameters. cipher_suite, &cipher_suites[i], 2); _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT, session->security_parameters. cipher_suite); retval = 0; goto finish; } } } } else { /* server selects */ for (i = 0; i < cipher_suites_size; i += 2) { for (j = 0; j < datalen; j += 2) { if (memcmp(&cipher_suites[i], &data[j], 2) == 0) { _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session, _gnutls_cipher_suite_get_name (&data[j])); memcpy(session-> security_parameters. cipher_suite, &cipher_suites[i], 2); _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT, session->security_parameters. cipher_suite); retval = 0; goto finish; } } } } finish: if (retval != 0) { gnutls_assert(); return retval; } /* check if the credentials (username, public key etc.) are ok */ if (_gnutls_get_kx_cred (session, _gnutls_cipher_suite_get_kx_algo(session->security_parameters. cipher_suite)) == NULL) { gnutls_assert(); return GNUTLS_E_INSUFFICIENT_CREDENTIALS; } /* set the mod_auth_st to the appropriate struct * according to the KX algorithm. This is needed since all the * handshake functions are read from there; */ session->internals.auth_struct = _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo (session->security_parameters. cipher_suite)); if (session->internals.auth_struct == NULL) { _gnutls_handshake_log ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n", session); gnutls_assert(); return GNUTLS_E_INTERNAL_ERROR; } return 0; }
258083912886334761023165928095225492685
gnutls_handshake.c
160528780373648505874425532995323250651
CWE-310
CVE-2014-3566
The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other products, uses nondeterministic CBC padding, which makes it easier for man-in-the-middle attackers to obtain cleartext data via a padding-oracle attack, aka the "POODLE" issue.
https://nvd.nist.gov/vuln/detail/CVE-2014-3566
201,885
vim
b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5
https://github.com/vim/vim
https://github.com/vim/vim/commit/b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5
patch 8.2.4646: using buffer line after it has been freed Problem: Using buffer line after it has been freed in old regexp engine. Solution: After getting mark get the line again.
1
regmatch( char_u *scan, // Current node. proftime_T *tm UNUSED, // timeout limit or NULL int *timed_out UNUSED) // flag set on timeout or NULL { char_u *next; // Next node. int op; int c; regitem_T *rp; int no; int status; // one of the RA_ values: #ifdef FEAT_RELTIME int tm_count = 0; #endif // Make "regstack" and "backpos" empty. They are allocated and freed in // bt_regexec_both() to reduce malloc()/free() calls. regstack.ga_len = 0; backpos.ga_len = 0; // Repeat until "regstack" is empty. for (;;) { // Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q". // Allow interrupting them with CTRL-C. fast_breakcheck(); #ifdef DEBUG if (scan != NULL && regnarrate) { mch_errmsg((char *)regprop(scan)); mch_errmsg("(\n"); } #endif // Repeat for items that can be matched sequentially, without using the // regstack. for (;;) { if (got_int || scan == NULL) { status = RA_FAIL; break; } #ifdef FEAT_RELTIME // Check for timeout once in a 100 times to avoid overhead. if (tm != NULL && ++tm_count == 100) { tm_count = 0; if (profile_passed_limit(tm)) { if (timed_out != NULL) *timed_out = TRUE; status = RA_FAIL; break; } } #endif status = RA_CONT; #ifdef DEBUG if (regnarrate) { mch_errmsg((char *)regprop(scan)); mch_errmsg("...\n"); # ifdef FEAT_SYN_HL if (re_extmatch_in != NULL) { int i; mch_errmsg(_("External submatches:\n")); for (i = 0; i < NSUBEXP; i++) { mch_errmsg(" \""); if (re_extmatch_in->matches[i] != NULL) mch_errmsg((char *)re_extmatch_in->matches[i]); mch_errmsg("\"\n"); } } # endif } #endif next = regnext(scan); op = OP(scan); // Check for character class with NL added. if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI && *rex.input == NUL && rex.lnum <= rex.reg_maxline) { reg_nextline(); } else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n') { ADVANCE_REGINPUT(); } else { if (WITH_NL(op)) op -= ADD_NL; if (has_mbyte) c = (*mb_ptr2char)(rex.input); else c = *rex.input; switch (op) { case BOL: if (rex.input != rex.line) status = RA_NOMATCH; break; case EOL: if (c != NUL) status = RA_NOMATCH; break; case RE_BOF: // We're not at the beginning of the file when below the first // line where we started, not at the start of the line or we // didn't start at the first line of the buffer. if (rex.lnum != 0 || rex.input != rex.line || (REG_MULTI && rex.reg_firstlnum > 1)) status = RA_NOMATCH; break; case RE_EOF: if (rex.lnum != rex.reg_maxline || c != NUL) status = RA_NOMATCH; break; case CURSOR: // Check if the buffer is in a window and compare the // rex.reg_win->w_cursor position to the match position. if (rex.reg_win == NULL || (rex.lnum + rex.reg_firstlnum != rex.reg_win->w_cursor.lnum) || ((colnr_T)(rex.input - rex.line) != rex.reg_win->w_cursor.col)) status = RA_NOMATCH; break; case RE_MARK: // Compare the mark position to the match position. { int mark = OPERAND(scan)[0]; int cmp = OPERAND(scan)[1]; pos_T *pos; pos = getmark_buf(rex.reg_buf, mark, FALSE); if (pos == NULL // mark doesn't exist || pos->lnum <= 0) // mark isn't set in reg_buf { status = RA_NOMATCH; } else { colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum && pos->col == MAXCOL ? (colnr_T)STRLEN(reg_getline( pos->lnum - rex.reg_firstlnum)) : pos->col; if ((pos->lnum == rex.lnum + rex.reg_firstlnum ? (pos_col == (colnr_T)(rex.input - rex.line) ? (cmp == '<' || cmp == '>') : (pos_col < (colnr_T)(rex.input - rex.line) ? cmp != '>' : cmp != '<')) : (pos->lnum < rex.lnum + rex.reg_firstlnum ? cmp != '>' : cmp != '<'))) status = RA_NOMATCH; } } break; case RE_VISUAL: if (!reg_match_visual()) status = RA_NOMATCH; break; case RE_LNUM: if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum), scan)) status = RA_NOMATCH; break; case RE_COL: if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan)) status = RA_NOMATCH; break; case RE_VCOL: if (!re_num_cmp((long_u)win_linetabsize( rex.reg_win == NULL ? curwin : rex.reg_win, rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan)) status = RA_NOMATCH; break; case BOW: // \<word; rex.input points to w if (c == NUL) // Can't match at end of line status = RA_NOMATCH; else if (has_mbyte) { int this_class; // Get class of current and previous char (if it exists). this_class = mb_get_class_buf(rex.input, rex.reg_buf); if (this_class <= 1) status = RA_NOMATCH; // not on a word at all else if (reg_prev_class() == this_class) status = RA_NOMATCH; // previous char is in same word } else { if (!vim_iswordc_buf(c, rex.reg_buf) || (rex.input > rex.line && vim_iswordc_buf(rex.input[-1], rex.reg_buf))) status = RA_NOMATCH; } break; case EOW: // word\>; rex.input points after d if (rex.input == rex.line) // Can't match at start of line status = RA_NOMATCH; else if (has_mbyte) { int this_class, prev_class; // Get class of current and previous char (if it exists). this_class = mb_get_class_buf(rex.input, rex.reg_buf); prev_class = reg_prev_class(); if (this_class == prev_class || prev_class == 0 || prev_class == 1) status = RA_NOMATCH; } else { if (!vim_iswordc_buf(rex.input[-1], rex.reg_buf) || (rex.input[0] != NUL && vim_iswordc_buf(c, rex.reg_buf))) status = RA_NOMATCH; } break; // Matched with EOW case ANY: // ANY does not match new lines. if (c == NUL) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case IDENT: if (!vim_isIDc(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SIDENT: if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case KWORD: if (!vim_iswordp_buf(rex.input, rex.reg_buf)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SKWORD: if (VIM_ISDIGIT(*rex.input) || !vim_iswordp_buf(rex.input, rex.reg_buf)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case FNAME: if (!vim_isfilec(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SFNAME: if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case PRINT: if (!vim_isprintc(PTR2CHAR(rex.input))) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SPRINT: if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input))) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case WHITE: if (!VIM_ISWHITE(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NWHITE: if (c == NUL || VIM_ISWHITE(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case DIGIT: if (!ri_digit(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NDIGIT: if (c == NUL || ri_digit(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case HEX: if (!ri_hex(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NHEX: if (c == NUL || ri_hex(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case OCTAL: if (!ri_octal(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NOCTAL: if (c == NUL || ri_octal(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case WORD: if (!ri_word(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NWORD: if (c == NUL || ri_word(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case HEAD: if (!ri_head(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NHEAD: if (c == NUL || ri_head(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case ALPHA: if (!ri_alpha(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NALPHA: if (c == NUL || ri_alpha(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case LOWER: if (!ri_lower(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NLOWER: if (c == NUL || ri_lower(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case UPPER: if (!ri_upper(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NUPPER: if (c == NUL || ri_upper(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case EXACTLY: { int len; char_u *opnd; opnd = OPERAND(scan); // Inline the first byte, for speed. if (*opnd != *rex.input && (!rex.reg_ic || (!enc_utf8 && MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input)))) status = RA_NOMATCH; else if (*opnd == NUL) { // match empty string always works; happens when "~" is // empty. } else { if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic)) { len = 1; // matched a single byte above } else { // Need to match first byte again for multi-byte. len = (int)STRLEN(opnd); if (cstrncmp(opnd, rex.input, &len) != 0) status = RA_NOMATCH; } // Check for following composing character, unless %C // follows (skips over all composing chars). if (status != RA_NOMATCH && enc_utf8 && UTF_COMPOSINGLIKE(rex.input, rex.input + len) && !rex.reg_icombine && OP(next) != RE_COMPOSING) { // raaron: This code makes a composing character get // ignored, which is the correct behavior (sometimes) // for voweled Hebrew texts. status = RA_NOMATCH; } if (status != RA_NOMATCH) rex.input += len; } } break; case ANYOF: case ANYBUT: if (c == NUL) status = RA_NOMATCH; else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case MULTIBYTECODE: if (has_mbyte) { int i, len; char_u *opnd; int opndc = 0, inpc; opnd = OPERAND(scan); // Safety check (just in case 'encoding' was changed since // compiling the program). if ((len = (*mb_ptr2len)(opnd)) < 2) { status = RA_NOMATCH; break; } if (enc_utf8) opndc = utf_ptr2char(opnd); if (enc_utf8 && utf_iscomposing(opndc)) { // When only a composing char is given match at any // position where that composing char appears. status = RA_NOMATCH; for (i = 0; rex.input[i] != NUL; i += utf_ptr2len(rex.input + i)) { inpc = utf_ptr2char(rex.input + i); if (!utf_iscomposing(inpc)) { if (i > 0) break; } else if (opndc == inpc) { // Include all following composing chars. len = i + utfc_ptr2len(rex.input + i); status = RA_MATCH; break; } } } else for (i = 0; i < len; ++i) if (opnd[i] != rex.input[i]) { status = RA_NOMATCH; break; } rex.input += len; } else status = RA_NOMATCH; break; case RE_COMPOSING: if (enc_utf8) { // Skip composing characters. while (utf_iscomposing(utf_ptr2char(rex.input))) MB_CPTR_ADV(rex.input); } break; case NOTHING: break; case BACK: { int i; backpos_T *bp; // When we run into BACK we need to check if we don't keep // looping without matching any input. The second and later // times a BACK is encountered it fails if the input is still // at the same position as the previous time. // The positions are stored in "backpos" and found by the // current value of "scan", the position in the RE program. bp = (backpos_T *)backpos.ga_data; for (i = 0; i < backpos.ga_len; ++i) if (bp[i].bp_scan == scan) break; if (i == backpos.ga_len) { // First time at this BACK, make room to store the pos. if (ga_grow(&backpos, 1) == FAIL) status = RA_FAIL; else { // get "ga_data" again, it may have changed bp = (backpos_T *)backpos.ga_data; bp[i].bp_scan = scan; ++backpos.ga_len; } } else if (reg_save_equal(&bp[i].bp_pos)) // Still at same position as last time, fail. status = RA_NOMATCH; if (status != RA_FAIL && status != RA_NOMATCH) reg_save(&bp[i].bp_pos, &backpos); } break; case MOPEN + 0: // Match start: \zs case MOPEN + 1: // \( case MOPEN + 2: case MOPEN + 3: case MOPEN + 4: case MOPEN + 5: case MOPEN + 6: case MOPEN + 7: case MOPEN + 8: case MOPEN + 9: { no = op - MOPEN; cleanup_subexpr(); rp = regstack_push(RS_MOPEN, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &rex.reg_startpos[no], &rex.reg_startp[no]); // We simply continue and handle the result when done. } } break; case NOPEN: // \%( case NCLOSE: // \) after \%( if (regstack_push(RS_NOPEN, scan) == NULL) status = RA_FAIL; // We simply continue and handle the result when done. break; #ifdef FEAT_SYN_HL case ZOPEN + 1: case ZOPEN + 2: case ZOPEN + 3: case ZOPEN + 4: case ZOPEN + 5: case ZOPEN + 6: case ZOPEN + 7: case ZOPEN + 8: case ZOPEN + 9: { no = op - ZOPEN; cleanup_zsubexpr(); rp = regstack_push(RS_ZOPEN, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &reg_startzpos[no], &reg_startzp[no]); // We simply continue and handle the result when done. } } break; #endif case MCLOSE + 0: // Match end: \ze case MCLOSE + 1: // \) case MCLOSE + 2: case MCLOSE + 3: case MCLOSE + 4: case MCLOSE + 5: case MCLOSE + 6: case MCLOSE + 7: case MCLOSE + 8: case MCLOSE + 9: { no = op - MCLOSE; cleanup_subexpr(); rp = regstack_push(RS_MCLOSE, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &rex.reg_endpos[no], &rex.reg_endp[no]); // We simply continue and handle the result when done. } } break; #ifdef FEAT_SYN_HL case ZCLOSE + 1: // \) after \z( case ZCLOSE + 2: case ZCLOSE + 3: case ZCLOSE + 4: case ZCLOSE + 5: case ZCLOSE + 6: case ZCLOSE + 7: case ZCLOSE + 8: case ZCLOSE + 9: { no = op - ZCLOSE; cleanup_zsubexpr(); rp = regstack_push(RS_ZCLOSE, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &reg_endzpos[no], &reg_endzp[no]); // We simply continue and handle the result when done. } } break; #endif case BACKREF + 1: case BACKREF + 2: case BACKREF + 3: case BACKREF + 4: case BACKREF + 5: case BACKREF + 6: case BACKREF + 7: case BACKREF + 8: case BACKREF + 9: { int len; no = op - BACKREF; cleanup_subexpr(); if (!REG_MULTI) // Single-line regexp { if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL) { // Backref was not set: Match an empty string. len = 0; } else { // Compare current input with back-ref in the same // line. len = (int)(rex.reg_endp[no] - rex.reg_startp[no]); if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0) status = RA_NOMATCH; } } else // Multi-line regexp { if (rex.reg_startpos[no].lnum < 0 || rex.reg_endpos[no].lnum < 0) { // Backref was not set: Match an empty string. len = 0; } else { if (rex.reg_startpos[no].lnum == rex.lnum && rex.reg_endpos[no].lnum == rex.lnum) { // Compare back-ref within the current line. len = rex.reg_endpos[no].col - rex.reg_startpos[no].col; if (cstrncmp(rex.line + rex.reg_startpos[no].col, rex.input, &len) != 0) status = RA_NOMATCH; } else { // Messy situation: Need to compare between two // lines. int r = match_with_backref( rex.reg_startpos[no].lnum, rex.reg_startpos[no].col, rex.reg_endpos[no].lnum, rex.reg_endpos[no].col, &len); if (r != RA_MATCH) status = r; } } } // Matched the backref, skip over it. rex.input += len; } break; #ifdef FEAT_SYN_HL case ZREF + 1: case ZREF + 2: case ZREF + 3: case ZREF + 4: case ZREF + 5: case ZREF + 6: case ZREF + 7: case ZREF + 8: case ZREF + 9: { int len; cleanup_zsubexpr(); no = op - ZREF; if (re_extmatch_in != NULL && re_extmatch_in->matches[no] != NULL) { len = (int)STRLEN(re_extmatch_in->matches[no]); if (cstrncmp(re_extmatch_in->matches[no], rex.input, &len) != 0) status = RA_NOMATCH; else rex.input += len; } else { // Backref was not set: Match an empty string. } } break; #endif case BRANCH: { if (OP(next) != BRANCH) // No choice. next = OPERAND(scan); // Avoid recursion. else { rp = regstack_push(RS_BRANCH, scan); if (rp == NULL) status = RA_FAIL; else status = RA_BREAK; // rest is below } } break; case BRACE_LIMITS: { if (OP(next) == BRACE_SIMPLE) { bl_minval = OPERAND_MIN(scan); bl_maxval = OPERAND_MAX(scan); } else if (OP(next) >= BRACE_COMPLEX && OP(next) < BRACE_COMPLEX + 10) { no = OP(next) - BRACE_COMPLEX; brace_min[no] = OPERAND_MIN(scan); brace_max[no] = OPERAND_MAX(scan); brace_count[no] = 0; } else { internal_error("BRACE_LIMITS"); status = RA_FAIL; } } break; case BRACE_COMPLEX + 0: case BRACE_COMPLEX + 1: case BRACE_COMPLEX + 2: case BRACE_COMPLEX + 3: case BRACE_COMPLEX + 4: case BRACE_COMPLEX + 5: case BRACE_COMPLEX + 6: case BRACE_COMPLEX + 7: case BRACE_COMPLEX + 8: case BRACE_COMPLEX + 9: { no = op - BRACE_COMPLEX; ++brace_count[no]; // If not matched enough times yet, try one more if (brace_count[no] <= (brace_min[no] <= brace_max[no] ? brace_min[no] : brace_max[no])) { rp = regstack_push(RS_BRCPLX_MORE, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; reg_save(&rp->rs_un.regsave, &backpos); next = OPERAND(scan); // We continue and handle the result when done. } break; } // If matched enough times, may try matching some more if (brace_min[no] <= brace_max[no]) { // Range is the normal way around, use longest match if (brace_count[no] <= brace_max[no]) { rp = regstack_push(RS_BRCPLX_LONG, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; reg_save(&rp->rs_un.regsave, &backpos); next = OPERAND(scan); // We continue and handle the result when done. } } } else { // Range is backwards, use shortest match first if (brace_count[no] <= brace_min[no]) { rp = regstack_push(RS_BRCPLX_SHORT, scan); if (rp == NULL) status = RA_FAIL; else { reg_save(&rp->rs_un.regsave, &backpos); // We continue and handle the result when done. } } } } break; case BRACE_SIMPLE: case STAR: case PLUS: { regstar_T rst; // Lookahead to avoid useless match attempts when we know // what character comes next. if (OP(next) == EXACTLY) { rst.nextb = *OPERAND(next); if (rex.reg_ic) { if (MB_ISUPPER(rst.nextb)) rst.nextb_ic = MB_TOLOWER(rst.nextb); else rst.nextb_ic = MB_TOUPPER(rst.nextb); } else rst.nextb_ic = rst.nextb; } else { rst.nextb = NUL; rst.nextb_ic = NUL; } if (op != BRACE_SIMPLE) { rst.minval = (op == STAR) ? 0 : 1; rst.maxval = MAX_LIMIT; } else { rst.minval = bl_minval; rst.maxval = bl_maxval; } // When maxval > minval, try matching as much as possible, up // to maxval. When maxval < minval, try matching at least the // minimal number (since the range is backwards, that's also // maxval!). rst.count = regrepeat(OPERAND(scan), rst.maxval); if (got_int) { status = RA_FAIL; break; } if (rst.minval <= rst.maxval ? rst.count >= rst.minval : rst.count >= rst.maxval) { // It could match. Prepare for trying to match what // follows. The code is below. Parameters are stored in // a regstar_T on the regstack. if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { emsg(_(e_pattern_uses_more_memory_than_maxmempattern)); status = RA_FAIL; } else if (ga_grow(&regstack, sizeof(regstar_T)) == FAIL) status = RA_FAIL; else { regstack.ga_len += sizeof(regstar_T); rp = regstack_push(rst.minval <= rst.maxval ? RS_STAR_LONG : RS_STAR_SHORT, scan); if (rp == NULL) status = RA_FAIL; else { *(((regstar_T *)rp) - 1) = rst; status = RA_BREAK; // skip the restore bits } } } else status = RA_NOMATCH; } break; case NOMATCH: case MATCH: case SUBPAT: rp = regstack_push(RS_NOMATCH, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = op; reg_save(&rp->rs_un.regsave, &backpos); next = OPERAND(scan); // We continue and handle the result when done. } break; case BEHIND: case NOBEHIND: // Need a bit of room to store extra positions. if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { emsg(_(e_pattern_uses_more_memory_than_maxmempattern)); status = RA_FAIL; } else if (ga_grow(&regstack, sizeof(regbehind_T)) == FAIL) status = RA_FAIL; else { regstack.ga_len += sizeof(regbehind_T); rp = regstack_push(RS_BEHIND1, scan); if (rp == NULL) status = RA_FAIL; else { // Need to save the subexpr to be able to restore them // when there is a match but we don't use it. save_subexpr(((regbehind_T *)rp) - 1); rp->rs_no = op; reg_save(&rp->rs_un.regsave, &backpos); // First try if what follows matches. If it does then we // check the behind match by looping. } } break; case BHPOS: if (REG_MULTI) { if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line) || behind_pos.rs_u.pos.lnum != rex.lnum) status = RA_NOMATCH; } else if (behind_pos.rs_u.ptr != rex.input) status = RA_NOMATCH; break; case NEWL: if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline || rex.reg_line_lbr) && (c != '\n' || !rex.reg_line_lbr)) status = RA_NOMATCH; else if (rex.reg_line_lbr) ADVANCE_REGINPUT(); else reg_nextline(); break; case END: status = RA_MATCH; // Success! break; default: iemsg(_(e_corrupted_regexp_program)); #ifdef DEBUG printf("Illegal op code %d\n", op); #endif status = RA_FAIL; break; } } // If we can't continue sequentially, break the inner loop. if (status != RA_CONT) break; // Continue in inner loop, advance to next item. scan = next; } // end of inner loop // If there is something on the regstack execute the code for the state. // If the state is popped then loop and use the older state. while (regstack.ga_len > 0 && status != RA_FAIL) { rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1; switch (rp->rs_state) { case RS_NOPEN: // Result is passed on as-is, simply pop the state. regstack_pop(&scan); break; case RS_MOPEN: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no], &rex.reg_startp[rp->rs_no]); regstack_pop(&scan); break; #ifdef FEAT_SYN_HL case RS_ZOPEN: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &reg_startzpos[rp->rs_no], &reg_startzp[rp->rs_no]); regstack_pop(&scan); break; #endif case RS_MCLOSE: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no], &rex.reg_endp[rp->rs_no]); regstack_pop(&scan); break; #ifdef FEAT_SYN_HL case RS_ZCLOSE: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &reg_endzpos[rp->rs_no], &reg_endzp[rp->rs_no]); regstack_pop(&scan); break; #endif case RS_BRANCH: if (status == RA_MATCH) // this branch matched, use it regstack_pop(&scan); else { if (status != RA_BREAK) { // After a non-matching branch: try next one. reg_restore(&rp->rs_un.regsave, &backpos); scan = rp->rs_scan; } if (scan == NULL || OP(scan) != BRANCH) { // no more branches, didn't find a match status = RA_NOMATCH; regstack_pop(&scan); } else { // Prepare to try a branch. rp->rs_scan = regnext(scan); reg_save(&rp->rs_un.regsave, &backpos); scan = OPERAND(scan); } } break; case RS_BRCPLX_MORE: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) { reg_restore(&rp->rs_un.regsave, &backpos); --brace_count[rp->rs_no]; // decrement match count } regstack_pop(&scan); break; case RS_BRCPLX_LONG: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) { // There was no match, but we did find enough matches. reg_restore(&rp->rs_un.regsave, &backpos); --brace_count[rp->rs_no]; // continue with the items after "\{}" status = RA_CONT; } regstack_pop(&scan); if (status == RA_CONT) scan = regnext(scan); break; case RS_BRCPLX_SHORT: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) // There was no match, try to match one more item. reg_restore(&rp->rs_un.regsave, &backpos); regstack_pop(&scan); if (status == RA_NOMATCH) { scan = OPERAND(scan); status = RA_CONT; } break; case RS_NOMATCH: // Pop the state. If the operand matches for NOMATCH or // doesn't match for MATCH/SUBPAT, we fail. Otherwise backup, // except for SUBPAT, and continue with the next item. if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH)) status = RA_NOMATCH; else { status = RA_CONT; if (rp->rs_no != SUBPAT) // zero-width reg_restore(&rp->rs_un.regsave, &backpos); } regstack_pop(&scan); if (status == RA_CONT) scan = regnext(scan); break; case RS_BEHIND1: if (status == RA_NOMATCH) { regstack_pop(&scan); regstack.ga_len -= sizeof(regbehind_T); } else { // The stuff after BEHIND/NOBEHIND matches. Now try if // the behind part does (not) match before the current // position in the input. This must be done at every // position in the input and checking if the match ends at // the current position. // save the position after the found match for next reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos); // Start looking for a match with operand at the current // position. Go back one character until we find the // result, hitting the start of the line or the previous // line (for multi-line matching). // Set behind_pos to where the match should end, BHPOS // will match it. Save the current value. (((regbehind_T *)rp) - 1)->save_behind = behind_pos; behind_pos = rp->rs_un.regsave; rp->rs_state = RS_BEHIND2; reg_restore(&rp->rs_un.regsave, &backpos); scan = OPERAND(rp->rs_scan) + 4; } break; case RS_BEHIND2: // Looping for BEHIND / NOBEHIND match. if (status == RA_MATCH && reg_save_equal(&behind_pos)) { // found a match that ends where "next" started behind_pos = (((regbehind_T *)rp) - 1)->save_behind; if (rp->rs_no == BEHIND) reg_restore(&(((regbehind_T *)rp) - 1)->save_after, &backpos); else { // But we didn't want a match. Need to restore the // subexpr, because what follows matched, so they have // been set. status = RA_NOMATCH; restore_subexpr(((regbehind_T *)rp) - 1); } regstack_pop(&scan); regstack.ga_len -= sizeof(regbehind_T); } else { long limit; // No match or a match that doesn't end where we want it: Go // back one character. May go to previous line once. no = OK; limit = OPERAND_MIN(rp->rs_scan); if (REG_MULTI) { if (limit > 0 && ((rp->rs_un.regsave.rs_u.pos.lnum < behind_pos.rs_u.pos.lnum ? (colnr_T)STRLEN(rex.line) : behind_pos.rs_u.pos.col) - rp->rs_un.regsave.rs_u.pos.col >= limit)) no = FAIL; else if (rp->rs_un.regsave.rs_u.pos.col == 0) { if (rp->rs_un.regsave.rs_u.pos.lnum < behind_pos.rs_u.pos.lnum || reg_getline( --rp->rs_un.regsave.rs_u.pos.lnum) == NULL) no = FAIL; else { reg_restore(&rp->rs_un.regsave, &backpos); rp->rs_un.regsave.rs_u.pos.col = (colnr_T)STRLEN(rex.line); } } else { if (has_mbyte) { char_u *line = reg_getline(rp->rs_un.regsave.rs_u.pos.lnum); rp->rs_un.regsave.rs_u.pos.col -= (*mb_head_off)(line, line + rp->rs_un.regsave.rs_u.pos.col - 1) + 1; } else --rp->rs_un.regsave.rs_u.pos.col; } } else { if (rp->rs_un.regsave.rs_u.ptr == rex.line) no = FAIL; else { MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr); if (limit > 0 && (long)(behind_pos.rs_u.ptr - rp->rs_un.regsave.rs_u.ptr) > limit) no = FAIL; } } if (no == OK) { // Advanced, prepare for finding match again. reg_restore(&rp->rs_un.regsave, &backpos); scan = OPERAND(rp->rs_scan) + 4; if (status == RA_MATCH) { // We did match, so subexpr may have been changed, // need to restore them for the next try. status = RA_NOMATCH; restore_subexpr(((regbehind_T *)rp) - 1); } } else { // Can't advance. For NOBEHIND that's a match. behind_pos = (((regbehind_T *)rp) - 1)->save_behind; if (rp->rs_no == NOBEHIND) { reg_restore(&(((regbehind_T *)rp) - 1)->save_after, &backpos); status = RA_MATCH; } else { // We do want a proper match. Need to restore the // subexpr if we had a match, because they may have // been set. if (status == RA_MATCH) { status = RA_NOMATCH; restore_subexpr(((regbehind_T *)rp) - 1); } } regstack_pop(&scan); regstack.ga_len -= sizeof(regbehind_T); } } break; case RS_STAR_LONG: case RS_STAR_SHORT: { regstar_T *rst = ((regstar_T *)rp) - 1; if (status == RA_MATCH) { regstack_pop(&scan); regstack.ga_len -= sizeof(regstar_T); break; } // Tried once already, restore input pointers. if (status != RA_BREAK) reg_restore(&rp->rs_un.regsave, &backpos); // Repeat until we found a position where it could match. for (;;) { if (status != RA_BREAK) { // Tried first position already, advance. if (rp->rs_state == RS_STAR_LONG) { // Trying for longest match, but couldn't or // didn't match -- back up one char. if (--rst->count < rst->minval) break; if (rex.input == rex.line) { // backup to last char of previous line if (rex.lnum == 0) { status = RA_NOMATCH; break; } --rex.lnum; rex.line = reg_getline(rex.lnum); // Just in case regrepeat() didn't count // right. if (rex.line == NULL) break; rex.input = rex.line + STRLEN(rex.line); fast_breakcheck(); } else MB_PTR_BACK(rex.line, rex.input); } else { // Range is backwards, use shortest match first. // Careful: maxval and minval are exchanged! // Couldn't or didn't match: try advancing one // char. if (rst->count == rst->minval || regrepeat(OPERAND(rp->rs_scan), 1L) == 0) break; ++rst->count; } if (got_int) break; } else status = RA_NOMATCH; // If it could match, try it. if (rst->nextb == NUL || *rex.input == rst->nextb || *rex.input == rst->nextb_ic) { reg_save(&rp->rs_un.regsave, &backpos); scan = regnext(rp->rs_scan); status = RA_CONT; break; } } if (status != RA_CONT) { // Failed. regstack_pop(&scan); regstack.ga_len -= sizeof(regstar_T); status = RA_NOMATCH; } } break; } // If we want to continue the inner loop or didn't pop a state // continue matching loop if (status == RA_CONT || rp == (regitem_T *) ((char *)regstack.ga_data + regstack.ga_len) - 1) break; } // May need to continue with the inner loop, starting at "scan". if (status == RA_CONT) continue; // If the regstack is empty or something failed we are done. if (regstack.ga_len == 0 || status == RA_FAIL) { if (scan == NULL) { // We get here only if there's trouble -- normally "case END" is // the terminating point. iemsg(_(e_corrupted_regexp_program)); #ifdef DEBUG printf("Premature EOL\n"); #endif } return (status == RA_MATCH); } } // End of loop until the regstack is empty. // NOTREACHED }
155703094073588454659918901719534941663
regexp_bt.c
104418656195819662091775816956319387020
CWE-416
CVE-2022-1154
Use after free in utf_ptr2char in GitHub repository vim/vim prior to 8.2.4646.
https://nvd.nist.gov/vuln/detail/CVE-2022-1154
326,119
vim
b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5
https://github.com/vim/vim
https://github.com/vim/vim/commit/b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5
patch 8.2.4646: using buffer line after it has been freed Problem: Using buffer line after it has been freed in old regexp engine. Solution: After getting mark get the line again.
0
regmatch( char_u *scan, // Current node. proftime_T *tm UNUSED, // timeout limit or NULL int *timed_out UNUSED) // flag set on timeout or NULL { char_u *next; // Next node. int op; int c; regitem_T *rp; int no; int status; // one of the RA_ values: #ifdef FEAT_RELTIME int tm_count = 0; #endif // Make "regstack" and "backpos" empty. They are allocated and freed in // bt_regexec_both() to reduce malloc()/free() calls. regstack.ga_len = 0; backpos.ga_len = 0; // Repeat until "regstack" is empty. for (;;) { // Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q". // Allow interrupting them with CTRL-C. fast_breakcheck(); #ifdef DEBUG if (scan != NULL && regnarrate) { mch_errmsg((char *)regprop(scan)); mch_errmsg("(\n"); } #endif // Repeat for items that can be matched sequentially, without using the // regstack. for (;;) { if (got_int || scan == NULL) { status = RA_FAIL; break; } #ifdef FEAT_RELTIME // Check for timeout once in a 100 times to avoid overhead. if (tm != NULL && ++tm_count == 100) { tm_count = 0; if (profile_passed_limit(tm)) { if (timed_out != NULL) *timed_out = TRUE; status = RA_FAIL; break; } } #endif status = RA_CONT; #ifdef DEBUG if (regnarrate) { mch_errmsg((char *)regprop(scan)); mch_errmsg("...\n"); # ifdef FEAT_SYN_HL if (re_extmatch_in != NULL) { int i; mch_errmsg(_("External submatches:\n")); for (i = 0; i < NSUBEXP; i++) { mch_errmsg(" \""); if (re_extmatch_in->matches[i] != NULL) mch_errmsg((char *)re_extmatch_in->matches[i]); mch_errmsg("\"\n"); } } # endif } #endif next = regnext(scan); op = OP(scan); // Check for character class with NL added. if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI && *rex.input == NUL && rex.lnum <= rex.reg_maxline) { reg_nextline(); } else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n') { ADVANCE_REGINPUT(); } else { if (WITH_NL(op)) op -= ADD_NL; if (has_mbyte) c = (*mb_ptr2char)(rex.input); else c = *rex.input; switch (op) { case BOL: if (rex.input != rex.line) status = RA_NOMATCH; break; case EOL: if (c != NUL) status = RA_NOMATCH; break; case RE_BOF: // We're not at the beginning of the file when below the first // line where we started, not at the start of the line or we // didn't start at the first line of the buffer. if (rex.lnum != 0 || rex.input != rex.line || (REG_MULTI && rex.reg_firstlnum > 1)) status = RA_NOMATCH; break; case RE_EOF: if (rex.lnum != rex.reg_maxline || c != NUL) status = RA_NOMATCH; break; case CURSOR: // Check if the buffer is in a window and compare the // rex.reg_win->w_cursor position to the match position. if (rex.reg_win == NULL || (rex.lnum + rex.reg_firstlnum != rex.reg_win->w_cursor.lnum) || ((colnr_T)(rex.input - rex.line) != rex.reg_win->w_cursor.col)) status = RA_NOMATCH; break; case RE_MARK: // Compare the mark position to the match position. { int mark = OPERAND(scan)[0]; int cmp = OPERAND(scan)[1]; pos_T *pos; size_t col = REG_MULTI ? rex.input - rex.line : 0; pos = getmark_buf(rex.reg_buf, mark, FALSE); // Line may have been freed, get it again. if (REG_MULTI) { rex.line = reg_getline(rex.lnum); rex.input = rex.line + col; } if (pos == NULL // mark doesn't exist || pos->lnum <= 0) // mark isn't set in reg_buf { status = RA_NOMATCH; } else { colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum && pos->col == MAXCOL ? (colnr_T)STRLEN(reg_getline( pos->lnum - rex.reg_firstlnum)) : pos->col; if ((pos->lnum == rex.lnum + rex.reg_firstlnum ? (pos_col == (colnr_T)(rex.input - rex.line) ? (cmp == '<' || cmp == '>') : (pos_col < (colnr_T)(rex.input - rex.line) ? cmp != '>' : cmp != '<')) : (pos->lnum < rex.lnum + rex.reg_firstlnum ? cmp != '>' : cmp != '<'))) status = RA_NOMATCH; } } break; case RE_VISUAL: if (!reg_match_visual()) status = RA_NOMATCH; break; case RE_LNUM: if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum), scan)) status = RA_NOMATCH; break; case RE_COL: if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan)) status = RA_NOMATCH; break; case RE_VCOL: if (!re_num_cmp((long_u)win_linetabsize( rex.reg_win == NULL ? curwin : rex.reg_win, rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan)) status = RA_NOMATCH; break; case BOW: // \<word; rex.input points to w if (c == NUL) // Can't match at end of line status = RA_NOMATCH; else if (has_mbyte) { int this_class; // Get class of current and previous char (if it exists). this_class = mb_get_class_buf(rex.input, rex.reg_buf); if (this_class <= 1) status = RA_NOMATCH; // not on a word at all else if (reg_prev_class() == this_class) status = RA_NOMATCH; // previous char is in same word } else { if (!vim_iswordc_buf(c, rex.reg_buf) || (rex.input > rex.line && vim_iswordc_buf(rex.input[-1], rex.reg_buf))) status = RA_NOMATCH; } break; case EOW: // word\>; rex.input points after d if (rex.input == rex.line) // Can't match at start of line status = RA_NOMATCH; else if (has_mbyte) { int this_class, prev_class; // Get class of current and previous char (if it exists). this_class = mb_get_class_buf(rex.input, rex.reg_buf); prev_class = reg_prev_class(); if (this_class == prev_class || prev_class == 0 || prev_class == 1) status = RA_NOMATCH; } else { if (!vim_iswordc_buf(rex.input[-1], rex.reg_buf) || (rex.input[0] != NUL && vim_iswordc_buf(c, rex.reg_buf))) status = RA_NOMATCH; } break; // Matched with EOW case ANY: // ANY does not match new lines. if (c == NUL) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case IDENT: if (!vim_isIDc(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SIDENT: if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case KWORD: if (!vim_iswordp_buf(rex.input, rex.reg_buf)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SKWORD: if (VIM_ISDIGIT(*rex.input) || !vim_iswordp_buf(rex.input, rex.reg_buf)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case FNAME: if (!vim_isfilec(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SFNAME: if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case PRINT: if (!vim_isprintc(PTR2CHAR(rex.input))) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case SPRINT: if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input))) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case WHITE: if (!VIM_ISWHITE(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NWHITE: if (c == NUL || VIM_ISWHITE(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case DIGIT: if (!ri_digit(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NDIGIT: if (c == NUL || ri_digit(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case HEX: if (!ri_hex(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NHEX: if (c == NUL || ri_hex(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case OCTAL: if (!ri_octal(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NOCTAL: if (c == NUL || ri_octal(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case WORD: if (!ri_word(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NWORD: if (c == NUL || ri_word(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case HEAD: if (!ri_head(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NHEAD: if (c == NUL || ri_head(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case ALPHA: if (!ri_alpha(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NALPHA: if (c == NUL || ri_alpha(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case LOWER: if (!ri_lower(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NLOWER: if (c == NUL || ri_lower(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case UPPER: if (!ri_upper(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case NUPPER: if (c == NUL || ri_upper(c)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case EXACTLY: { int len; char_u *opnd; opnd = OPERAND(scan); // Inline the first byte, for speed. if (*opnd != *rex.input && (!rex.reg_ic || (!enc_utf8 && MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input)))) status = RA_NOMATCH; else if (*opnd == NUL) { // match empty string always works; happens when "~" is // empty. } else { if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic)) { len = 1; // matched a single byte above } else { // Need to match first byte again for multi-byte. len = (int)STRLEN(opnd); if (cstrncmp(opnd, rex.input, &len) != 0) status = RA_NOMATCH; } // Check for following composing character, unless %C // follows (skips over all composing chars). if (status != RA_NOMATCH && enc_utf8 && UTF_COMPOSINGLIKE(rex.input, rex.input + len) && !rex.reg_icombine && OP(next) != RE_COMPOSING) { // raaron: This code makes a composing character get // ignored, which is the correct behavior (sometimes) // for voweled Hebrew texts. status = RA_NOMATCH; } if (status != RA_NOMATCH) rex.input += len; } } break; case ANYOF: case ANYBUT: if (c == NUL) status = RA_NOMATCH; else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF)) status = RA_NOMATCH; else ADVANCE_REGINPUT(); break; case MULTIBYTECODE: if (has_mbyte) { int i, len; char_u *opnd; int opndc = 0, inpc; opnd = OPERAND(scan); // Safety check (just in case 'encoding' was changed since // compiling the program). if ((len = (*mb_ptr2len)(opnd)) < 2) { status = RA_NOMATCH; break; } if (enc_utf8) opndc = utf_ptr2char(opnd); if (enc_utf8 && utf_iscomposing(opndc)) { // When only a composing char is given match at any // position where that composing char appears. status = RA_NOMATCH; for (i = 0; rex.input[i] != NUL; i += utf_ptr2len(rex.input + i)) { inpc = utf_ptr2char(rex.input + i); if (!utf_iscomposing(inpc)) { if (i > 0) break; } else if (opndc == inpc) { // Include all following composing chars. len = i + utfc_ptr2len(rex.input + i); status = RA_MATCH; break; } } } else for (i = 0; i < len; ++i) if (opnd[i] != rex.input[i]) { status = RA_NOMATCH; break; } rex.input += len; } else status = RA_NOMATCH; break; case RE_COMPOSING: if (enc_utf8) { // Skip composing characters. while (utf_iscomposing(utf_ptr2char(rex.input))) MB_CPTR_ADV(rex.input); } break; case NOTHING: break; case BACK: { int i; backpos_T *bp; // When we run into BACK we need to check if we don't keep // looping without matching any input. The second and later // times a BACK is encountered it fails if the input is still // at the same position as the previous time. // The positions are stored in "backpos" and found by the // current value of "scan", the position in the RE program. bp = (backpos_T *)backpos.ga_data; for (i = 0; i < backpos.ga_len; ++i) if (bp[i].bp_scan == scan) break; if (i == backpos.ga_len) { // First time at this BACK, make room to store the pos. if (ga_grow(&backpos, 1) == FAIL) status = RA_FAIL; else { // get "ga_data" again, it may have changed bp = (backpos_T *)backpos.ga_data; bp[i].bp_scan = scan; ++backpos.ga_len; } } else if (reg_save_equal(&bp[i].bp_pos)) // Still at same position as last time, fail. status = RA_NOMATCH; if (status != RA_FAIL && status != RA_NOMATCH) reg_save(&bp[i].bp_pos, &backpos); } break; case MOPEN + 0: // Match start: \zs case MOPEN + 1: // \( case MOPEN + 2: case MOPEN + 3: case MOPEN + 4: case MOPEN + 5: case MOPEN + 6: case MOPEN + 7: case MOPEN + 8: case MOPEN + 9: { no = op - MOPEN; cleanup_subexpr(); rp = regstack_push(RS_MOPEN, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &rex.reg_startpos[no], &rex.reg_startp[no]); // We simply continue and handle the result when done. } } break; case NOPEN: // \%( case NCLOSE: // \) after \%( if (regstack_push(RS_NOPEN, scan) == NULL) status = RA_FAIL; // We simply continue and handle the result when done. break; #ifdef FEAT_SYN_HL case ZOPEN + 1: case ZOPEN + 2: case ZOPEN + 3: case ZOPEN + 4: case ZOPEN + 5: case ZOPEN + 6: case ZOPEN + 7: case ZOPEN + 8: case ZOPEN + 9: { no = op - ZOPEN; cleanup_zsubexpr(); rp = regstack_push(RS_ZOPEN, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &reg_startzpos[no], &reg_startzp[no]); // We simply continue and handle the result when done. } } break; #endif case MCLOSE + 0: // Match end: \ze case MCLOSE + 1: // \) case MCLOSE + 2: case MCLOSE + 3: case MCLOSE + 4: case MCLOSE + 5: case MCLOSE + 6: case MCLOSE + 7: case MCLOSE + 8: case MCLOSE + 9: { no = op - MCLOSE; cleanup_subexpr(); rp = regstack_push(RS_MCLOSE, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &rex.reg_endpos[no], &rex.reg_endp[no]); // We simply continue and handle the result when done. } } break; #ifdef FEAT_SYN_HL case ZCLOSE + 1: // \) after \z( case ZCLOSE + 2: case ZCLOSE + 3: case ZCLOSE + 4: case ZCLOSE + 5: case ZCLOSE + 6: case ZCLOSE + 7: case ZCLOSE + 8: case ZCLOSE + 9: { no = op - ZCLOSE; cleanup_zsubexpr(); rp = regstack_push(RS_ZCLOSE, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; save_se(&rp->rs_un.sesave, &reg_endzpos[no], &reg_endzp[no]); // We simply continue and handle the result when done. } } break; #endif case BACKREF + 1: case BACKREF + 2: case BACKREF + 3: case BACKREF + 4: case BACKREF + 5: case BACKREF + 6: case BACKREF + 7: case BACKREF + 8: case BACKREF + 9: { int len; no = op - BACKREF; cleanup_subexpr(); if (!REG_MULTI) // Single-line regexp { if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL) { // Backref was not set: Match an empty string. len = 0; } else { // Compare current input with back-ref in the same // line. len = (int)(rex.reg_endp[no] - rex.reg_startp[no]); if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0) status = RA_NOMATCH; } } else // Multi-line regexp { if (rex.reg_startpos[no].lnum < 0 || rex.reg_endpos[no].lnum < 0) { // Backref was not set: Match an empty string. len = 0; } else { if (rex.reg_startpos[no].lnum == rex.lnum && rex.reg_endpos[no].lnum == rex.lnum) { // Compare back-ref within the current line. len = rex.reg_endpos[no].col - rex.reg_startpos[no].col; if (cstrncmp(rex.line + rex.reg_startpos[no].col, rex.input, &len) != 0) status = RA_NOMATCH; } else { // Messy situation: Need to compare between two // lines. int r = match_with_backref( rex.reg_startpos[no].lnum, rex.reg_startpos[no].col, rex.reg_endpos[no].lnum, rex.reg_endpos[no].col, &len); if (r != RA_MATCH) status = r; } } } // Matched the backref, skip over it. rex.input += len; } break; #ifdef FEAT_SYN_HL case ZREF + 1: case ZREF + 2: case ZREF + 3: case ZREF + 4: case ZREF + 5: case ZREF + 6: case ZREF + 7: case ZREF + 8: case ZREF + 9: { int len; cleanup_zsubexpr(); no = op - ZREF; if (re_extmatch_in != NULL && re_extmatch_in->matches[no] != NULL) { len = (int)STRLEN(re_extmatch_in->matches[no]); if (cstrncmp(re_extmatch_in->matches[no], rex.input, &len) != 0) status = RA_NOMATCH; else rex.input += len; } else { // Backref was not set: Match an empty string. } } break; #endif case BRANCH: { if (OP(next) != BRANCH) // No choice. next = OPERAND(scan); // Avoid recursion. else { rp = regstack_push(RS_BRANCH, scan); if (rp == NULL) status = RA_FAIL; else status = RA_BREAK; // rest is below } } break; case BRACE_LIMITS: { if (OP(next) == BRACE_SIMPLE) { bl_minval = OPERAND_MIN(scan); bl_maxval = OPERAND_MAX(scan); } else if (OP(next) >= BRACE_COMPLEX && OP(next) < BRACE_COMPLEX + 10) { no = OP(next) - BRACE_COMPLEX; brace_min[no] = OPERAND_MIN(scan); brace_max[no] = OPERAND_MAX(scan); brace_count[no] = 0; } else { internal_error("BRACE_LIMITS"); status = RA_FAIL; } } break; case BRACE_COMPLEX + 0: case BRACE_COMPLEX + 1: case BRACE_COMPLEX + 2: case BRACE_COMPLEX + 3: case BRACE_COMPLEX + 4: case BRACE_COMPLEX + 5: case BRACE_COMPLEX + 6: case BRACE_COMPLEX + 7: case BRACE_COMPLEX + 8: case BRACE_COMPLEX + 9: { no = op - BRACE_COMPLEX; ++brace_count[no]; // If not matched enough times yet, try one more if (brace_count[no] <= (brace_min[no] <= brace_max[no] ? brace_min[no] : brace_max[no])) { rp = regstack_push(RS_BRCPLX_MORE, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; reg_save(&rp->rs_un.regsave, &backpos); next = OPERAND(scan); // We continue and handle the result when done. } break; } // If matched enough times, may try matching some more if (brace_min[no] <= brace_max[no]) { // Range is the normal way around, use longest match if (brace_count[no] <= brace_max[no]) { rp = regstack_push(RS_BRCPLX_LONG, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = no; reg_save(&rp->rs_un.regsave, &backpos); next = OPERAND(scan); // We continue and handle the result when done. } } } else { // Range is backwards, use shortest match first if (brace_count[no] <= brace_min[no]) { rp = regstack_push(RS_BRCPLX_SHORT, scan); if (rp == NULL) status = RA_FAIL; else { reg_save(&rp->rs_un.regsave, &backpos); // We continue and handle the result when done. } } } } break; case BRACE_SIMPLE: case STAR: case PLUS: { regstar_T rst; // Lookahead to avoid useless match attempts when we know // what character comes next. if (OP(next) == EXACTLY) { rst.nextb = *OPERAND(next); if (rex.reg_ic) { if (MB_ISUPPER(rst.nextb)) rst.nextb_ic = MB_TOLOWER(rst.nextb); else rst.nextb_ic = MB_TOUPPER(rst.nextb); } else rst.nextb_ic = rst.nextb; } else { rst.nextb = NUL; rst.nextb_ic = NUL; } if (op != BRACE_SIMPLE) { rst.minval = (op == STAR) ? 0 : 1; rst.maxval = MAX_LIMIT; } else { rst.minval = bl_minval; rst.maxval = bl_maxval; } // When maxval > minval, try matching as much as possible, up // to maxval. When maxval < minval, try matching at least the // minimal number (since the range is backwards, that's also // maxval!). rst.count = regrepeat(OPERAND(scan), rst.maxval); if (got_int) { status = RA_FAIL; break; } if (rst.minval <= rst.maxval ? rst.count >= rst.minval : rst.count >= rst.maxval) { // It could match. Prepare for trying to match what // follows. The code is below. Parameters are stored in // a regstar_T on the regstack. if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { emsg(_(e_pattern_uses_more_memory_than_maxmempattern)); status = RA_FAIL; } else if (ga_grow(&regstack, sizeof(regstar_T)) == FAIL) status = RA_FAIL; else { regstack.ga_len += sizeof(regstar_T); rp = regstack_push(rst.minval <= rst.maxval ? RS_STAR_LONG : RS_STAR_SHORT, scan); if (rp == NULL) status = RA_FAIL; else { *(((regstar_T *)rp) - 1) = rst; status = RA_BREAK; // skip the restore bits } } } else status = RA_NOMATCH; } break; case NOMATCH: case MATCH: case SUBPAT: rp = regstack_push(RS_NOMATCH, scan); if (rp == NULL) status = RA_FAIL; else { rp->rs_no = op; reg_save(&rp->rs_un.regsave, &backpos); next = OPERAND(scan); // We continue and handle the result when done. } break; case BEHIND: case NOBEHIND: // Need a bit of room to store extra positions. if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { emsg(_(e_pattern_uses_more_memory_than_maxmempattern)); status = RA_FAIL; } else if (ga_grow(&regstack, sizeof(regbehind_T)) == FAIL) status = RA_FAIL; else { regstack.ga_len += sizeof(regbehind_T); rp = regstack_push(RS_BEHIND1, scan); if (rp == NULL) status = RA_FAIL; else { // Need to save the subexpr to be able to restore them // when there is a match but we don't use it. save_subexpr(((regbehind_T *)rp) - 1); rp->rs_no = op; reg_save(&rp->rs_un.regsave, &backpos); // First try if what follows matches. If it does then we // check the behind match by looping. } } break; case BHPOS: if (REG_MULTI) { if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line) || behind_pos.rs_u.pos.lnum != rex.lnum) status = RA_NOMATCH; } else if (behind_pos.rs_u.ptr != rex.input) status = RA_NOMATCH; break; case NEWL: if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline || rex.reg_line_lbr) && (c != '\n' || !rex.reg_line_lbr)) status = RA_NOMATCH; else if (rex.reg_line_lbr) ADVANCE_REGINPUT(); else reg_nextline(); break; case END: status = RA_MATCH; // Success! break; default: iemsg(_(e_corrupted_regexp_program)); #ifdef DEBUG printf("Illegal op code %d\n", op); #endif status = RA_FAIL; break; } } // If we can't continue sequentially, break the inner loop. if (status != RA_CONT) break; // Continue in inner loop, advance to next item. scan = next; } // end of inner loop // If there is something on the regstack execute the code for the state. // If the state is popped then loop and use the older state. while (regstack.ga_len > 0 && status != RA_FAIL) { rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1; switch (rp->rs_state) { case RS_NOPEN: // Result is passed on as-is, simply pop the state. regstack_pop(&scan); break; case RS_MOPEN: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no], &rex.reg_startp[rp->rs_no]); regstack_pop(&scan); break; #ifdef FEAT_SYN_HL case RS_ZOPEN: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &reg_startzpos[rp->rs_no], &reg_startzp[rp->rs_no]); regstack_pop(&scan); break; #endif case RS_MCLOSE: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no], &rex.reg_endp[rp->rs_no]); regstack_pop(&scan); break; #ifdef FEAT_SYN_HL case RS_ZCLOSE: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) restore_se(&rp->rs_un.sesave, &reg_endzpos[rp->rs_no], &reg_endzp[rp->rs_no]); regstack_pop(&scan); break; #endif case RS_BRANCH: if (status == RA_MATCH) // this branch matched, use it regstack_pop(&scan); else { if (status != RA_BREAK) { // After a non-matching branch: try next one. reg_restore(&rp->rs_un.regsave, &backpos); scan = rp->rs_scan; } if (scan == NULL || OP(scan) != BRANCH) { // no more branches, didn't find a match status = RA_NOMATCH; regstack_pop(&scan); } else { // Prepare to try a branch. rp->rs_scan = regnext(scan); reg_save(&rp->rs_un.regsave, &backpos); scan = OPERAND(scan); } } break; case RS_BRCPLX_MORE: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) { reg_restore(&rp->rs_un.regsave, &backpos); --brace_count[rp->rs_no]; // decrement match count } regstack_pop(&scan); break; case RS_BRCPLX_LONG: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) { // There was no match, but we did find enough matches. reg_restore(&rp->rs_un.regsave, &backpos); --brace_count[rp->rs_no]; // continue with the items after "\{}" status = RA_CONT; } regstack_pop(&scan); if (status == RA_CONT) scan = regnext(scan); break; case RS_BRCPLX_SHORT: // Pop the state. Restore pointers when there is no match. if (status == RA_NOMATCH) // There was no match, try to match one more item. reg_restore(&rp->rs_un.regsave, &backpos); regstack_pop(&scan); if (status == RA_NOMATCH) { scan = OPERAND(scan); status = RA_CONT; } break; case RS_NOMATCH: // Pop the state. If the operand matches for NOMATCH or // doesn't match for MATCH/SUBPAT, we fail. Otherwise backup, // except for SUBPAT, and continue with the next item. if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH)) status = RA_NOMATCH; else { status = RA_CONT; if (rp->rs_no != SUBPAT) // zero-width reg_restore(&rp->rs_un.regsave, &backpos); } regstack_pop(&scan); if (status == RA_CONT) scan = regnext(scan); break; case RS_BEHIND1: if (status == RA_NOMATCH) { regstack_pop(&scan); regstack.ga_len -= sizeof(regbehind_T); } else { // The stuff after BEHIND/NOBEHIND matches. Now try if // the behind part does (not) match before the current // position in the input. This must be done at every // position in the input and checking if the match ends at // the current position. // save the position after the found match for next reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos); // Start looking for a match with operand at the current // position. Go back one character until we find the // result, hitting the start of the line or the previous // line (for multi-line matching). // Set behind_pos to where the match should end, BHPOS // will match it. Save the current value. (((regbehind_T *)rp) - 1)->save_behind = behind_pos; behind_pos = rp->rs_un.regsave; rp->rs_state = RS_BEHIND2; reg_restore(&rp->rs_un.regsave, &backpos); scan = OPERAND(rp->rs_scan) + 4; } break; case RS_BEHIND2: // Looping for BEHIND / NOBEHIND match. if (status == RA_MATCH && reg_save_equal(&behind_pos)) { // found a match that ends where "next" started behind_pos = (((regbehind_T *)rp) - 1)->save_behind; if (rp->rs_no == BEHIND) reg_restore(&(((regbehind_T *)rp) - 1)->save_after, &backpos); else { // But we didn't want a match. Need to restore the // subexpr, because what follows matched, so they have // been set. status = RA_NOMATCH; restore_subexpr(((regbehind_T *)rp) - 1); } regstack_pop(&scan); regstack.ga_len -= sizeof(regbehind_T); } else { long limit; // No match or a match that doesn't end where we want it: Go // back one character. May go to previous line once. no = OK; limit = OPERAND_MIN(rp->rs_scan); if (REG_MULTI) { if (limit > 0 && ((rp->rs_un.regsave.rs_u.pos.lnum < behind_pos.rs_u.pos.lnum ? (colnr_T)STRLEN(rex.line) : behind_pos.rs_u.pos.col) - rp->rs_un.regsave.rs_u.pos.col >= limit)) no = FAIL; else if (rp->rs_un.regsave.rs_u.pos.col == 0) { if (rp->rs_un.regsave.rs_u.pos.lnum < behind_pos.rs_u.pos.lnum || reg_getline( --rp->rs_un.regsave.rs_u.pos.lnum) == NULL) no = FAIL; else { reg_restore(&rp->rs_un.regsave, &backpos); rp->rs_un.regsave.rs_u.pos.col = (colnr_T)STRLEN(rex.line); } } else { if (has_mbyte) { char_u *line = reg_getline(rp->rs_un.regsave.rs_u.pos.lnum); rp->rs_un.regsave.rs_u.pos.col -= (*mb_head_off)(line, line + rp->rs_un.regsave.rs_u.pos.col - 1) + 1; } else --rp->rs_un.regsave.rs_u.pos.col; } } else { if (rp->rs_un.regsave.rs_u.ptr == rex.line) no = FAIL; else { MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr); if (limit > 0 && (long)(behind_pos.rs_u.ptr - rp->rs_un.regsave.rs_u.ptr) > limit) no = FAIL; } } if (no == OK) { // Advanced, prepare for finding match again. reg_restore(&rp->rs_un.regsave, &backpos); scan = OPERAND(rp->rs_scan) + 4; if (status == RA_MATCH) { // We did match, so subexpr may have been changed, // need to restore them for the next try. status = RA_NOMATCH; restore_subexpr(((regbehind_T *)rp) - 1); } } else { // Can't advance. For NOBEHIND that's a match. behind_pos = (((regbehind_T *)rp) - 1)->save_behind; if (rp->rs_no == NOBEHIND) { reg_restore(&(((regbehind_T *)rp) - 1)->save_after, &backpos); status = RA_MATCH; } else { // We do want a proper match. Need to restore the // subexpr if we had a match, because they may have // been set. if (status == RA_MATCH) { status = RA_NOMATCH; restore_subexpr(((regbehind_T *)rp) - 1); } } regstack_pop(&scan); regstack.ga_len -= sizeof(regbehind_T); } } break; case RS_STAR_LONG: case RS_STAR_SHORT: { regstar_T *rst = ((regstar_T *)rp) - 1; if (status == RA_MATCH) { regstack_pop(&scan); regstack.ga_len -= sizeof(regstar_T); break; } // Tried once already, restore input pointers. if (status != RA_BREAK) reg_restore(&rp->rs_un.regsave, &backpos); // Repeat until we found a position where it could match. for (;;) { if (status != RA_BREAK) { // Tried first position already, advance. if (rp->rs_state == RS_STAR_LONG) { // Trying for longest match, but couldn't or // didn't match -- back up one char. if (--rst->count < rst->minval) break; if (rex.input == rex.line) { // backup to last char of previous line if (rex.lnum == 0) { status = RA_NOMATCH; break; } --rex.lnum; rex.line = reg_getline(rex.lnum); // Just in case regrepeat() didn't count // right. if (rex.line == NULL) break; rex.input = rex.line + STRLEN(rex.line); fast_breakcheck(); } else MB_PTR_BACK(rex.line, rex.input); } else { // Range is backwards, use shortest match first. // Careful: maxval and minval are exchanged! // Couldn't or didn't match: try advancing one // char. if (rst->count == rst->minval || regrepeat(OPERAND(rp->rs_scan), 1L) == 0) break; ++rst->count; } if (got_int) break; } else status = RA_NOMATCH; // If it could match, try it. if (rst->nextb == NUL || *rex.input == rst->nextb || *rex.input == rst->nextb_ic) { reg_save(&rp->rs_un.regsave, &backpos); scan = regnext(rp->rs_scan); status = RA_CONT; break; } } if (status != RA_CONT) { // Failed. regstack_pop(&scan); regstack.ga_len -= sizeof(regstar_T); status = RA_NOMATCH; } } break; } // If we want to continue the inner loop or didn't pop a state // continue matching loop if (status == RA_CONT || rp == (regitem_T *) ((char *)regstack.ga_data + regstack.ga_len) - 1) break; } // May need to continue with the inner loop, starting at "scan". if (status == RA_CONT) continue; // If the regstack is empty or something failed we are done. if (regstack.ga_len == 0 || status == RA_FAIL) { if (scan == NULL) { // We get here only if there's trouble -- normally "case END" is // the terminating point. iemsg(_(e_corrupted_regexp_program)); #ifdef DEBUG printf("Premature EOL\n"); #endif } return (status == RA_MATCH); } } // End of loop until the regstack is empty. // NOTREACHED }
159439689195764393844711247359472650436
regexp_bt.c
101007884968871143689098417071305864398
CWE-416
CVE-2022-1154
Use after free in utf_ptr2char in GitHub repository vim/vim prior to 8.2.4646.
https://nvd.nist.gov/vuln/detail/CVE-2022-1154