project
string
commit_id
string
target
int64
func
string
cwe
string
big_vul_idx
string
idx
int64
hash
string
size
float64
message
string
dataset
string
Chrome
fb83de09f2c986ee91741f3a2776feea0e18e3f6
1
void OverlayWindowViews::OnGestureEvent(ui::GestureEvent* event) { if (event->type() != ui::ET_GESTURE_TAP) return; hide_controls_timer_.Reset(); if (!GetControlsScrimLayer()->visible()) { UpdateControlsVisibility(true); return; } if (GetCloseControlsBounds().Contains(event->location())) { controller_->Close(true /* should_pause_video */, true /* should_reset_pip_player */); event->SetHandled(); } else if (GetPlayPauseControlsBounds().Contains(event->location())) { TogglePlayPause(); event->SetHandled(); } views::Widget::OnGestureEvent(event); }
186551
7,290
303506592678362065050884877503185093458
null
null
null
Chrome
610f904d8215075c4681be4eb413f4348860bf9f
0
CallbackList& callbacks() { return callbacks_; }
101065
90,816
6378649268612680894492270454042834907
null
null
null
tensorflow
92dba16749fae36c246bec3f9ba474d9ddeb7662
1
bool DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const { if (!IsIdentity(node) && !IsIdentityN(node)) { return true; } if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) { return false; } if (!fetch_nodes_known_) { // The output values of this node may be needed. return false; } if (node.input_size() < 1) { // Node lacks input, is invalid return false; } const NodeDef* input = node_map_->GetNode(NodeName(node.input(0))); CHECK(input != nullptr) << "node = " << node.name() << " input = " << node.input(0); // Don't remove Identity nodes corresponding to Variable reads or following // Recv. if (IsVariable(*input) || IsRecv(*input)) { return false; } for (const auto& consumer : node_map_->GetOutputs(node.name())) { if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) { return false; } if (IsSwitch(*input)) { for (const string& consumer_input : consumer->input()) { if (consumer_input == AsControlDependency(node.name())) { return false; } } } } return true; }
null
null
195,059
280470408197015060590448712190364740247
40
Prevent a null-pointer dereference / `CHECK`-fail in grappler. PiperOrigin-RevId: 409187354 Change-Id: I369c249cca32e6c56ec193f0ebbf2f2768fc7d43
other
tensorflow
8a513cec4bec15961fbfdedcaa5376522980455c
1
StatusOr<FullTypeDef> SpecializeType(const AttrSlice& attrs, const OpDef& op_def) { FullTypeDef ft; ft.set_type_id(TFT_PRODUCT); for (int i = 0; i < op_def.output_arg_size(); i++) { auto* t = ft.add_args(); *t = op_def.output_arg(i).experimental_full_type(); // Resolve dependent types. The convention for op registrations is to use // attributes as type variables. // See https://www.tensorflow.org/guide/create_op#type_polymorphism. // Once the op signature can be defined entirely in FullType, this // convention can be deprecated. // // Note: While this code performs some basic verifications, it generally // assumes consistent op defs and attributes. If more complete // verifications are needed, they should be done by separately, and in a // way that can be reused for type inference. for (int j = 0; j < t->args_size(); j++) { auto* arg = t->mutable_args(i); if (arg->type_id() == TFT_VAR) { const auto* attr = attrs.Find(arg->s()); DCHECK(attr != nullptr); if (attr->value_case() == AttrValue::kList) { const auto& attr_list = attr->list(); arg->set_type_id(TFT_PRODUCT); for (int i = 0; i < attr_list.type_size(); i++) { map_dtype_to_tensor(attr_list.type(i), arg->add_args()); } } else if (attr->value_case() == AttrValue::kType) { map_dtype_to_tensor(attr->type(), arg); } else { return Status(error::UNIMPLEMENTED, absl::StrCat("unknown attribute type", attrs.DebugString(), " key=", arg->s())); } arg->clear_s(); } } } return ft; }
null
null
195,067
127871006948263872569838116397374697164
48
Prevent null dereference read in `SpecializeType()` For some adversarial protos, the attribute for a key might not exist. PiperOrigin-RevId: 408382090 Change-Id: Ie7eabe532c9ff280fce5dce1f6cdb93c76c2e040
other
gpac
a69b567b8c95c72f9560c873c5ab348be058f340
1
GF_AV1Config *gf_odf_av1_cfg_read_bs_size(GF_BitStream *bs, u32 size) { #ifndef GPAC_DISABLE_AV_PARSERS AV1State state; u8 reserved; GF_AV1Config *cfg; if (!size) size = (u32) gf_bs_available(bs); if (!size) return NULL; cfg = gf_odf_av1_cfg_new(); gf_av1_init_state(&state); state.config = cfg; cfg->marker = gf_bs_read_int(bs, 1); cfg->version = gf_bs_read_int(bs, 7); cfg->seq_profile = gf_bs_read_int(bs, 3); cfg->seq_level_idx_0 = gf_bs_read_int(bs, 5); cfg->seq_tier_0 = gf_bs_read_int(bs, 1); cfg->high_bitdepth = gf_bs_read_int(bs, 1); cfg->twelve_bit = gf_bs_read_int(bs, 1); cfg->monochrome = gf_bs_read_int(bs, 1); cfg->chroma_subsampling_x = gf_bs_read_int(bs, 1); cfg->chroma_subsampling_y = gf_bs_read_int(bs, 1); cfg->chroma_sample_position = gf_bs_read_int(bs, 2); reserved = gf_bs_read_int(bs, 3); if (reserved != 0 || cfg->marker != 1 || cfg->version != 1) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] wrong avcC reserved %d / marker %d / version %d expecting 0 1 1\n", reserved, cfg->marker, cfg->version)); gf_odf_av1_cfg_del(cfg); return NULL; } cfg->initial_presentation_delay_present = gf_bs_read_int(bs, 1); if (cfg->initial_presentation_delay_present) { cfg->initial_presentation_delay_minus_one = gf_bs_read_int(bs, 4); } else { /*reserved = */gf_bs_read_int(bs, 4); cfg->initial_presentation_delay_minus_one = 0; } size -= 4; while (size) { u64 pos, obu_size; ObuType obu_type; GF_AV1_OBUArrayEntry *a; pos = gf_bs_get_position(bs); obu_size = 0; if (gf_av1_parse_obu(bs, &obu_type, &obu_size, NULL, &state) != GF_OK) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[AV1] could not parse AV1 OBU at position "LLU". Leaving parsing.\n", pos)); break; } assert(obu_size == gf_bs_get_position(bs) - pos); GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] parsed AV1 OBU type=%u size="LLU" at position "LLU".\n", obu_type, obu_size, pos)); if (!av1_is_obu_header(obu_type)) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] AV1 unexpected OBU type=%u size="LLU" found at position "LLU". Forwarding.\n", pos)); } GF_SAFEALLOC(a, GF_AV1_OBUArrayEntry); if (!a) break; a->obu = gf_malloc((size_t)obu_size); if (!a->obu) { gf_free(a); break; } gf_bs_seek(bs, pos); gf_bs_read_data(bs, (char *) a->obu, (u32)obu_size); a->obu_length = obu_size; a->obu_type = obu_type; gf_list_add(cfg->obu_array, a); if (size<obu_size) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[AV1] AV1 config misses %d bytes to fit the entire OBU\n", obu_size - size)); break; } size -= (u32) obu_size; } gf_av1_reset_state(& state, GF_TRUE); return cfg; #else return NULL; #endif }
null
null
195,074
94331888032186617444846251549702110835
83
fixed #1895
other
tensorflow
5b491cd5e41ad63735161cec9c2a568172c8b6a3
1
bool Tensor::FromProto(Allocator* a, const TensorProto& proto) { CHECK_NOTNULL(a); TensorBuffer* p = nullptr; if (!TensorShape::IsValid(proto.tensor_shape())) return false; if (proto.dtype() == DT_INVALID) return false; TensorShape shape(proto.tensor_shape()); const int64_t N = shape.num_elements(); if (N > 0 && proto.dtype()) { bool dtype_error = false; if (!proto.tensor_content().empty()) { const auto& content = proto.tensor_content(); CASES_WITH_DEFAULT(proto.dtype(), p = Helper<T>::Decode(a, content, N), dtype_error = true, dtype_error = true); } else { CASES_WITH_DEFAULT(proto.dtype(), p = FromProtoField<T>(a, proto, N), dtype_error = true, dtype_error = true); } if (dtype_error || p == nullptr) return false; } shape_ = shape; set_dtype(proto.dtype()); UnrefIfNonNull(buf_); buf_ = p; // TODO(misard) add tracking of which kernels and steps are calling // FromProto. if (MemoryLoggingEnabled() && buf_ != nullptr && buf_->data() != nullptr) { LogMemory::RecordTensorAllocation("Unknown (from Proto)", LogMemory::UNKNOWN_STEP_ID, *this); } return true; }
null
null
195,083
293865285807198215508518477303207322028
31
Validate `proto.dtype()` before calling `set_dtype()`. This prevents a `DCHECK`-fail when the proto contains an invalid dtype for a tensor shape with 0 elements or for an incomplete tensor shape. PiperOrigin-RevId: 408369083 Change-Id: Ia21a3e3d62a90d642a4561f08f3b543e5ad00c46
other
ImageMagick
f221ea0fa3171f0f4fdf74ac9d81b203b9534c23
1
static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CropBox "CropBox" #define DeviceCMYK "DeviceCMYK" #define MediaBox "MediaBox" #define RenderPCLText " Rendering PCL... " char command[MagickPathExtent], *density, filename[MagickPathExtent], geometry[MagickPathExtent], *options, input_filename[MagickPathExtent]; const DelegateInfo *delegate_info; Image *image, *next_image; ImageInfo *read_info; MagickBooleanType cmyk, status; PointInfo delta; RectangleInfo bounding_box, page; char *p; ssize_t c; SegmentInfo bounds; size_t height, width; ssize_t count; 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); /* Open image file. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); if ((flags & RhoValue) != 0) image->resolution.x=geometry_info.rho; image->resolution.y=image->resolution.x; if ((flags & SigmaValue) != 0) image->resolution.y=geometry_info.sigma; } /* Determine page geometry from the PCL media box. */ cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; count=0; (void) memset(&bounding_box,0,sizeof(bounding_box)); (void) memset(&bounds,0,sizeof(bounds)); (void) memset(&page,0,sizeof(page)); (void) memset(command,0,sizeof(command)); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if (image_info->page != (char *) NULL) continue; /* Note PCL elements. */ *p++=(char) c; if ((c != (int) '/') && (c != '\n') && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Is this a CMYK document? */ if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; /* Set PCL render geometry. */ width=(size_t) floor(bounds.x2-bounds.x1+0.5); height=(size_t) floor(bounds.y2-bounds.y1+0.5); if (width > page.width) page.width=width; if (height > page.height) page.height=height; } (void) CloseBlob(image); /* Render PCL with the GhostPCL delegate. */ if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); (void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",(double) page.width,(double) page.height); if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("pcl:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("pcl:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("pcl:color",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { image=DestroyImage(image); return((Image *) NULL); } if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MagickPathExtent,"%gx%g", image->resolution.x,image->resolution.y); if (image_info->ping != MagickFalse) (void) FormatLocaleString(density,MagickPathExtent,"2.0x2.0"); page.width=(size_t) floor(page.width*image->resolution.x/delta.x+0.5); page.height=(size_t) floor(page.height*image->resolution.y/delta.y+0.5); (void) FormatLocaleString(options,MagickPathExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); image=DestroyImage(image); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { if (read_info->number_scenes != 1) (void) FormatLocaleString(options,MagickPathExtent,"-dLastPage=%.20g", (double) (read_info->scene+read_info->number_scenes)); else (void) FormatLocaleString(options,MagickPathExtent, "-dFirstPage=%.20g -dLastPage=%.20g",(double) read_info->scene+1, (double) (read_info->scene+read_info->number_scenes)); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MagickPathExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options, read_info->filename,input_filename); options=DestroyString(options); density=DestroyString(density); status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command, (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse; image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); (void) RelinquishUniqueFileResource(input_filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) ThrowReaderException(DelegateError,"PCLDelegateFailed"); if (LocaleCompare(image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(image,exception); if (cmyk_image != (Image *) NULL) { image=DestroyImageList(image); image=cmyk_image; } } do { (void) CopyMagickString(image->filename,filename,MagickPathExtent); image->page=page; if (image_info->ping != MagickFalse) { image->magick_columns*=image->resolution.x/2.0; image->magick_rows*=image->resolution.y/2.0; image->columns*=image->resolution.x/2.0; image->rows*=image->resolution.y/2.0; } next_image=SyncNextImageInList(image); if (next_image != (Image *) NULL) image=next_image; } while (next_image != (Image *) NULL); return(GetFirstImageInList(image)); }
null
null
195,237
64211844764718959430074467543645938607
257
Fixes #4985: 4e+26 is outside the range of representable values of type 'unsigned long' at coders/pcl.c:299 (#4986) * fix Division by zero in XMenuWidget() of MagickCore/widget.c * Fix memory leak in AnimateImageCommand() of MagickWand/animate.c and DisplayImageCommand() of MagickWand/display.c * fix Division by zero in ReadEnhMetaFile() of coders/emf.c * Resolve conflicts * fix issue: outside the range of representable values of type 'unsigned char' at coders/psd.c:1025 * fix error: 4e+26 is outside the range of representable values of type 'unsigned long' at coders/pcl.c:299 Co-authored-by: zhailiangliang <[email protected]>
other
tensorflow
1b54cadd19391b60b6fcccd8d076426f7221d5e8
1
void Compute(OpKernelContext *ctx) override { const Tensor *indices_t, *values_t, *shape_t, *dense_t; OP_REQUIRES_OK(ctx, ctx->input("sp_indices", &indices_t)); OP_REQUIRES_OK(ctx, ctx->input("sp_values", &values_t)); OP_REQUIRES_OK(ctx, ctx->input("sp_shape", &shape_t)); OP_REQUIRES_OK(ctx, ctx->input("dense", &dense_t)); // Validations. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()), errors::InvalidArgument( "Input sp_indices should be a matrix but received shape: ", indices_t->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values_t->shape()) && TensorShapeUtils::IsVector(shape_t->shape()), errors::InvalidArgument( "Inputs sp_values and sp_shape should be vectors " "but received shapes: ", values_t->shape().DebugString(), " and ", shape_t->shape().DebugString())); OP_REQUIRES( ctx, values_t->dim_size(0) == indices_t->dim_size(0), errors::InvalidArgument( "The first dimension of values and indices should match. (", values_t->dim_size(0), " vs. ", indices_t->dim_size(0), ")")); const auto indices_mat = indices_t->matrix<int64_t>(); const auto shape_vec = shape_t->vec<int64_t>(); const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec)); const auto rhs_dims = BCast::FromShape(dense_t->shape()); BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims. // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal // to dims in rhs (from right to left). auto VecGreaterEq = [](ArraySlice<int64_t> lhs, ArraySlice<int64_t> rhs) { if (lhs.size() < rhs.size()) return false; for (size_t i = 0; i < rhs.size(); ++i) { if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false; } return true; }; OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(), errors::InvalidArgument( "SparseDenseBinaryOpShared broadcasts dense to sparse " "only; got incompatible shapes: [", absl::StrJoin(lhs_dims, ","), "] vs. [", absl::StrJoin(rhs_dims, ","), "]")); Tensor *output_values = nullptr; Tensor dense_gathered; const int64_t nnz = indices_t->dim_size(0); OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({nnz}), &output_values)); OP_REQUIRES_OK( ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape({nnz}), &dense_gathered)); bool op_is_div = false; if (absl::StrContains(ctx->op_kernel().type_string_view(), "Div")) { op_is_div = true; } // Pulls relevant entries from the dense side, with reshape and broadcasting // *of the dense side* taken into account. Use a TensorRef to avoid blowing // up memory. // // We can directly use the sparse indices to look up dense side, because // "b.y_reshape()" and "b.y_bcast()" are guaranteed to have rank "ndims". auto dense_gathered_flat = dense_gathered.flat<T>(); const int ndims = lhs_dims.size(); switch (ndims) { #define CASE(NDIM) \ case NDIM: { \ TensorRef<Eigen::Tensor<const T, NDIM, Eigen::RowMajor>> rhs_ref = \ dense_t->shaped<T, NDIM>(b.y_reshape()) \ .broadcast(BCast::ToIndexArray<NDIM>(b.y_bcast())); \ Eigen::array<Eigen::DenseIndex, NDIM> idx; \ bool indices_valid = true; \ for (int i = 0; i < nnz; ++i) { \ for (int d = 0; d < NDIM; ++d) { \ idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \ if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \ indices_valid = false; \ } \ } \ OP_REQUIRES( \ ctx, indices_valid, \ errors::InvalidArgument("Provided indices are out-of-bounds w.r.t. " \ "dense side with broadcasted shape")); \ dense_gathered_flat(i) = rhs_ref.coeff(idx); \ if (op_is_div) { \ OP_REQUIRES(ctx, dense_gathered_flat(i) != 0, \ errors::InvalidArgument( \ "SparseDenseCwiseDiv cannot divide by zero," \ "but input dense tensor contains zero ")); \ } \ } \ break; \ } CASE(1); CASE(2); CASE(3); CASE(4); CASE(5); default: OP_REQUIRES( ctx, false, errors::InvalidArgument("Only tensors with ranks between 1 and 5 " "are currently supported. Tensor rank: ", ndims)); #undef CASE } output_values->flat<T>().device(ctx->eigen_device<Device>()) = values_t->flat<T>().binaryExpr(dense_gathered_flat, typename Functor::func()); }
null
null
195,242
149037414387774871757110019685380440226
116
Add missing validation to sparse dense cwise ops. PiperOrigin-RevId: 415543133 Change-Id: I5baf3284e919338afb96178c468ad3d3cb0d956c
other
radare2
37897226a1a31f982bfefdc4aeefc2e50355c73c
1
R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) { RIOBank *bank = r_io_bank_get (io, bankid); RIOMap *map = r_io_map_get (io, mapid); r_return_val_if_fail (io && bank && map, false); RIOMapRef *mapref = _mapref_from_map (map); if (!mapref) { return false; } RIOSubMap *sm = r_io_submap_new (io, mapref); if (!sm) { free (mapref); return false; } RRBNode *entry = _find_entry_submap_node (bank, sm); if (!entry) { // no intersection with any submap, so just insert if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } bank->last_used = NULL; RIOSubMap *bd = (RIOSubMap *)entry->data; if (r_io_submap_to (bd) == r_io_submap_to (sm) && r_io_submap_from (bd) >= r_io_submap_from (sm)) { // _find_entry_submap_node guarantees, that there is no submap // prior to bd in the range of sm, so instead of deleting and inserting // we can just memcpy memcpy (bd, sm, sizeof (RIOSubMap)); free (sm); r_list_append (bank->maprefs, mapref); return true; } if (r_io_submap_from (bd) < r_io_submap_from (sm) && r_io_submap_to (sm) < r_io_submap_to (bd)) { // split bd into 2 maps => bd and bdsm RIOSubMap *bdsm = R_NEWCOPY (RIOSubMap, bd); if (!bdsm) { free (sm); free (mapref); return false; } r_io_submap_set_from (bdsm, r_io_submap_to (sm) + 1); r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); // TODO: insert and check return value, before adjusting sm size if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (bdsm); free (mapref); return false; } if (!r_crbtree_insert (bank->submaps, bdsm, _find_sm_by_from_vaddr_cb, NULL)) { r_crbtree_delete (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL); free (sm); free (bdsm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } // guaranteed intersection if (r_io_submap_from (bd) < r_io_submap_from (sm)) { r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); entry = r_rbnode_next (entry); } while (entry && r_io_submap_to (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { //delete all submaps that are completly included in sm RRBNode *next = r_rbnode_next (entry); // this can be optimized, there is no need to do search here r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL); entry = next; } if (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { bd = (RIOSubMap *)entry->data; r_io_submap_set_from (bd, r_io_submap_to (sm) + 1); } if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; }
null
null
195,302
166117759561842192488491492863600381325
89
Fix use-after-free in iobank rbtree usage ##io * See havoc4 bin for reproducer * Reported via huntr.dev by 'Cen Zhang'
other
flatpak
65cbfac982cb1c83993a9e19aa424daee8e9f042
1
flatpak_dir_ensure_bundle_remote (FlatpakDir *self, GFile *file, GBytes *extra_gpg_data, FlatpakDecomposed **out_ref, char **out_checksum, char **out_metadata, gboolean *out_created_remote, GCancellable *cancellable, GError **error) { g_autoptr(FlatpakDecomposed) ref = NULL; gboolean created_remote = FALSE; g_autoptr(GBytes) deploy_data = NULL; g_autoptr(GVariant) metadata = NULL; g_autofree char *origin = NULL; g_autofree char *fp_metadata = NULL; g_autofree char *basename = NULL; g_autoptr(GBytes) included_gpg_data = NULL; GBytes *gpg_data = NULL; g_autofree char *to_checksum = NULL; g_autofree char *remote = NULL; g_autofree char *collection_id = NULL; if (!flatpak_dir_ensure_repo (self, cancellable, error)) return NULL; metadata = flatpak_bundle_load (file, &to_checksum, &ref, &origin, NULL, &fp_metadata, NULL, &included_gpg_data, &collection_id, error); if (metadata == NULL) return NULL; gpg_data = extra_gpg_data ? extra_gpg_data : included_gpg_data; deploy_data = flatpak_dir_get_deploy_data (self, ref, FLATPAK_DEPLOY_VERSION_ANY, cancellable, NULL); if (deploy_data != NULL) { remote = g_strdup (flatpak_deploy_data_get_origin (deploy_data)); /* We need to import any gpg keys because otherwise the pull will fail */ if (gpg_data != NULL) { g_autoptr(GKeyFile) new_config = NULL; new_config = ostree_repo_copy_config (flatpak_dir_get_repo (self)); if (!flatpak_dir_modify_remote (self, remote, new_config, gpg_data, cancellable, error)) return NULL; } } else { g_autofree char *id = flatpak_decomposed_dup_id (ref); /* Add a remote for later updates */ basename = g_file_get_basename (file); remote = flatpak_dir_create_origin_remote (self, origin, id, basename, flatpak_decomposed_get_ref (ref), gpg_data, collection_id, &created_remote, cancellable, error); if (remote == NULL) return NULL; } if (out_created_remote) *out_created_remote = created_remote; if (out_ref) *out_ref = g_steal_pointer (&ref); if (out_checksum) *out_checksum = g_steal_pointer (&to_checksum); if (out_metadata) *out_metadata = g_steal_pointer (&fp_metadata); return g_steal_pointer (&remote); }
null
null
195,385
228799429357940261115009589207592722070
89
Ensure that bundles have metadata on install If we have a bundle without metadata we wouldn't properly present the permissions in the transaction.
other
v4l2loopback
e4cd225557486c420f6a34411f98c575effd43dd
1
static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct v4l2_loopback_device *dev = v4l2loopback_getdevice(file); int labellen = (sizeof(cap->card) < sizeof(dev->card_label)) ? sizeof(cap->card) : sizeof(dev->card_label); int device_nr = ((struct v4l2loopback_private *)video_get_drvdata(dev->vdev)) ->device_nr; __u32 capabilities = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; strlcpy(cap->driver, "v4l2 loopback", sizeof(cap->driver)); snprintf(cap->card, labellen, dev->card_label); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:v4l2loopback-%03d", device_nr); #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 1, 0) /* since 3.1.0, the v4l2-core system is supposed to set the version */ cap->version = V4L2LOOPBACK_VERSION_CODE; #endif #ifdef V4L2_CAP_VIDEO_M2M capabilities |= V4L2_CAP_VIDEO_M2M; #endif /* V4L2_CAP_VIDEO_M2M */ if (dev->announce_all_caps) { capabilities |= V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT; } else { if (dev->ready_for_capture) { capabilities |= V4L2_CAP_VIDEO_CAPTURE; } if (dev->ready_for_output) { capabilities |= V4L2_CAP_VIDEO_OUTPUT; } } #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 7, 0) dev->vdev->device_caps = #endif /* >=linux-4.7.0 */ cap->device_caps = cap->capabilities = capabilities; #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 3, 0) cap->capabilities |= V4L2_CAP_DEVICE_CAPS; #endif memset(cap->reserved, 0, sizeof(cap->reserved)); return 0; }
null
null
195,398
315173664575668559594492834827107741837
49
add explicit format specifier to printf() invocations CWE-134
other
tensorflow
a1e1511dde36b3f8aa27a6ec630838e7ea40e091
1
int TfLiteIntArrayGetSizeInBytes(int size) { static TfLiteIntArray dummy; int computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size; #if defined(_MSC_VER) // Context for why this is needed is in http://b/189926408#comment21 computed_size -= sizeof(dummy.data[0]); #endif return computed_size; }
null
null
195,402
57995846542337948463298638540979134332
10
[lite] Update TfLiteIntArrayCreate to return size_t PiperOrigin-RevId: 416439896 Change-Id: I847f69b68d1ddaff4b1e925a09b8b69c1756653b
other
hhvm
dabd48caf74995e605f1700344f1ff4a5d83441d
1
bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; }
null
null
195,549
230969768529717165037239975546250419627
499
Fix a json_decode crash when depth==0 Summary: Setting depth=0 is an error, and should result in NULL, but we weren't checking for it, so in the case of a single, top-level string, we would reading the -1th element of the stack. Differential Revision: D19609959 fbshipit-source-id: 04ca1e0965e04b44df2d5c806a73c3da99ff66fb
other
hhvm
1888810e77b446a79a7674784d5f139fcfa605e2
1
bool WddxPacket::recursiveAddVar(const String& varName, const Variant& varVariant, bool hasVarTag) { bool isArray = varVariant.isArray(); bool isObject = varVariant.isObject(); if (isArray || isObject) { if (hasVarTag) { m_packetString.append("<var name='"); m_packetString.append(varName.data()); m_packetString.append("'>"); } Array varAsArray; Object varAsObject = varVariant.toObject(); if (isArray) varAsArray = varVariant.toArray(); if (isObject) varAsArray = varAsObject.toArray(); int length = varAsArray.length(); if (length > 0) { ArrayIter it = ArrayIter(varAsArray); if (it.first().isString()) isObject = true; if (isObject) { m_packetString.append("<struct>"); if (!isArray) { m_packetString.append("<var name='php_class_name'><string>"); m_packetString.append(varAsObject->getClassName()); m_packetString.append("</string></var>"); } } else { m_packetString.append("<array length='"); m_packetString.append(std::to_string(length)); m_packetString.append("'>"); } for (ArrayIter it(varAsArray); it; ++it) { Variant key = it.first(); Variant value = it.second(); recursiveAddVar(key.toString(), value, isObject); } if (isObject) { m_packetString.append("</struct>"); } else { m_packetString.append("</array>"); } } else { //empty object if (isObject) { m_packetString.append("<struct>"); if (!isArray) { m_packetString.append("<var name='php_class_name'><string>"); m_packetString.append(varAsObject->getClassName()); m_packetString.append("</string></var>"); } m_packetString.append("</struct>"); } } if (hasVarTag) { m_packetString.append("</var>"); } return true; } String varType = getDataTypeString(varVariant.getType()); if (!getWddxEncoded(varType, "", varName, false).empty()) { String varValue; if (varType.compare("boolean") == 0) { varValue = varVariant.toBoolean() ? "true" : "false"; } else { varValue = StringUtil::HtmlEncode(varVariant.toString(), StringUtil::QuoteStyle::Double, "UTF-8", false, false).toCppString(); } m_packetString.append( getWddxEncoded(varType, varValue, varName, hasVarTag)); return true; } return false; }
null
null
195,551
257002953542231292524849386209084454732
82
Fix infinite recursion in wddx Summary: It wasn't checking for infinite recursion due to references or self-referential objects. As it turns out closures always return themselves when converted to an array. Raising a warning and returning is how PHP-src deals with this problem, nothing special is done for closures. Reviewed By: alexmalyshev Differential Revision: D3465655 fbshipit-source-id: a42bc34d30cf4825faf33596139c0c05f8e4f5f1
other
pjproject
856f87c2e97a27b256482dbe0d748b1194355a21
1
static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner) { pj_xml_node *node; pj_str_t end_name; PJ_CHECK_STACK(); if (*scanner->curptr != '<') on_syntax_error(scanner); /* Handle Processing Instructino (PI) construct (i.e. "<?") */ if (*scanner->curptr == '<' && *(scanner->curptr+1) == '?') { pj_scan_advance_n(scanner, 2, PJ_FALSE); for (;;) { pj_str_t dummy; pj_scan_get_until_ch(scanner, '?', &dummy); if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') { pj_scan_advance_n(scanner, 2, PJ_TRUE); break; } else { pj_scan_advance_n(scanner, 1, PJ_FALSE); } } return xml_parse_node(pool, scanner); } /* Handle comments construct (i.e. "<!") */ if (pj_scan_strcmp(scanner, "<!", 2) == 0) { pj_scan_advance_n(scanner, 2, PJ_FALSE); for (;;) { pj_str_t dummy; pj_scan_get_until_ch(scanner, '>', &dummy); if (pj_scan_strcmp(scanner, ">", 1) == 0) { pj_scan_advance_n(scanner, 1, PJ_TRUE); break; } else { pj_scan_advance_n(scanner, 1, PJ_FALSE); } } return xml_parse_node(pool, scanner); } /* Alloc node. */ node = alloc_node(pool); /* Get '<' */ pj_scan_get_char(scanner); /* Get node name. */ pj_scan_get_until_chr( scanner, " />\t\r\n", &node->name); /* Get attributes. */ while (*scanner->curptr != '>' && *scanner->curptr != '/') { pj_xml_attr *attr = alloc_attr(pool); pj_scan_get_until_chr( scanner, "=> \t\r\n", &attr->name); if (*scanner->curptr == '=') { pj_scan_get_char( scanner ); pj_scan_get_quotes(scanner, "\"'", "\"'", 2, &attr->value); /* remove quote characters */ ++attr->value.ptr; attr->value.slen -= 2; } pj_list_push_back( &node->attr_head, attr ); } if (*scanner->curptr == '/') { pj_scan_get_char(scanner); if (pj_scan_get_char(scanner) != '>') on_syntax_error(scanner); return node; } /* Enclosing bracket. */ if (pj_scan_get_char(scanner) != '>') on_syntax_error(scanner); /* Sub nodes. */ while (*scanner->curptr == '<' && *(scanner->curptr+1) != '/' && *(scanner->curptr+1) != '!') { pj_xml_node *sub_node = xml_parse_node(pool, scanner); pj_list_push_back( &node->node_head, sub_node ); } /* Content. */ if (!pj_scan_is_eof(scanner) && *scanner->curptr != '<') { pj_scan_get_until_ch(scanner, '<', &node->content); } /* CDATA content. */ if (*scanner->curptr == '<' && *(scanner->curptr+1) == '!' && pj_scan_strcmp(scanner, "<![CDATA[", 9) == 0) { pj_scan_advance_n(scanner, 9, PJ_FALSE); pj_scan_get_until_ch(scanner, ']', &node->content); while (pj_scan_strcmp(scanner, "]]>", 3)) { pj_str_t dummy; pj_scan_get_until_ch(scanner, ']', &dummy); } node->content.slen = scanner->curptr - node->content.ptr; pj_scan_advance_n(scanner, 3, PJ_TRUE); } /* Enclosing node. */ if (pj_scan_get_char(scanner) != '<' || pj_scan_get_char(scanner) != '/') on_syntax_error(scanner); pj_scan_get_until_chr(scanner, " \t>", &end_name); /* Compare name. */ if (pj_stricmp(&node->name, &end_name) != 0) on_syntax_error(scanner); /* Enclosing '>' */ if (pj_scan_get_char(scanner) != '>') on_syntax_error(scanner); return node; }
null
null
195,670
137312951595763938703339557990324963725
121
Merge pull request from GHSA-5x45-qp78-g4p4 * Prevent infinite loop in scanning xml content * Simplify scanning method * Optimization
other
glibc
23e0e8f5f1fb5ed150253d986ecccdc90c2dcd5e
1
__getcwd_generic (char *buf, size_t size) { /* Lengths of big file name components and entire file names, and a deep level of file name nesting. These numbers are not upper bounds; they are merely large values suitable for initial allocations, designed to be large enough for most real-world uses. */ enum { BIG_FILE_NAME_COMPONENT_LENGTH = 255, BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1), DEEP_NESTING = 100 }; #if HAVE_OPENAT_SUPPORT int fd = AT_FDCWD; bool fd_needs_closing = false; #else char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1]; char *dotlist = dots; size_t dotsize = sizeof dots; size_t dotlen = 0; #endif DIR *dirstream = NULL; dev_t rootdev, thisdev; ino_t rootino, thisino; char *dir; register char *dirp; struct __stat64_t64 st; size_t allocated = size; size_t used; #if HAVE_MINIMALLY_WORKING_GETCWD /* If AT_FDCWD is not defined, the algorithm below is O(N**2) and this is much slower than the system getcwd (at least on GNU/Linux). So trust the system getcwd's results unless they look suspicious. Use the system getcwd even if we have openat support, since the system getcwd works even when a parent is unreadable, while the openat-based approach does not. But on AIX 5.1..7.1, the system getcwd is not even minimally working: If the current directory name is slightly longer than PATH_MAX, it omits the first directory component and returns this wrong result with errno = 0. */ # undef getcwd dir = getcwd_system (buf, size); if (dir || (size && errno == ERANGE)) return dir; /* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has internal magic that lets it work even if an ancestor directory is inaccessible, which is better in many cases. So in this case try again with a buffer that's almost always big enough. */ if (errno == EINVAL && buf == NULL && size == 0) { char big_buffer[BIG_FILE_NAME_LENGTH + 1]; dir = getcwd_system (big_buffer, sizeof big_buffer); if (dir) return strdup (dir); } # if HAVE_PARTLY_WORKING_GETCWD /* The system getcwd works, except it sometimes fails when it shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. */ if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT) return NULL; # endif #endif if (size == 0) { if (buf != NULL) { __set_errno (EINVAL); return NULL; } allocated = BIG_FILE_NAME_LENGTH + 1; } if (buf == NULL) { dir = malloc (allocated); if (dir == NULL) return NULL; } else dir = buf; dirp = dir + allocated; *--dirp = '\0'; if (__lstat64_time64 (".", &st) < 0) goto lose; thisdev = st.st_dev; thisino = st.st_ino; if (__lstat64_time64 ("/", &st) < 0) goto lose; rootdev = st.st_dev; rootino = st.st_ino; while (!(thisdev == rootdev && thisino == rootino)) { struct dirent64 *d; dev_t dotdev; ino_t dotino; bool mount_point; int parent_status; size_t dirroom; size_t namlen; bool use_d_ino = true; /* Look at the parent directory. */ #if HAVE_OPENAT_SUPPORT fd = __openat64 (fd, "..", O_RDONLY); if (fd < 0) goto lose; fd_needs_closing = true; parent_status = __fstat64_time64 (fd, &st); #else dotlist[dotlen++] = '.'; dotlist[dotlen++] = '.'; dotlist[dotlen] = '\0'; parent_status = __lstat64_time64 (dotlist, &st); #endif if (parent_status != 0) goto lose; if (dirstream && __closedir (dirstream) != 0) { dirstream = NULL; goto lose; } /* Figure out if this directory is a mount point. */ dotdev = st.st_dev; dotino = st.st_ino; mount_point = dotdev != thisdev; /* Search for the last directory. */ #if HAVE_OPENAT_SUPPORT dirstream = __fdopendir (fd); if (dirstream == NULL) goto lose; fd_needs_closing = false; #else dirstream = __opendir (dotlist); if (dirstream == NULL) goto lose; dotlist[dotlen++] = '/'; #endif for (;;) { /* Clear errno to distinguish EOF from error if readdir returns NULL. */ __set_errno (0); d = __readdir64 (dirstream); /* When we've iterated through all directory entries without finding one with a matching d_ino, rewind the stream and consider each name again, but this time, using lstat. This is necessary in a chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where .., ../.., ../../.., etc. all had the same device number, yet the d_ino values for entries in / did not match those obtained via lstat. */ if (d == NULL && errno == 0 && use_d_ino) { use_d_ino = false; __rewinddir (dirstream); d = __readdir64 (dirstream); } if (d == NULL) { if (errno == 0) /* EOF on dirstream, which can mean e.g., that the current directory has been removed. */ __set_errno (ENOENT); goto lose; } if (d->d_name[0] == '.' && (d->d_name[1] == '\0' || (d->d_name[1] == '.' && d->d_name[2] == '\0'))) continue; if (use_d_ino) { bool match = (MATCHING_INO (d, thisino) || mount_point); if (! match) continue; } { int entry_status; #if HAVE_OPENAT_SUPPORT entry_status = __fstatat64_time64 (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW); #else /* Compute size needed for this file name, or for the file name ".." in the same directory, whichever is larger. Room for ".." might be needed the next time through the outer loop. */ size_t name_alloc = _D_ALLOC_NAMLEN (d); size_t filesize = dotlen + MAX (sizeof "..", name_alloc); if (filesize < dotlen) goto memory_exhausted; if (dotsize < filesize) { /* My, what a deep directory tree you have, Grandma. */ size_t newsize = MAX (filesize, dotsize * 2); size_t i; if (newsize < dotsize) goto memory_exhausted; if (dotlist != dots) free (dotlist); dotlist = malloc (newsize); if (dotlist == NULL) goto lose; dotsize = newsize; i = 0; do { dotlist[i++] = '.'; dotlist[i++] = '.'; dotlist[i++] = '/'; } while (i < dotlen); } memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d)); entry_status = __lstat64_time64 (dotlist, &st); #endif /* We don't fail here if we cannot stat() a directory entry. This can happen when (network) file systems fail. If this entry is in fact the one we are looking for we will find out soon as we reach the end of the directory without having found anything. */ if (entry_status == 0 && S_ISDIR (st.st_mode) && st.st_dev == thisdev && st.st_ino == thisino) break; } } dirroom = dirp - dir; namlen = _D_EXACT_NAMLEN (d); if (dirroom <= namlen) { if (size != 0) { __set_errno (ERANGE); goto lose; } else { char *tmp; size_t oldsize = allocated; allocated += MAX (allocated, namlen); if (allocated < oldsize || ! (tmp = realloc (dir, allocated))) goto memory_exhausted; /* Move current contents up to the end of the buffer. This is guaranteed to be non-overlapping. */ dirp = memcpy (tmp + allocated - (oldsize - dirroom), tmp + dirroom, oldsize - dirroom); dir = tmp; } } dirp -= namlen; memcpy (dirp, d->d_name, namlen); *--dirp = '/'; thisdev = dotdev; thisino = dotino; } if (dirstream && __closedir (dirstream) != 0) { dirstream = NULL; goto lose; } if (dirp == &dir[allocated - 1]) *--dirp = '/'; #if ! HAVE_OPENAT_SUPPORT if (dotlist != dots) free (dotlist); #endif used = dir + allocated - dirp; memmove (dir, dirp, used); if (size == 0) /* Ensure that the buffer is only as large as necessary. */ buf = (used < allocated ? realloc (dir, used) : dir); if (buf == NULL) /* Either buf was NULL all along, or 'realloc' failed but we still have the original string. */ buf = dir; return buf; memory_exhausted: __set_errno (ENOMEM); lose: { int save = errno; if (dirstream) __closedir (dirstream); #if HAVE_OPENAT_SUPPORT if (fd_needs_closing) __close_nocancel_nostatus (fd); #else if (dotlist != dots) free (dotlist); #endif if (buf == NULL) free (dir); __set_errno (save); } return NULL; }
null
null
195,716
204737856749159993041789176797064964819
333
getcwd: Set errno to ERANGE for size == 1 (CVE-2021-3999) No valid path returned by getcwd would fit into 1 byte, so reject the size early and return NULL with errno set to ERANGE. This change is prompted by CVE-2021-3999, which describes a single byte buffer underflow and overflow when all of the following conditions are met: - The buffer size (i.e. the second argument of getcwd) is 1 byte - The current working directory is too long - '/' is also mounted on the current working directory Sequence of events: - In sysdeps/unix/sysv/linux/getcwd.c, the syscall returns ENAMETOOLONG because the linux kernel checks for name length before it checks buffer size - The code falls back to the generic getcwd in sysdeps/posix - In the generic func, the buf[0] is set to '\0' on line 250 - this while loop on line 262 is bypassed: while (!(thisdev == rootdev && thisino == rootino)) since the rootfs (/) is bind mounted onto the directory and the flow goes on to line 449, where it puts a '/' in the byte before the buffer. - Finally on line 458, it moves 2 bytes (the underflowed byte and the '\0') to the buf[0] and buf[1], resulting in a 1 byte buffer overflow. - buf is returned on line 469 and errno is not set. This resolves BZ #28769. Reviewed-by: Andreas Schwab <[email protected]> Reviewed-by: Adhemerval Zanella <[email protected]> Signed-off-by: Qualys Security Advisory <[email protected]> Signed-off-by: Siddhesh Poyarekar <[email protected]>
other
mvfst
a67083ff4b8dcbb7ee2839da6338032030d712b0
1
void updateHandshakeState(QuicServerConnectionState& conn) { // Zero RTT read cipher is available after chlo is processed with the // condition that early data attempt is accepted. auto handshakeLayer = conn.serverHandshakeLayer; auto zeroRttReadCipher = handshakeLayer->getZeroRttReadCipher(); auto zeroRttHeaderCipher = handshakeLayer->getZeroRttReadHeaderCipher(); // One RTT write cipher is available at Fizz layer after chlo is processed. // However, the cipher is only exported to QUIC if early data attempt is // accepted. Otherwise, the cipher will be available after cfin is // processed. auto oneRttWriteCipher = handshakeLayer->getOneRttWriteCipher(); // One RTT read cipher is available after cfin is processed. auto oneRttReadCipher = handshakeLayer->getOneRttReadCipher(); auto oneRttWriteHeaderCipher = handshakeLayer->getOneRttWriteHeaderCipher(); auto oneRttReadHeaderCipher = handshakeLayer->getOneRttReadHeaderCipher(); if (zeroRttReadCipher) { if (conn.qLogger) { conn.qLogger->addTransportStateUpdate(kDerivedZeroRttReadCipher); } QUIC_TRACE(fst_trace, conn, "derived 0-rtt read cipher"); conn.readCodec->setZeroRttReadCipher(std::move(zeroRttReadCipher)); } if (zeroRttHeaderCipher) { conn.readCodec->setZeroRttHeaderCipher(std::move(zeroRttHeaderCipher)); } if (oneRttWriteHeaderCipher) { conn.oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher); } if (oneRttReadHeaderCipher) { conn.readCodec->setOneRttHeaderCipher(std::move(oneRttReadHeaderCipher)); } if (oneRttWriteCipher) { if (conn.qLogger) { conn.qLogger->addTransportStateUpdate(kDerivedOneRttWriteCipher); } QUIC_TRACE(fst_trace, conn, "derived 1-rtt write cipher"); CHECK(!conn.oneRttWriteCipher.get()); conn.oneRttWriteCipher = std::move(oneRttWriteCipher); updatePacingOnKeyEstablished(conn); // We negotiate the transport parameters whenever we have the 1-RTT write // keys available. auto clientParams = handshakeLayer->getClientTransportParams(); if (!clientParams) { throw QuicTransportException( "No client transport params", TransportErrorCode::TRANSPORT_PARAMETER_ERROR); } processClientInitialParams(conn, std::move(*clientParams)); } if (oneRttReadCipher) { if (conn.qLogger) { conn.qLogger->addTransportStateUpdate(kDerivedOneRttReadCipher); } QUIC_TRACE(fst_trace, conn, "derived 1-rtt read cipher"); // Clear limit because CFIN is received at this point conn.writableBytesLimit = folly::none; conn.readCodec->setOneRttReadCipher(std::move(oneRttReadCipher)); } auto handshakeReadCipher = handshakeLayer->getHandshakeReadCipher(); auto handshakeReadHeaderCipher = handshakeLayer->getHandshakeReadHeaderCipher(); if (handshakeReadCipher) { CHECK(handshakeReadHeaderCipher); conn.readCodec->setHandshakeReadCipher(std::move(handshakeReadCipher)); conn.readCodec->setHandshakeHeaderCipher( std::move(handshakeReadHeaderCipher)); } if (handshakeLayer->isHandshakeDone()) { CHECK(conn.oneRttWriteCipher); if (conn.version != QuicVersion::MVFST_D24 && !conn.sentHandshakeDone) { sendSimpleFrame(conn, HandshakeDoneFrame()); conn.sentHandshakeDone = true; } } }
null
null
195,720
181509801354210897629105034468408496700
80
Close connection if we derive an extra 1-rtt write cipher Summary: Fixes CVE-2021-24029 Reviewed By: mjoras, lnicco Differential Revision: D26613890 fbshipit-source-id: 19bb2be2c731808144e1a074ece313fba11f1945
other
tensorflow
02cc160e29d20631de3859c6653184e3f876b9d7
1
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in // the step container, and return it as the output. const Tensor* indices; OP_REQUIRES_OK(ctx, ctx->input("indices", &indices)); const Tensor* values; OP_REQUIRES_OK(ctx, ctx->input("values", &values)); const Tensor* dense_shape; OP_REQUIRES_OK(ctx, ctx->input("dense_shape", &dense_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()), errors::InvalidArgument( "Input indices should be a matrix but received shape ", indices->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()), errors::InvalidArgument( "Input values should be a vector but received shape ", indices->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()), errors::InvalidArgument( "Input shape should be a vector but received shape ", dense_shape->shape().DebugString())); // We currently ensure that `sparse_tensor` is ordered in the // batch dimension. // TODO(mrry): Investigate ways to avoid this unconditional check // if we can be sure that the sparse tensor was produced in an // appropriate order (e.g. by `tf.parse_example()` or a Dataset // that batches elements into rows of a SparseTensor). int64_t previous_batch_index = -1; for (int64_t i = 0; i < indices->dim_size(0); ++i) { int64_t next_batch_index = indices->matrix<int64>()(i, 0); OP_REQUIRES( ctx, next_batch_index >= previous_batch_index, errors::Unimplemented("The SparseTensor must be ordered in the batch " "dimension; handling arbitrarily ordered input " "is not currently supported.")); previous_batch_index = next_batch_index; } gtl::InlinedVector<int64, 8> std_order(dense_shape->NumElements(), 0); sparse::SparseTensor tensor; OP_REQUIRES_OK( ctx, sparse::SparseTensor::Create( *indices, *values, TensorShape(dense_shape->vec<int64>()), std_order, &tensor)); *output = new Dataset<T>(ctx, std::move(tensor)); }
null
null
195,752
171363723210961322415209119251133937799
47
Prevent nullptr deref in SparseTensorSliceDataset The arguments must determine a valid sparse tensor. This means that when indices are empty then the values must be empty too (and the reverse). Also added test, by modifying existing test with empty sparse tensor to now run with an invalid sparse tensor input. PiperOrigin-RevId: 388562757 Change-Id: Id8b54cd7c2316025b4f9a77292c8fb5344d17609
other
php-src
0c8a2a2cd1056b7dc403eacb5d2c0eec6ce47c6f
1
*/ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry *pce; zval obj; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zval_ptr_dtor(&ent1->data); ZVAL_STR(&ent1->data, new_str); } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } /* Initialize target object */ object_init_ex(&obj, pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; }
null
null
195,801
281179289723329197214540489283702639538
125
Fix for bug #72790 and bug #72799 (cherry picked from commit a14fdb9746262549bbbb96abb87338bacd147e1b) Conflicts: ext/wddx/wddx.c
other
mongo
6518b22420c5bbd92c42caf907671c3a2b140bb6
1
DocumentSource::GetNextResult DocumentSourceUnionWith::doGetNext() { if (!_pipeline) { // We must have already been disposed, so we're finished. return GetNextResult::makeEOF(); } if (_executionState == ExecutionProgress::kIteratingSource) { auto nextInput = pSource->getNext(); if (!nextInput.isEOF()) { return nextInput; } _executionState = ExecutionProgress::kStartingSubPipeline; // All documents from the base collection have been returned, switch to iterating the sub- // pipeline by falling through below. } if (_executionState == ExecutionProgress::kStartingSubPipeline) { auto serializedPipe = _pipeline->serializeToBson(); LOGV2_DEBUG(23869, 1, "$unionWith attaching cursor to pipeline {pipeline}", "pipeline"_attr = serializedPipe); // $$SEARCH_META can be set during runtime earlier in the pipeline, and therefore must be // copied to the subpipeline manually. if (pExpCtx->variables.hasConstantValue(Variables::kSearchMetaId)) { _pipeline->getContext()->variables.setReservedValue( Variables::kSearchMetaId, pExpCtx->variables.getValue(Variables::kSearchMetaId, Document()), true); } try { _pipeline = pExpCtx->mongoProcessInterface->attachCursorSourceToPipeline(_pipeline.release()); _executionState = ExecutionProgress::kIteratingSubPipeline; } catch (const ExceptionFor<ErrorCodes::CommandOnShardedViewNotSupportedOnMongod>& e) { _pipeline = buildPipelineFromViewDefinition( pExpCtx, ExpressionContext::ResolvedNamespace{e->getNamespace(), e->getPipeline()}, serializedPipe); LOGV2_DEBUG(4556300, 3, "$unionWith found view definition. ns: {ns}, pipeline: {pipeline}. New " "$unionWith sub-pipeline: {new_pipe}", "ns"_attr = e->getNamespace(), "pipeline"_attr = Value(e->getPipeline()), "new_pipe"_attr = _pipeline->serializeToBson()); return doGetNext(); } } auto res = _pipeline->getNext(); if (res) return std::move(*res); // Record the plan summary stats after $unionWith operation is done. recordPlanSummaryStats(*_pipeline); _executionState = ExecutionProgress::kFinished; return GetNextResult::makeEOF(); }
null
null
195,804
77189124809087292115725641020447994671
60
SERVER-58203 factor out logging statements into helper functions
other
lsquic
a74702c630e108125e71898398737baec8f02238
1
lsquic_qeh_settings (struct qpack_enc_hdl *qeh, unsigned max_table_size, unsigned dyn_table_size, unsigned max_risked_streams, int server) { enum lsqpack_enc_opts enc_opts; assert(qeh->qeh_flags & QEH_INITIALIZED); if (qeh->qeh_flags & QEH_HAVE_SETTINGS) { LSQ_WARN("settings already set"); return -1; } enc_opts = LSQPACK_ENC_OPT_STAGE_2 | (server ? LSQPACK_ENC_OPT_SERVER : 0); qeh->qeh_tsu_sz = sizeof(qeh->qeh_tsu_buf); if (0 != lsqpack_enc_init(&qeh->qeh_encoder, (void *) qeh->qeh_conn, max_table_size, dyn_table_size, max_risked_streams, enc_opts, qeh->qeh_tsu_buf, &qeh->qeh_tsu_sz)) { LSQ_INFO("could not initialize QPACK encoder"); return -1; } LSQ_DEBUG("%zu-byte post-init TSU", qeh->qeh_tsu_sz); qeh->qeh_flags |= QEH_HAVE_SETTINGS; qeh->qeh_max_prefix_size = lsqpack_enc_header_block_prefix_size(&qeh->qeh_encoder); LSQ_DEBUG("have settings: max table size=%u; dyn table size=%u; max risked " "streams=%u", max_table_size, dyn_table_size, max_risked_streams); if (qeh->qeh_enc_sm_out) qeh_begin_out(qeh); return 0; }
null
null
196,276
288925027585735265622903529553530375426
33
Release 3.1.0
other
minetest
da71e86633d0b27cd02d7aac9fdac625d141ca13
1
static inline int checkSettingSecurity(lua_State* L, const std::string &name) { if (ScriptApiSecurity::isSecure(L) && name.compare(0, 7, "secure.") == 0) throw LuaError("Attempt to set secure setting."); bool is_mainmenu = false; #ifndef SERVER is_mainmenu = ModApiBase::getGuiEngine(L) != nullptr; #endif if (!is_mainmenu && (name == "mg_name" || name == "mg_flags")) { errorstream << "Tried to set global setting " << name << ", ignoring. " "minetest.set_mapgen_setting() should be used instead." << std::endl; infostream << script_get_backtrace(L) << std::endl; return -1; } return 0; }
null
null
196,670
14542184638408056621499358845757545617
18
Protect a few more settings from being set from mods Of those settings main_menu_script has concrete security impact, the rest are added out of abundance of caution.
other
njs
81af26364c21c196dd21fb5e14c7fa9ce7debd17
1
njs_array_convert_to_slow_array(njs_vm_t *vm, njs_array_t *array) { uint32_t i, length; njs_value_t index, value; njs_object_prop_t *prop; njs_set_array(&value, array); array->object.fast_array = 0; length = array->length; for (i = 0; i < length; i++) { if (njs_is_valid(&array->start[i])) { njs_uint32_to_string(&index, i); prop = njs_object_property_add(vm, &value, &index, 0); if (njs_slow_path(prop == NULL)) { return NJS_ERROR; } prop->value = array->start[i]; } } /* GC: release value. */ njs_mp_free(vm->mem_pool, array->start); array->start = NULL; return NJS_OK; }
null
null
196,817
15778839275107817850632511934182345441
30
Fixed Object.defineProperty() when a recursive descriptor is provided. This closes #481 issue on Github.
other
furnace
0eb02422d5161767e9983bdaa5c429762d3477ce
1
inline void FurnaceGUI::patternRow(int i, bool isPlaying, float lineHeight, int chans, int ord, const DivPattern** patCache) { static char id[32]; bool selectedRow=(i>=sel1.y && i<=sel2.y); ImGui::TableNextRow(0,lineHeight); ImGui::TableNextColumn(); float cursorPosY=ImGui::GetCursorPos().y-ImGui::GetScrollY(); // check if the row is visible if (cursorPosY<-lineHeight || cursorPosY>ImGui::GetWindowSize().y) { return; } // check if we are in range if (ord<0 || ord>=e->song.ordersLen) { return; } if (i<0 || i>=e->song.patLen) { return; } bool isPushing=false; ImVec4 activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE]; ImVec4 inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE]; ImVec4 rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX]; if (e->song.hilightB>0 && !(i%e->song.hilightB)) { activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI2]; inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI2]; rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI2]; } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) { activeColor=uiColors[GUI_COLOR_PATTERN_ACTIVE_HI1]; inactiveColor=uiColors[GUI_COLOR_PATTERN_INACTIVE_HI1]; rowIndexColor=uiColors[GUI_COLOR_PATTERN_ROW_INDEX_HI1]; } // check overflow highlight if (settings.overflowHighlight) { if (edit && cursor.y==i) { ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING])); } else if (isPlaying && oldRow==i) { ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD])); } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) { ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2])); } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) { ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1])); } } else { isPushing=true; if (edit && cursor.y==i) { ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_EDITING])); } else if (isPlaying && oldRow==i) { ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_PLAY_HEAD])); } else if (e->song.hilightB>0 && !(i%e->song.hilightB)) { ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_2])); } else if (e->song.hilightA>0 && !(i%e->song.hilightA)) { ImGui::PushStyleColor(ImGuiCol_Header,ImGui::GetColorU32(uiColors[GUI_COLOR_PATTERN_HI_1])); } else { isPushing=false; } } // row number if (settings.patRowsBase==1) { ImGui::TextColored(rowIndexColor," %.2X ",i); } else { ImGui::TextColored(rowIndexColor,"%3d ",i); } // for each column for (int j=0; j<chans; j++) { // check if channel is not hidden if (!e->song.chanShow[j]) { patChanX[j]=ImGui::GetCursorPosX(); continue; } int chanVolMax=e->getMaxVolumeChan(j); if (chanVolMax<1) chanVolMax=1; const DivPattern* pat=patCache[j]; ImGui::TableNextColumn(); patChanX[j]=ImGui::GetCursorPosX(); // selection highlight flags int sel1XSum=sel1.xCoarse*32+sel1.xFine; int sel2XSum=sel2.xCoarse*32+sel2.xFine; int j32=j*32; bool selectedNote=selectedRow && (j32>=sel1XSum && j32<=sel2XSum); bool selectedIns=selectedRow && (j32+1>=sel1XSum && j32+1<=sel2XSum); bool selectedVol=selectedRow && (j32+2>=sel1XSum && j32+2<=sel2XSum); bool cursorNote=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==0); bool cursorIns=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==1); bool cursorVol=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==2); // note sprintf(id,"%s##PN_%d_%d",noteName(pat->data[i][0],pat->data[i][1]),i,j); if (pat->data[i][0]==0 && pat->data[i][1]==0) { ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor); } else { ImGui::PushStyleColor(ImGuiCol_Text,activeColor); } if (cursorNote) { ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]); ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]); ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]); ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,threeChars); demandX=ImGui::GetCursorPosX(); ImGui::PopStyleColor(3); } else { if (selectedNote) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]); ImGui::Selectable(id,isPushing || selectedNote,ImGuiSelectableFlags_NoPadWithHalfSpacing,threeChars); if (selectedNote) ImGui::PopStyleColor(); } if (ImGui::IsItemClicked()) { startSelection(j,0,i); } if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { updateSelection(j,0,i); } ImGui::PopStyleColor(); // the following is only visible when the channel is not collapsed if (!e->song.chanCollapse[j]) { // instrument if (pat->data[i][2]==-1) { ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor); sprintf(id,"..##PI_%d_%d",i,j); } else { if (pat->data[i][2]<0 || pat->data[i][2]>=e->song.insLen) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS_ERROR]); } else { DivInstrumentType t=e->song.ins[pat->data[i][2]]->type; if (t!=DIV_INS_AMIGA && t!=e->getPreferInsType(j)) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS_WARN]); } else { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_INS]); } } sprintf(id,"%.2X##PI_%d_%d",pat->data[i][2],i,j); } ImGui::SameLine(0.0f,0.0f); if (cursorIns) { ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]); ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]); ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]); ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); demandX=ImGui::GetCursorPosX(); ImGui::PopStyleColor(3); } else { if (selectedIns) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]); ImGui::Selectable(id,isPushing || selectedIns,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); if (selectedIns) ImGui::PopStyleColor(); } if (ImGui::IsItemClicked()) { startSelection(j,1,i); } if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { updateSelection(j,1,i); } ImGui::PopStyleColor(); // volume if (pat->data[i][3]==-1) { sprintf(id,"..##PV_%d_%d",i,j); ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor); } else { int volColor=(pat->data[i][3]*127)/chanVolMax; if (volColor>127) volColor=127; if (volColor<0) volColor=0; sprintf(id,"%.2X##PV_%d_%d",pat->data[i][3],i,j); ImGui::PushStyleColor(ImGuiCol_Text,volColors[volColor]); } ImGui::SameLine(0.0f,0.0f); if (cursorVol) { ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]); ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]); ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]); ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); demandX=ImGui::GetCursorPosX(); ImGui::PopStyleColor(3); } else { if (selectedVol) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]); ImGui::Selectable(id,isPushing || selectedVol,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); if (selectedVol) ImGui::PopStyleColor(); } if (ImGui::IsItemClicked()) { startSelection(j,2,i); } if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { updateSelection(j,2,i); } ImGui::PopStyleColor(); // effects for (int k=0; k<e->song.pat[j].effectRows; k++) { int index=4+(k<<1); bool selectedEffect=selectedRow && (j32+index-1>=sel1XSum && j32+index-1<=sel2XSum); bool selectedEffectVal=selectedRow && (j32+index>=sel1XSum && j32+index<=sel2XSum); bool cursorEffect=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==index-1); bool cursorEffectVal=(cursor.y==i && cursor.xCoarse==j && cursor.xFine==index); // effect if (pat->data[i][index]==-1) { sprintf(id,"..##PE%d_%d_%d",k,i,j); ImGui::PushStyleColor(ImGuiCol_Text,inactiveColor); } else { sprintf(id,"%.2X##PE%d_%d_%d",pat->data[i][index],k,i,j); if (pat->data[i][index]<0x10) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[fxColors[pat->data[i][index]]]); } else if (pat->data[i][index]<0x20) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_PRIMARY]); } else if (pat->data[i][index]<0x30) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_SECONDARY]); } else if (pat->data[i][index]<0x48) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SYS_PRIMARY]); } else if (pat->data[i][index]<0x90) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]); } else if (pat->data[i][index]<0xa0) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_MISC]); } else if (pat->data[i][index]<0xc0) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]); } else if (pat->data[i][index]<0xd0) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_SPEED]); } else if (pat->data[i][index]<0xe0) { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[GUI_COLOR_PATTERN_EFFECT_INVALID]); } else { ImGui::PushStyleColor(ImGuiCol_Text,uiColors[extFxColors[pat->data[i][index]-0xe0]]); } } ImGui::SameLine(0.0f,0.0f); if (cursorEffect) { ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]); ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]); ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]); ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); demandX=ImGui::GetCursorPosX(); ImGui::PopStyleColor(3); } else { if (selectedEffect) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]); ImGui::Selectable(id,isPushing || selectedEffect,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); if (selectedEffect) ImGui::PopStyleColor(); } if (ImGui::IsItemClicked()) { startSelection(j,index-1,i); } if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { updateSelection(j,index-1,i); } // effect value if (pat->data[i][index+1]==-1) { sprintf(id,"..##PF%d_%d_%d",k,i,j); } else { sprintf(id,"%.2X##PF%d_%d_%d",pat->data[i][index+1],k,i,j); } ImGui::SameLine(0.0f,0.0f); if (cursorEffectVal) { ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_CURSOR]); ImGui::PushStyleColor(ImGuiCol_HeaderActive,uiColors[GUI_COLOR_PATTERN_CURSOR_ACTIVE]); ImGui::PushStyleColor(ImGuiCol_HeaderHovered,uiColors[GUI_COLOR_PATTERN_CURSOR_HOVER]); ImGui::Selectable(id,true,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); demandX=ImGui::GetCursorPosX(); ImGui::PopStyleColor(3); } else { if (selectedEffectVal) ImGui::PushStyleColor(ImGuiCol_Header,uiColors[GUI_COLOR_PATTERN_SELECTION]); ImGui::Selectable(id,isPushing || selectedEffectVal,ImGuiSelectableFlags_NoPadWithHalfSpacing,twoChars); if (selectedEffectVal) ImGui::PopStyleColor(); } if (ImGui::IsItemClicked()) { startSelection(j,index,i); } if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { updateSelection(j,index,i); } ImGui::PopStyleColor(); } } } if (isPushing) { ImGui::PopStyleColor(); } ImGui::TableNextColumn(); patChanX[chans]=ImGui::GetCursorPosX(); }
null
null
196,841
136686899264564982027774933242322169613
275
fix possible pattern crash issue #325
other
libjxl
7dfa400ded53919d986c5d3d23446a09e0cf481b
1
Status DecodeImageAPNG(Span<const uint8_t> bytes, ThreadPool* pool, CodecInOut* io) { Reader r; unsigned int id, i, j, w, h, w0, h0, x0, y0; unsigned int delay_num, delay_den, dop, bop, rowbytes, imagesize; unsigned char sig[8]; png_structp png_ptr; png_infop info_ptr; CHUNK chunk; CHUNK chunkIHDR; std::vector<CHUNK> chunksInfo; bool isAnimated = false; bool skipFirst = false; bool hasInfo = false; bool all_dispose_bg = true; APNGFrame frameRaw = {}; r = {bytes.data(), bytes.data() + bytes.size()}; // Not an aPNG => not an error unsigned char png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; if (r.Read(sig, 8) || memcmp(sig, png_signature, 8) != 0) { return false; } id = read_chunk(&r, &chunkIHDR); io->frames.clear(); io->dec_pixels = 0; io->metadata.m.SetUintSamples(8); io->metadata.m.SetAlphaBits(8); io->metadata.m.color_encoding = ColorEncoding::SRGB(); // todo: get data from png metadata (void)io->dec_hints.Foreach( [](const std::string& key, const std::string& /*value*/) { JXL_WARNING("APNG decoder ignoring %s hint", key.c_str()); return true; }); bool errorstate = true; if (id == kId_IHDR && chunkIHDR.size == 25) { w0 = w = png_get_uint_32(chunkIHDR.p + 8); h0 = h = png_get_uint_32(chunkIHDR.p + 12); if (w > cMaxPNGSize || h > cMaxPNGSize) { return false; } x0 = 0; y0 = 0; delay_num = 1; delay_den = 10; dop = 0; bop = 0; rowbytes = w * 4; imagesize = h * rowbytes; frameRaw.p = new unsigned char[imagesize]; frameRaw.rows = new png_bytep[h * sizeof(png_bytep)]; for (j = 0; j < h; j++) frameRaw.rows[j] = frameRaw.p + j * rowbytes; if (!processing_start(png_ptr, info_ptr, (void*)&frameRaw, hasInfo, chunkIHDR, chunksInfo)) { bool last_base_was_none = true; while (!r.Eof()) { id = read_chunk(&r, &chunk); if (!id) break; JXL_ASSERT(chunk.p != nullptr); if (id == kId_acTL && !hasInfo && !isAnimated) { isAnimated = true; skipFirst = true; io->metadata.m.have_animation = true; io->metadata.m.animation.tps_numerator = 1000; } else if (id == kId_IEND || (id == kId_fcTL && (!hasInfo || isAnimated))) { if (hasInfo) { if (!processing_finish(png_ptr, info_ptr)) { ImageBundle bundle(&io->metadata.m); bundle.duration = delay_num * 1000 / delay_den; bundle.origin.x0 = x0; bundle.origin.y0 = y0; // TODO(veluca): this could in principle be implemented. if (last_base_was_none && !all_dispose_bg && (x0 != 0 || y0 != 0 || w0 != w || h0 != h || bop != 0)) { return JXL_FAILURE( "APNG with dispose-to-0 is not supported for non-full or " "blended frames"); } switch (dop) { case 0: bundle.use_for_next_frame = true; last_base_was_none = false; all_dispose_bg = false; break; case 2: bundle.use_for_next_frame = false; all_dispose_bg = false; break; default: bundle.use_for_next_frame = false; last_base_was_none = true; } bundle.blend = bop != 0; io->dec_pixels += w0 * h0; Image3F sub_frame(w0, h0); ImageF sub_frame_alpha(w0, h0); for (size_t y = 0; y < h0; ++y) { float* const JXL_RESTRICT row_r = sub_frame.PlaneRow(0, y); float* const JXL_RESTRICT row_g = sub_frame.PlaneRow(1, y); float* const JXL_RESTRICT row_b = sub_frame.PlaneRow(2, y); float* const JXL_RESTRICT row_alpha = sub_frame_alpha.Row(y); uint8_t* const f = frameRaw.rows[y]; for (size_t x = 0; x < w0; ++x) { if (f[4 * x + 3] == 0) { row_alpha[x] = 0; row_r[x] = 0; row_g[x] = 0; row_b[x] = 0; continue; } row_r[x] = f[4 * x + 0] * (1.f / 255); row_g[x] = f[4 * x + 1] * (1.f / 255); row_b[x] = f[4 * x + 2] * (1.f / 255); row_alpha[x] = f[4 * x + 3] * (1.f / 255); } } bundle.SetFromImage(std::move(sub_frame), ColorEncoding::SRGB()); bundle.SetAlpha(std::move(sub_frame_alpha), /*alpha_is_premultiplied=*/false); io->frames.push_back(std::move(bundle)); } else { delete[] chunk.p; break; } } if (id == kId_IEND) { errorstate = false; break; } // At this point the old frame is done. Let's start a new one. w0 = png_get_uint_32(chunk.p + 12); h0 = png_get_uint_32(chunk.p + 16); x0 = png_get_uint_32(chunk.p + 20); y0 = png_get_uint_32(chunk.p + 24); delay_num = png_get_uint_16(chunk.p + 28); delay_den = png_get_uint_16(chunk.p + 30); dop = chunk.p[32]; bop = chunk.p[33]; if (w0 > cMaxPNGSize || h0 > cMaxPNGSize || x0 > cMaxPNGSize || y0 > cMaxPNGSize || x0 + w0 > w || y0 + h0 > h || dop > 2 || bop > 1) { delete[] chunk.p; break; } if (hasInfo) { memcpy(chunkIHDR.p + 8, chunk.p + 12, 8); if (processing_start(png_ptr, info_ptr, (void*)&frameRaw, hasInfo, chunkIHDR, chunksInfo)) { delete[] chunk.p; break; } } else skipFirst = false; if (io->frames.size() == (skipFirst ? 1 : 0)) { bop = 0; if (dop == 2) dop = 1; } } else if (id == kId_IDAT) { hasInfo = true; if (processing_data(png_ptr, info_ptr, chunk.p, chunk.size)) { delete[] chunk.p; break; } } else if (id == kId_fdAT && isAnimated) { png_save_uint_32(chunk.p + 4, chunk.size - 16); memcpy(chunk.p + 8, "IDAT", 4); if (processing_data(png_ptr, info_ptr, chunk.p + 4, chunk.size - 4)) { delete[] chunk.p; break; } } else if (!isAbc(chunk.p[4]) || !isAbc(chunk.p[5]) || !isAbc(chunk.p[6]) || !isAbc(chunk.p[7])) { delete[] chunk.p; break; } else if (!hasInfo) { if (processing_data(png_ptr, info_ptr, chunk.p, chunk.size)) { delete[] chunk.p; break; } chunksInfo.push_back(chunk); continue; } delete[] chunk.p; } } delete[] frameRaw.rows; delete[] frameRaw.p; } for (i = 0; i < chunksInfo.size(); i++) delete[] chunksInfo[i].p; chunksInfo.clear(); delete[] chunkIHDR.p; if (errorstate) return false; SetIntensityTarget(io); return true; }
null
null
196,993
123816616739143632951179511270786230002
212
Fix handling of APNG with 0 delay_den (#313)
other
drogon
3c785326c63a34aa1799a639ae185bc9453cb447
1
int HttpFileImpl::save(const std::string &path) const { assert(!path.empty()); if (fileName_.empty()) return -1; filesystem::path fsPath(utils::toNativePath(path)); if (!fsPath.is_absolute() && (!fsPath.has_parent_path() || (fsPath.begin()->string() != "." && fsPath.begin()->string() != ".."))) { filesystem::path fsUploadPath(utils::toNativePath( HttpAppFrameworkImpl::instance().getUploadPath())); fsPath = fsUploadPath / fsPath; } filesystem::path fsFileName(utils::toNativePath(fileName_)); if (!filesystem::exists(fsPath)) { LOG_TRACE << "create path:" << fsPath; drogon::error_code err; filesystem::create_directories(fsPath, err); if (err) { LOG_SYSERR; return -1; } } return saveTo(fsPath / fsFileName); }
null
null
197,057
300389952786254526295960796960160809202
28
Prevent malformed upload path causing arbitrary write (#1174)
other
tensorflow
bc9c546ce7015c57c2f15c168b3d9201de679a1d
1
void Compute(OpKernelContext* c) override { core::RefCountPtr<Var> v; OP_REQUIRES_OK(c, LookupResource(c, HandleFromInput(c, 0), &v)); OP_REQUIRES_OK(c, EnsureSparseVariableAccess<Device, T>(c, v.get())); // NOTE: We hold the lock for the whole gather operation instead // of increasing the reference count of v->tensor() to avoid a // situation where a write to the same variable will see a // reference count greater than one and make a copy of the // (potentially very large) tensor buffer. tf_shared_lock ml(*v->mu()); const Tensor& params = *v->tensor(); const Tensor& indices = c->input(1); OP_REQUIRES( c, TensorShapeUtils::IsVectorOrHigher(params.shape()), errors::InvalidArgument("params must be at least 1 dimensional")); // Check that we have enough index space const int64_t N = indices.NumElements(); OP_REQUIRES( c, params.dim_size(0) <= std::numeric_limits<Index>::max(), errors::InvalidArgument("params.shape[0] too large for ", DataTypeString(DataTypeToEnum<Index>::v()), " indexing: ", params.dim_size(0), " > ", std::numeric_limits<Index>::max())); // The result shape is params.shape[:batch_dims] + // indices.shape[batch_dims:] + params.shape[batch_dims+1:]. TensorShape result_shape; for (int i = 0; i < batch_dims_; ++i) { result_shape.AddDim(params.dim_size(i)); } for (int i = batch_dims_; i < indices.dims(); ++i) { result_shape.AddDim(indices.dim_size(i)); } for (int i = batch_dims_ + 1; i < params.dims(); ++i) { result_shape.AddDim(params.dim_size(i)); } Tensor* out = nullptr; Tensor tmp; if (params.dtype() == DT_VARIANT) { tmp = Tensor(DT_VARIANT, result_shape); c->set_output(0, tmp); out = &tmp; } else { OP_REQUIRES_OK(c, c->allocate_output(0, result_shape, &out)); } if (N > 0) { Tensor tmp_indices; // Points to the original or updated (if batch_dims is set) indices. const Tensor* op_indices = &indices; if (batch_dims_ > 0) { OP_REQUIRES_OK(c, c->allocate_temp(indices.dtype(), indices.shape(), &tmp_indices)); functor::DenseUpdate<Device, Index, ASSIGN> copy_functor; copy_functor(c->eigen_device<Device>(), tmp_indices.flat<Index>(), indices.flat<Index>()); AddBatchOffsets(&tmp_indices, params); op_indices = &tmp_indices; } int64_t gather_dim_size = 1; for (int idx = 0; idx <= batch_dims_; ++idx) { gather_dim_size *= params.dim_size(idx); } int64_t inner_size = 1; for (int i = batch_dims_ + 1; i < params.dims(); ++i) { inner_size *= params.dim_size(i); } auto params_flat = params.shaped<T, 3>({1, gather_dim_size, inner_size}); const auto indices_flat = op_indices->flat<Index>(); auto out_flat = out->shaped<T, 3>({1, N, out->NumElements() / N}); functor::GatherFunctor<Device, T, Index> functor; int64_t bad_i = functor(c, params_flat, indices_flat, out_flat); OP_REQUIRES( c, bad_i < 0, errors::InvalidArgument( "indices", SliceDebugString(indices.shape(), bad_i), " = ", indices_flat(bad_i), " is not in [0, ", params.dim_size(0), ")")); } }
null
null
197,110
294361236653337986849576392701719119932
86
Prevent heap oob access in `resource_variable_ops.cc` PiperOrigin-RevId: 387936433 Change-Id: I9e71ddaa8dbd51ec6afbf163a6b3b591f193b4f6
other
tinyexr
a685e3332f61cd4e59324bf3f669d36973d64270
1
static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; if ((data_width < 0) || (data_height < 0)) { if (err) { std::stringstream ss; ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if ((data_width > threshold) || (data_height > threshold)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { if (err) { (*err) += "Insufficient data size.\n"; } return TINYEXR_ERROR_INVALID_DATA; } size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } if (tile_coordinates[3] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { if (err) { (*err) += "Insufficient data length.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; exr_image->num_tiles = static_cast<int>(num_tiles); } } else { // scanline format // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown ) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #ifdef _OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (size_t(data_len) > data_size) { invalid_data = true; } else if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example `data_len // < 4` invalid_data = true; } else { // line_no may be negative. int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window[1]); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { line_no -= exr_header->data_window[1]; } if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } } // omp parallel } if (invalid_data) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; }
null
null
197,111
270881477601119047421793150845336761803
277
Make line_no with too large value(2**20) invalid. Fixes #124
other
mongo
07b8851825836911265e909d6842d4586832f9bb
1
DocumentSource::GetNextResult DocumentSourceGroup::initialize() { const size_t numAccumulators = _accumulatedFields.size(); // Barring any pausing, this loop exhausts 'pSource' and populates '_groups'. GetNextResult input = pSource->getNext(); for (; input.isAdvanced(); input = pSource->getNext()) { if (_memoryTracker.shouldSpillWithAttemptToSaveMemory([this]() { return freeMemory(); })) { _sortedFiles.push_back(spill()); } // We release the result document here so that it does not outlive the end of this loop // iteration. Not releasing could lead to an array copy when this group follows an unwind. auto rootDocument = input.releaseDocument(); Value id = computeId(rootDocument); // Look for the _id value in the map. If it's not there, add a new entry with a blank // accumulator. This is done in a somewhat odd way in order to avoid hashing 'id' and // looking it up in '_groups' multiple times. const size_t oldSize = _groups->size(); vector<intrusive_ptr<AccumulatorState>>& group = (*_groups)[id]; const bool inserted = _groups->size() != oldSize; if (inserted) { _memoryTracker.memoryUsageBytes += id.getApproximateSize(); // Initialize and add the accumulators Value expandedId = expandId(id); Document idDoc = expandedId.getType() == BSONType::Object ? expandedId.getDocument() : Document(); group.reserve(numAccumulators); for (auto&& accumulatedField : _accumulatedFields) { auto accum = accumulatedField.makeAccumulator(); Value initializerValue = accumulatedField.expr.initializer->evaluate(idDoc, &pExpCtx->variables); accum->startNewGroup(initializerValue); group.push_back(accum); } } else { for (auto&& groupObj : group) { // subtract old mem usage. New usage added back after processing. _memoryTracker.memoryUsageBytes -= groupObj->memUsageForSorter(); } } /* tickle all the accumulators for the group we found */ dassert(numAccumulators == group.size()); for (size_t i = 0; i < numAccumulators; i++) { group[i]->process( _accumulatedFields[i].expr.argument->evaluate(rootDocument, &pExpCtx->variables), _doingMerge); _memoryTracker.memoryUsageBytes += group[i]->memUsageForSorter(); } if (kDebugBuild && !storageGlobalParams.readOnly) { // In debug mode, spill every time we have a duplicate id to stress merge logic. if (!inserted && // is a dup !pExpCtx->inMongos && // can't spill to disk in mongos !_memoryTracker.allowDiskUse && // don't change behavior when testing external sort _sortedFiles.size() < 20) { // don't open too many FDs _sortedFiles.push_back(spill()); } } } switch (input.getStatus()) { case DocumentSource::GetNextResult::ReturnStatus::kAdvanced: { MONGO_UNREACHABLE; // We consumed all advances above. } case DocumentSource::GetNextResult::ReturnStatus::kPauseExecution: { return input; // Propagate pause. } case DocumentSource::GetNextResult::ReturnStatus::kEOF: { // Do any final steps necessary to prepare to output results. if (!_sortedFiles.empty()) { _spilled = true; if (!_groups->empty()) { _sortedFiles.push_back(spill()); } // We won't be using groups again so free its memory. _groups = pExpCtx->getValueComparator().makeUnorderedValueMap<Accumulators>(); _sorterIterator.reset(Sorter<Value, Value>::Iterator::merge( _sortedFiles, SortOptions(), SorterComparator(pExpCtx->getValueComparator()))); // prepare current to accumulate data _currentAccumulators.reserve(numAccumulators); for (auto&& accumulatedField : _accumulatedFields) { _currentAccumulators.push_back(accumulatedField.makeAccumulator()); } verify(_sorterIterator->more()); // we put data in, we should get something out. _firstPartOfNextGroup = _sorterIterator->next(); } else { // start the group iterator groupsIterator = _groups->begin(); } // This must happen last so that, unless control gets here, we will re-enter // initialization after getting a GetNextResult::ResultState::kPauseExecution. _initialized = true; return input; } } MONGO_UNREACHABLE; }
null
null
197,179
299639630867010953869050856327872645652
110
SERVER-60218-44: SERVER-60218 add initialize helper function for document_source_group (cherry picked from commit 867f52afbb79bc00e35c70f8e0681b7d602f97b2)
other
gpac
dc7de8d3d604426c7a6e628d90cb9fb88e7b4c2c
1
GF_Err BD_DecMFFieldVec(GF_BifsDecoder * codec, GF_BitStream *bs, GF_Node *node, GF_FieldInfo *field, Bool is_mem_com) { GF_Err e; u32 NbBits, nbFields; u32 i; GF_ChildNodeItem *last; u8 qp_local, qp_on, initial_qp; GF_FieldInfo sffield; memset(&sffield, 0, sizeof(GF_FieldInfo)); sffield.fieldIndex = field->fieldIndex; sffield.fieldType = gf_sg_vrml_get_sf_type(field->fieldType); sffield.NDTtype = field->NDTtype; sffield.name = field->name; initial_qp = qp_local = qp_on = 0; //vector description - alloc the MF size before NbBits = gf_bs_read_int(bs, 5); nbFields = gf_bs_read_int(bs, NbBits); if (codec->ActiveQP) { initial_qp = 1; /*this is for QP 14*/ gf_bifs_dec_qp14_set_length(codec, nbFields); } if (field->fieldType != GF_SG_VRML_MFNODE) { e = gf_sg_vrml_mf_alloc(field->far_ptr, field->fieldType, nbFields); if (e) return e; for (i=0; i<nbFields; i++) { e = gf_sg_vrml_mf_get_item(field->far_ptr, field->fieldType, & sffield.far_ptr, i); if (e) return e; e = gf_bifs_dec_sf_field(codec, bs, node, &sffield, GF_FALSE); if (e) return e; } } else { last = NULL; for (i=0; i<nbFields; i++) { GF_Node *new_node = gf_bifs_dec_node(codec, bs, field->NDTtype); if (new_node) { e = gf_node_register(new_node, is_mem_com ? NULL : node); if (e) return e; if (node) { /*special case for QP, register as the current QP*/ if (gf_node_get_tag(new_node) == TAG_MPEG4_QuantizationParameter) { qp_local = ((M_QuantizationParameter *)new_node)->isLocal; /*we have a QP in the same scope, remove previous NB: we assume this is the right behavior, the spec doesn't say whether QP is cumulative or not*/ if (qp_on) gf_bifs_dec_qp_remove(codec, GF_FALSE); e = gf_bifs_dec_qp_set(codec, new_node); if (e) return e; qp_on = 1; if (qp_local) qp_local = 2; if (codec->force_keep_qp) { e = gf_node_list_add_child_last(field->far_ptr, new_node, &last); if (e) return e; } else { gf_node_register(new_node, NULL); gf_node_unregister(new_node, node); } } else { e = gf_node_list_add_child_last(field->far_ptr, new_node, &last); if (e) return e; } } /*proto coding*/ else if (codec->pCurrentProto) { /*TO DO: what happens if this is a QP node on the interface ?*/ e = gf_node_list_add_child_last( (GF_ChildNodeItem **)field->far_ptr, new_node, &last); if (e) return e; } } else { return codec->LastError ? codec->LastError : GF_NON_COMPLIANT_BITSTREAM; } } /*according to the spec, the QP applies to the current node itself, not just children. If IsLocal is TRUE remove the node*/ if (qp_on && qp_local) { if (qp_local == 2) { // qp_local = 1; } else { //ask to get rid of QP and reactivate if we had a QP when entering the node gf_bifs_dec_qp_remove(codec, initial_qp); // qp_local = 0; } } } /*finally delete the QP if any (local or not) as we get out of this node*/ if (qp_on) gf_bifs_dec_qp_remove(codec, GF_TRUE); return GF_OK; }
null
null
197,499
299257728605197431750731122978204720459
96
fixed #2212
other
radare2
fc285cecb8469f0262db0170bf6dd7c01d9b8ed5
1
static RList *oneshotall_buffer(RBin *bin, RBuffer *b) { RList *list = r_list_newf (free); RBinXtrData *meta = get_the_meta (bin, b); r_list_append (list, meta); return list; }
null
null
197,579
140388220319988183510409398909926632593
6
Fix #20354
other
tensorflow
be7a4de6adfbd303ce08be4332554dff70362612
1
void Compute(OpKernelContext* context) override { // Read ragged_splits inputs. OpInputList ragged_nested_splits_in; OP_REQUIRES_OK(context, context->input_list("rt_nested_splits", &ragged_nested_splits_in)); const int ragged_nested_splits_len = ragged_nested_splits_in.size(); RaggedTensorVariant batched_ragged_input; // Read ragged_values input. batched_ragged_input.set_values(context->input(ragged_nested_splits_len)); batched_ragged_input.mutable_nested_splits()->reserve( ragged_nested_splits_len); for (int i = 0; i < ragged_nested_splits_len; i++) { batched_ragged_input.append_splits(ragged_nested_splits_in[i]); } if (!batched_input_) { // Encode as a Scalar Variant Tensor. Tensor* encoded_scalar; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}), &encoded_scalar)); encoded_scalar->scalar<Variant>()() = std::move(batched_ragged_input); return; } // Unbatch the Ragged Tensor and encode the components. std::vector<RaggedTensorVariant> unbatched_ragged_input; auto batched_splits_top_vec = batched_ragged_input.splits(0).vec<SPLIT_TYPE>(); int num_components = batched_splits_top_vec.size() - 1; OP_REQUIRES(context, num_components >= 0, errors::Internal("Invalid split argument.")); OP_REQUIRES_OK(context, UnbatchRaggedZerothDim<VALUE_TYPE, SPLIT_TYPE>( batched_ragged_input, &unbatched_ragged_input)); // Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor. Tensor* encoded_vector; int output_size = unbatched_ragged_input.size(); OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({output_size}), &encoded_vector)); auto encoded_vector_t = encoded_vector->vec<Variant>(); for (int i = 0; i < output_size; i++) { encoded_vector_t(i) = unbatched_ragged_input[i]; } }
null
null
197,719
209500931068648342443345704454092620756
45
Ensure non-empty rt_nested_splits in tf.raw_ops.RaggedTensorToVariant PiperOrigin-RevId: 387664237 Change-Id: Ia1700c34b5610873d63561abc86e23b46ead93b3
other
tensorflow
c79ba87153ee343401dbe9d1954d7f79e521eb14
1
Status TransposeShapeFn(InferenceContext* c) { ShapeHandle input = c->input(0); ShapeHandle perm_shape = c->input(1); const Tensor* perm = c->input_tensor(1); DimensionHandle perm_elems = c->NumElements(perm_shape); // If we don't have rank information on the input or value information on // perm we can't return any shape information, otherwise we have enough // information to at least find the rank of the output. if (!c->RankKnown(input) && !c->ValueKnown(perm_elems) && perm == nullptr) { c->set_output(0, c->UnknownShape()); return Status::OK(); } // Find our value of the rank. int64_t rank; if (c->RankKnown(input)) { rank = c->Rank(input); } else if (c->ValueKnown(perm_elems)) { rank = c->Value(perm_elems); } else { rank = perm->NumElements(); } if (!c->RankKnown(input) && rank < 2) { // A permutation array containing a single element is ambiguous. It could // indicate either a scalar or a 1-dimensional array, both of which the // transpose op returns unchanged. c->set_output(0, input); return Status::OK(); } std::vector<DimensionHandle> dims; dims.resize(rank); TF_RETURN_IF_ERROR(c->WithRank(input, rank, &input)); // Ensure that perm is a vector and has rank elements. TF_RETURN_IF_ERROR(c->WithRank(perm_shape, 1, &perm_shape)); TF_RETURN_IF_ERROR(c->WithValue(perm_elems, rank, &perm_elems)); // If we know the rank of the input and the value of perm, we can return // all shape information, otherwise we can only return rank information, // but no information for the dimensions. if (perm != nullptr) { std::vector<int64_t> data; if (perm->dtype() == DT_INT32) { data = AsInt64<int32>(perm, rank); } else { data = AsInt64<int64_t>(perm, rank); } for (int32_t i = 0; i < rank; ++i) { int64_t in_idx = data[i]; if (in_idx >= rank) { return errors::InvalidArgument("perm dim ", in_idx, " is out of range of input rank ", rank); } dims[i] = c->Dim(input, in_idx); } } else { for (int i = 0; i < rank; ++i) { dims[i] = c->UnknownDim(); } } c->set_output(0, c->MakeShape(dims)); return Status::OK(); }
null
null
197,748
34055993943311259251029225987542874775
65
Make Transpose's shape inference function validate that negative `perm` values are within the tensor's rank. PiperOrigin-RevId: 403252853 Change-Id: Ia6b31b45b237312668bb31c2c3b3c7bbce2d2610
other
tensorflow
bb6a0383ed553c286f87ca88c207f6774d5c4a8f
1
TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { switch (params->type) { case kTfLiteFloat32: return GatherNd<float, IndicesT>(params, indices, output); case kTfLiteUInt8: return GatherNd<uint8_t, IndicesT>(params, indices, output); case kTfLiteInt8: return GatherNd<int8_t, IndicesT>(params, indices, output); case kTfLiteInt16: return GatherNd<int16_t, IndicesT>(params, indices, output); case kTfLiteInt32: return GatherNd<int32_t, IndicesT>(params, indices, output); case kTfLiteInt64: return GatherNd<int64_t, IndicesT>(params, indices, output); case kTfLiteString: return GatherNdString<IndicesT>(params, indices, output); default: context->ReportError(context, "Params type '%s' are not supported by gather_nd.", TfLiteTypeGetName(params->type)); return kTfLiteError; } }
null
null
197,760
79501722422646953902317860019376579160
24
Prevent heap OOB read in TFLite's `gather_nd.cc`. Passing negative indices is illegal but there was a missing check so that resulted in OOB accesses. PiperOrigin-RevId: 387208551 Change-Id: I6b7a8a62d3e7c13a16d81619e5bc23ae2cdbc7fd
other
curl
8dfc93e573ca740544a2d79ebb0ed786592c65c3
1
Curl_cookie_add(struct Curl_easy *data, /* * The 'data' pointer here may be NULL at times, and thus * must only be used very carefully for things that can deal * with data being NULL. Such as infof() and similar */ struct CookieInfo *c, bool httpheader, /* TRUE if HTTP header-style line */ bool noexpire, /* if TRUE, skip remove_expired() */ char *lineptr, /* first character of the line */ const char *domain, /* default domain */ const char *path, /* full path used when this cookie is set, used to get default path for the cookie unless set */ bool secure) /* TRUE if connection is over secure origin */ { struct Cookie *clist; struct Cookie *co; struct Cookie *lastc = NULL; struct Cookie *replace_co = NULL; struct Cookie *replace_clist = NULL; time_t now = time(NULL); bool replace_old = FALSE; bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */ size_t myhash; #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; #endif DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */ if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT) return NULL; /* First, alloc and init a new struct for it */ co = calloc(1, sizeof(struct Cookie)); if(!co) return NULL; /* bail out if we're this low on memory */ if(httpheader) { /* This line was read off a HTTP-header */ char name[MAX_NAME]; char what[MAX_NAME]; const char *ptr; const char *semiptr; size_t linelength = strlen(lineptr); if(linelength > MAX_COOKIE_LINE) { /* discard overly long lines at once */ free(co); return NULL; } semiptr = strchr(lineptr, ';'); /* first, find a semicolon */ while(*lineptr && ISBLANK(*lineptr)) lineptr++; ptr = lineptr; do { /* we have a <what>=<this> pair or a stand-alone word here */ name[0] = what[0] = 0; /* init the buffers */ if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%" MAX_NAME_TXT "[^;\r\n]", name, what)) { /* * Use strstore() below to properly deal with received cookie * headers that have the same string property set more than once, * and then we use the last one. */ const char *whatptr; bool done = FALSE; bool sep; size_t len = strlen(what); size_t nlen = strlen(name); const char *endofn = &ptr[ nlen ]; /* * Check for too long individual name or contents, or too long * combination of name + contents. Chrome and Firefox support 4095 or * 4096 bytes combo */ if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) || ((nlen + len) > MAX_NAME)) { freecookie(co); infof(data, "oversized cookie dropped, name/val %zu + %zu bytes", nlen, len); return NULL; } /* name ends with a '=' ? */ sep = (*endofn == '=')?TRUE:FALSE; if(nlen) { endofn--; /* move to the last character */ if(ISBLANK(*endofn)) { /* skip trailing spaces in name */ while(*endofn && ISBLANK(*endofn) && nlen) { endofn--; nlen--; } name[nlen] = 0; /* new end of name */ } } /* Strip off trailing whitespace from the 'what' */ while(len && ISBLANK(what[len-1])) { what[len-1] = 0; len--; } /* Skip leading whitespace from the 'what' */ whatptr = what; while(*whatptr && ISBLANK(*whatptr)) whatptr++; /* * Check if we have a reserved prefix set before anything else, as we * otherwise have to test for the prefix in both the cookie name and * "the rest". Prefixes must start with '__' and end with a '-', so * only test for names where that can possibly be true. */ if(nlen > 3 && name[0] == '_' && name[1] == '_') { if(!strncmp("__Secure-", name, 9)) co->prefix |= COOKIE_PREFIX__SECURE; else if(!strncmp("__Host-", name, 7)) co->prefix |= COOKIE_PREFIX__HOST; } if(!co->name) { /* The very first name/value pair is the actual cookie name */ if(!sep) { /* Bad name/value pair. */ badcookie = TRUE; break; } co->name = strdup(name); co->value = strdup(whatptr); done = TRUE; if(!co->name || !co->value) { badcookie = TRUE; break; } } else if(!len) { /* * this was a "<name>=" with no content, and we must allow * 'secure' and 'httponly' specified this weirdly */ done = TRUE; /* * secure cookies are only allowed to be set when the connection is * using a secure protocol, or when the cookie is being set by * reading from file */ if(strcasecompare("secure", name)) { if(secure || !c->running) { co->secure = TRUE; } else { badcookie = TRUE; break; } } else if(strcasecompare("httponly", name)) co->httponly = TRUE; else if(sep) /* there was a '=' so we're not done parsing this field */ done = FALSE; } if(done) ; else if(strcasecompare("path", name)) { strstore(&co->path, whatptr); if(!co->path) { badcookie = TRUE; /* out of memory bad */ break; } free(co->spath); /* if this is set again */ co->spath = sanitize_cookie_path(co->path); if(!co->spath) { badcookie = TRUE; /* out of memory bad */ break; } } else if(strcasecompare("domain", name) && whatptr[0]) { bool is_ip; /* * Now, we make sure that our host is within the given domain, or * the given domain is not valid and thus cannot be set. */ if('.' == whatptr[0]) whatptr++; /* ignore preceding dot */ #ifndef USE_LIBPSL /* * Without PSL we don't know when the incoming cookie is set on a * TLD or otherwise "protected" suffix. To reduce risk, we require a * dot OR the exact host name being "localhost". */ if(bad_domain(whatptr)) domain = ":"; #endif is_ip = Curl_host_is_ipnum(domain ? domain : whatptr); if(!domain || (is_ip && !strcmp(whatptr, domain)) || (!is_ip && tailmatch(whatptr, domain))) { strstore(&co->domain, whatptr); if(!co->domain) { badcookie = TRUE; break; } if(!is_ip) co->tailmatch = TRUE; /* we always do that if the domain name was given */ } else { /* * We did not get a tailmatch and then the attempted set domain is * not a domain to which the current host belongs. Mark as bad. */ badcookie = TRUE; infof(data, "skipped cookie with bad tailmatch domain: %s", whatptr); } } else if(strcasecompare("version", name)) { strstore(&co->version, whatptr); if(!co->version) { badcookie = TRUE; break; } } else if(strcasecompare("max-age", name)) { /* * Defined in RFC2109: * * Optional. The Max-Age attribute defines the lifetime of the * cookie, in seconds. The delta-seconds value is a decimal non- * negative integer. After delta-seconds seconds elapse, the * client should discard the cookie. A value of zero means the * cookie should be discarded immediately. */ strstore(&co->maxage, whatptr); if(!co->maxage) { badcookie = TRUE; break; } } else if(strcasecompare("expires", name)) { strstore(&co->expirestr, whatptr); if(!co->expirestr) { badcookie = TRUE; break; } } /* * Else, this is the second (or more) name we don't know about! */ } else { /* this is an "illegal" <what>=<this> pair */ } if(!semiptr || !*semiptr) { /* we already know there are no more cookies */ semiptr = NULL; continue; } ptr = semiptr + 1; while(*ptr && ISBLANK(*ptr)) ptr++; semiptr = strchr(ptr, ';'); /* now, find the next semicolon */ if(!semiptr && *ptr) /* * There are no more semicolons, but there's a final name=value pair * coming up */ semiptr = strchr(ptr, '\0'); } while(semiptr); if(co->maxage) { CURLofft offt; offt = curlx_strtoofft((*co->maxage == '\"')? &co->maxage[1]:&co->maxage[0], NULL, 10, &co->expires); if(offt == CURL_OFFT_FLOW) /* overflow, used max value */ co->expires = CURL_OFF_T_MAX; else if(!offt) { if(!co->expires) /* already expired */ co->expires = 1; else if(CURL_OFF_T_MAX - now < co->expires) /* would overflow */ co->expires = CURL_OFF_T_MAX; else co->expires += now; } } else if(co->expirestr) { /* * Note that if the date couldn't get parsed for whatever reason, the * cookie will be treated as a session cookie */ co->expires = Curl_getdate_capped(co->expirestr); /* * Session cookies have expires set to 0 so if we get that back from the * date parser let's add a second to make it a non-session cookie */ if(co->expires == 0) co->expires = 1; else if(co->expires < 0) co->expires = 0; } if(!badcookie && !co->domain) { if(domain) { /* no domain was given in the header line, set the default */ co->domain = strdup(domain); if(!co->domain) badcookie = TRUE; } } if(!badcookie && !co->path && path) { /* * No path was given in the header line, set the default. Note that the * passed-in path to this function MAY have a '?' and following part that * MUST NOT be stored as part of the path. */ char *queryp = strchr(path, '?'); /* * queryp is where the interesting part of the path ends, so now we * want to the find the last */ char *endslash; if(!queryp) endslash = strrchr(path, '/'); else endslash = memrchr(path, '/', (queryp - path)); if(endslash) { size_t pathlen = (endslash-path + 1); /* include end slash */ co->path = malloc(pathlen + 1); /* one extra for the zero byte */ if(co->path) { memcpy(co->path, path, pathlen); co->path[pathlen] = 0; /* null-terminate */ co->spath = sanitize_cookie_path(co->path); if(!co->spath) badcookie = TRUE; /* out of memory bad */ } else badcookie = TRUE; } } /* * If we didn't get a cookie name, or a bad one, the this is an illegal * line so bail out. */ if(badcookie || !co->name) { freecookie(co); return NULL; } data->req.setcookies++; } else { /* * This line is NOT a HTTP header style line, we do offer support for * reading the odd netscape cookies-file format here */ char *ptr; char *firstptr; char *tok_buf = NULL; int fields; /* * IE introduced HTTP-only cookies to prevent XSS attacks. Cookies marked * with httpOnly after the domain name are not accessible from javascripts, * but since curl does not operate at javascript level, we include them * anyway. In Firefox's cookie files, these lines are preceded with * #HttpOnly_ and then everything is as usual, so we skip 10 characters of * the line.. */ if(strncmp(lineptr, "#HttpOnly_", 10) == 0) { lineptr += 10; co->httponly = TRUE; } if(lineptr[0]=='#') { /* don't even try the comments */ free(co); return NULL; } /* strip off the possible end-of-line characters */ ptr = strchr(lineptr, '\r'); if(ptr) *ptr = 0; /* clear it */ ptr = strchr(lineptr, '\n'); if(ptr) *ptr = 0; /* clear it */ firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */ /* * Now loop through the fields and init the struct we already have * allocated */ for(ptr = firstptr, fields = 0; ptr && !badcookie; ptr = strtok_r(NULL, "\t", &tok_buf), fields++) { switch(fields) { case 0: if(ptr[0]=='.') /* skip preceding dots */ ptr++; co->domain = strdup(ptr); if(!co->domain) badcookie = TRUE; break; case 1: /* * flag: A TRUE/FALSE value indicating if all machines within a given * domain can access the variable. Set TRUE when the cookie says * .domain.com and to false when the domain is complete www.domain.com */ co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE; break; case 2: /* The file format allows the path field to remain not filled in */ if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) { /* only if the path doesn't look like a boolean option! */ co->path = strdup(ptr); if(!co->path) badcookie = TRUE; else { co->spath = sanitize_cookie_path(co->path); if(!co->spath) { badcookie = TRUE; /* out of memory bad */ } } break; } /* this doesn't look like a path, make one up! */ co->path = strdup("/"); if(!co->path) badcookie = TRUE; co->spath = strdup("/"); if(!co->spath) badcookie = TRUE; fields++; /* add a field and fall down to secure */ /* FALLTHROUGH */ case 3: co->secure = FALSE; if(strcasecompare(ptr, "TRUE")) { if(secure || c->running) co->secure = TRUE; else badcookie = TRUE; } break; case 4: if(curlx_strtoofft(ptr, NULL, 10, &co->expires)) badcookie = TRUE; break; case 5: co->name = strdup(ptr); if(!co->name) badcookie = TRUE; else { /* For Netscape file format cookies we check prefix on the name */ if(strncasecompare("__Secure-", co->name, 9)) co->prefix |= COOKIE_PREFIX__SECURE; else if(strncasecompare("__Host-", co->name, 7)) co->prefix |= COOKIE_PREFIX__HOST; } break; case 6: co->value = strdup(ptr); if(!co->value) badcookie = TRUE; break; } } if(6 == fields) { /* we got a cookie with blank contents, fix it */ co->value = strdup(""); if(!co->value) badcookie = TRUE; else fields++; } if(!badcookie && (7 != fields)) /* we did not find the sufficient number of fields */ badcookie = TRUE; if(badcookie) { freecookie(co); return NULL; } } if(co->prefix & COOKIE_PREFIX__SECURE) { /* The __Secure- prefix only requires that the cookie be set secure */ if(!co->secure) { freecookie(co); return NULL; } } if(co->prefix & COOKIE_PREFIX__HOST) { /* * The __Host- prefix requires the cookie to be secure, have a "/" path * and not have a domain set. */ if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch) ; else { freecookie(co); return NULL; } } if(!c->running && /* read from a file */ c->newsession && /* clean session cookies */ !co->expires) { /* this is a session cookie since it doesn't expire! */ freecookie(co); return NULL; } co->livecookie = c->running; co->creationtime = ++c->lastct; /* * Now we have parsed the incoming line, we must now check if this supersedes * an already existing cookie, which it may if the previous have the same * domain and path as this. */ /* at first, remove expired cookies */ if(!noexpire) remove_expired(c); #ifdef USE_LIBPSL /* * Check if the domain is a Public Suffix and if yes, ignore the cookie. We * must also check that the data handle isn't NULL since the psl code will * dereference it. */ if(data && (domain && co->domain && !Curl_host_is_ipnum(co->domain))) { const psl_ctx_t *psl = Curl_psl_use(data); int acceptable; if(psl) { acceptable = psl_is_cookie_domain_acceptable(psl, domain, co->domain); Curl_psl_release(data); } else acceptable = !bad_domain(domain); if(!acceptable) { infof(data, "cookie '%s' dropped, domain '%s' must not " "set cookies for '%s'", co->name, domain, co->domain); freecookie(co); return NULL; } } #endif /* A non-secure cookie may not overlay an existing secure cookie. */ myhash = cookiehash(co->domain); clist = c->cookies[myhash]; while(clist) { if(strcasecompare(clist->name, co->name)) { /* the names are identical */ bool matching_domains = FALSE; if(clist->domain && co->domain) { if(strcasecompare(clist->domain, co->domain)) /* The domains are identical */ matching_domains = TRUE; } else if(!clist->domain && !co->domain) matching_domains = TRUE; if(matching_domains && /* the domains were identical */ clist->spath && co->spath && /* both have paths */ clist->secure && !co->secure && !secure) { size_t cllen; const char *sep; /* * A non-secure cookie may not overlay an existing secure cookie. * For an existing cookie "a" with path "/login", refuse a new * cookie "a" with for example path "/login/en", while the path * "/loginhelper" is ok. */ sep = strchr(clist->spath + 1, '/'); if(sep) cllen = sep - clist->spath; else cllen = strlen(clist->spath); if(strncasecompare(clist->spath, co->spath, cllen)) { infof(data, "cookie '%s' for domain '%s' dropped, would " "overlay an existing cookie", co->name, co->domain); freecookie(co); return NULL; } } } if(!replace_co && strcasecompare(clist->name, co->name)) { /* the names are identical */ if(clist->domain && co->domain) { if(strcasecompare(clist->domain, co->domain) && (clist->tailmatch == co->tailmatch)) /* The domains are identical */ replace_old = TRUE; } else if(!clist->domain && !co->domain) replace_old = TRUE; if(replace_old) { /* the domains were identical */ if(clist->spath && co->spath) { if(strcasecompare(clist->spath, co->spath)) replace_old = TRUE; else replace_old = FALSE; } else if(!clist->spath && !co->spath) replace_old = TRUE; else replace_old = FALSE; } if(replace_old && !co->livecookie && clist->livecookie) { /* * Both cookies matched fine, except that the already present cookie is * "live", which means it was set from a header, while the new one was * read from a file and thus isn't "live". "live" cookies are preferred * so the new cookie is freed. */ freecookie(co); return NULL; } if(replace_old) { replace_co = co; replace_clist = clist; } } lastc = clist; clist = clist->next; } if(replace_co) { co = replace_co; clist = replace_clist; co->next = clist->next; /* get the next-pointer first */ /* when replacing, creationtime is kept from old */ co->creationtime = clist->creationtime; /* then free all the old pointers */ free(clist->name); free(clist->value); free(clist->domain); free(clist->path); free(clist->spath); free(clist->expirestr); free(clist->version); free(clist->maxage); *clist = *co; /* then store all the new data */ free(co); /* free the newly allocated memory */ co = clist; } if(c->running) /* Only show this when NOT reading the cookies from a file */ infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, " "expire %" CURL_FORMAT_CURL_OFF_T, replace_old?"Replaced":"Added", co->name, co->value, co->domain, co->path, co->expires); if(!replace_old) { /* then make the last item point on this new one */ if(lastc) lastc->next = co; else c->cookies[myhash] = co; c->numcookies++; /* one more cookie in the jar */ } /* * Now that we've added a new cookie to the jar, update the expiration * tracker in case it is the next one to expire. */ if(co->expires && (co->expires < c->next_expiration)) c->next_expiration = co->expires; return co; }
null
null
197,805
340011739869148140831706810976304098697
717
cookie: reject cookies with "control bytes" Rejects 0x01 - 0x1f (except 0x09) plus 0x7f Reported-by: Axel Chong Bug: https://curl.se/docs/CVE-2022-35252.html CVE-2022-35252 Closes #9381
other
jerryscript
f3a420b672927037beb4508d7bdd68fb25d2caf6
1
lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */ uint32_t ident_opts) /**< lexer_obj_ident_opts_t option bits */ { lexer_skip_spaces (context_p); if (context_p->source_p >= context_p->source_end_p) { parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED); } context_p->token.keyword_type = LEXER_EOS; context_p->token.line = context_p->line; context_p->token.column = context_p->column; bool create_literal_object = false; JERRY_ASSERT ((ident_opts & LEXER_OBJ_IDENT_CLASS_IDENTIFIER) || !(ident_opts & LEXER_OBJ_IDENT_CLASS_NO_STATIC)); #if JERRY_FUNCTION_TO_STRING if (ident_opts & LEXER_OBJ_IDENT_SET_FUNCTION_START) { context_p->function_start_p = context_p->source_p; } #endif /* JERRY_FUNCTION_TO_STRING */ if (lexer_parse_identifier (context_p, LEXER_PARSE_NO_OPTS)) { if (!(ident_opts & (LEXER_OBJ_IDENT_ONLY_IDENTIFIERS | LEXER_OBJ_IDENT_OBJECT_PATTERN))) { lexer_skip_spaces (context_p); context_p->token.flags = (uint8_t) (context_p->token.flags | LEXER_NO_SKIP_SPACES); if (context_p->source_p < context_p->source_end_p #if JERRY_ESNEXT && context_p->source_p[0] != LIT_CHAR_COMMA && context_p->source_p[0] != LIT_CHAR_RIGHT_BRACE && context_p->source_p[0] != LIT_CHAR_LEFT_PAREN && context_p->source_p[0] != LIT_CHAR_SEMICOLON && context_p->source_p[0] != LIT_CHAR_EQUALS #endif /* JERRY_ESNEXT */ && context_p->source_p[0] != LIT_CHAR_COLON) { if (lexer_compare_literal_to_string (context_p, "get", 3)) { context_p->token.type = LEXER_PROPERTY_GETTER; return; } if (lexer_compare_literal_to_string (context_p, "set", 3)) { context_p->token.type = LEXER_PROPERTY_SETTER; return; } #if JERRY_ESNEXT if (lexer_compare_literal_to_string (context_p, "async", 5)) { context_p->token.type = LEXER_KEYW_ASYNC; return; } if (ident_opts & LEXER_OBJ_IDENT_CLASS_NO_STATIC) { if (lexer_compare_literal_to_string (context_p, "static", 6)) { context_p->token.type = LEXER_KEYW_STATIC; } return; } #endif /* JERRY_ESNEXT */ } } create_literal_object = true; } #if JERRY_ESNEXT else if (ident_opts & LEXER_OBJ_IDENT_CLASS_PRIVATE) { parser_raise_error (context_p, PARSER_ERR_INVALID_CHARACTER); } #endif /* JERRY_ESNEXT */ else { switch (context_p->source_p[0]) { case LIT_CHAR_DOUBLE_QUOTE: case LIT_CHAR_SINGLE_QUOTE: { lexer_parse_string (context_p, LEXER_STRING_NO_OPTS); create_literal_object = true; break; } #if JERRY_ESNEXT case LIT_CHAR_LEFT_SQUARE: { #if JERRY_FUNCTION_TO_STRING const uint8_t *function_start_p = context_p->function_start_p; #endif /* JERRY_FUNCTION_TO_STRING */ lexer_consume_next_character (context_p); lexer_next_token (context_p); parser_parse_expression (context_p, PARSE_EXPR_NO_COMMA); if (context_p->token.type != LEXER_RIGHT_SQUARE) { parser_raise_error (context_p, PARSER_ERR_RIGHT_SQUARE_EXPECTED); } #if JERRY_FUNCTION_TO_STRING context_p->function_start_p = function_start_p; #endif /* JERRY_FUNCTION_TO_STRING */ return; } case LIT_CHAR_ASTERISK: { if (ident_opts & (LEXER_OBJ_IDENT_ONLY_IDENTIFIERS | LEXER_OBJ_IDENT_OBJECT_PATTERN)) { break; } context_p->token.type = LEXER_MULTIPLY; lexer_consume_next_character (context_p); return; } case LIT_CHAR_HASHMARK: { if (ident_opts & LEXER_OBJ_IDENT_CLASS_IDENTIFIER) { context_p->token.type = LEXER_HASHMARK; return; } break; } #endif /* JERRY_ESNEXT */ case LIT_CHAR_LEFT_BRACE: { if (ident_opts & (LEXER_OBJ_IDENT_CLASS_NO_STATIC | LEXER_OBJ_IDENT_CLASS_PRIVATE)) { break; } context_p->token.type = LEXER_LEFT_BRACE; lexer_consume_next_character (context_p); return; } case LIT_CHAR_RIGHT_BRACE: { if (ident_opts & LEXER_OBJ_IDENT_ONLY_IDENTIFIERS) { break; } context_p->token.type = LEXER_RIGHT_BRACE; lexer_consume_next_character (context_p); return; } #if JERRY_ESNEXT case LIT_CHAR_DOT: { if (!(context_p->source_p + 1 >= context_p->source_end_p || lit_char_is_decimal_digit (context_p->source_p[1]))) { if ((ident_opts & ((uint32_t) ~(LEXER_OBJ_IDENT_OBJECT_PATTERN | LEXER_OBJ_IDENT_SET_FUNCTION_START))) || context_p->source_p + 2 >= context_p->source_end_p || context_p->source_p[1] != LIT_CHAR_DOT || context_p->source_p[2] != LIT_CHAR_DOT) { break; } context_p->token.type = LEXER_THREE_DOTS; context_p->token.flags &= (uint8_t) ~LEXER_NO_SKIP_SPACES; PARSER_PLUS_EQUAL_LC (context_p->column, 3); context_p->source_p += 3; return; } /* FALLTHRU */ } #endif /* JERRY_ESNEXT */ default: { const uint8_t *char_p = context_p->source_p; if (char_p[0] == LIT_CHAR_DOT) { char_p++; } if (char_p < context_p->source_end_p && char_p[0] >= LIT_CHAR_0 && char_p[0] <= LIT_CHAR_9) { lexer_parse_number (context_p); if (!(ident_opts & LEXER_OBJ_IDENT_CLASS_IDENTIFIER)) { lexer_construct_number_object (context_p, false, false); } return; } break; } } } if (create_literal_object) { #if JERRY_ESNEXT if (ident_opts & LEXER_OBJ_IDENT_CLASS_IDENTIFIER) { return; } if (ident_opts & LEXER_OBJ_IDENT_CLASS_PRIVATE) { parser_resolve_private_identifier (context_p); return; } #endif /* JERRY_ESNEXT */ lexer_construct_literal_object (context_p, &context_p->token.lit_location, LEXER_STRING_LITERAL); return; } parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED); } /* lexer_expect_object_literal_id */
null
null
197,825
18090551596235490242321914030640150439
221
Fix class static block opening brace parsing (#4942) The next character should not be consumed after finding the static block opening brace. This patch fixes #4916. JerryScript-DCO-1.0-Signed-off-by: Martin Negyokru [email protected]
other
tensorflow
7731e8dfbe4a56773be5dc94d631611211156659
1
bool IsConstantFoldable( const Node* n, const std::unordered_map<string, std::vector<PartialTensorShape>>* shape_map, const std::function<bool(const Node*)>& consider, int64_t max_constant_size_in_bytes, std::unordered_map<const Node*, std::vector<Tensor>>* shape_replacement_map) { if (n->IsConstant()) { return true; } if (MaybeReplaceShapeOp(n, shape_map, shape_replacement_map)) { return true; } if (n->op_def().is_stateful()) { return false; } if (consider && !consider(n)) { return false; } if (shape_map != nullptr) { // We can skip the node if an output is known to be oversized. auto shape_it = shape_map->find(n->name()); if (shape_it != shape_map->end()) { for (int64_t i = 0; i < shape_it->second.size(); ++i) { const auto& out_shape = shape_it->second[i]; if (out_shape.IsFullyDefined() && out_shape.num_elements() * DataTypeSize(n->output_type(i)) > max_constant_size_in_bytes) { return false; } } } } if (n->IsControlFlow() || n->IsSend() || n->IsRecv()) { return false; } // TODO(yuanbyu): For now disable these session handle operations. if (n->IsGetSessionHandle() || n->IsGetSessionTensor() || n->IsDeleteSessionTensor()) { return false; } if (n->IsSource()) { return false; } if (n->IsSink()) { return false; } if (n->IsFakeParam()) { return false; } // Since constant-folding runs on the CPU, do not attempt to constant-fold // operators that have no CPU kernel. Also implies that we will not // constant-fold functions. // TODO(phawkins): allow constant-folding for functions; functions may // be arbitrarily expensive to execute. if (!KernelDefAvailable(DeviceType(DEVICE_CPU), n->def())) { return false; } // Do not constant fold nodes which will be allocated by ScopedAllocator. // This is because the constant-folding graph will not contain the // `_ScopedAllocator` node, and that is necessary to be able to run a node // that will use this allocator. if (n->attrs().Find(kScopedAllocatorAttrName) != nullptr) { VLOG(2) << "Skip node [" << n->DebugString() << "] for constant folding due to scoped allocator"; return false; } return true; }
null
null
197,826
172373573712419656450812250984956481158
70
Don't constant-fold DT_RESOURCE constants. PiperOrigin-RevId: 391803952 Change-Id: I0ea3ec31d3e7dfda0f03b4027a237f08d00a3091
other
samba
d92dfb0dabf9cfccb86f2b1146d6c353af2e1435
1
static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call) { struct ldap_SearchRequest *req = &call->request->r.SearchRequest; struct ldap_Result *done; struct ldapsrv_reply *done_r; TALLOC_CTX *local_ctx; struct ldapsrv_context *callback_ctx = NULL; struct ldb_context *samdb = talloc_get_type(call->conn->ldb, struct ldb_context); struct ldb_dn *basedn; struct ldb_request *lreq; struct ldb_control *search_control; struct ldb_search_options_control *search_options; struct ldb_control *extended_dn_control; struct ldb_extended_dn_control *extended_dn_decoded = NULL; struct ldb_control *notification_control = NULL; enum ldb_scope scope = LDB_SCOPE_DEFAULT; const char **attrs = NULL; const char *scope_str, *errstr = NULL; int result = -1; int ldb_ret = -1; unsigned int i; int extended_type = 1; DEBUG(10, ("SearchRequest")); DEBUGADD(10, (" basedn: %s", req->basedn)); DEBUGADD(10, (" filter: %s\n", ldb_filter_from_tree(call, req->tree))); local_ctx = talloc_new(call); NT_STATUS_HAVE_NO_MEMORY(local_ctx); basedn = ldb_dn_new(local_ctx, samdb, req->basedn); NT_STATUS_HAVE_NO_MEMORY(basedn); DEBUG(10, ("SearchRequest: basedn: [%s]\n", req->basedn)); DEBUG(10, ("SearchRequest: filter: [%s]\n", ldb_filter_from_tree(call, req->tree))); switch (req->scope) { case LDAP_SEARCH_SCOPE_BASE: scope_str = "BASE"; scope = LDB_SCOPE_BASE; break; case LDAP_SEARCH_SCOPE_SINGLE: scope_str = "ONE"; scope = LDB_SCOPE_ONELEVEL; break; case LDAP_SEARCH_SCOPE_SUB: scope_str = "SUB"; scope = LDB_SCOPE_SUBTREE; break; default: result = LDAP_PROTOCOL_ERROR; map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL, &errstr); errstr = talloc_asprintf(local_ctx, "%s. Invalid scope", errstr); goto reply; } DEBUG(10,("SearchRequest: scope: [%s]\n", scope_str)); if (req->num_attributes >= 1) { attrs = talloc_array(local_ctx, const char *, req->num_attributes+1); NT_STATUS_HAVE_NO_MEMORY(attrs); for (i=0; i < req->num_attributes; i++) { DEBUG(10,("SearchRequest: attrs: [%s]\n",req->attributes[i])); attrs[i] = req->attributes[i]; } attrs[i] = NULL; } DEBUG(5,("ldb_request %s dn=%s filter=%s\n", scope_str, req->basedn, ldb_filter_from_tree(call, req->tree))); callback_ctx = talloc_zero(local_ctx, struct ldapsrv_context); NT_STATUS_HAVE_NO_MEMORY(callback_ctx); callback_ctx->call = call; callback_ctx->extended_type = extended_type; callback_ctx->attributesonly = req->attributesonly; ldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx, basedn, scope, req->tree, attrs, call->request->controls, callback_ctx, ldap_server_search_callback, NULL); if (ldb_ret != LDB_SUCCESS) { goto reply; } if (call->conn->global_catalog) { search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID); search_options = NULL; if (search_control) { search_options = talloc_get_type(search_control->data, struct ldb_search_options_control); search_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT; } else { search_options = talloc(lreq, struct ldb_search_options_control); NT_STATUS_HAVE_NO_MEMORY(search_options); search_options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT; ldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options); } } else { ldb_request_add_control(lreq, DSDB_CONTROL_NO_GLOBAL_CATALOG, false, NULL); } extended_dn_control = ldb_request_get_control(lreq, LDB_CONTROL_EXTENDED_DN_OID); if (extended_dn_control) { if (extended_dn_control->data) { extended_dn_decoded = talloc_get_type(extended_dn_control->data, struct ldb_extended_dn_control); extended_type = extended_dn_decoded->type; } else { extended_type = 0; } callback_ctx->extended_type = extended_type; } notification_control = ldb_request_get_control(lreq, LDB_CONTROL_NOTIFICATION_OID); if (notification_control != NULL) { const struct ldapsrv_call *pc = NULL; size_t count = 0; for (pc = call->conn->pending_calls; pc != NULL; pc = pc->next) { count += 1; } if (count >= call->conn->limits.max_notifications) { DEBUG(10,("SearchRequest: error MaxNotificationPerConn\n")); result = map_ldb_error(local_ctx, LDB_ERR_ADMIN_LIMIT_EXCEEDED, "MaxNotificationPerConn reached", &errstr); goto reply; } /* * For now we need to do periodic retries on our own. * As the dsdb_notification module will return after each run. */ call->notification.busy = true; } { const char *scheme = NULL; switch (call->conn->referral_scheme) { case LDAP_REFERRAL_SCHEME_LDAPS: scheme = "ldaps"; break; default: scheme = "ldap"; } ldb_ret = ldb_set_opaque( samdb, LDAP_REFERRAL_SCHEME_OPAQUE, discard_const_p(char *, scheme)); if (ldb_ret != LDB_SUCCESS) { goto reply; } } { time_t timeout = call->conn->limits.search_timeout; if (timeout == 0 || (req->timelimit != 0 && req->timelimit < timeout)) { timeout = req->timelimit; } ldb_set_timeout(samdb, lreq, timeout); } if (!call->conn->is_privileged) { ldb_req_mark_untrusted(lreq); } LDB_REQ_SET_LOCATION(lreq); ldb_ret = ldb_request(samdb, lreq); if (ldb_ret != LDB_SUCCESS) { goto reply; } ldb_ret = ldb_wait(lreq->handle, LDB_WAIT_ALL); if (ldb_ret == LDB_SUCCESS) { if (call->notification.busy) { /* Move/Add it to the end */ DLIST_DEMOTE(call->conn->pending_calls, call); call->notification.generation = call->conn->service->notification.generation; if (callback_ctx->count != 0) { call->notification.generation += 1; ldapsrv_notification_retry_setup(call->conn->service, true); } talloc_free(local_ctx); return NT_STATUS_OK; } } reply: DLIST_REMOVE(call->conn->pending_calls, call); call->notification.busy = false; done_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultDone); NT_STATUS_HAVE_NO_MEMORY(done_r); done = &done_r->msg->r.SearchResultDone; done->dn = NULL; done->referral = NULL; if (result != -1) { } else if (ldb_ret == LDB_SUCCESS) { if (callback_ctx->controls) { done_r->msg->controls = callback_ctx->controls; talloc_steal(done_r->msg, callback_ctx->controls); } result = LDB_SUCCESS; } else { DEBUG(10,("SearchRequest: error\n")); result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb), &errstr); } done->resultcode = result; done->errormessage = (errstr?talloc_strdup(done_r, errstr):NULL); talloc_free(local_ctx); return ldapsrv_queue_reply_forced(call, done_r); }
null
null
197,830
314918662591421001470003516678988238334
238
CVE-2021-3670 ldap_server: Remove duplicate print of LDAP search details BUG: https://bugzilla.samba.org/show_bug.cgi?id=14694 Signed-off-by: Andrew Bartlett <[email protected]> Reviewed-by: Douglas Bagnall <[email protected]> (cherry picked from commit 2b3af3b560c9617a233c131376c870fce146c002)
other
openscad
b81369dffc3f385257a9b1f5c271118a88671d6d
1
static std::string getComment(const std::string &fulltext, int line) { if (line < 1) return ""; // Locate line unsigned int start = 0; for (; start<fulltext.length() ; ++start) { if (line <= 1) break; if (fulltext[start] == '\n') line--; } int end = start + 1; while (fulltext[end] != '\n') end++; std::string comment = fulltext.substr(start, end - start); // Locate comment unsigned int startText = 0; int noOfSemicolon = 0; bool inString = false; for (; startText < comment.length() - 1; ++startText) { if (inString && comment.compare(startText, 2, "\\\"") == 0) { startText++; continue; } if (comment[startText] == '"') inString = !inString; if (!inString) { if (comment.compare(startText, 2, "//") == 0) break; if (comment[startText] == ';' && noOfSemicolon > 0) return ""; if (comment[startText] == ';') noOfSemicolon++; } } if (startText + 2 > comment.length()) return ""; std::string result = comment.substr(startText + 2); return result; }
null
null
197,891
313568077470000783177680974177297728787
38
Add file bounds check to comment parser
other
crun
1aeeed2e4fdeffb4875c0d0b439915894594c8c6
1
crun_command_exec (struct crun_global_arguments *global_args, int argc, char **argv, libcrun_error_t *err) { int first_arg = 0, ret = 0; libcrun_context_t crun_context = { 0, }; cleanup_process_schema runtime_spec_schema_config_schema_process *process = NULL; struct libcrun_container_exec_options_s exec_opts; memset (&exec_opts, 0, sizeof (exec_opts)); exec_opts.struct_size = sizeof (exec_opts); crun_context.preserve_fds = 0; crun_context.listen_fds = 0; argp_parse (&run_argp, argc, argv, ARGP_IN_ORDER, &first_arg, &exec_options); crun_assert_n_args (argc - first_arg, exec_options.process ? 1 : 2, -1); ret = init_libcrun_context (&crun_context, argv[first_arg], global_args, err); if (UNLIKELY (ret < 0)) return ret; crun_context.detach = exec_options.detach; crun_context.console_socket = exec_options.console_socket; crun_context.pid_file = exec_options.pid_file; crun_context.preserve_fds = exec_options.preserve_fds; if (getenv ("LISTEN_FDS")) { crun_context.listen_fds = strtoll (getenv ("LISTEN_FDS"), NULL, 10); crun_context.preserve_fds += crun_context.listen_fds; } if (exec_options.process) exec_opts.path = exec_options.process; else { process = xmalloc0 (sizeof (*process)); int i; process->args_len = argc; process->args = xmalloc0 ((argc + 1) * sizeof (*process->args)); for (i = 0; i < argc - first_arg; i++) process->args[i] = xstrdup (argv[first_arg + i + 1]); process->args[i] = NULL; if (exec_options.cwd) process->cwd = exec_options.cwd; process->terminal = exec_options.tty; process->env = exec_options.env; process->env_len = exec_options.env_size; process->user = make_oci_process_user (exec_options.user); if (exec_options.process_label != NULL) process->selinux_label = exec_options.process_label; if (exec_options.apparmor != NULL) process->apparmor_profile = exec_options.apparmor; if (exec_options.cap_size > 0) { runtime_spec_schema_config_schema_process_capabilities *capabilities = xmalloc (sizeof (runtime_spec_schema_config_schema_process_capabilities)); capabilities->effective = exec_options.cap; capabilities->effective_len = exec_options.cap_size; capabilities->inheritable = dup_array (exec_options.cap, exec_options.cap_size); capabilities->inheritable_len = exec_options.cap_size; capabilities->bounding = dup_array (exec_options.cap, exec_options.cap_size); capabilities->bounding_len = exec_options.cap_size; capabilities->ambient = dup_array (exec_options.cap, exec_options.cap_size); capabilities->ambient_len = exec_options.cap_size; capabilities->permitted = dup_array (exec_options.cap, exec_options.cap_size); capabilities->permitted_len = exec_options.cap_size; process->capabilities = capabilities; } // noNewPriviledges will remain `false` if basespec has `false` unless specified // Default is always `true` in generated basespec config if (exec_options.no_new_privs) process->no_new_privileges = 1; exec_opts.process = process; } exec_opts.cgroup = exec_options.cgroup; return libcrun_container_exec_with_options (&crun_context, argv[first_arg], &exec_opts, err); }
null
null
197,973
67555112620788823184421673030526843273
93
exec: --cap do not set inheritable capabilities Closes: CVE-2022-27650 Signed-off-by: Giuseppe Scrivano <[email protected]>
other
jerryscript
3ad76f932c8d2e3b9ba2d95e64848698ec7d7290
1
vm_loop (vm_frame_ctx_t *frame_ctx_p) /**< frame context */ { const ecma_compiled_code_t *bytecode_header_p = frame_ctx_p->shared_p->bytecode_header_p; const uint8_t *byte_code_p = frame_ctx_p->byte_code_p; ecma_value_t *literal_start_p = frame_ctx_p->literal_start_p; ecma_value_t *stack_top_p; uint16_t encoding_limit; uint16_t encoding_delta; uint16_t register_end; uint16_t ident_end; uint16_t const_literal_end; int32_t branch_offset = 0; uint8_t branch_offset_length = 0; ecma_value_t left_value; ecma_value_t right_value; ecma_value_t result = ECMA_VALUE_EMPTY; bool is_strict = ((bytecode_header_p->status_flags & CBC_CODE_FLAGS_STRICT_MODE) != 0); /* Prepare for byte code execution. */ if (!(bytecode_header_p->status_flags & CBC_CODE_FLAGS_FULL_LITERAL_ENCODING)) { encoding_limit = CBC_SMALL_LITERAL_ENCODING_LIMIT; encoding_delta = CBC_SMALL_LITERAL_ENCODING_DELTA; } else { encoding_limit = CBC_FULL_LITERAL_ENCODING_LIMIT; encoding_delta = CBC_FULL_LITERAL_ENCODING_DELTA; } if (bytecode_header_p->status_flags & CBC_CODE_FLAGS_UINT16_ARGUMENTS) { cbc_uint16_arguments_t *args_p = (cbc_uint16_arguments_t *) (bytecode_header_p); register_end = args_p->register_end; ident_end = args_p->ident_end; const_literal_end = args_p->const_literal_end; } else { cbc_uint8_arguments_t *args_p = (cbc_uint8_arguments_t *) (bytecode_header_p); register_end = args_p->register_end; ident_end = args_p->ident_end; const_literal_end = args_p->const_literal_end; } stack_top_p = frame_ctx_p->stack_top_p; /* Outer loop for exception handling. */ while (true) { /* Internal loop for byte code execution. */ while (true) { const uint8_t *byte_code_start_p = byte_code_p; uint8_t opcode = *byte_code_p++; uint32_t opcode_data = opcode; if (opcode == CBC_EXT_OPCODE) { opcode = *byte_code_p++; opcode_data = (uint32_t) ((CBC_END + 1) + opcode); } opcode_data = vm_decode_table[opcode_data]; left_value = ECMA_VALUE_UNDEFINED; right_value = ECMA_VALUE_UNDEFINED; uint32_t operands = VM_OC_GET_ARGS_INDEX (opcode_data); if (operands >= VM_OC_GET_LITERAL) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); READ_LITERAL (literal_index, left_value); if (operands != VM_OC_GET_LITERAL) { switch (operands) { case VM_OC_GET_LITERAL_LITERAL: { uint16_t second_literal_index; READ_LITERAL_INDEX (second_literal_index); READ_LITERAL (second_literal_index, right_value); break; } case VM_OC_GET_STACK_LITERAL: { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); right_value = left_value; left_value = *(--stack_top_p); break; } default: { JERRY_ASSERT (operands == VM_OC_GET_THIS_LITERAL); right_value = left_value; left_value = ecma_copy_value (frame_ctx_p->this_binding); break; } } } } else if (operands >= VM_OC_GET_STACK) { JERRY_ASSERT (operands == VM_OC_GET_STACK || operands == VM_OC_GET_STACK_STACK); JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); left_value = *(--stack_top_p); if (operands == VM_OC_GET_STACK_STACK) { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); right_value = left_value; left_value = *(--stack_top_p); } } else if (operands == VM_OC_GET_BRANCH) { branch_offset_length = CBC_BRANCH_OFFSET_LENGTH (opcode); JERRY_ASSERT (branch_offset_length >= 1 && branch_offset_length <= 3); branch_offset = *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length != 1)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length == 3)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); } } if (opcode_data & VM_OC_BACKWARD_BRANCH) { #if JERRY_VM_EXEC_STOP if (JERRY_CONTEXT (vm_exec_stop_cb) != NULL && --JERRY_CONTEXT (vm_exec_stop_counter) == 0) { result = JERRY_CONTEXT (vm_exec_stop_cb) (JERRY_CONTEXT (vm_exec_stop_user_p)); if (ecma_is_value_undefined (result)) { JERRY_CONTEXT (vm_exec_stop_counter) = JERRY_CONTEXT (vm_exec_stop_frequency); } else { JERRY_CONTEXT (vm_exec_stop_counter) = 1; if (ecma_is_value_error_reference (result)) { ecma_raise_error_from_error_reference (result); } else { jcontext_raise_exception (result); } JERRY_ASSERT (jcontext_has_pending_exception ()); jcontext_set_abort_flag (true); result = ECMA_VALUE_ERROR; goto error; } } #endif /* JERRY_VM_EXEC_STOP */ branch_offset = -branch_offset; } } switch (VM_OC_GROUP_GET_INDEX (opcode_data)) { case VM_OC_POP: { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); ecma_free_value (*(--stack_top_p)); continue; } case VM_OC_POP_BLOCK: { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, 0)); VM_GET_REGISTERS (frame_ctx_p)[0] = *(--stack_top_p); continue; } case VM_OC_PUSH: { *stack_top_p++ = left_value; continue; } case VM_OC_PUSH_TWO: { *stack_top_p++ = left_value; *stack_top_p++ = right_value; continue; } case VM_OC_PUSH_THREE: { uint16_t literal_index; *stack_top_p++ = left_value; left_value = ECMA_VALUE_UNDEFINED; READ_LITERAL_INDEX (literal_index); READ_LITERAL (literal_index, left_value); *stack_top_p++ = right_value; *stack_top_p++ = left_value; continue; } case VM_OC_PUSH_UNDEFINED: { *stack_top_p++ = ECMA_VALUE_UNDEFINED; continue; } case VM_OC_PUSH_TRUE: { *stack_top_p++ = ECMA_VALUE_TRUE; continue; } case VM_OC_PUSH_FALSE: { *stack_top_p++ = ECMA_VALUE_FALSE; continue; } case VM_OC_PUSH_NULL: { *stack_top_p++ = ECMA_VALUE_NULL; continue; } case VM_OC_PUSH_THIS: { *stack_top_p++ = ecma_copy_value (frame_ctx_p->this_binding); continue; } case VM_OC_PUSH_0: { *stack_top_p++ = ecma_make_integer_value (0); continue; } case VM_OC_PUSH_POS_BYTE: { ecma_integer_value_t number = *byte_code_p++; *stack_top_p++ = ecma_make_integer_value (number + 1); continue; } case VM_OC_PUSH_NEG_BYTE: { ecma_integer_value_t number = *byte_code_p++; *stack_top_p++ = ecma_make_integer_value (-(number + 1)); continue; } case VM_OC_PUSH_LIT_0: { stack_top_p[0] = left_value; stack_top_p[1] = ecma_make_integer_value (0); stack_top_p += 2; continue; } case VM_OC_PUSH_LIT_POS_BYTE: { ecma_integer_value_t number = *byte_code_p++; stack_top_p[0] = left_value; stack_top_p[1] = ecma_make_integer_value (number + 1); stack_top_p += 2; continue; } case VM_OC_PUSH_LIT_NEG_BYTE: { ecma_integer_value_t number = *byte_code_p++; stack_top_p[0] = left_value; stack_top_p[1] = ecma_make_integer_value (-(number + 1)); stack_top_p += 2; continue; } case VM_OC_PUSH_OBJECT: { ecma_object_t *obj_p = ecma_create_object (ecma_builtin_get (ECMA_BUILTIN_ID_OBJECT_PROTOTYPE), 0, ECMA_OBJECT_TYPE_GENERAL); *stack_top_p++ = ecma_make_object_value (obj_p); continue; } case VM_OC_PUSH_NAMED_FUNC_EXPR: { ecma_object_t *func_p = ecma_get_object_from_value (left_value); JERRY_ASSERT (ecma_get_object_type (func_p) == ECMA_OBJECT_TYPE_FUNCTION); ecma_extended_object_t *ext_func_p = (ecma_extended_object_t *) func_p; JERRY_ASSERT (frame_ctx_p->lex_env_p == ECMA_GET_NON_NULL_POINTER_FROM_POINTER_TAG (ecma_object_t, ext_func_p->u.function.scope_cp)); ecma_object_t *name_lex_env = ecma_create_decl_lex_env (frame_ctx_p->lex_env_p); ecma_op_create_immutable_binding (name_lex_env, ecma_get_string_from_value (right_value), left_value); ECMA_SET_NON_NULL_POINTER_TAG (ext_func_p->u.function.scope_cp, name_lex_env, 0); ecma_free_value (right_value); ecma_deref_object (name_lex_env); *stack_top_p++ = left_value; continue; } case VM_OC_CREATE_BINDING: { #if !JERRY_ESNEXT JERRY_ASSERT (opcode == CBC_CREATE_VAR); #endif /* !JERRY_ESNEXT */ uint32_t literal_index; READ_LITERAL_INDEX (literal_index); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE; #if JERRY_ESNEXT if (opcode == CBC_CREATE_LET) { prop_attributes = ECMA_PROPERTY_ENUMERABLE_WRITABLE; } else if (opcode == CBC_CREATE_CONST) { prop_attributes = ECMA_PROPERTY_FLAG_ENUMERABLE; } ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); if (opcode != CBC_CREATE_VAR) { property_value_p->value = ECMA_VALUE_UNINITIALIZED; } #else /* !JERRY_ESNEXT */ ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); #endif /* JERRY_ESNEXT */ continue; } case VM_OC_VAR_EVAL: { uint32_t literal_index; ecma_value_t lit_value = ECMA_VALUE_UNDEFINED; if (opcode == CBC_CREATE_VAR_FUNC_EVAL) { uint32_t value_index; READ_LITERAL_INDEX (value_index); JERRY_ASSERT (value_index >= const_literal_end); lit_value = vm_construct_literal_object (frame_ctx_p, literal_start_p[value_index]); } READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { #if JERRY_ESNEXT && !(defined JERRY_NDEBUG) if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* JERRY_ESNEXT && !JERRY_NDEBUG */ JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); } #if JERRY_ESNEXT && !(defined JERRY_NDEBUG) if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* JERRY_ESNEXT && !JERRY_NDEBUG */ /* 'Variable declaration' */ result = ecma_op_has_binding (lex_env_p, name_p); #if JERRY_BUILTIN_PROXY if (ECMA_IS_VALUE_ERROR (result)) { goto error; } #endif /* JERRY_BUILTIN_PROXY */ ecma_property_t *prop_p = NULL; if (ecma_is_value_false (result)) { bool is_configurable = (frame_ctx_p->status_flags & VM_FRAME_CTX_DIRECT_EVAL) != 0; prop_p = ecma_op_create_mutable_binding (lex_env_p, name_p, is_configurable); if (JERRY_UNLIKELY (prop_p == ECMA_PROPERTY_POINTER_ERROR)) { result = ECMA_VALUE_ERROR; goto error; } } if (lit_value != ECMA_VALUE_UNDEFINED) { JERRY_ASSERT (ecma_is_value_object (lit_value)); if (prop_p != NULL) { JERRY_ASSERT (ecma_is_value_undefined (ECMA_PROPERTY_VALUE_PTR (prop_p)->value)); JERRY_ASSERT (ecma_is_property_writable (*prop_p)); ECMA_PROPERTY_VALUE_PTR (prop_p)->value = lit_value; ecma_free_object (lit_value); } else { result = ecma_op_put_value_lex_env_base (lex_env_p, name_p, is_strict, lit_value); ecma_free_object (lit_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } } } continue; } #if JERRY_ESNEXT case VM_OC_EXT_VAR_EVAL: { uint32_t literal_index; ecma_value_t lit_value = ECMA_VALUE_UNDEFINED; JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE); if (opcode == CBC_EXT_CREATE_VAR_FUNC_EVAL) { uint32_t value_index; READ_LITERAL_INDEX (value_index); JERRY_ASSERT (value_index >= const_literal_end); lit_value = vm_construct_literal_object (frame_ctx_p, literal_start_p[value_index]); } READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; ecma_object_t *prev_lex_env_p = NULL; while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { #if !(defined JERRY_NDEBUG) if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* !JERRY_NDEBUG */ JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); prev_lex_env_p = lex_env_p; lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); } JERRY_ASSERT (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (prev_lex_env_p != NULL && ecma_get_lex_env_type (prev_lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); ecma_property_t *property_p = ecma_find_named_property (prev_lex_env_p, name_p); ecma_property_value_t *property_value_p; if (property_p == NULL) { property_value_p = ecma_create_named_data_property (prev_lex_env_p, name_p, ECMA_PROPERTY_CONFIGURABLE_WRITABLE, NULL); if (lit_value == ECMA_VALUE_UNDEFINED) { continue; } } else { if (lit_value == ECMA_VALUE_UNDEFINED) { continue; } property_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); ecma_free_value_if_not_object (property_value_p->value); } property_value_p->value = lit_value; ecma_deref_object (ecma_get_object_from_value (lit_value)); continue; } #endif /* JERRY_ESNEXT */ case VM_OC_CREATE_ARGUMENTS: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_ARG_LIST); result = ecma_op_create_arguments_object ((vm_frame_ctx_shared_args_t *) (frame_ctx_p->shared_p), frame_ctx_p->lex_env_p); if (literal_index < register_end) { JERRY_ASSERT (VM_GET_REGISTER (frame_ctx_p, literal_index) == ECMA_VALUE_UNDEFINED); VM_GET_REGISTER (frame_ctx_p, literal_index) = result; continue; } ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE; ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); property_value_p->value = result; ecma_deref_object (ecma_get_object_from_value (result)); continue; } #if JERRY_SNAPSHOT_EXEC case VM_OC_SET_BYTECODE_PTR: { memcpy (&byte_code_p, byte_code_p++, sizeof (uintptr_t)); frame_ctx_p->byte_code_start_p = byte_code_p; continue; } #endif /* JERRY_SNAPSHOT_EXEC */ case VM_OC_INIT_ARG_OR_FUNC: { uint32_t literal_index, value_index; ecma_value_t lit_value; bool release = false; READ_LITERAL_INDEX (value_index); if (value_index < register_end) { /* Take (not copy) the reference. */ lit_value = ecma_copy_value_if_not_object (VM_GET_REGISTER (frame_ctx_p, value_index)); } else { lit_value = vm_construct_literal_object (frame_ctx_p, literal_start_p[value_index]); release = true; } READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (value_index != literal_index); JERRY_ASSERT (value_index >= register_end || literal_index >= register_end); if (literal_index < register_end) { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); JERRY_ASSERT (release); VM_GET_REGISTER (frame_ctx_p, literal_index) = lit_value; continue; } ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, ECMA_PROPERTY_FLAG_WRITABLE, NULL); JERRY_ASSERT (property_value_p->value == ECMA_VALUE_UNDEFINED); property_value_p->value = lit_value; if (release) { ecma_deref_object (ecma_get_object_from_value (lit_value)); } continue; } #if JERRY_ESNEXT case VM_OC_CHECK_VAR: { JERRY_ASSERT (CBC_FUNCTION_GET_TYPE (frame_ctx_p->shared_p->bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT); uint32_t literal_index; READ_LITERAL_INDEX (literal_index); if ((frame_ctx_p->lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) == 0) { continue; } ecma_string_t *const literal_name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_property_t *const binding_p = ecma_find_named_property (frame_ctx_p->lex_env_p, literal_name_p); if (binding_p != NULL) { result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared)); goto error; } continue; } case VM_OC_CHECK_LET: { JERRY_ASSERT (CBC_FUNCTION_GET_TYPE (frame_ctx_p->shared_p->bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT); uint32_t literal_index; READ_LITERAL_INDEX (literal_index); ecma_string_t *literal_name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; if (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { result = opfunc_lexical_scope_has_restricted_binding (frame_ctx_p, literal_name_p); if (!ecma_is_value_false (result)) { if (ecma_is_value_true (result)) { result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared)); } JERRY_ASSERT (ECMA_IS_VALUE_ERROR (result)); goto error; } continue; } result = ecma_op_has_binding (lex_env_p, literal_name_p); #if JERRY_BUILTIN_PROXY if (ECMA_IS_VALUE_ERROR (result)) { goto error; } #endif /* JERRY_BUILTIN_PROXY */ if (ecma_is_value_true (result)) { result = ecma_raise_syntax_error (ECMA_ERR_MSG (ecma_error_local_variable_is_redeclared)); goto error; } continue; } case VM_OC_ASSIGN_LET_CONST: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE || (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_CLASS && (frame_ctx_p->lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_LEXICAL_ENV_HAS_DATA))); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_property_t *property_p = ecma_find_named_property (frame_ctx_p->lex_env_p, name_p); JERRY_ASSERT (property_p != NULL && ECMA_PROPERTY_IS_RAW_DATA (*property_p) && (*property_p & ECMA_PROPERTY_FLAG_DATA)); JERRY_ASSERT (ECMA_PROPERTY_VALUE_PTR (property_p)->value == ECMA_VALUE_UNINITIALIZED); ECMA_PROPERTY_VALUE_PTR (property_p)->value = left_value; if (ecma_is_value_object (left_value)) { ecma_deref_object (ecma_get_object_from_value (left_value)); } continue; } case VM_OC_INIT_BINDING: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); JERRY_ASSERT (ecma_get_lex_env_type (frame_ctx_p->lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (ecma_find_named_property (frame_ctx_p->lex_env_p, name_p) == NULL); uint8_t prop_attributes = ECMA_PROPERTY_FLAG_WRITABLE; if (opcode == CBC_INIT_LET) { prop_attributes = ECMA_PROPERTY_ENUMERABLE_WRITABLE; } else if (opcode == CBC_INIT_CONST) { prop_attributes = ECMA_PROPERTY_FLAG_ENUMERABLE; } ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (frame_ctx_p->lex_env_p, name_p, prop_attributes, NULL); JERRY_ASSERT (property_value_p->value == ECMA_VALUE_UNDEFINED); ecma_value_t value = *(--stack_top_p); property_value_p->value = value; ecma_deref_if_object (value); continue; } case VM_OC_THROW_CONST_ERROR: { result = ecma_raise_type_error (ECMA_ERR_MSG ("Constant bindings cannot be reassigned")); goto error; } case VM_OC_COPY_TO_GLOBAL: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; while (lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) { #ifndef JERRY_NDEBUG if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); JERRY_ASSERT (property_p == NULL || !(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); } #endif /* !JERRY_NDEBUG */ JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); } if (ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE) { ecma_property_t *property_p = ecma_find_named_property (lex_env_p, name_p); ecma_property_value_t *prop_value_p; if (property_p == NULL) { prop_value_p = ecma_create_named_data_property (lex_env_p, name_p, ECMA_PROPERTY_FLAG_WRITABLE, NULL); } else { #ifndef JERRY_NDEBUG JERRY_ASSERT (!(*property_p & ECMA_PROPERTY_FLAG_ENUMERABLE)); #endif /* !JERRY_NDEBUG */ prop_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); } ecma_named_data_property_assign_value (lex_env_p, prop_value_p, left_value); } else { result = ecma_op_set_mutable_binding (lex_env_p, name_p, left_value, is_strict); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } } goto free_left_value; } case VM_OC_COPY_FROM_ARG: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index >= register_end); ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; ecma_object_t *arg_lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); JERRY_ASSERT ((lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) && ecma_get_lex_env_type (lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); JERRY_ASSERT (arg_lex_env_p != NULL && !(arg_lex_env_p->type_flags_refs & ECMA_OBJECT_FLAG_BLOCK) && ecma_get_lex_env_type (arg_lex_env_p) == ECMA_LEXICAL_ENVIRONMENT_DECLARATIVE); ecma_property_value_t *property_value_p; property_value_p = ecma_create_named_data_property (lex_env_p, name_p, ECMA_PROPERTY_FLAG_WRITABLE, NULL); ecma_property_t *property_p = ecma_find_named_property (arg_lex_env_p, name_p); JERRY_ASSERT (property_p != NULL); ecma_property_value_t *arg_prop_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); property_value_p->value = ecma_copy_value_if_not_object (arg_prop_value_p->value); continue; } case VM_OC_CLONE_CONTEXT: { JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE); bool copy_values = (byte_code_start_p[1] == CBC_EXT_CLONE_FULL_CONTEXT); frame_ctx_p->lex_env_p = ecma_clone_decl_lexical_environment (frame_ctx_p->lex_env_p, copy_values); continue; } case VM_OC_SET__PROTO__: { result = ecma_builtin_object_object_set_proto (stack_top_p[-1], left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_PUSH_STATIC_FIELD_FUNC: { JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE && (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_FIELD_FUNC || byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC)); bool push_computed = (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC); ecma_value_t value = stack_top_p[-1]; if (!push_computed) { stack_top_p++; } memmove (stack_top_p - 3, stack_top_p - 4, 3 * sizeof (ecma_value_t)); stack_top_p[-4] = left_value; if (!push_computed) { continue; } left_value = value; /* FALLTHRU */ } case VM_OC_ADD_COMPUTED_FIELD: { JERRY_ASSERT (byte_code_start_p[0] == CBC_EXT_OPCODE && (byte_code_start_p[1] == CBC_EXT_PUSH_STATIC_COMPUTED_FIELD_FUNC || byte_code_start_p[1] == CBC_EXT_ADD_COMPUTED_FIELD || byte_code_start_p[1] == CBC_EXT_ADD_STATIC_COMPUTED_FIELD)); int index = (byte_code_start_p[1] == CBC_EXT_ADD_COMPUTED_FIELD) ? -2 : -4; result = opfunc_add_computed_field (stack_top_p[index], left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_COPY_DATA_PROPERTIES: { left_value = *(--stack_top_p); if (ecma_is_value_undefined (left_value) || ecma_is_value_null (left_value)) { continue; } result = opfunc_copy_data_properties (stack_top_p[-1], left_value, ECMA_VALUE_UNDEFINED); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_SET_COMPUTED_PROPERTY: { /* Swap values. */ left_value ^= right_value; right_value ^= left_value; left_value ^= right_value; /* FALLTHRU */ } #endif /* JERRY_ESNEXT */ case VM_OC_SET_PROPERTY: { JERRY_STATIC_ASSERT (VM_OC_NON_STATIC_FLAG == VM_OC_BACKWARD_BRANCH, vm_oc_non_static_flag_must_be_equal_to_vm_oc_backward_branch); JERRY_ASSERT ((opcode_data >> VM_OC_NON_STATIC_SHIFT) <= 0x1); ecma_string_t *prop_name_p = ecma_op_to_property_key (right_value); if (JERRY_UNLIKELY (prop_name_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } #if JERRY_ESNEXT if (JERRY_UNLIKELY (ecma_compare_ecma_string_to_magic_id (prop_name_p, LIT_MAGIC_STRING_PROTOTYPE)) && !(opcode_data & VM_OC_NON_STATIC_FLAG)) { result = ecma_raise_type_error (ECMA_ERR_MSG (ecma_error_class_is_non_configurable)); goto error; } const int index = (int) (opcode_data >> VM_OC_NON_STATIC_SHIFT) - 2; #else /* !JERRY_ESNEXT */ const int index = -1; #endif /* JERRY_ESNEXT */ ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[index]); opfunc_set_data_property (object_p, prop_name_p, left_value); ecma_deref_ecma_string (prop_name_p); goto free_both_values; } case VM_OC_SET_GETTER: case VM_OC_SET_SETTER: { JERRY_ASSERT ((opcode_data >> VM_OC_NON_STATIC_SHIFT) <= 0x1); ecma_string_t *prop_name_p = ecma_op_to_property_key (left_value); if (JERRY_UNLIKELY (prop_name_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } #if JERRY_ESNEXT if (JERRY_UNLIKELY (ecma_compare_ecma_string_to_magic_id (prop_name_p, LIT_MAGIC_STRING_PROTOTYPE)) && !(opcode_data & VM_OC_NON_STATIC_FLAG)) { result = ecma_raise_type_error (ECMA_ERR_MSG (ecma_error_class_is_non_configurable)); goto error; } const int index = (int) (opcode_data >> VM_OC_NON_STATIC_SHIFT) - 2; #else /* !JERRY_ESNEXT */ const int index = -1; #endif /* JERRY_ESNEXT */ opfunc_set_accessor (VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_SET_GETTER, stack_top_p[index], prop_name_p, right_value); ecma_deref_ecma_string (prop_name_p); goto free_both_values; } case VM_OC_PUSH_ARRAY: { /* Note: this operation cannot throw an exception */ *stack_top_p++ = ecma_make_object_value (ecma_op_new_array_object (0)); continue; } #if JERRY_ESNEXT case VM_OC_LOCAL_EVAL: { ECMA_CLEAR_LOCAL_PARSE_OPTS (); uint8_t parse_opts = *byte_code_p++; ECMA_SET_LOCAL_PARSE_OPTS (parse_opts); continue; } case VM_OC_SUPER_CALL: { uint8_t arguments_list_len = *byte_code_p++; if (opcode >= CBC_EXT_SPREAD_SUPER_CALL) { stack_top_p -= arguments_list_len; ecma_collection_t *arguments_p = opfunc_spread_arguments (stack_top_p, arguments_list_len); if (JERRY_UNLIKELY (arguments_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } stack_top_p++; ECMA_SET_INTERNAL_VALUE_POINTER (stack_top_p[-1], arguments_p); } else { stack_top_p -= arguments_list_len; } frame_ctx_p->call_operation = VM_EXEC_SUPER_CALL; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_PUSH_CLASS_ENVIRONMENT: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); opfunc_push_class_environment (frame_ctx_p, &stack_top_p, literal_start_p[literal_index]); continue; } case VM_OC_PUSH_IMPLICIT_CTOR: { *stack_top_p++ = opfunc_create_implicit_class_constructor (opcode, frame_ctx_p->shared_p->bytecode_header_p); continue; } case VM_OC_INIT_CLASS: { result = opfunc_init_class (frame_ctx_p, stack_top_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } continue; } case VM_OC_FINALIZE_CLASS: { JERRY_ASSERT (opcode == CBC_EXT_FINALIZE_NAMED_CLASS || opcode == CBC_EXT_FINALIZE_ANONYMOUS_CLASS); if (opcode == CBC_EXT_FINALIZE_NAMED_CLASS) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); left_value = literal_start_p[literal_index]; } opfunc_finalize_class (frame_ctx_p, &stack_top_p, left_value); continue; } case VM_OC_SET_FIELD_INIT: { ecma_string_t *property_name_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_CLASS_FIELD_INIT); ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[-2]); ecma_property_value_t *property_value_p = ecma_create_named_data_property (object_p, property_name_p, ECMA_PROPERTY_FIXED, NULL); property_value_p->value = left_value; property_name_p = ecma_get_internal_string (LIT_INTERNAL_MAGIC_STRING_CLASS_FIELD_COMPUTED); ecma_property_t *property_p = ecma_find_named_property (object_p, property_name_p); if (property_p != NULL) { property_value_p = ECMA_PROPERTY_VALUE_PTR (property_p); ecma_value_t *compact_collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_value_t, property_value_p->value); compact_collection_p = ecma_compact_collection_shrink (compact_collection_p); ECMA_SET_INTERNAL_VALUE_POINTER (property_value_p->value, compact_collection_p); } goto free_left_value; } case VM_OC_RUN_FIELD_INIT: { JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_NON_ARROW_FUNC); result = opfunc_init_class_fields (frame_ctx_p->shared_p->function_object_p, frame_ctx_p->this_binding); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } continue; } case VM_OC_RUN_STATIC_FIELD_INIT: { left_value = stack_top_p[-2]; stack_top_p[-2] = stack_top_p[-1]; stack_top_p--; result = opfunc_init_static_class_fields (left_value, stack_top_p[-1]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_SET_NEXT_COMPUTED_FIELD: { ecma_integer_value_t next_index = ecma_get_integer_from_value (stack_top_p[-2]) + 1; stack_top_p[-2] = ecma_make_integer_value (next_index); stack_top_p++; JERRY_ASSERT (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_CLASS_FIELDS); ecma_value_t *computed_class_fields_p = VM_GET_COMPUTED_CLASS_FIELDS (frame_ctx_p); JERRY_ASSERT ((ecma_value_t) next_index < ECMA_COMPACT_COLLECTION_GET_SIZE (computed_class_fields_p)); result = stack_top_p[-2]; stack_top_p[-1] = ecma_copy_value (computed_class_fields_p[next_index]); stack_top_p[-2] = ecma_copy_value (frame_ctx_p->this_binding); break; } case VM_OC_PUSH_SUPER_CONSTRUCTOR: { result = ecma_op_function_get_super_constructor (vm_get_class_function (frame_ctx_p)); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; continue; } case VM_OC_RESOLVE_LEXICAL_THIS: { result = ecma_op_get_this_binding (frame_ctx_p->lex_env_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; continue; } case VM_OC_OBJECT_LITERAL_HOME_ENV: { if (opcode == CBC_EXT_PUSH_OBJECT_SUPER_ENVIRONMENT) { ecma_value_t obj_value = stack_top_p[-1]; ecma_object_t *obj_env_p = ecma_create_lex_env_class (frame_ctx_p->lex_env_p, 0); ECMA_SET_NON_NULL_POINTER (obj_env_p->u1.bound_object_cp, ecma_get_object_from_value (obj_value)); stack_top_p[-1] = ecma_make_object_value (obj_env_p); *stack_top_p++ = obj_value; } else { JERRY_ASSERT (opcode == CBC_EXT_POP_OBJECT_SUPER_ENVIRONMENT); ecma_deref_object (ecma_get_object_from_value (stack_top_p[-2])); stack_top_p[-2] = stack_top_p[-1]; stack_top_p--; } continue; } case VM_OC_SET_HOME_OBJECT: { int offset = opcode == CBC_EXT_OBJECT_LITERAL_SET_HOME_OBJECT_COMPUTED ? -1 : 0; opfunc_set_home_object (ecma_get_object_from_value (stack_top_p[-1]), ecma_get_object_from_value (stack_top_p[-3 + offset])); continue; } case VM_OC_SUPER_REFERENCE: { result = opfunc_form_super_reference (&stack_top_p, frame_ctx_p, left_value, opcode); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } goto free_left_value; } case VM_OC_SET_FUNCTION_NAME: { char *prefix_p = NULL; lit_utf8_size_t prefix_size = 0; if (opcode != CBC_EXT_SET_FUNCTION_NAME) { ecma_value_t prop_name_value; if (opcode == CBC_EXT_SET_CLASS_NAME) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); prop_name_value = literal_start_p[literal_index]; } else { prop_name_value = stack_top_p[-2]; } ecma_string_t *prop_name_p = ecma_op_to_property_key (prop_name_value); if (JERRY_UNLIKELY (prop_name_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } left_value = ecma_make_prop_name_value (prop_name_p); if (opcode != CBC_EXT_SET_CLASS_NAME) { ecma_ref_ecma_string (prop_name_p); ecma_free_value (stack_top_p[-2]); stack_top_p[-2] = left_value; } if (opcode == CBC_EXT_SET_COMPUTED_GETTER_NAME || opcode == CBC_EXT_SET_COMPUTED_SETTER_NAME) { prefix_p = (opcode == CBC_EXT_SET_COMPUTED_GETTER_NAME) ? "get " : "set "; prefix_size = 4; } } ecma_object_t *func_obj_p = ecma_get_object_from_value (stack_top_p[-1]); if (ecma_find_named_property (func_obj_p, ecma_get_magic_string (LIT_MAGIC_STRING_NAME)) != NULL) { ecma_free_value (left_value); continue; } ecma_property_value_t *value_p; value_p = ecma_create_named_data_property (func_obj_p, ecma_get_magic_string (LIT_MAGIC_STRING_NAME), ECMA_PROPERTY_FLAG_CONFIGURABLE, NULL); if (ecma_get_object_type (func_obj_p) == ECMA_OBJECT_TYPE_FUNCTION) { ECMA_SET_SECOND_BIT_TO_POINTER_TAG (((ecma_extended_object_t *) func_obj_p)->u.function.scope_cp); } value_p->value = ecma_op_function_form_name (ecma_get_prop_name_from_value (left_value), prefix_p, prefix_size); ecma_free_value (left_value); continue; } case VM_OC_PUSH_SPREAD_ELEMENT: { *stack_top_p++ = ECMA_VALUE_SPREAD_ELEMENT; continue; } case VM_OC_PUSH_REST_OBJECT: { vm_frame_ctx_shared_t *shared_p = frame_ctx_p->shared_p; JERRY_ASSERT (shared_p->status_flags & VM_FRAME_CTX_SHARED_HAS_ARG_LIST); const ecma_value_t *arg_list_p = ((vm_frame_ctx_shared_args_t *) shared_p)->arg_list_p; uint32_t arg_list_len = ((vm_frame_ctx_shared_args_t *) shared_p)->arg_list_len; uint16_t argument_end; if (bytecode_header_p->status_flags & CBC_CODE_FLAGS_UINT16_ARGUMENTS) { argument_end = ((cbc_uint16_arguments_t *) bytecode_header_p)->argument_end; } else { argument_end = ((cbc_uint8_arguments_t *) bytecode_header_p)->argument_end; } if (arg_list_len < argument_end) { arg_list_len = argument_end; } result = ecma_op_new_array_object_from_buffer (arg_list_p + argument_end, arg_list_len - argument_end); JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (result)); *stack_top_p++ = result; continue; } case VM_OC_ITERATOR_CONTEXT_CREATE: { result = ecma_op_get_iterator (stack_top_p[-1], ECMA_VALUE_SYNC_ITERATOR, &left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } uint32_t context_size = (uint32_t) (stack_top_p + PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION - VM_LAST_CONTEXT_END ()); stack_top_p += PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION; VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, context_size); stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_ITERATOR, context_size) | VM_CONTEXT_CLOSE_ITERATOR; stack_top_p[-2] = result; stack_top_p[-3] = left_value; continue; } case VM_OC_ITERATOR_STEP: { ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_value_t iterator = last_context_end_p[-2]; ecma_value_t next_method = last_context_end_p[-3]; result = ecma_op_iterator_step (iterator, next_method); if (ECMA_IS_VALUE_ERROR (result)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; goto error; } ecma_value_t value = ECMA_VALUE_UNDEFINED; if (!ecma_is_value_false (result)) { value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (value)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = value; goto error; } } else { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; } *stack_top_p++ = value; continue; } case VM_OC_ITERATOR_CONTEXT_END: { JERRY_ASSERT (VM_LAST_CONTEXT_END () == stack_top_p); if (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR) { stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = ecma_op_iterator_close (stack_top_p[-2]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } } stack_top_p = vm_stack_context_abort_variable_length (frame_ctx_p, stack_top_p, PARSER_ITERATOR_CONTEXT_STACK_ALLOCATION); continue; } case VM_OC_DEFAULT_INITIALIZER: { JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); if (stack_top_p[-1] != ECMA_VALUE_UNDEFINED) { byte_code_p = byte_code_start_p + branch_offset; continue; } stack_top_p--; continue; } case VM_OC_REST_INITIALIZER: { ecma_object_t *array_p = ecma_op_new_array_object (0); JERRY_ASSERT (ecma_op_object_is_fast_array (array_p)); ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_value_t iterator = last_context_end_p[-2]; ecma_value_t next_method = last_context_end_p[-3]; uint32_t index = 0; while (true) { result = ecma_op_iterator_step (iterator, next_method); if (ECMA_IS_VALUE_ERROR (result)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; ecma_deref_object (array_p); goto error; } if (ecma_is_value_false (result)) { last_context_end_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; break; } ecma_value_t value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (value)) { ecma_deref_object (array_p); result = value; goto error; } bool set_result = ecma_fast_array_set_property (array_p, index++, value); JERRY_ASSERT (set_result); ecma_free_value (value); } *stack_top_p++ = ecma_make_object_value (array_p); continue; } case VM_OC_OBJ_INIT_CONTEXT_CREATE: { left_value = stack_top_p[-1]; vm_stack_context_type_t context_type = VM_CONTEXT_OBJ_INIT; uint32_t context_stack_allocation = PARSER_OBJ_INIT_CONTEXT_STACK_ALLOCATION; if (opcode == CBC_EXT_OBJ_INIT_REST_CONTEXT_CREATE) { context_type = VM_CONTEXT_OBJ_INIT_REST; context_stack_allocation = PARSER_OBJ_INIT_REST_CONTEXT_STACK_ALLOCATION; } uint32_t context_size = (uint32_t) (stack_top_p + context_stack_allocation - VM_LAST_CONTEXT_END ()); stack_top_p += context_stack_allocation; VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, context_size); stack_top_p[-1] = VM_CREATE_CONTEXT (context_type, context_size); stack_top_p[-2] = left_value; if (context_type == VM_CONTEXT_OBJ_INIT_REST) { stack_top_p[-3] = ecma_make_object_value (ecma_op_new_array_object (0)); } continue; } case VM_OC_OBJ_INIT_CONTEXT_END: { JERRY_ASSERT (stack_top_p == VM_LAST_CONTEXT_END ()); uint32_t context_stack_allocation = PARSER_OBJ_INIT_CONTEXT_STACK_ALLOCATION; if (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_OBJ_INIT_REST) { context_stack_allocation = PARSER_OBJ_INIT_REST_CONTEXT_STACK_ALLOCATION; } stack_top_p = vm_stack_context_abort_variable_length (frame_ctx_p, stack_top_p, context_stack_allocation); continue; } case VM_OC_OBJ_INIT_PUSH_REST: { ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); if (!ecma_op_require_object_coercible (last_context_end_p[-2])) { result = ECMA_VALUE_ERROR; goto error; } ecma_object_t *prototype_p = ecma_builtin_get (ECMA_BUILTIN_ID_OBJECT_PROTOTYPE); ecma_object_t *result_object_p = ecma_create_object (prototype_p, 0, ECMA_OBJECT_TYPE_GENERAL); left_value = ecma_make_object_value (result_object_p); result = opfunc_copy_data_properties (left_value, last_context_end_p[-2], last_context_end_p[-3]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_free_value (last_context_end_p[-3]); last_context_end_p[-3] = last_context_end_p[-2]; last_context_end_p[-2] = ECMA_VALUE_UNDEFINED; *stack_top_p++ = left_value; continue; } case VM_OC_INITIALIZER_PUSH_NAME: { if (JERRY_UNLIKELY (!ecma_is_value_prop_name (left_value))) { ecma_string_t *property_key = ecma_op_to_property_key (left_value); if (property_key == NULL) { result = ECMA_VALUE_ERROR; goto error; } ecma_free_value (left_value); left_value = ecma_make_string_value (property_key); } ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_object_t *array_obj_p = ecma_get_object_from_value (last_context_end_p[-3]); JERRY_ASSERT (ecma_get_object_type (array_obj_p) == ECMA_OBJECT_TYPE_ARRAY); ecma_extended_object_t *ext_array_obj_p = (ecma_extended_object_t *) array_obj_p; ecma_fast_array_set_property (array_obj_p, ext_array_obj_p->u.array.length, left_value); /* FALLTHRU */ } case VM_OC_INITIALIZER_PUSH_PROP: { ecma_value_t *last_context_end_p = VM_LAST_CONTEXT_END (); ecma_value_t base = last_context_end_p[-2]; if (opcode == CBC_EXT_INITIALIZER_PUSH_PROP) { left_value = *last_context_end_p++; while (last_context_end_p < stack_top_p) { last_context_end_p[-1] = *last_context_end_p; last_context_end_p++; } stack_top_p--; } result = vm_op_get_value (base, left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_SPREAD_ARGUMENTS: { uint8_t arguments_list_len = *byte_code_p++; stack_top_p -= arguments_list_len; ecma_collection_t *arguments_p = opfunc_spread_arguments (stack_top_p, arguments_list_len); if (JERRY_UNLIKELY (arguments_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } stack_top_p++; ECMA_SET_INTERNAL_VALUE_POINTER (stack_top_p[-1], arguments_p); frame_ctx_p->call_operation = VM_EXEC_SPREAD_OP; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_CREATE_GENERATOR: { frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; vm_executable_object_t *executable_object_p; executable_object_p = opfunc_create_executable_object (frame_ctx_p, VM_CREATE_EXECUTABLE_OBJECT_GENERATOR); return ecma_make_object_value ((ecma_object_t *) executable_object_p); } case VM_OC_YIELD: { frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = --stack_top_p; return *stack_top_p; } case VM_OC_ASYNC_YIELD: { ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); opfunc_async_generator_yield (async_generator_object_p, stack_top_p[-1]); frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = --stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_ASYNC_YIELD_ITERATOR: { ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); JERRY_ASSERT (!(async_generator_object_p->u.cls.u2.executable_obj_flags & ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD)); /* Byte code is executed at the first time. */ left_value = stack_top_p[-1]; result = ecma_op_get_iterator (left_value, ECMA_VALUE_ASYNC_ITERATOR, stack_top_p - 1); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_free_value (left_value); left_value = result; result = ecma_op_iterator_next (left_value, stack_top_p[-1], ECMA_VALUE_UNDEFINED); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } result = ecma_promise_async_await (async_generator_object_p, result); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } async_generator_object_p->u.cls.u2.executable_obj_flags |= ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD; *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p) = left_value; frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_AWAIT: { if (JERRY_UNLIKELY (!(frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE))) { frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = --stack_top_p; result = opfunc_async_create_and_await (frame_ctx_p, *stack_top_p, 0); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } return result; } /* FALLTHRU */ } case VM_OC_GENERATOR_AWAIT: { ecma_extended_object_t *async_generator_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); result = ecma_promise_async_await (async_generator_object_p, *(--stack_top_p)); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_EXT_RETURN: { result = left_value; left_value = ECMA_VALUE_UNDEFINED; ecma_value_t *stack_bottom_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; while (stack_top_p > stack_bottom_p) { ecma_fast_free_value (*(--stack_top_p)); } goto error; } case VM_OC_ASYNC_EXIT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); if (!(frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE)) { result = ecma_op_create_promise_object (ECMA_VALUE_EMPTY, ECMA_VALUE_UNDEFINED, NULL); } else { result = *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p); *VM_GET_EXECUTABLE_ITERATOR (frame_ctx_p) = ECMA_VALUE_UNDEFINED; } vm_stack_context_type_t context_type = VM_GET_CONTEXT_TYPE (stack_top_p[-1]); if (context_type == VM_CONTEXT_TRY) { JERRY_ASSERT (frame_ctx_p->context_depth == PARSER_TRY_CONTEXT_STACK_ALLOCATION); left_value = ECMA_VALUE_UNDEFINED; } else { JERRY_ASSERT (frame_ctx_p->context_depth == PARSER_FINALLY_CONTEXT_STACK_ALLOCATION); left_value = stack_top_p[-2]; } if (context_type == VM_CONTEXT_FINALLY_THROW) { ecma_reject_promise (result, left_value); } else { JERRY_ASSERT (context_type == VM_CONTEXT_TRY || context_type == VM_CONTEXT_FINALLY_RETURN); ecma_fulfill_promise (result, left_value); } ecma_free_value (left_value); frame_ctx_p->context_depth = 0; frame_ctx_p->call_operation = VM_NO_EXEC_OP; return result; } case VM_OC_STRING_CONCAT: { ecma_string_t *left_str_p = ecma_op_to_string (left_value); if (JERRY_UNLIKELY (left_str_p == NULL)) { result = ECMA_VALUE_ERROR; goto error; } ecma_string_t *right_str_p = ecma_op_to_string (right_value); if (JERRY_UNLIKELY (right_str_p == NULL)) { ecma_deref_ecma_string (left_str_p); result = ECMA_VALUE_ERROR; goto error; } ecma_string_t *result_str_p = ecma_concat_ecma_strings (left_str_p, right_str_p); ecma_deref_ecma_string (right_str_p); *stack_top_p++ = ecma_make_string_value (result_str_p); goto free_both_values; } case VM_OC_GET_TEMPLATE_OBJECT: { uint8_t tagged_idx = *byte_code_p++; ecma_collection_t *collection_p = ecma_compiled_code_get_tagged_template_collection (bytecode_header_p); JERRY_ASSERT (tagged_idx < collection_p->item_count); *stack_top_p++ = ecma_copy_value (collection_p->buffer_p[tagged_idx]); continue; } case VM_OC_PUSH_NEW_TARGET: { ecma_object_t *new_target_object_p = JERRY_CONTEXT (current_new_target_p); if (new_target_object_p == NULL) { *stack_top_p++ = ECMA_VALUE_UNDEFINED; } else { ecma_ref_object (new_target_object_p); *stack_top_p++ = ecma_make_object_value (new_target_object_p); } continue; } case VM_OC_REQUIRE_OBJECT_COERCIBLE: { if (!ecma_op_require_object_coercible (stack_top_p[-1])) { result = ECMA_VALUE_ERROR; goto error; } continue; } case VM_OC_ASSIGN_SUPER: { result = opfunc_assign_super_reference (&stack_top_p, frame_ctx_p, opcode_data); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } continue; } #endif /* JERRY_ESNEXT */ case VM_OC_PUSH_ELISON: { *stack_top_p++ = ECMA_VALUE_ARRAY_HOLE; continue; } case VM_OC_APPEND_ARRAY: { uint16_t values_length = *byte_code_p++; stack_top_p -= values_length; #if JERRY_ESNEXT if (*byte_code_start_p == CBC_EXT_OPCODE) { values_length = (uint16_t) (values_length | OPFUNC_HAS_SPREAD_ELEMENT); } #endif /* JERRY_ESNEXT */ result = opfunc_append_array (stack_top_p, values_length); #if JERRY_ESNEXT if (ECMA_IS_VALUE_ERROR (result)) { goto error; } #else /* !JERRY_ESNEXT */ JERRY_ASSERT (ecma_is_value_empty (result)); #endif /* JERRY_ESNEXT */ continue; } case VM_OC_IDENT_REFERENCE: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index < ident_end); if (literal_index < register_end) { *stack_top_p++ = ECMA_VALUE_REGISTER_REF; *stack_top_p++ = ecma_make_integer_value (literal_index); *stack_top_p++ = ecma_fast_copy_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); } else { ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *ref_base_lex_env_p; result = ecma_op_get_value_lex_env_base (frame_ctx_p->lex_env_p, &ref_base_lex_env_p, name_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_ref_object (ref_base_lex_env_p); ecma_ref_ecma_string (name_p); *stack_top_p++ = ecma_make_object_value (ref_base_lex_env_p); *stack_top_p++ = ecma_make_string_value (name_p); *stack_top_p++ = result; } continue; } case VM_OC_PROP_GET: { result = vm_op_get_value (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_PROP_REFERENCE: { /* Forms with reference requires preserving the base and offset. */ if (opcode == CBC_PUSH_PROP_REFERENCE) { left_value = stack_top_p[-2]; right_value = stack_top_p[-1]; } else if (opcode == CBC_PUSH_PROP_LITERAL_REFERENCE) { *stack_top_p++ = left_value; right_value = left_value; left_value = stack_top_p[-2]; } else { JERRY_ASSERT (opcode == CBC_PUSH_PROP_LITERAL_LITERAL_REFERENCE || opcode == CBC_PUSH_PROP_THIS_LITERAL_REFERENCE); *stack_top_p++ = left_value; *stack_top_p++ = right_value; } /* FALLTHRU */ } case VM_OC_PROP_PRE_INCR: case VM_OC_PROP_PRE_DECR: case VM_OC_PROP_POST_INCR: case VM_OC_PROP_POST_DECR: { result = vm_op_get_value (left_value, right_value); if (opcode < CBC_PRE_INCR) { left_value = ECMA_VALUE_UNDEFINED; right_value = ECMA_VALUE_UNDEFINED; } if (ECMA_IS_VALUE_ERROR (result)) { goto error; } if (opcode < CBC_PRE_INCR) { break; } stack_top_p += 2; left_value = result; right_value = ECMA_VALUE_UNDEFINED; /* FALLTHRU */ } case VM_OC_PRE_INCR: case VM_OC_PRE_DECR: case VM_OC_POST_INCR: case VM_OC_POST_DECR: { uint32_t opcode_flags = VM_OC_GROUP_GET_INDEX (opcode_data) - VM_OC_PROP_PRE_INCR; ecma_number_t result_number; byte_code_p = byte_code_start_p + 1; if (ecma_is_value_integer_number (left_value)) { result = left_value; left_value = ECMA_VALUE_UNDEFINED; ecma_integer_value_t int_value = (ecma_integer_value_t) result; ecma_integer_value_t int_increase = 0; if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG) { if (int_value > ECMA_INTEGER_NUMBER_MIN_SHIFTED) { int_increase = -(1 << ECMA_DIRECT_SHIFT); } } else if (int_value < ECMA_INTEGER_NUMBER_MAX_SHIFTED) { int_increase = 1 << ECMA_DIRECT_SHIFT; } if (JERRY_LIKELY (int_increase != 0)) { /* Postfix operators require the unmodifed number value. */ if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG) { POST_INCREASE_DECREASE_PUT_RESULT (result); } result = (ecma_value_t) (int_value + int_increase); break; } result_number = (ecma_number_t) ecma_get_integer_from_value (result); } else if (ecma_is_value_float_number (left_value)) { result = left_value; left_value = ECMA_VALUE_UNDEFINED; result_number = ecma_get_number_from_value (result); } else { result = ecma_op_to_numeric (left_value, &result_number, ECMA_TO_NUMERIC_ALLOW_BIGINT); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_free_value (left_value); left_value = ECMA_VALUE_UNDEFINED; #if JERRY_BUILTIN_BIGINT if (JERRY_UNLIKELY (ecma_is_value_bigint (result))) { ecma_bigint_unary_operation_type operation_type = ECMA_BIGINT_UNARY_INCREASE; if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG) { operation_type = ECMA_BIGINT_UNARY_DECREASE; } /* Postfix operators require the unmodifed number value. */ if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG) { POST_INCREASE_DECREASE_PUT_RESULT (result); result = ecma_bigint_unary (result, operation_type); } else { ecma_value_t original_value = result; result = ecma_bigint_unary (original_value, operation_type); ecma_free_value (original_value); } if (ECMA_IS_VALUE_ERROR (result)) { goto error; } break; } #endif /* JERRY_BUILTIN_BIGINT */ result = ecma_make_number_value (result_number); } ecma_number_t increase = ECMA_NUMBER_ONE; if (opcode_flags & VM_OC_DECREMENT_OPERATOR_FLAG) { /* For decrement operators */ increase = ECMA_NUMBER_MINUS_ONE; } /* Postfix operators require the unmodifed number value. */ if (opcode_flags & VM_OC_POST_INCR_DECR_OPERATOR_FLAG) { POST_INCREASE_DECREASE_PUT_RESULT (result); result = ecma_make_number_value (result_number + increase); break; } if (ecma_is_value_integer_number (result)) { result = ecma_make_number_value (result_number + increase); } else { result = ecma_update_float_number (result, result_number + increase); } break; } case VM_OC_ASSIGN: { result = left_value; left_value = ECMA_VALUE_UNDEFINED; break; } case VM_OC_MOV_IDENT: { uint32_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index < register_end); JERRY_ASSERT (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))); ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); VM_GET_REGISTER (frame_ctx_p, literal_index) = left_value; continue; } case VM_OC_ASSIGN_PROP: { result = stack_top_p[-1]; stack_top_p[-1] = left_value; left_value = ECMA_VALUE_UNDEFINED; break; } case VM_OC_ASSIGN_PROP_THIS: { result = stack_top_p[-1]; stack_top_p[-1] = ecma_copy_value (frame_ctx_p->this_binding); *stack_top_p++ = left_value; left_value = ECMA_VALUE_UNDEFINED; break; } case VM_OC_RETURN_FUNCTION_END: { if (CBC_FUNCTION_GET_TYPE (bytecode_header_p->status_flags) == CBC_FUNCTION_SCRIPT) { result = VM_GET_REGISTER (frame_ctx_p, 0); VM_GET_REGISTERS (frame_ctx_p)[0] = ECMA_VALUE_UNDEFINED; } else { result = ECMA_VALUE_UNDEFINED; } goto error; } case VM_OC_RETURN: { JERRY_ASSERT (opcode == CBC_RETURN || opcode == CBC_RETURN_WITH_LITERAL); result = left_value; left_value = ECMA_VALUE_UNDEFINED; goto error; } case VM_OC_THROW: { jcontext_raise_exception (left_value); result = ECMA_VALUE_ERROR; left_value = ECMA_VALUE_UNDEFINED; goto error; } case VM_OC_THROW_REFERENCE_ERROR: { result = ecma_raise_reference_error (ECMA_ERR_MSG ("Undefined reference")); goto error; } case VM_OC_EVAL: { JERRY_CONTEXT (status_flags) |= ECMA_STATUS_DIRECT_EVAL; JERRY_ASSERT ((*byte_code_p >= CBC_CALL && *byte_code_p <= CBC_CALL2_PROP_BLOCK) || (*byte_code_p == CBC_EXT_OPCODE && byte_code_p[1] >= CBC_EXT_SPREAD_CALL && byte_code_p[1] <= CBC_EXT_SPREAD_CALL_PROP_BLOCK)); continue; } case VM_OC_CALL: { frame_ctx_p->call_operation = VM_EXEC_CALL; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_NEW: { frame_ctx_p->call_operation = VM_EXEC_CONSTRUCT; frame_ctx_p->byte_code_p = byte_code_start_p; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } case VM_OC_ERROR: { JERRY_ASSERT (frame_ctx_p->byte_code_p[1] == CBC_EXT_ERROR); #if JERRY_DEBUGGER frame_ctx_p->byte_code_p = JERRY_CONTEXT (debugger_exception_byte_code_p); #endif /* JERRY_DEBUGGER */ result = ECMA_VALUE_ERROR; goto error; } case VM_OC_RESOLVE_BASE_FOR_CALL: { ecma_value_t this_value = stack_top_p[-3]; if (this_value == ECMA_VALUE_REGISTER_REF) { /* Lexical environment cannot be 'this' value. */ stack_top_p[-2] = ECMA_VALUE_UNDEFINED; stack_top_p[-3] = ECMA_VALUE_UNDEFINED; } else if (vm_get_implicit_this_value (&this_value)) { ecma_free_value (stack_top_p[-3]); stack_top_p[-3] = this_value; } continue; } case VM_OC_PROP_DELETE: { result = vm_op_delete_prop (left_value, right_value, is_strict); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } JERRY_ASSERT (ecma_is_value_boolean (result)); *stack_top_p++ = result; goto free_both_values; } case VM_OC_DELETE: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); if (literal_index < register_end) { *stack_top_p++ = ECMA_VALUE_FALSE; continue; } result = vm_op_delete_var (literal_start_p[literal_index], frame_ctx_p->lex_env_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } JERRY_ASSERT (ecma_is_value_boolean (result)); *stack_top_p++ = result; continue; } case VM_OC_JUMP: { byte_code_p = byte_code_start_p + branch_offset; continue; } case VM_OC_BRANCH_IF_STRICT_EQUAL: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (stack_top_p > VM_GET_REGISTERS (frame_ctx_p) + register_end); if (ecma_op_strict_equality_compare (value, stack_top_p[-1])) { byte_code_p = byte_code_start_p + branch_offset; ecma_free_value (*--stack_top_p); } ecma_free_value (value); continue; } case VM_OC_BRANCH_IF_TRUE: case VM_OC_BRANCH_IF_FALSE: case VM_OC_BRANCH_IF_LOGICAL_TRUE: case VM_OC_BRANCH_IF_LOGICAL_FALSE: { uint32_t opcode_flags = VM_OC_GROUP_GET_INDEX (opcode_data) - VM_OC_BRANCH_IF_TRUE; ecma_value_t value = *(--stack_top_p); bool boolean_value = ecma_op_to_boolean (value); if (opcode_flags & VM_OC_BRANCH_IF_FALSE_FLAG) { boolean_value = !boolean_value; } if (boolean_value) { byte_code_p = byte_code_start_p + branch_offset; if (opcode_flags & VM_OC_LOGICAL_BRANCH_FLAG) { /* "Push" the value back to the stack. */ ++stack_top_p; continue; } } ecma_fast_free_value (value); continue; } #if JERRY_ESNEXT case VM_OC_BRANCH_IF_NULLISH: { left_value = stack_top_p[-1]; if (!ecma_is_value_null (left_value) && !ecma_is_value_undefined (left_value)) { byte_code_p = byte_code_start_p + branch_offset; continue; } --stack_top_p; continue; } #endif /* JERRY_ESNEXT */ case VM_OC_PLUS: case VM_OC_MINUS: { result = opfunc_unary_operation (left_value, VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_PLUS); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_NOT: { *stack_top_p++ = ecma_make_boolean_value (!ecma_op_to_boolean (left_value)); JERRY_ASSERT (ecma_is_value_boolean (stack_top_p[-1])); goto free_left_value; } case VM_OC_BIT_NOT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_is_value_integer_number (left_value)) { *stack_top_p++ = (~ECMA_DIRECT_TYPE_MASK) ^ left_value; goto free_left_value; } result = do_number_bitwise_not (left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_VOID: { *stack_top_p++ = ECMA_VALUE_UNDEFINED; goto free_left_value; } case VM_OC_TYPEOF_IDENT: { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); JERRY_ASSERT (literal_index < ident_end); if (literal_index < register_end) { left_value = ecma_copy_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); } else { ecma_string_t *name_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_object_t *ref_base_lex_env_p; result = ecma_op_get_value_lex_env_base (frame_ctx_p->lex_env_p, &ref_base_lex_env_p, name_p); if (ref_base_lex_env_p == NULL) { jcontext_release_exception (); result = ECMA_VALUE_UNDEFINED; } else if (ECMA_IS_VALUE_ERROR (result)) { goto error; } left_value = result; } /* FALLTHRU */ } case VM_OC_TYPEOF: { result = opfunc_typeof (left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_left_value; } case VM_OC_ADD: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer + right_integer)); continue; } if (ecma_is_value_float_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t new_value = (ecma_get_float_from_value (left_value) + ecma_get_number_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (left_value, new_value); ecma_free_number (right_value); continue; } if (ecma_is_value_float_number (right_value) && ecma_is_value_integer_number (left_value)) { ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) + ecma_get_float_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (right_value, new_value); continue; } result = opfunc_addition (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_SUB: { JERRY_STATIC_ASSERT (ECMA_INTEGER_NUMBER_MAX * 2 <= INT32_MAX && ECMA_INTEGER_NUMBER_MIN * 2 >= INT32_MIN, doubled_ecma_numbers_must_fit_into_int32_range); JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer - right_integer)); continue; } if (ecma_is_value_float_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t new_value = (ecma_get_float_from_value (left_value) - ecma_get_number_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (left_value, new_value); ecma_free_number (right_value); continue; } if (ecma_is_value_float_number (right_value) && ecma_is_value_integer_number (left_value)) { ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) - ecma_get_float_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (right_value, new_value); continue; } result = do_number_arithmetic (NUMBER_ARITHMETIC_SUBTRACTION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_MUL: { JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); JERRY_STATIC_ASSERT (ECMA_INTEGER_MULTIPLY_MAX * ECMA_INTEGER_MULTIPLY_MAX <= ECMA_INTEGER_NUMBER_MAX && -(ECMA_INTEGER_MULTIPLY_MAX * ECMA_INTEGER_MULTIPLY_MAX) >= ECMA_INTEGER_NUMBER_MIN, square_of_integer_multiply_max_must_fit_into_integer_value_range); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); if (-ECMA_INTEGER_MULTIPLY_MAX <= left_integer && left_integer <= ECMA_INTEGER_MULTIPLY_MAX && -ECMA_INTEGER_MULTIPLY_MAX <= right_integer && right_integer <= ECMA_INTEGER_MULTIPLY_MAX && left_integer != 0 && right_integer != 0) { *stack_top_p++ = ecma_integer_multiply (left_integer, right_integer); continue; } ecma_number_t multiply = (ecma_number_t) left_integer * (ecma_number_t) right_integer; *stack_top_p++ = ecma_make_number_value (multiply); continue; } if (ecma_is_value_float_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t new_value = (ecma_get_float_from_value (left_value) * ecma_get_number_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (left_value, new_value); ecma_free_number (right_value); continue; } if (ecma_is_value_float_number (right_value) && ecma_is_value_integer_number (left_value)) { ecma_number_t new_value = ((ecma_number_t) ecma_get_integer_from_value (left_value) * ecma_get_float_from_value (right_value)); *stack_top_p++ = ecma_update_float_number (right_value, new_value); continue; } result = do_number_arithmetic (NUMBER_ARITHMETIC_MULTIPLICATION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_DIV: { JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); result = do_number_arithmetic (NUMBER_ARITHMETIC_DIVISION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_MOD: { JERRY_ASSERT (!ECMA_IS_VALUE_ERROR (left_value) && !ECMA_IS_VALUE_ERROR (right_value)); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); if (right_integer != 0) { ecma_integer_value_t mod_result = left_integer % right_integer; if (mod_result != 0 || left_integer >= 0) { *stack_top_p++ = ecma_make_integer_value (mod_result); continue; } } } result = do_number_arithmetic (NUMBER_ARITHMETIC_REMAINDER, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } #if JERRY_ESNEXT case VM_OC_EXP: { result = do_number_arithmetic (NUMBER_ARITHMETIC_EXPONENTIATION, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } #endif /* JERRY_ESNEXT */ case VM_OC_EQUAL: { result = opfunc_equality (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_NOT_EQUAL: { result = opfunc_equality (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = ecma_invert_boolean_value (result); goto free_both_values; } case VM_OC_STRICT_EQUAL: { bool is_equal = ecma_op_strict_equality_compare (left_value, right_value); result = ecma_make_boolean_value (is_equal); *stack_top_p++ = result; goto free_both_values; } case VM_OC_STRICT_NOT_EQUAL: { bool is_equal = ecma_op_strict_equality_compare (left_value, right_value); result = ecma_make_boolean_value (!is_equal); *stack_top_p++ = result; goto free_both_values; } case VM_OC_BIT_OR: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { *stack_top_p++ = left_value | right_value; continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_OR, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_BIT_XOR: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { *stack_top_p++ = left_value ^ right_value; continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_XOR, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_BIT_AND: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { *stack_top_p++ = left_value & right_value; continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_LOGIC_AND, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_LEFT_SHIFT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_int32_value ((int32_t) (left_integer << (right_integer & 0x1f))); continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_LEFT, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_RIGHT_SHIFT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_integer_value (left_integer >> (right_integer & 0x1f)); continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_RIGHT, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_UNS_RIGHT_SHIFT: { JERRY_STATIC_ASSERT (ECMA_DIRECT_TYPE_MASK == ((1 << ECMA_DIRECT_SHIFT) - 1), direct_type_mask_must_fill_all_bits_before_the_value_starts); if (ecma_are_values_integer_numbers (left_value, right_value)) { uint32_t left_uint32 = (uint32_t) ecma_get_integer_from_value (left_value); ecma_integer_value_t right_integer = ecma_get_integer_from_value (right_value); *stack_top_p++ = ecma_make_uint32_value (left_uint32 >> (right_integer & 0x1f)); continue; } result = do_number_bitwise_logic (NUMBER_BITWISE_SHIFT_URIGHT, left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_LESS: { if (ecma_are_values_integer_numbers (left_value, right_value)) { bool is_less = (ecma_integer_value_t) left_value < (ecma_integer_value_t) right_value; #if !JERRY_VM_EXEC_STOP /* This is a lookahead to the next opcode to improve performance. * If it is CBC_BRANCH_IF_TRUE_BACKWARD, execute it. */ if (*byte_code_p <= CBC_BRANCH_IF_TRUE_BACKWARD_3 && *byte_code_p >= CBC_BRANCH_IF_TRUE_BACKWARD) { byte_code_start_p = byte_code_p++; branch_offset_length = CBC_BRANCH_OFFSET_LENGTH (*byte_code_start_p); JERRY_ASSERT (branch_offset_length >= 1 && branch_offset_length <= 3); if (is_less) { branch_offset = *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length != 1)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); if (JERRY_UNLIKELY (branch_offset_length == 3)) { branch_offset <<= 8; branch_offset |= *(byte_code_p++); } } /* Note: The opcode is a backward branch. */ byte_code_p = byte_code_start_p - branch_offset; } else { byte_code_p += branch_offset_length; } continue; } #endif /* !JERRY_VM_EXEC_STOP */ *stack_top_p++ = ecma_make_boolean_value (is_less); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number < right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, true, false); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_GREATER: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value; ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value; *stack_top_p++ = ecma_make_boolean_value (left_integer > right_integer); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number > right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, false, false); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_LESS_EQUAL: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value; ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value; *stack_top_p++ = ecma_make_boolean_value (left_integer <= right_integer); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number <= right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, false, true); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_GREATER_EQUAL: { if (ecma_are_values_integer_numbers (left_value, right_value)) { ecma_integer_value_t left_integer = (ecma_integer_value_t) left_value; ecma_integer_value_t right_integer = (ecma_integer_value_t) right_value; *stack_top_p++ = ecma_make_boolean_value (left_integer >= right_integer); continue; } if (ecma_is_value_number (left_value) && ecma_is_value_number (right_value)) { ecma_number_t left_number = ecma_get_number_from_value (left_value); ecma_number_t right_number = ecma_get_number_from_value (right_value); *stack_top_p++ = ecma_make_boolean_value (left_number >= right_number); goto free_both_values; } result = opfunc_relation (left_value, right_value, true, true); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_IN: { result = opfunc_in (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_INSTANCEOF: { result = opfunc_instanceof (left_value, right_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; goto free_both_values; } case VM_OC_BLOCK_CREATE_CONTEXT: { #if JERRY_ESNEXT ecma_value_t *stack_context_top_p; stack_context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; JERRY_ASSERT (stack_context_top_p == stack_top_p || stack_context_top_p == stack_top_p - 1); if (byte_code_start_p[0] != CBC_EXT_OPCODE) { branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); if (stack_context_top_p != stack_top_p) { /* Preserve the value of switch statement. */ stack_context_top_p[1] = stack_context_top_p[0]; } stack_context_top_p[0] = VM_CREATE_CONTEXT_WITH_ENV (VM_CONTEXT_BLOCK, branch_offset); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_BLOCK_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_BLOCK_CONTEXT_STACK_ALLOCATION; } else { JERRY_ASSERT (byte_code_start_p[1] == CBC_EXT_TRY_CREATE_ENV); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_TRY || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_CATCH || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_THROW || VM_GET_CONTEXT_TYPE (stack_context_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN); JERRY_ASSERT (!(stack_context_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV)); stack_context_top_p[-1] |= VM_CONTEXT_HAS_LEX_ENV; } #else /* !JERRY_ESNEXT */ JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-2]) == VM_CONTEXT_CATCH && !(stack_top_p[-2] & VM_CONTEXT_HAS_LEX_ENV)); stack_top_p[-2] |= VM_CONTEXT_HAS_LEX_ENV; #endif /* JERRY_ESNEXT */ frame_ctx_p->lex_env_p = ecma_create_decl_lex_env (frame_ctx_p->lex_env_p); frame_ctx_p->lex_env_p->type_flags_refs |= ECMA_OBJECT_FLAG_BLOCK; continue; } case VM_OC_WITH: { ecma_value_t value = *(--stack_top_p); ecma_object_t *object_p; ecma_object_t *with_env_p; branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); result = ecma_op_to_object (value); ecma_free_value (value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } object_p = ecma_get_object_from_value (result); with_env_p = ecma_create_object_lex_env (frame_ctx_p->lex_env_p, object_p); ecma_deref_object (object_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_WITH_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_WITH_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT_WITH_ENV (VM_CONTEXT_WITH, branch_offset); with_env_p->type_flags_refs |= ECMA_OBJECT_FLAG_BLOCK; frame_ctx_p->lex_env_p = with_env_p; continue; } case VM_OC_FOR_IN_INIT: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_value_t expr_obj_value = ECMA_VALUE_UNDEFINED; ecma_collection_t *prop_names_p = opfunc_for_in (value, &expr_obj_value); ecma_free_value (value); if (prop_names_p == NULL) { #if JERRY_ESNEXT if (JERRY_UNLIKELY (ECMA_IS_VALUE_ERROR (expr_obj_value))) { result = expr_obj_value; goto error; } #endif /* JERRY_ESNEXT */ /* The collection is already released */ byte_code_p = byte_code_start_p + branch_offset; continue; } branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_IN, branch_offset); ECMA_SET_INTERNAL_VALUE_ANY_POINTER (stack_top_p[-2], prop_names_p); stack_top_p[-3] = 0; stack_top_p[-4] = expr_obj_value; #if JERRY_ESNEXT if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT) { /* No need to duplicate the first context. */ byte_code_p += 2; } #endif /* JERRY_ESNEXT */ continue; } case VM_OC_FOR_IN_GET_NEXT: { ecma_value_t *context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; ecma_collection_t *collection_p; collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, context_top_p[-2]); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_IN); uint32_t index = context_top_p[-3]; ecma_value_t *buffer_p = collection_p->buffer_p; *stack_top_p++ = buffer_p[index]; context_top_p[-3]++; continue; } case VM_OC_FOR_IN_HAS_NEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_collection_t *collection_p; collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, stack_top_p[-2]); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_IN); ecma_value_t *buffer_p = collection_p->buffer_p; ecma_object_t *object_p = ecma_get_object_from_value (stack_top_p[-4]); uint32_t index = stack_top_p[-3]; while (index < collection_p->item_count) { ecma_string_t *prop_name_p = ecma_get_prop_name_from_value (buffer_p[index]); result = ecma_op_object_has_property (object_p, prop_name_p); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } if (JERRY_LIKELY (ecma_is_value_true (result))) { byte_code_p = byte_code_start_p + branch_offset; break; } ecma_deref_ecma_string (prop_name_p); index++; } if (index == collection_p->item_count) { ecma_deref_object (object_p); ecma_collection_destroy (collection_p); VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION); stack_top_p -= PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION; } else { stack_top_p[-3] = index; } continue; } #if JERRY_ESNEXT case VM_OC_FOR_OF_INIT: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_value_t next_method; ecma_value_t iterator = ecma_op_get_iterator (value, ECMA_VALUE_SYNC_ITERATOR, &next_method); ecma_free_value (value); if (ECMA_IS_VALUE_ERROR (iterator)) { result = iterator; goto error; } result = ecma_op_iterator_step (iterator, next_method); if (ECMA_IS_VALUE_ERROR (result)) { ecma_free_value (iterator); ecma_free_value (next_method); goto error; } if (ecma_is_value_false (result)) { ecma_free_value (iterator); ecma_free_value (next_method); byte_code_p = byte_code_start_p + branch_offset; continue; } ecma_value_t next_value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (next_value)) { result = next_value; ecma_free_value (iterator); ecma_free_value (next_method); goto error; } branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_OF, branch_offset) | VM_CONTEXT_CLOSE_ITERATOR; stack_top_p[-2] = next_value; stack_top_p[-3] = iterator; stack_top_p[-4] = next_method; if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT) { /* No need to duplicate the first context. */ byte_code_p += 2; } continue; } case VM_OC_FOR_OF_GET_NEXT: { ecma_value_t *context_top_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_OF || VM_GET_CONTEXT_TYPE (context_top_p[-1]) == VM_CONTEXT_FOR_AWAIT_OF); JERRY_ASSERT (context_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR); *stack_top_p++ = context_top_p[-2]; context_top_p[-2] = ECMA_VALUE_UNDEFINED; continue; } case VM_OC_FOR_OF_HAS_NEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_OF); JERRY_ASSERT (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR); stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = ecma_op_iterator_step (stack_top_p[-3], stack_top_p[-4]); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } if (ecma_is_value_false (result)) { ecma_free_value (stack_top_p[-2]); ecma_free_value (stack_top_p[-3]); ecma_free_value (stack_top_p[-4]); VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION); stack_top_p -= PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION; continue; } ecma_value_t next_value = ecma_op_iterator_value (result); ecma_free_value (result); if (ECMA_IS_VALUE_ERROR (next_value)) { result = next_value; goto error; } JERRY_ASSERT (stack_top_p[-2] == ECMA_VALUE_UNDEFINED); stack_top_p[-1] |= VM_CONTEXT_CLOSE_ITERATOR; stack_top_p[-2] = next_value; byte_code_p = byte_code_start_p + branch_offset; continue; } case VM_OC_FOR_AWAIT_OF_INIT: { ecma_value_t value = *(--stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); ecma_value_t next_method; result = ecma_op_get_iterator (value, ECMA_VALUE_ASYNC_ITERATOR, &next_method); ecma_free_value (value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_value_t iterator = result; result = ecma_op_iterator_next (result, next_method, ECMA_VALUE_EMPTY); if (ECMA_IS_VALUE_ERROR (result)) { ecma_free_value (iterator); ecma_free_value (next_method); goto error; } branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FOR_AWAIT_OF_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_FOR_AWAIT_OF_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FOR_AWAIT_OF, branch_offset); stack_top_p[-2] = ECMA_VALUE_UNDEFINED; stack_top_p[-3] = iterator; stack_top_p[-4] = next_method; if (byte_code_p[0] == CBC_EXT_OPCODE && byte_code_p[1] == CBC_EXT_CLONE_CONTEXT) { /* No need to duplicate the first context. */ byte_code_p += 2; } frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_p; frame_ctx_p->stack_top_p = stack_top_p; uint16_t extra_flags = (ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD | (ECMA_AWAIT_FOR_NEXT << ECMA_AWAIT_STATE_SHIFT)); if (CBC_FUNCTION_GET_TYPE (bytecode_header_p->status_flags) == CBC_FUNCTION_ASYNC_GENERATOR || (frame_ctx_p->shared_p->status_flags & VM_FRAME_CTX_SHARED_EXECUTABLE)) { ecma_extended_object_t *executable_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); result = ecma_promise_async_await (executable_object_p, result); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } executable_object_p->u.cls.u2.executable_obj_flags |= extra_flags; return ECMA_VALUE_UNDEFINED; } result = opfunc_async_create_and_await (frame_ctx_p, result, extra_flags); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } return result; } case VM_OC_FOR_AWAIT_OF_HAS_NEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FOR_AWAIT_OF); JERRY_ASSERT (stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR); stack_top_p[-1] &= (uint32_t) ~VM_CONTEXT_CLOSE_ITERATOR; result = ecma_op_iterator_next (stack_top_p[-3], stack_top_p[-4], ECMA_VALUE_EMPTY); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } ecma_extended_object_t *executable_object_p = VM_GET_EXECUTABLE_OBJECT (frame_ctx_p); result = ecma_promise_async_await (executable_object_p, result); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } uint16_t extra_flags = (ECMA_EXECUTABLE_OBJECT_DO_AWAIT_OR_YIELD | (ECMA_AWAIT_FOR_NEXT << ECMA_AWAIT_STATE_SHIFT)); executable_object_p->u.cls.u2.executable_obj_flags |= extra_flags; frame_ctx_p->call_operation = VM_EXEC_RETURN; frame_ctx_p->byte_code_p = byte_code_start_p + branch_offset; frame_ctx_p->stack_top_p = stack_top_p; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ case VM_OC_TRY: { /* Try opcode simply creates the try context. */ branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_TRY_CONTEXT_STACK_ALLOCATION); stack_top_p += PARSER_TRY_CONTEXT_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_TRY, branch_offset); continue; } case VM_OC_CATCH: { /* Catches are ignored and turned to jumps. */ JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_TRY); byte_code_p = byte_code_start_p + branch_offset; continue; } case VM_OC_FINALLY: { branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_TRY || VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_CATCH); if (stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV) { ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); frame_ctx_p->lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); ecma_deref_object (lex_env_p); } VM_PLUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FINALLY_CONTEXT_EXTRA_STACK_ALLOCATION); stack_top_p += PARSER_FINALLY_CONTEXT_EXTRA_STACK_ALLOCATION; stack_top_p[-1] = VM_CREATE_CONTEXT (VM_CONTEXT_FINALLY_JUMP, branch_offset); stack_top_p[-2] = (ecma_value_t) branch_offset; continue; } case VM_OC_CONTEXT_END: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (!(stack_top_p[-1] & VM_CONTEXT_CLOSE_ITERATOR)); ecma_value_t context_type = VM_GET_CONTEXT_TYPE (stack_top_p[-1]); if (!VM_CONTEXT_IS_FINALLY (context_type)) { stack_top_p = vm_stack_context_abort (frame_ctx_p, stack_top_p); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); continue; } #if JERRY_ESNEXT if (stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV) { ecma_object_t *lex_env_p = frame_ctx_p->lex_env_p; JERRY_ASSERT (lex_env_p->u2.outer_reference_cp != JMEM_CP_NULL); frame_ctx_p->lex_env_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, lex_env_p->u2.outer_reference_cp); ecma_deref_object (lex_env_p); } #endif /* JERRY_ESNEXT */ VM_MINUS_EQUAL_U16 (frame_ctx_p->context_depth, PARSER_FINALLY_CONTEXT_STACK_ALLOCATION); stack_top_p -= PARSER_FINALLY_CONTEXT_STACK_ALLOCATION; if (context_type == VM_CONTEXT_FINALLY_RETURN) { result = *stack_top_p; goto error; } if (context_type == VM_CONTEXT_FINALLY_THROW) { jcontext_raise_exception (*stack_top_p); #if JERRY_VM_THROW JERRY_CONTEXT (status_flags) |= ECMA_STATUS_ERROR_THROWN; #endif /* JERRY_VM_THROW */ result = ECMA_VALUE_ERROR; #if JERRY_DEBUGGER JERRY_DEBUGGER_SET_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN); #endif /* JERRY_DEBUGGER */ goto error; } JERRY_ASSERT (context_type == VM_CONTEXT_FINALLY_JUMP); uint32_t jump_target = *stack_top_p; vm_stack_found_type type = vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_JUMP, jump_target); stack_top_p = frame_ctx_p->stack_top_p; switch (type) { case VM_CONTEXT_FOUND_FINALLY: { byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = jump_target; break; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_ERROR: { JERRY_ASSERT (jcontext_has_pending_exception ()); result = ECMA_VALUE_ERROR; goto error; } case VM_CONTEXT_FOUND_AWAIT: { JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = jump_target; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { byte_code_p = frame_ctx_p->byte_code_start_p + jump_target; break; } } JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); continue; } case VM_OC_JUMP_AND_EXIT_CONTEXT: { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (!jcontext_has_pending_exception ()); branch_offset += (int32_t) (byte_code_start_p - frame_ctx_p->byte_code_start_p); vm_stack_found_type type = vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_JUMP, (uint32_t) branch_offset); stack_top_p = frame_ctx_p->stack_top_p; switch (type) { case VM_CONTEXT_FOUND_FINALLY: { byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = (uint32_t) branch_offset; break; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_ERROR: { JERRY_ASSERT (jcontext_has_pending_exception ()); result = ECMA_VALUE_ERROR; goto error; } case VM_CONTEXT_FOUND_AWAIT: { JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_JUMP); stack_top_p[-2] = (uint32_t) branch_offset; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { byte_code_p = frame_ctx_p->byte_code_start_p + branch_offset; break; } } JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); continue; } #if JERRY_MODULE_SYSTEM case VM_OC_MODULE_IMPORT: { left_value = *(--stack_top_p); ecma_value_t user_value = ECMA_VALUE_UNDEFINED; ecma_value_t script_value = ((cbc_uint8_arguments_t *) bytecode_header_p)->script_value; #if JERRY_SNAPSHOT_EXEC if (JERRY_UNLIKELY (!(bytecode_header_p->status_flags & CBC_CODE_FLAGS_STATIC_FUNCTION))) { #endif /* JERRY_SNAPSHOT_EXEC */ cbc_script_t *script_p = ECMA_GET_INTERNAL_VALUE_POINTER (cbc_script_t, script_value); if (script_p->refs_and_type & CBC_SCRIPT_HAS_USER_VALUE) { user_value = CBC_SCRIPT_GET_USER_VALUE (script_p); } #if JERRY_SNAPSHOT_EXEC } #endif /* JERRY_SNAPSHOT_EXEC */ result = ecma_module_import (left_value, user_value); ecma_free_value (left_value); if (ECMA_IS_VALUE_ERROR (result)) { goto error; } *stack_top_p++ = result; continue; } case VM_OC_MODULE_IMPORT_META: { ecma_value_t script_value = ((cbc_uint8_arguments_t *) bytecode_header_p)->script_value; cbc_script_t *script_p = ECMA_GET_INTERNAL_VALUE_POINTER (cbc_script_t, script_value); JERRY_ASSERT (script_p->refs_and_type & CBC_SCRIPT_HAS_IMPORT_META); ecma_value_t import_meta = CBC_SCRIPT_GET_IMPORT_META (script_p, script_p->refs_and_type); ecma_object_t *import_meta_object_p = ecma_get_object_from_value (import_meta); if (ecma_get_object_type (import_meta_object_p) != ECMA_OBJECT_TYPE_GENERAL) { JERRY_ASSERT (ecma_object_class_is (import_meta_object_p, ECMA_OBJECT_CLASS_MODULE)); ecma_value_t module = import_meta; import_meta_object_p = ecma_create_object (NULL, 0, ECMA_OBJECT_TYPE_GENERAL); import_meta = ecma_make_object_value (import_meta_object_p); if (JERRY_CONTEXT (module_import_meta_callback_p) != NULL) { void *user_p = JERRY_CONTEXT (module_import_meta_callback_user_p); JERRY_CONTEXT (module_import_meta_callback_p) (module, import_meta, user_p); } CBC_SCRIPT_GET_IMPORT_META (script_p, script_p->refs_and_type) = import_meta; } else { ecma_ref_object (import_meta_object_p); } *stack_top_p++ = import_meta; continue; } #endif /* JERRY_MODULE_SYSTEM */ #if JERRY_DEBUGGER case VM_OC_BREAKPOINT_ENABLED: { if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_IGNORE) { continue; } JERRY_ASSERT (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED); JERRY_ASSERT (!(frame_ctx_p->shared_p->bytecode_header_p->status_flags & CBC_CODE_FLAGS_DEBUGGER_IGNORE)); frame_ctx_p->byte_code_p = byte_code_start_p; jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { result = ECMA_VALUE_ERROR; goto error; } continue; } case VM_OC_BREAKPOINT_DISABLED: { if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_IGNORE) { continue; } JERRY_ASSERT (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED); JERRY_ASSERT (!(frame_ctx_p->shared_p->bytecode_header_p->status_flags & CBC_CODE_FLAGS_DEBUGGER_IGNORE)); frame_ctx_p->byte_code_p = byte_code_start_p; if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_STOP) && (JERRY_CONTEXT (debugger_stop_context) == NULL || JERRY_CONTEXT (debugger_stop_context) == JERRY_CONTEXT (vm_top_context_p))) { jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { result = ECMA_VALUE_ERROR; goto error; } continue; } if (JERRY_CONTEXT (debugger_message_delay) > 0) { JERRY_CONTEXT (debugger_message_delay)--; continue; } JERRY_CONTEXT (debugger_message_delay) = JERRY_DEBUGGER_MESSAGE_FREQUENCY; if (jerry_debugger_receive (NULL)) { continue; } if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_STOP) && (JERRY_CONTEXT (debugger_stop_context) == NULL || JERRY_CONTEXT (debugger_stop_context) == JERRY_CONTEXT (vm_top_context_p))) { jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_BREAKPOINT_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { result = ECMA_VALUE_ERROR; goto error; } } continue; } #endif /* JERRY_DEBUGGER */ case VM_OC_NONE: default: { JERRY_ASSERT (VM_OC_GROUP_GET_INDEX (opcode_data) == VM_OC_NONE); jerry_fatal (ERR_DISABLED_BYTE_CODE); } } JERRY_ASSERT (VM_OC_HAS_PUT_RESULT (opcode_data)); if (opcode_data & VM_OC_PUT_IDENT) { uint16_t literal_index; READ_LITERAL_INDEX (literal_index); if (literal_index < register_end) { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, literal_index)); VM_GET_REGISTER (frame_ctx_p, literal_index) = result; if (opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK)) { result = ecma_fast_copy_value (result); } } else { ecma_string_t *var_name_str_p = ecma_get_string_from_value (literal_start_p[literal_index]); ecma_value_t put_value_result = ecma_op_put_value_lex_env_base (frame_ctx_p->lex_env_p, var_name_str_p, is_strict, result); if (ECMA_IS_VALUE_ERROR (put_value_result)) { ecma_free_value (result); result = put_value_result; goto error; } if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))) { ecma_fast_free_value (result); } } } else if (opcode_data & VM_OC_PUT_REFERENCE) { ecma_value_t property = *(--stack_top_p); ecma_value_t base = *(--stack_top_p); if (base == ECMA_VALUE_REGISTER_REF) { property = (ecma_value_t) ecma_get_integer_from_value (property); ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, property)); VM_GET_REGISTER (frame_ctx_p, property) = result; if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))) { goto free_both_values; } result = ecma_fast_copy_value (result); } else { ecma_value_t set_value_result = vm_op_set_value (base, property, result, is_strict); if (ECMA_IS_VALUE_ERROR (set_value_result)) { ecma_free_value (result); result = set_value_result; goto error; } if (!(opcode_data & (VM_OC_PUT_STACK | VM_OC_PUT_BLOCK))) { ecma_fast_free_value (result); goto free_both_values; } } } if (opcode_data & VM_OC_PUT_STACK) { *stack_top_p++ = result; } else if (opcode_data & VM_OC_PUT_BLOCK) { ecma_fast_free_value (VM_GET_REGISTER (frame_ctx_p, 0)); VM_GET_REGISTERS (frame_ctx_p)[0] = result; } free_both_values: ecma_fast_free_value (right_value); free_left_value: ecma_fast_free_value (left_value); } error: ecma_fast_free_value (left_value); ecma_fast_free_value (right_value); if (ECMA_IS_VALUE_ERROR (result)) { JERRY_ASSERT (jcontext_has_pending_exception ()); ecma_value_t *stack_bottom_p = VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth; while (stack_top_p > stack_bottom_p) { ecma_value_t stack_item = *(--stack_top_p); #if JERRY_ESNEXT if (stack_item == ECMA_VALUE_RELEASE_LEX_ENV) { opfunc_pop_lexical_environment (frame_ctx_p); continue; } #endif /* JERRY_ESNEXT */ ecma_fast_free_value (stack_item); } #if JERRY_VM_THROW if (!(JERRY_CONTEXT (status_flags) & ECMA_STATUS_ERROR_THROWN)) { JERRY_CONTEXT (status_flags) |= ECMA_STATUS_ERROR_THROWN; jerry_vm_throw_callback_t vm_throw_callback_p = JERRY_CONTEXT (vm_throw_callback_p); if (vm_throw_callback_p != NULL) { vm_throw_callback_p (JERRY_CONTEXT (error_value), JERRY_CONTEXT (vm_throw_callback_user_p)); } } #endif /* JERRY_VM_THROW */ #if JERRY_DEBUGGER const uint32_t dont_stop = (JERRY_DEBUGGER_VM_IGNORE_EXCEPTION | JERRY_DEBUGGER_VM_IGNORE | JERRY_DEBUGGER_VM_EXCEPTION_THROWN); if ((JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) && !(frame_ctx_p->shared_p->bytecode_header_p->status_flags & (CBC_CODE_FLAGS_DEBUGGER_IGNORE | CBC_CODE_FLAGS_STATIC_FUNCTION)) && !(JERRY_CONTEXT (debugger_flags) & dont_stop)) { /* Save the error to a local value, because the engine enters breakpoint mode after, therefore an evaluation error, or user-created error throw would overwrite it. */ ecma_value_t current_error_value = JERRY_CONTEXT (error_value); if (jerry_debugger_send_exception_string (current_error_value)) { jerry_debugger_breakpoint_hit (JERRY_DEBUGGER_EXCEPTION_HIT); if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_VM_EXCEPTION_THROWN) { ecma_free_value (current_error_value); } else { JERRY_CONTEXT (error_value) = current_error_value; } JERRY_DEBUGGER_SET_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN); } } #endif /* JERRY_DEBUGGER */ } JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); if (frame_ctx_p->context_depth == 0) { /* In most cases there is no context. */ frame_ctx_p->call_operation = VM_NO_EXEC_OP; return result; } if (!ECMA_IS_VALUE_ERROR (result)) { switch (vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_RETURN, 0)) { case VM_CONTEXT_FOUND_FINALLY: { stack_top_p = frame_ctx_p->stack_top_p; byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN); JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); stack_top_p[-2] = result; continue; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_ERROR: { JERRY_ASSERT (jcontext_has_pending_exception ()); ecma_free_value (result); stack_top_p = frame_ctx_p->stack_top_p; result = ECMA_VALUE_ERROR; break; } case VM_CONTEXT_FOUND_AWAIT: { stack_top_p = frame_ctx_p->stack_top_p; JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_RETURN); stack_top_p[-2] = result; return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { goto finish; } } } JERRY_ASSERT (jcontext_has_pending_exception ()); if (!jcontext_has_pending_abort ()) { switch (vm_stack_find_finally (frame_ctx_p, stack_top_p, VM_CONTEXT_FINALLY_THROW, 0)) { case VM_CONTEXT_FOUND_FINALLY: { stack_top_p = frame_ctx_p->stack_top_p; byte_code_p = frame_ctx_p->byte_code_p; JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); JERRY_ASSERT (!(stack_top_p[-1] & VM_CONTEXT_HAS_LEX_ENV)); #if JERRY_DEBUGGER JERRY_DEBUGGER_CLEAR_FLAGS (JERRY_DEBUGGER_VM_EXCEPTION_THROWN); #endif /* JERRY_DEBUGGER */ result = jcontext_take_exception (); if (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_FINALLY_THROW) { stack_top_p[-2] = result; continue; } JERRY_ASSERT (VM_GET_CONTEXT_TYPE (stack_top_p[-1]) == VM_CONTEXT_CATCH); *stack_top_p++ = result; continue; } #if JERRY_ESNEXT case VM_CONTEXT_FOUND_AWAIT: { JERRY_ASSERT (VM_GET_CONTEXT_TYPE (frame_ctx_p->stack_top_p[-1]) == VM_CONTEXT_FINALLY_THROW); return ECMA_VALUE_UNDEFINED; } #endif /* JERRY_ESNEXT */ default: { break; } } } else { do { JERRY_ASSERT (VM_GET_REGISTERS (frame_ctx_p) + register_end + frame_ctx_p->context_depth == stack_top_p); stack_top_p = vm_stack_context_abort (frame_ctx_p, stack_top_p); } while (frame_ctx_p->context_depth > 0); } finish: frame_ctx_p->call_operation = VM_NO_EXEC_OP; return result; } } /* vm_loop */
null
null
197,989
117248586394637887953246786581777711038
3,977
Fix for-in collection cleanup on abrupt 'has' result (#4807) This patch fixes #4747 JerryScript-DCO-1.0-Signed-off-by: Robert Fancsik [email protected]
other
tensorflow
e86605c0a336c088b638da02135ea6f9f6753618
1
void Compute(OpKernelContext* ctx) override { auto x = ctx->input(0); auto i = ctx->input(1); auto v = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(i.shape()), errors::InvalidArgument("i must be a vector. ", i.shape().DebugString())); OP_REQUIRES(ctx, x.dims() == v.dims(), errors::InvalidArgument( "x and v shape doesn't match (ranks differ): ", x.shape().DebugString(), " vs. ", v.shape().DebugString())); for (int i = 1; i < x.dims(); ++i) { OP_REQUIRES( ctx, x.dim_size(i) == v.dim_size(i), errors::InvalidArgument("x and v shape doesn't match at index ", i, " : ", x.shape().DebugString(), " vs. ", v.shape().DebugString())); } OP_REQUIRES(ctx, i.dim_size(0) == v.dim_size(0), errors::InvalidArgument( "i and x shape doesn't match at index 0: ", i.shape().DebugString(), " vs. ", v.shape().DebugString())); Tensor y = x; // This creates an alias intentionally. // Skip processing if tensors are empty. if (x.NumElements() > 0 || v.NumElements() > 0) { OP_REQUIRES_OK(ctx, DoCompute(ctx, i, v, &y)); } ctx->set_output(0, y); }
null
null
198,003
93663684494140260682969182544172664356
31
Fix FPE in inpace update ops. PiperOrigin-RevId: 388303197 Change-Id: Ib48309b6213ffe53eba81004b00e889d653e4b83
other
gpac
d7daa8aeb6df4b6c3ec102622e1599279310a19e
1
GF_Err gf_isom_get_sample_for_movie_time(GF_ISOFile *the_file, u32 trackNumber, u64 movieTime, u32 *StreamDescriptionIndex, GF_ISOSearchMode SearchMode, GF_ISOSample **sample, u32 *sampleNumber, u64 *data_offset) { Double tsscale; GF_Err e; GF_TrackBox *trak; u64 mediaTime, nextMediaTime; s64 segStartTime, mediaOffset; u32 sampNum; u8 useEdit; trak = gf_isom_get_track_from_file(the_file, trackNumber); if (!trak) return GF_BAD_PARAM; //only check duration if initially set - do not check duration as updated after fragment merge since that duration does not take //into account tfdt if (trak->Header->initial_duration && gf_timestamp_greater(movieTime, trak->Media->mediaHeader->timeScale, trak->Header->initial_duration, trak->moov->mvhd->timeScale) ) { if (sampleNumber) *sampleNumber = 0; *StreamDescriptionIndex = 0; return GF_EOS; } //get the media time for this movie time... mediaTime = segStartTime = 0; *StreamDescriptionIndex = 0; nextMediaTime = 0; e = GetMediaTime(trak, (SearchMode==GF_ISOM_SEARCH_SYNC_FORWARD) ? GF_TRUE : GF_FALSE, movieTime, &mediaTime, &segStartTime, &mediaOffset, &useEdit, &nextMediaTime); if (e) return e; /*here we check if we were playing or not and return no sample in normal search modes*/ if (useEdit && mediaOffset == -1) { if ((SearchMode==GF_ISOM_SEARCH_FORWARD) || (SearchMode==GF_ISOM_SEARCH_BACKWARD)) { /*get next sample time in MOVIE timescale*/ if (SearchMode==GF_ISOM_SEARCH_FORWARD) e = GetNextMediaTime(trak, movieTime, &mediaTime); else e = GetPrevMediaTime(trak, movieTime, &mediaTime); if (e) return e; return gf_isom_get_sample_for_movie_time(the_file, trackNumber, (u32) mediaTime, StreamDescriptionIndex, GF_ISOM_SEARCH_SYNC_FORWARD, sample, sampleNumber, data_offset); } if (sampleNumber) *sampleNumber = 0; if (sample) { if (! (*sample)) { *sample = gf_isom_sample_new(); if (! *sample) return GF_OUT_OF_MEM; } (*sample)->DTS = movieTime; (*sample)->dataLength = 0; (*sample)->CTS_Offset = 0; } return GF_OK; } /*dwell edit in non-sync mode, fetch next/prev sample depending on mode. Otherwise return the dwell entry*/ if (useEdit==2) { if ((SearchMode==GF_ISOM_SEARCH_FORWARD) || (SearchMode==GF_ISOM_SEARCH_BACKWARD)) { /*get next sample time in MOVIE timescale*/ if (SearchMode==GF_ISOM_SEARCH_FORWARD) e = GetNextMediaTime(trak, movieTime, &mediaTime); else e = GetPrevMediaTime(trak, movieTime, &mediaTime); if (e) return e; return gf_isom_get_sample_for_movie_time(the_file, trackNumber, (u32) mediaTime, StreamDescriptionIndex, GF_ISOM_SEARCH_SYNC_FORWARD, sample, sampleNumber, data_offset); } } tsscale = trak->Media->mediaHeader->timeScale; tsscale /= trak->moov->mvhd->timeScale; //OK, we have a sample so fetch it e = gf_isom_get_sample_for_media_time(the_file, trackNumber, mediaTime, StreamDescriptionIndex, SearchMode, sample, &sampNum, data_offset); if (e) { if (e==GF_EOS) { #ifndef GPAC_DISABLE_ISOM_FRAGMENTS //movie is fragmented and samples not yet received, return EOS if (the_file->moov->mvex && !trak->Media->information->sampleTable->SampleSize->sampleCount) return e; #endif if (nextMediaTime && (nextMediaTime-1 != movieTime)) return gf_isom_get_sample_for_movie_time(the_file, trackNumber, nextMediaTime-1, StreamDescriptionIndex, SearchMode, sample, sampleNumber, data_offset); } return e; } //OK, now the trick: we have to rebuild the time stamps, according //to the media time scale (used by SLConfig) - add the edit start time but stay in //the track TS if (sample && useEdit) { u64 _ts = (u64)(segStartTime * tsscale); (*sample)->DTS += _ts; /*watchout, the sample fetched may be before the first sample in the edit list (when seeking)*/ if ( (*sample)->DTS > (u64) mediaOffset) { (*sample)->DTS -= (u64) mediaOffset; } else { (*sample)->DTS = 0; } } if (sampleNumber) *sampleNumber = sampNum; #ifndef GPAC_DISABLE_ISOM_FRAGMENTS if (sample && (*sample) ) (*sample)->DTS += trak->dts_at_seg_start; #endif return GF_OK; }
null
null
198,178
148501486251921845480245286379253106973
108
fixed #2108
other
mruby
00acae117da1b45b318dc36531a7b0021b8097ae
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->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); }
null
null
198,512
251133800800873458523255728173671147403
1,828
vm.c: target class may be NULL.
other
tensorflow
5ecec9c6fbdbc6be03295685190a45e7eee726ab
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); } }
null
null
198,523
201044185104134614142321846533666874996
28
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
other
engine
7df766124f87768b43b9e8947c5a01e17545772c
1
static int pkey_GOST_ECcp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { GOST_KEY_TRANSPORT *gkt = NULL; EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx); struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx); int pkey_nid = EVP_PKEY_base_id(pubk); ASN1_OBJECT *crypt_params_obj = (pkey_nid == NID_id_GostR3410_2001 || pkey_nid == NID_id_GostR3410_2001DH) ? OBJ_nid2obj(NID_id_Gost28147_89_CryptoPro_A_ParamSet) : OBJ_nid2obj(NID_id_tc26_gost_28147_param_Z); const struct gost_cipher_info *param = get_encryption_params(crypt_params_obj); unsigned char ukm[8], shared_key[32], crypted_key[44]; int ret = 0; int key_is_ephemeral = 1; gost_ctx cctx; EVP_PKEY *sec_key = EVP_PKEY_CTX_get0_peerkey(pctx); if (data->shared_ukm_size) { memcpy(ukm, data->shared_ukm, 8); } else { if (RAND_bytes(ukm, 8) <= 0) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR); return 0; } } if (!param) goto err; /* Check for private key in the peer_key of context */ if (sec_key) { key_is_ephemeral = 0; if (!gost_get0_priv_key(sec_key)) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR); goto err; } } else { key_is_ephemeral = 1; if (out) { sec_key = EVP_PKEY_new(); if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new()) || !EVP_PKEY_copy_parameters(sec_key, pubk) || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_ERROR_COMPUTING_SHARED_KEY); goto err; } } } if (out) { int dgst_nid = NID_undef; EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid); if (dgst_nid == NID_id_GostR3411_2012_512) dgst_nid = NID_id_GostR3411_2012_256; if (!VKO_compute_key(shared_key, EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)), EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_ERROR_COMPUTING_SHARED_KEY); goto err; } gost_init(&cctx, param->sblock); keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key); } gkt = GOST_KEY_TRANSPORT_new(); if (!gkt) { goto err; } if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) { goto err; } if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) { goto err; } if (!ASN1_OCTET_STRING_set (gkt->key_info->encrypted_key, crypted_key + 8, 32)) { goto err; } if (key_is_ephemeral) { if (!X509_PUBKEY_set (&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY); goto err; } } ASN1_OBJECT_free(gkt->key_agreement_info->cipher); gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid); if (key_is_ephemeral) EVP_PKEY_free(sec_key); if (!key_is_ephemeral) { /* Set control "public key from client certificate used" */ if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL) <= 0) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED); goto err; } } if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, out ? &out : NULL)) > 0) ret = 1; OPENSSL_cleanse(shared_key, sizeof(shared_key)); GOST_KEY_TRANSPORT_free(gkt); return ret; err: OPENSSL_cleanse(shared_key, sizeof(shared_key)); if (key_is_ephemeral) EVP_PKEY_free(sec_key); GOST_KEY_TRANSPORT_free(gkt); return -1; }
null
null
198,552
119311370633297214893271826756266062107
111
Fix buffer overrun in creating key transport blob according to RFC 9189, 4.2.4.2 Resolves: CVE-2022-29242
other
Bento4
33331ce2d35d45d855af7441db6116b4a9e2b70f
1
main(int argc, char** argv) { if (argc < 2) { PrintUsageAndExit(); } // default options Options.input = NULL; Options.verbose = false; Options.hls_version = 0; Options.pmt_pid = 0x100; Options.audio_pid = 0x101; Options.video_pid = 0x102; Options.audio_track_id = -1; Options.video_track_id = -1; Options.audio_format = AUDIO_FORMAT_TS; Options.output_single_file = false; Options.show_info = false; Options.index_filename = "stream.m3u8"; Options.iframe_index_filename = NULL; Options.segment_filename_template = NULL; Options.segment_url_template = NULL; Options.segment_duration = 6; Options.segment_duration_threshold = DefaultSegmentDurationThreshold; Options.allow_cache = NULL; Options.encryption_key_hex = NULL; Options.encryption_mode = ENCRYPTION_MODE_NONE; Options.encryption_iv_mode = ENCRYPTION_IV_MODE_NONE; Options.encryption_key_uri = "key.bin"; Options.encryption_key_format = NULL; Options.encryption_key_format_versions = NULL; Options.pcr_offset = AP4_MPEG2_TS_DEFAULT_PCR_OFFSET; AP4_SetMemory(Options.encryption_key, 0, sizeof(Options.encryption_key)); AP4_SetMemory(Options.encryption_iv, 0, sizeof(Options.encryption_iv)); AP4_SetMemory(&Stats, 0, sizeof(Stats)); // parse command line AP4_Result result; char** args = argv+1; while (const char* arg = *args++) { if (!strcmp(arg, "--verbose")) { Options.verbose = true; } else if (!strcmp(arg, "--hls-version")) { if (*args == NULL) { fprintf(stderr, "ERROR: --hls-version requires a number\n"); return 1; } Options.hls_version = (unsigned int)strtoul(*args++, NULL, 10); if (Options.hls_version ==0) { fprintf(stderr, "ERROR: --hls-version requires number > 0\n"); return 1; } } else if (!strcmp(arg, "--segment-duration")) { if (*args == NULL) { fprintf(stderr, "ERROR: --segment-duration requires a number\n"); return 1; } Options.segment_duration = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--segment-duration-threshold")) { if (*args == NULL) { fprintf(stderr, "ERROR: --segment-duration-threshold requires a number\n"); return 1; } Options.segment_duration_threshold = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--segment-filename-template")) { if (*args == NULL) { fprintf(stderr, "ERROR: --segment-filename-template requires an argument\n"); return 1; } Options.segment_filename_template = *args++; } else if (!strcmp(arg, "--segment-url-template")) { if (*args == NULL) { fprintf(stderr, "ERROR: --segment-url-template requires an argument\n"); return 1; } Options.segment_url_template = *args++; } else if (!strcmp(arg, "--allow-cache")) { if (*args == NULL || (strcmp(*args, "NO") && strcmp(*args, "YES"))) { fprintf(stderr, "ERROR: --allow-cache requires a YES or NO argument\n"); return 1; } Options.allow_cache = *args++; } else if (!strcmp(arg, "--pmt-pid")) { if (*args == NULL) { fprintf(stderr, "ERROR: --pmt-pid requires a number\n"); return 1; } Options.pmt_pid = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--audio-pid")) { if (*args == NULL) { fprintf(stderr, "ERROR: --audio-pid requires a number\n"); return 1; } Options.audio_pid = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--video-pid")) { if (*args == NULL) { fprintf(stderr, "ERROR: --video-pid requires a number\n"); return 1; } Options.video_pid = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--audio-track-id")) { if (*args == NULL) { fprintf(stderr, "ERROR: --audio-track-id requires a number\n"); return 1; } Options.audio_track_id = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--audio-format")) { if (*args == NULL) { fprintf(stderr, "ERROR: --audio-format requires an argument\n"); return 1; } const char* format = *args++; if (!strcmp(format, "ts")) { Options.audio_format = AUDIO_FORMAT_TS; } else if (!strcmp(format, "packed")) { Options.audio_format = AUDIO_FORMAT_PACKED; } else { fprintf(stderr, "ERROR: unknown audio format\n"); return 1; } } else if (!strcmp(arg, "--video-track-id")) { if (*args == NULL) { fprintf(stderr, "ERROR: --video-track-id requires a number\n"); return 1; } Options.video_track_id = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--pcr-offset")) { if (*args == NULL) { fprintf(stderr, "ERROR: --pcr-offset requires a number\n"); return 1; } Options.pcr_offset = (unsigned int)strtoul(*args++, NULL, 10); } else if (!strcmp(arg, "--output-single-file")) { Options.output_single_file = true; } else if (!strcmp(arg, "--index-filename")) { if (*args == NULL) { fprintf(stderr, "ERROR: --index-filename requires a filename\n"); return 1; } Options.index_filename = *args++; } else if (!strcmp(arg, "--iframe-index-filename")) { if (*args == NULL) { fprintf(stderr, "ERROR: --iframe-index-filename requires a filename\n"); return 1; } Options.iframe_index_filename = *args++; } else if (!strcmp(arg, "--show-info")) { Options.show_info = true; } else if (!strcmp(arg, "--encryption-key")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-key requires an argument\n"); return 1; } Options.encryption_key_hex = *args++; result = AP4_ParseHex(Options.encryption_key_hex, Options.encryption_key, 16); if (AP4_FAILED(result)) { fprintf(stderr, "ERROR: invalid hex key\n"); return 1; } if (Options.encryption_mode == ENCRYPTION_MODE_NONE) { Options.encryption_mode = ENCRYPTION_MODE_AES_128; } } else if (!strcmp(arg, "--encryption-mode")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-mode requires an argument\n"); return 1; } if (strncmp(*args, "AES-128", 7) == 0) { Options.encryption_mode = ENCRYPTION_MODE_AES_128; } else if (strncmp(*args, "SAMPLE-AES", 10) == 0) { Options.encryption_mode = ENCRYPTION_MODE_SAMPLE_AES; } else { fprintf(stderr, "ERROR: unknown encryption mode\n"); return 1; } ++args; } else if (!strcmp(arg, "--encryption-iv-mode")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-iv-mode requires an argument\n"); return 1; } if (strncmp(*args, "sequence", 8) == 0) { Options.encryption_iv_mode = ENCRYPTION_IV_MODE_SEQUENCE; } else if (strncmp(*args, "random", 6) == 0) { Options.encryption_iv_mode = ENCRYPTION_IV_MODE_RANDOM; } else if (strncmp(*args, "fps", 3) == 0) { Options.encryption_iv_mode = ENCRYPTION_IV_MODE_FPS; } else { fprintf(stderr, "ERROR: unknown encryption IV mode\n"); return 1; } ++args; } else if (!strcmp(arg, "--encryption-key-uri")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-key-uri requires an argument\n"); return 1; } Options.encryption_key_uri = *args++; } else if (!strcmp(arg, "--encryption-key-format")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-key-format requires an argument\n"); return 1; } Options.encryption_key_format = *args++; } else if (!strcmp(arg, "--encryption-key-format-versions")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-key-format-versions requires an argument\n"); return 1; } Options.encryption_key_format_versions = *args++; } else if (!strcmp(arg, "--encryption-key-line")) { if (*args == NULL) { fprintf(stderr, "ERROR: --encryption-key-line requires an argument\n"); return 1; } Options.encryption_key_lines.Append(*args++); } else if (Options.input == NULL) { Options.input = arg; } else { fprintf(stderr, "ERROR: unexpected argument: %s\n", arg); return 1; } } // check args if (Options.input == NULL) { fprintf(stderr, "ERROR: missing input file name\n"); return 1; } if (Options.encryption_mode == ENCRYPTION_MODE_NONE && Options.encryption_key_lines.ItemCount() != 0) { fprintf(stderr, "ERROR: --encryption-key-line requires --encryption-key and --encryption-key-mode\n"); return 1; } if (Options.encryption_mode != ENCRYPTION_MODE_NONE && Options.encryption_key_hex == NULL) { fprintf(stderr, "ERROR: no encryption key specified\n"); return 1; } if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES && Options.hls_version > 0 && Options.hls_version < 5) { Options.hls_version = 5; fprintf(stderr, "WARNING: forcing version to 5 in order to support SAMPLE-AES encryption\n"); } if (Options.iframe_index_filename && Options.hls_version > 0 && Options.hls_version < 4) { fprintf(stderr, "WARNING: forcing version to 4 in order to support I-FRAME-ONLY playlists\n"); Options.hls_version = 4; } if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_NONE && Options.encryption_mode != ENCRYPTION_MODE_NONE) { if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { // sequence-mode IVs don't work well with i-frame only playlists, use random instead Options.encryption_iv_mode = ENCRYPTION_IV_MODE_RANDOM; } else { Options.encryption_iv_mode = ENCRYPTION_IV_MODE_SEQUENCE; } } if ((Options.encryption_key_format || Options.encryption_key_format_versions) && Options.hls_version > 0 && Options.hls_version < 5) { Options.hls_version = 5; fprintf(stderr, "WARNING: forcing version to 5 in order to support KEYFORMAT and/or KEYFORMATVERSIONS\n"); } if (Options.output_single_file && Options.hls_version > 0 && Options.hls_version < 4) { Options.hls_version = 4; fprintf(stderr, "WARNING: forcing version to 4 in order to support single file output\n"); } if (Options.hls_version == 0) { // default version is 3 for cleartext or AES-128 encryption, and 5 for SAMPLE-AES if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { Options.hls_version = 5; } else if (Options.output_single_file || Options.iframe_index_filename) { Options.hls_version = 4; } else { Options.hls_version = 3; } } if (Options.verbose && Options.show_info) { fprintf(stderr, "WARNING: --verbose will be ignored because --show-info is selected\n"); Options.verbose = false; } // compute some derived values if (Options.iframe_index_filename == NULL) { if (Options.hls_version >= 4) { Options.iframe_index_filename = "iframes.m3u8"; } } if (Options.audio_format == AUDIO_FORMAT_TS) { if (Options.segment_filename_template == NULL) { if (Options.output_single_file) { Options.segment_filename_template = "stream.ts"; } else { Options.segment_filename_template = "segment-%d.ts"; } } if (Options.segment_url_template == NULL) { if (Options.output_single_file) { Options.segment_url_template = "stream.ts"; } else { Options.segment_url_template = "segment-%d.ts"; } } } if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_FPS) { if (AP4_StringLength(Options.encryption_key_hex) != 64) { fprintf(stderr, "ERROR: 'fps' IV mode requires a 32 byte key value (64 characters in hex)\n"); return 1; } result = AP4_ParseHex(Options.encryption_key_hex+32, Options.encryption_iv, 16); if (AP4_FAILED(result)) { fprintf(stderr, "ERROR: invalid hex IV\n"); return 1; } } else if (Options.encryption_iv_mode == ENCRYPTION_IV_MODE_RANDOM) { result = AP4_System_GenerateRandomBytes(Options.encryption_iv, sizeof(Options.encryption_iv)); if (AP4_FAILED(result)) { fprintf(stderr, "ERROR: failed to get random IV (%d)\n", result); return 1; } } // create the input stream AP4_ByteStream* input = NULL; result = AP4_FileByteStream::Create(Options.input, AP4_FileByteStream::STREAM_MODE_READ, input); if (AP4_FAILED(result)) { fprintf(stderr, "ERROR: cannot open input (%d)\n", result); return 1; } // open the file AP4_File* input_file = new AP4_File(*input, true); // get the movie AP4_SampleDescription* sample_description; AP4_Movie* movie = input_file->GetMovie(); if (movie == NULL) { fprintf(stderr, "ERROR: no movie in file\n"); return 1; } // get the audio and video tracks AP4_Track* audio_track = NULL; if (Options.audio_track_id == -1) { audio_track = movie->GetTrack(AP4_Track::TYPE_AUDIO); } else if (Options.audio_track_id > 0) { audio_track = movie->GetTrack((AP4_UI32)Options.audio_track_id); if (audio_track == NULL) { fprintf(stderr, "ERROR: audio track ID %d not found\n", Options.audio_track_id); return 1; } if (audio_track->GetType() != AP4_Track::TYPE_AUDIO) { fprintf(stderr, "ERROR: track ID %d is not an audio track\n", Options.audio_track_id); return 1; } } AP4_Track* video_track = NULL; if (Options.video_track_id == -1) { video_track = movie->GetTrack(AP4_Track::TYPE_VIDEO); } else if (Options.video_track_id > 0) { video_track = movie->GetTrack((AP4_UI32)Options.video_track_id); if (video_track == NULL) { fprintf(stderr, "ERROR: video track ID %d not found\n", Options.video_track_id); return 1; } if (video_track->GetType() != AP4_Track::TYPE_VIDEO) { fprintf(stderr, "ERROR: track ID %d is not a video track\n", Options.video_track_id); return 1; } } if (audio_track == NULL && video_track == NULL) { fprintf(stderr, "ERROR: no suitable tracks found\n"); delete input_file; input->Release(); return 1; } if (Options.audio_format == AUDIO_FORMAT_PACKED && video_track != NULL) { if (audio_track == NULL) { fprintf(stderr, "ERROR: packed audio format requires an audio track\n"); return 1; } fprintf(stderr, "WARNING: ignoring video track because of the packed audio format\n"); video_track = NULL; } if (video_track == NULL) { Options.segment_duration_threshold = 0; } // create the appropriate readers AP4_LinearReader* linear_reader = NULL; SampleReader* audio_reader = NULL; SampleReader* video_reader = NULL; if (movie->HasFragments()) { // create a linear reader to get the samples linear_reader = new AP4_LinearReader(*movie, input); if (audio_track) { linear_reader->EnableTrack(audio_track->GetId()); audio_reader = new FragmentedSampleReader(*linear_reader, audio_track->GetId()); } if (video_track) { linear_reader->EnableTrack(video_track->GetId()); video_reader = new FragmentedSampleReader(*linear_reader, video_track->GetId()); } } else { if (audio_track) { audio_reader = new TrackSampleReader(*audio_track); } if (video_track) { video_reader = new TrackSampleReader(*video_track); } } AP4_Mpeg2TsWriter* ts_writer = NULL; AP4_Mpeg2TsWriter::SampleStream* audio_stream = NULL; AP4_Mpeg2TsWriter::SampleStream* video_stream = NULL; AP4_UI08 nalu_length_size = 0; PackedAudioWriter* packed_writer = NULL; if (Options.audio_format == AUDIO_FORMAT_PACKED) { packed_writer = new PackedAudioWriter(); // figure out the file extensions if needed sample_description = audio_track->GetSampleDescription(0); if (sample_description == NULL) { fprintf(stderr, "ERROR: unable to parse audio sample description\n"); goto end; } if (Options.segment_filename_template == NULL || Options.segment_url_template == NULL) { const char* default_stream_name = "stream.es"; const char* default_stream_pattern = "segment-%d.es"; if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) { AP4_MpegAudioSampleDescription* mpeg_audio_desc = AP4_DYNAMIC_CAST(AP4_MpegAudioSampleDescription, sample_description); if (mpeg_audio_desc == NULL || !(mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG4_AUDIO || mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_LC || mpeg_audio_desc->GetObjectTypeId() == AP4_OTI_MPEG2_AAC_AUDIO_MAIN)) { fprintf(stderr, "ERROR: only AAC audio is supported\n"); return 1; } default_stream_name = "stream.aac"; default_stream_pattern = "segment-%d.aac"; } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) { default_stream_name = "stream.ac3"; default_stream_pattern = "segment-%d.ac3"; } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) { default_stream_name = "stream.ec3"; default_stream_pattern = "segment-%d.ec3"; } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_4) { default_stream_name = "stream.ac4"; default_stream_pattern = "segment-%d.ac4"; } // override the segment names if (Options.segment_filename_template == NULL) { if (Options.output_single_file) { Options.segment_filename_template = default_stream_name; } else { Options.segment_filename_template = default_stream_pattern; } } if (Options.segment_url_template == NULL) { if (Options.output_single_file) { Options.segment_url_template = default_stream_name; } else { Options.segment_url_template = default_stream_pattern; } } } } else { // create an MPEG2 TS Writer ts_writer = new AP4_Mpeg2TsWriter(Options.pmt_pid); // add the audio stream if (audio_track) { sample_description = audio_track->GetSampleDescription(0); if (sample_description == NULL) { fprintf(stderr, "ERROR: unable to parse audio sample description\n"); goto end; } unsigned int stream_type = 0; unsigned int stream_id = 0; if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_MP4A) { if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ISO_IEC_13818_7; } else { stream_type = AP4_MPEG2_STREAM_TYPE_ISO_IEC_13818_7; } stream_id = AP4_MPEG2_TS_DEFAULT_STREAM_ID_AUDIO; } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AC_3) { if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_AC3; } else { stream_type = AP4_MPEG2_STREAM_TYPE_ATSC_AC3; } stream_id = AP4_MPEG2_TS_STREAM_ID_PRIVATE_STREAM_1; } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_EC_3) { if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_ATSC_EAC3; } else { stream_type = AP4_MPEG2_STREAM_TYPE_ATSC_EAC3; } stream_id = AP4_MPEG2_TS_STREAM_ID_PRIVATE_STREAM_1; } else { fprintf(stderr, "ERROR: audio codec not supported\n"); return 1; } if (stream_type == AP4_MPEG2_STREAM_TYPE_ATSC_EAC3) { // E-AC-3 descriptor unsigned int number_of_channels = 0; AP4_String track_language; AP4_Dec3Atom* dec3 = AP4_DYNAMIC_CAST(AP4_Dec3Atom, sample_description->GetDetails().GetChild(AP4_ATOM_TYPE_DEC3)); AP4_BitWriter bits(8); bits.Write(0xCC, 8); bits.Write(0x06, 8); // fixed value bits.Write(0xC0, 8); // reserved, bsid_flag, mainid_flag, asvc_flag, mixinfoexists, substream1_flag, substream2_flag and substream3_flag bits.Write(24, 5); // reserved, full_service_flag and service_type if (dec3->GetSubStreams()[0].acmod == 0) { number_of_channels = 1; } else if (dec3->GetSubStreams()[0].acmod == 1) { number_of_channels = 0; } else if (dec3->GetSubStreams()[0].acmod == 2) { number_of_channels = 2; } else { number_of_channels = 4; } if (dec3->GetSubStreams()[0].num_dep_sub > 0) { number_of_channels = 5; } bits.Write(number_of_channels, 3); // number_of_channels bits.Write(4, 3); // language_flag, language_flag_2, reserved bits.Write(dec3->GetSubStreams()[0].bsid, 5); // bsid track_language = audio_track->GetTrackLanguage(); if (track_language.GetLength() == 3) { bits.Write(track_language.GetChars()[0], 8); bits.Write(track_language.GetChars()[1], 8); bits.Write(track_language.GetChars()[2], 8); } else { bits.Write(0x75, 8); bits.Write(0x6E, 8); bits.Write(0x64, 8); } // setup the audio stream result = ts_writer->SetAudioStream(audio_track->GetMediaTimeScale(), stream_type, stream_id, audio_stream, Options.audio_pid, bits.GetData(), 8, Options.pcr_offset); } else { // setup the audio stream result = ts_writer->SetAudioStream(audio_track->GetMediaTimeScale(), stream_type, stream_id, audio_stream, Options.audio_pid, NULL, 0, Options.pcr_offset); } if (AP4_FAILED(result)) { fprintf(stderr, "could not create audio stream (%d)\n", result); goto end; } } // add the video stream if (video_track) { sample_description = video_track->GetSampleDescription(0); if (sample_description == NULL) { fprintf(stderr, "ERROR: unable to parse video sample description\n"); goto end; } // decide on the stream type unsigned int stream_type = 0; unsigned int stream_id = AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO; if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC1 || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC2 || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC3 || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_AVC4 || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVAV || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVA1) { if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { stream_type = AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC; AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description); if (avc_desc == NULL) { fprintf(stderr, "ERROR: not a proper AVC track\n"); return 1; } nalu_length_size = avc_desc->GetNaluLengthSize(); } else { stream_type = AP4_MPEG2_STREAM_TYPE_AVC; } } else if (sample_description->GetFormat() == AP4_SAMPLE_FORMAT_HEV1 || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_HVC1 || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVHE || sample_description->GetFormat() == AP4_SAMPLE_FORMAT_DVH1) { stream_type = AP4_MPEG2_STREAM_TYPE_HEVC; } else { fprintf(stderr, "ERROR: video codec not supported\n"); return 1; } if (Options.encryption_mode == ENCRYPTION_MODE_SAMPLE_AES) { if (stream_type != AP4_MPEG2_STREAM_TYPE_SAMPLE_AES_AVC) { fprintf(stderr, "ERROR: AES-SAMPLE encryption can only be used with H.264 video\n"); return 1; } } // setup the video stream result = ts_writer->SetVideoStream(video_track->GetMediaTimeScale(), stream_type, stream_id, video_stream, Options.video_pid, NULL, 0, Options.pcr_offset); if (AP4_FAILED(result)) { fprintf(stderr, "could not create video stream (%d)\n", result); goto end; } } } result = WriteSamples(ts_writer, packed_writer, audio_track, audio_reader, audio_stream, video_track, video_reader, video_stream, Options.segment_duration_threshold, nalu_length_size); if (AP4_FAILED(result)) { fprintf(stderr, "ERROR: failed to write samples (%d)\n", result); } if (Options.show_info) { double average_segment_bitrate = 0.0; if (Stats.segments_total_duration != 0.0) { average_segment_bitrate = 8.0*(double)Stats.segments_total_size/Stats.segments_total_duration; } double average_iframe_bitrate = 0.0; if (Stats.segments_total_duration != 0.0) { average_iframe_bitrate = 8.0*(double)Stats.iframes_total_size/Stats.segments_total_duration; } double frame_rate = 0.0; if (video_track && (Stats.segments_total_duration != 0.0)) { double sample_count = (double)video_track->GetSampleCount(); double media_duration = (double)video_track->GetMediaDuration(); double timescale = (double)video_track->GetMediaTimeScale(); if (media_duration > 0.0) { frame_rate = sample_count/(media_duration/timescale); } } printf( "{\n" ); printf( " \"stats\": {\n" " \"duration\": %f,\n" " \"avg_segment_bitrate\": %f,\n" " \"max_segment_bitrate\": %f,\n" " \"avg_iframe_bitrate\": %f,\n" " \"max_iframe_bitrate\": %f,\n" " \"frame_rate\": %f\n" " }", (double)movie->GetDurationMs()/1000.0, average_segment_bitrate, Stats.max_segment_bitrate, average_iframe_bitrate, Stats.max_iframe_bitrate, frame_rate ); if (audio_track) { AP4_String codec; AP4_SampleDescription* sdesc = audio_track->GetSampleDescription(0); if (sdesc) { sdesc->GetCodecString(codec); } printf( ",\n" " \"audio\": {\n" " \"codec\": \"%s\"\n" " }", codec.GetChars() ); } if (video_track) { AP4_String codec; AP4_UI16 width = (AP4_UI16)(video_track->GetWidth()/65536.0); AP4_UI16 height = (AP4_UI16)(video_track->GetHeight()/65536.0); AP4_SampleDescription* sdesc = video_track->GetSampleDescription(0); if (sdesc) { sdesc->GetCodecString(codec); AP4_VideoSampleDescription* video_desc = AP4_DYNAMIC_CAST(AP4_VideoSampleDescription, sdesc); if (video_desc) { width = video_desc->GetWidth(); height = video_desc->GetHeight(); } } printf( ",\n" " \"video\": {\n" " \"codec\": \"%s\",\n" " \"width\": %d,\n" " \"height\": %d\n" " }", codec.GetChars(), width, height ); } printf( "\n" "}\n" ); } end: delete ts_writer; delete packed_writer; delete input_file; input->Release(); delete linear_reader; delete audio_reader; delete video_reader; return result == AP4_SUCCESS?0:1; }
null
null
198,555
309905552433608479525781569947809221165
725
fix #691
other
libmobi
eafc415bc6067e72577f70d6dd5acbf057ce6e6f
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; }
null
null
198,566
211795113703656920067010021209431193626
59
Fix wrong boundary checks in inflections parser resulting in stack buffer over-read with corrupt input
other
MilkyTracker
fd607a3439fcdd0992e5efded3c16fc79c804e34
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; }
null
null
198,695
232151339946137971220513489493449251730
415
Fix #184: Heap overflow in S3M loader
other
LuaJIT
53f82e6e2e858a0a62fd1a2ff47e9866693382e6
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; }
null
null
198,743
103249297125021918182204154082572508861
50
Fix frame traversal for __gc handler frames. Reported by Changochen.
other
pjproject
077b465c33f0aec05a49cd2ca456f9a1b112e896
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; }
null
null
199,836
250257059547301458667731790844822819454
16
Merge pull request from GHSA-7fw8-54cv-r7pm
other
vim
2813f38e021c6e6581c0c88fcf107e41788bc835
1
spell_move_to( win_T *wp, int dir, // FORWARD or BACKWARD int allwords, // TRUE for "[s"/"]s", FALSE for "[S"/"]S" int curline, hlf_T *attrp) // return: attributes of bad word or NULL // (only when "dir" is FORWARD) { linenr_T lnum; pos_T found_pos; int found_len = 0; char_u *line; char_u *p; char_u *endp; hlf_T attr; int len; #ifdef FEAT_SYN_HL int has_syntax = syntax_present(wp); #endif int col; int can_spell; char_u *buf = NULL; int buflen = 0; int skip = 0; int capcol = -1; int found_one = FALSE; int wrapped = FALSE; if (no_spell_checking(wp)) return 0; /* * Start looking for bad word at the start of the line, because we can't * start halfway a word, we don't know where it starts or ends. * * When searching backwards, we continue in the line to find the last * bad word (in the cursor line: before the cursor). * * We concatenate the start of the next line, so that wrapped words work * (e.g. "et<line-break>cetera"). Doesn't work when searching backwards * though... */ lnum = wp->w_cursor.lnum; CLEAR_POS(&found_pos); while (!got_int) { line = ml_get_buf(wp->w_buffer, lnum, FALSE); len = (int)STRLEN(line); if (buflen < len + MAXWLEN + 2) { vim_free(buf); buflen = len + MAXWLEN + 2; buf = alloc(buflen); if (buf == NULL) break; } // In first line check first word for Capital. if (lnum == 1) capcol = 0; // For checking first word with a capital skip white space. if (capcol == 0) capcol = getwhitecols(line); else if (curline && wp == curwin) { // For spellbadword(): check if first word needs a capital. col = getwhitecols(line); if (check_need_cap(lnum, col)) capcol = col; // Need to get the line again, may have looked at the previous // one. line = ml_get_buf(wp->w_buffer, lnum, FALSE); } // Copy the line into "buf" and append the start of the next line if // possible. STRCPY(buf, line); if (lnum < wp->w_buffer->b_ml.ml_line_count) spell_cat_line(buf + STRLEN(buf), ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN); p = buf + skip; endp = buf + len; while (p < endp) { // When searching backward don't search after the cursor. Unless // we wrapped around the end of the buffer. if (dir == BACKWARD && lnum == wp->w_cursor.lnum && !wrapped && (colnr_T)(p - buf) >= wp->w_cursor.col) break; // start of word attr = HLF_COUNT; len = spell_check(wp, p, &attr, &capcol, FALSE); if (attr != HLF_COUNT) { // We found a bad word. Check the attribute. if (allwords || attr == HLF_SPB) { // When searching forward only accept a bad word after // the cursor. if (dir == BACKWARD || lnum != wp->w_cursor.lnum || (wrapped || (colnr_T)(curline ? p - buf + len : p - buf) > wp->w_cursor.col)) { #ifdef FEAT_SYN_HL if (has_syntax) { col = (int)(p - buf); (void)syn_get_id(wp, lnum, (colnr_T)col, FALSE, &can_spell, FALSE); if (!can_spell) attr = HLF_COUNT; } else #endif can_spell = TRUE; if (can_spell) { found_one = TRUE; found_pos.lnum = lnum; found_pos.col = (int)(p - buf); found_pos.coladd = 0; if (dir == FORWARD) { // No need to search further. wp->w_cursor = found_pos; vim_free(buf); if (attrp != NULL) *attrp = attr; return len; } else if (curline) // Insert mode completion: put cursor after // the bad word. found_pos.col += len; found_len = len; } } else found_one = TRUE; } } // advance to character after the word p += len; capcol -= len; } if (dir == BACKWARD && found_pos.lnum != 0) { // Use the last match in the line (before the cursor). wp->w_cursor = found_pos; vim_free(buf); return found_len; } if (curline) break; // only check cursor line // If we are back at the starting line and searched it again there // is no match, give up. if (lnum == wp->w_cursor.lnum && wrapped) break; // Advance to next line. if (dir == BACKWARD) { if (lnum > 1) --lnum; else if (!p_ws) break; // at first line and 'nowrapscan' else { // Wrap around to the end of the buffer. May search the // starting line again and accept the last match. lnum = wp->w_buffer->b_ml.ml_line_count; wrapped = TRUE; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(top_bot_msg), TRUE); } capcol = -1; } else { if (lnum < wp->w_buffer->b_ml.ml_line_count) ++lnum; else if (!p_ws) break; // at first line and 'nowrapscan' else { // Wrap around to the start of the buffer. May search the // starting line again and accept the first match. lnum = 1; wrapped = TRUE; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(bot_top_msg), TRUE); } // If we are back at the starting line and there is no match then // give up. if (lnum == wp->w_cursor.lnum && !found_one) break; // Skip the characters at the start of the next line that were // included in a match crossing line boundaries. if (attr == HLF_COUNT) skip = (int)(p - endp); else skip = 0; // Capcol skips over the inserted space. --capcol; // But after empty line check first word in next line if (*skipwhite(line) == NUL) capcol = 0; } line_breakcheck(); } vim_free(buf); return 0; }
null
null
199,918
24431311156552293265437974373971430432
236
patch 8.2.5072: using uninitialized value and freed memory in spell command Problem: Using uninitialized value and freed memory in spell command. Solution: Initialize "attr". Check for empty line early.
other
samba
eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696
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; }
null
null
200,320
36864430679636639714404842179779335208
330
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
other
pjproject
560a1346f87aabe126509bb24930106dea292b00
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); }
null
null
201,007
133454390800145611389529375903489549180
63
Merge pull request from GHSA-f5qg-pqcg-765m
other
linux
a3727a8bac0a9e77c70820655fd8715523ba3db7
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); }
null
null
201,343
63175626254905822917570001000286668928
6
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]>
other
linux
e6a21a14106d9718aa4f8e115b1e474888eeba44
1
*vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args) { u32 priv_sz = sizeof(struct vidtv_s302m_ctx); struct vidtv_s302m_ctx *ctx; struct vidtv_encoder *e; e = kzalloc(sizeof(*e), GFP_KERNEL); if (!e) return NULL; e->id = S302M; if (args.name) e->name = kstrdup(args.name, GFP_KERNEL); e->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ); e->encoder_buf_sz = VIDTV_S302M_BUF_SZ; e->encoder_buf_offset = 0; e->sample_count = 0; e->src_buf = (args.src_buf) ? args.src_buf : NULL; e->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0; e->src_buf_offset = 0; e->is_video_encoder = false; ctx = kzalloc(priv_sz, GFP_KERNEL); if (!ctx) { kfree(e); return NULL; } e->ctx = ctx; ctx->last_duration = 0; e->encode = vidtv_s302m_encode; e->clear = vidtv_s302m_clear; e->es_pid = cpu_to_be16(args.es_pid); e->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1); e->sync = args.sync; e->sampling_rate_hz = S302M_SAMPLING_RATE_HZ; e->last_sample_cb = args.last_sample_cb; e->destroy = vidtv_s302m_encoder_destroy; if (args.head) { while (args.head->next) args.head = args.head->next; args.head->next = e; } e->next = NULL; return e; }
null
null
201,925
220376165242545767374971532665904547126
60
media: vidtv: Check for null return of vzalloc As the possible failure of the vzalloc(), e->encoder_buf might be NULL. Therefore, it should be better to check it in order to guarantee the success of the initialization. If fails, we need to free not only 'e' but also 'e->name'. Also, if the allocation for ctx fails, we need to free 'e->encoder_buf' else. Fixes: f90cf6079bf6 ("media: vidtv: add a bridge driver") Signed-off-by: Jiasheng Jiang <[email protected]> Signed-off-by: Hans Verkuil <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]>
other
spice
ca5bbc5692e052159bce1a75f55dc60b36078749
1
static int reds_init_ssl(RedsState *reds) { const SSL_METHOD *ssl_method; int return_code; /* Limit connection to TLSv1.1 or newer. * When some other SSL/TLS version becomes obsolete, add it to this * variable. */ long ssl_options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION | SSL_OP_NO_TLSv1; /* Global system initialization*/ openssl_global_init(); /* Create our context*/ /* SSLv23_method() handles TLSv1.x in addition to SSLv2/v3 */ ssl_method = SSLv23_method(); reds->ctx = SSL_CTX_new(ssl_method); if (!reds->ctx) { spice_warning("Could not allocate new SSL context"); red_dump_openssl_errors(); return -1; } SSL_CTX_set_options(reds->ctx, ssl_options); #if HAVE_DECL_SSL_CTX_SET_ECDH_AUTO || defined(SSL_CTX_set_ecdh_auto) SSL_CTX_set_ecdh_auto(reds->ctx, 1); #endif /* Load our keys and certificates*/ return_code = SSL_CTX_use_certificate_chain_file(reds->ctx, reds->config->ssl_parameters.certs_file); if (return_code == 1) { spice_debug("Loaded certificates from %s", reds->config->ssl_parameters.certs_file); } else { spice_warning("Could not load certificates from %s", reds->config->ssl_parameters.certs_file); red_dump_openssl_errors(); return -1; } SSL_CTX_set_default_passwd_cb(reds->ctx, ssl_password_cb); SSL_CTX_set_default_passwd_cb_userdata(reds->ctx, reds); return_code = SSL_CTX_use_PrivateKey_file(reds->ctx, reds->config->ssl_parameters.private_key_file, SSL_FILETYPE_PEM); if (return_code == 1) { spice_debug("Using private key from %s", reds->config->ssl_parameters.private_key_file); } else { spice_warning("Could not use private key file"); return -1; } /* Load the CAs we trust*/ return_code = SSL_CTX_load_verify_locations(reds->ctx, reds->config->ssl_parameters.ca_certificate_file, 0); if (return_code == 1) { spice_debug("Loaded CA certificates from %s", reds->config->ssl_parameters.ca_certificate_file); } else { spice_warning("Could not use CA file %s", reds->config->ssl_parameters.ca_certificate_file); red_dump_openssl_errors(); return -1; } if (strlen(reds->config->ssl_parameters.dh_key_file) > 0) { if (load_dh_params(reds->ctx, reds->config->ssl_parameters.dh_key_file) < 0) { return -1; } } SSL_CTX_set_session_id_context(reds->ctx, (const unsigned char *)"SPICE", 5); if (strlen(reds->config->ssl_parameters.ciphersuite) > 0) { if (!SSL_CTX_set_cipher_list(reds->ctx, reds->config->ssl_parameters.ciphersuite)) { return -1; } } return 0; }
null
null
202,678
122101275279986190714681083473068742276
74
With OpenSSL 1.1: Disable client-initiated renegotiation. Fixes issue #49 Fixes BZ#1904459 Signed-off-by: Julien Ropé <[email protected]> Reported-by: BlackKD Acked-by: Frediano Ziglio <[email protected]>
other
binaryen
6f599272c66f65472f5e4c8d759d5bca77e47da6
1
void WasmBinaryBuilder::visitRethrow(Rethrow* curr) { BYN_TRACE("zz node: Rethrow\n"); curr->target = getExceptionTargetName(getU32LEB()); // This special target is valid only for delegates assert(curr->target != DELEGATE_CALLER_TARGET); curr->finalize(); }
null
null
202,734
209177550826884079893421252076067255380
7
Turn an assertion on not colliding with an internal name into an error (#4422) Without this, the result in a build without assertions might be quite confusing. See #4410 Also make the internal names more obviously internal names.
other
ghostpdl
5d499272b95a6b890a1397e11d20937de000d31b
1
search_impl(i_ctx_t *i_ctx_p, bool forward) { os_ptr op = osp; os_ptr op1 = op - 1; uint size = r_size(op); uint count; byte *pat; byte *ptr; byte ch; int incr = forward ? 1 : -1; check_read_type(*op1, t_string); check_read_type(*op, t_string); if (size > r_size(op1)) { /* can't match */ make_false(op); return 0; } count = r_size(op1) - size; ptr = op1->value.bytes; if (size == 0) goto found; if (!forward) ptr += count; pat = op->value.bytes; ch = pat[0]; do { if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size))) goto found; ptr += incr; } while (count--); /* No match */ make_false(op); return 0; found: op->tas.type_attrs = op1->tas.type_attrs; op->value.bytes = ptr; r_set_size(op, size); push(2); op[-1] = *op1; r_set_size(op - 1, ptr - op[-1].value.bytes); op1->value.bytes = ptr + size; r_set_size(op1, count + (!forward ? (size - 1) : 0)); make_true(op); return 0; }
null
null
202,822
249132726675055919779887509398809507782
46
Bug 702582, CVE 2020-15900 Memory Corruption in Ghostscript 9.52 Fix the 'rsearch' calculation for the 'post' size to give the correct size. Previous calculation would result in a size that was too large, and could underflow to max uint32_t. Also fix 'rsearch' to return the correct 'pre' string with empty string match. A future change may 'undefine' this undocumented, non-standard operator during initialization as we do with the many other non-standard internal PostScript operators and procedures.
other
tty
15b3cd8ef46ad1b100e0d3c7e38774f330726820
1
con_insert_unipair(struct uni_pagedir *p, u_short unicode, u_short fontpos) { int i, n; u16 **p1, *p2; p1 = p->uni_pgdir[n = unicode >> 11]; if (!p1) { p1 = p->uni_pgdir[n] = kmalloc_array(32, sizeof(u16 *), GFP_KERNEL); if (!p1) return -ENOMEM; for (i = 0; i < 32; i++) p1[i] = NULL; } p2 = p1[n = (unicode >> 6) & 0x1f]; if (!p2) { p2 = p1[n] = kmalloc_array(64, sizeof(u16), GFP_KERNEL); if (!p2) { kfree(p1); p->uni_pgdir[n] = NULL; return -ENOMEM; } memset(p2, 0xff, 64*sizeof(u16)); /* No glyphs for the characters (yet) */ } p2[unicode & 0x3f] = fontpos; p->sum += (fontpos << 20) + unicode; return 0; }
null
null
203,622
61670946817080732094550256808909248342
31
Revert "consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c" This reverts commit 84ecc2f6eb1cb12e6d44818f94fa49b50f06e6ac. con_insert_unipair() is working with a sparse 3-dimensional array: - p->uni_pgdir[] is the top layer - p1 points to a middle layer - p2 points to a bottom layer If it needs to allocate a new middle layer, and then fails to allocate a new bottom layer, it would previously free only p2, and now it frees both p1 and p2. But since the new middle layer was already registered in the top layer, it was not leaked. However, if it looks up an *existing* middle layer and then fails to allocate a bottom layer, it now frees both p1 and p2 but does *not* free any other bottom layers under p1. So it *introduces* a memory leak. The error path also cleared the wrong index in p->uni_pgdir[], introducing a use-after-free. Signed-off-by: Ben Hutchings <[email protected]> Fixes: 84ecc2f6eb1c ("consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c") Signed-off-by: Greg Kroah-Hartman <[email protected]>
other
squashfs-tools
e0485802ec72996c20026da320650d8362f555bd
1
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_3 dirh; char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer; long long start; int bytes = 0; int dir_count, size, res; struct dir_ent *ent, *cur_ent = NULL; struct dir *dir; TRACE("squashfs_opendir: inode start block %d, offset %d\n", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) MEM_ERROR(); dir->dir_count = 0; dir->cur_entry = NULL; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 3) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; offset = (*i)->offset; size = (*i)->data + bytes - 3; while(bytes < size) { if(swap) { squashfs_dir_header_3 sdirh; res = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh)); if(res) SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh); } else res = read_directory_data(&dirh, &start, &offset, sizeof(dirh)); if(res == FALSE) goto corrupted; dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header @ byte position " "%d, %d directory entries\n", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR("File system corrupted: too many entries in directory\n"); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_3 sdire; res = read_directory_data(&sdire, &start, &offset, sizeof(sdire)); if(res) SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire); } else res = read_directory_data(dire, &start, &offset, sizeof(*dire)); if(res == FALSE) goto corrupted; bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR("File system corrupted: filename too long\n"); goto corrupted; } res = read_directory_data(dire->name, &start, &offset, dire->size + 1); if(res == FALSE) goto corrupted; dire->name[dire->size + 1] = '\0'; /* check name for invalid characters (i.e /, ., ..) */ if(check_name(dire->name, dire->size + 1) == FALSE) { ERROR("File system corrupted: invalid characters in name\n"); goto corrupted; } TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); ent = malloc(sizeof(struct dir_ent)); if(ent == NULL) MEM_ERROR(); ent->name = strdup(dire->name); ent->start_block = dirh.start_block; ent->offset = dire->offset; ent->type = dire->type; ent->next = NULL; if(cur_ent == NULL) dir->dirs = ent; else cur_ent->next = ent; cur_ent = ent; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: squashfs_closedir(dir); return NULL; }
null
null
204,017
65180591611652100911872766047415284947
132
Unsquashfs: additional write outside destination directory exploit fix An issue on github (https://github.com/plougher/squashfs-tools/issues/72) showed how some specially crafted Squashfs filesystems containing invalid file names (with '/' and '..') can cause Unsquashfs to write files outside of the destination directory. Since then it has been shown that specially crafted Squashfs filesystems that contain a symbolic link pointing outside of the destination directory, coupled with an identically named file within the same directory, can cause Unsquashfs to write files outside of the destination directory. Specifically the symbolic link produces a pathname pointing outside of the destination directory, which is then followed when writing the duplicate identically named file within the directory. This commit fixes this exploit by explictly checking for duplicate filenames within a directory. As directories in v2.1, v3.x, and v4.0 filesystems are sorted, this is achieved by checking for consecutively identical filenames. Additionally directories are checked to ensure they are sorted, to avoid attempts to evade the duplicate check. Version 1.x and 2.0 filesystems (where the directories were unsorted) are sorted and then the above duplicate filename check is applied. Signed-off-by: Phillip Lougher <[email protected]>
other
vim
28d032cc688ccfda18c5bbcab8b50aba6e18cde5
1
do_window( int nchar, long Prenum, int xchar) // extra char from ":wincmd gx" or NUL { long Prenum1; win_T *wp; #if defined(FEAT_SEARCHPATH) || defined(FEAT_FIND_ID) char_u *ptr; linenr_T lnum = -1; #endif #ifdef FEAT_FIND_ID int type = FIND_DEFINE; int len; #endif char_u cbuf[40]; if (ERROR_IF_ANY_POPUP_WINDOW) return; #ifdef FEAT_CMDWIN # define CHECK_CMDWIN \ do { \ if (cmdwin_type != 0) \ { \ emsg(_(e_invalid_in_cmdline_window)); \ return; \ } \ } while (0) #else # define CHECK_CMDWIN do { /**/ } while (0) #endif Prenum1 = Prenum == 0 ? 1 : Prenum; switch (nchar) { // split current window in two parts, horizontally case 'S': case Ctrl_S: case 's': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode #ifdef FEAT_QUICKFIX // When splitting the quickfix window open a new buffer in it, // don't replicate the quickfix buffer. if (bt_quickfix(curbuf)) goto newwindow; #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif (void)win_split((int)Prenum, 0); break; // split current window in two parts, vertically case Ctrl_V: case 'v': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode #ifdef FEAT_QUICKFIX // When splitting the quickfix window open a new buffer in it, // don't replicate the quickfix buffer. if (bt_quickfix(curbuf)) goto newwindow; #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif (void)win_split((int)Prenum, WSP_VERT); break; // split current window and edit alternate file case Ctrl_HAT: case '^': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode if (buflist_findnr(Prenum == 0 ? curwin->w_alt_fnum : Prenum) == NULL) { if (Prenum == 0) emsg(_(e_no_alternate_file)); else semsg(_(e_buffer_nr_not_found), Prenum); break; } if (!curbuf_locked() && win_split(0, 0) == OK) (void)buflist_getfile( Prenum == 0 ? curwin->w_alt_fnum : Prenum, (linenr_T)0, GETF_ALT, FALSE); break; // open new window case Ctrl_N: case 'n': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode #ifdef FEAT_QUICKFIX newwindow: #endif if (Prenum) // window height vim_snprintf((char *)cbuf, sizeof(cbuf) - 5, "%ld", Prenum); else cbuf[0] = NUL; #if defined(FEAT_QUICKFIX) if (nchar == 'v' || nchar == Ctrl_V) STRCAT(cbuf, "v"); #endif STRCAT(cbuf, "new"); do_cmdline_cmd(cbuf); break; // quit current window case Ctrl_Q: case 'q': reset_VIsual_and_resel(); // stop Visual mode cmd_with_count("quit", cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; // close current window case Ctrl_C: case 'c': reset_VIsual_and_resel(); // stop Visual mode cmd_with_count("close", cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; #if defined(FEAT_QUICKFIX) // close preview window case Ctrl_Z: case 'z': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode do_cmdline_cmd((char_u *)"pclose"); break; // cursor to preview window case 'P': FOR_ALL_WINDOWS(wp) if (wp->w_p_pvw) break; if (wp == NULL) emsg(_(e_there_is_no_preview_window)); else win_goto(wp); break; #endif // close all but current window case Ctrl_O: case 'o': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode cmd_with_count("only", cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; // cursor to next window with wrap around case Ctrl_W: case 'w': // cursor to previous window with wrap around case 'W': CHECK_CMDWIN; if (ONE_WINDOW && Prenum != 1) // just one window beep_flush(); else { if (Prenum) // go to specified window { for (wp = firstwin; --Prenum > 0; ) { if (wp->w_next == NULL) break; else wp = wp->w_next; } } else { if (nchar == 'W') // go to previous window { wp = curwin->w_prev; if (wp == NULL) wp = lastwin; // wrap around } else // go to next window { wp = curwin->w_next; if (wp == NULL) wp = firstwin; // wrap around } } win_goto(wp); } break; // cursor to window below case 'j': case K_DOWN: case Ctrl_J: CHECK_CMDWIN; win_goto_ver(FALSE, Prenum1); break; // cursor to window above case 'k': case K_UP: case Ctrl_K: CHECK_CMDWIN; win_goto_ver(TRUE, Prenum1); break; // cursor to left window case 'h': case K_LEFT: case Ctrl_H: case K_BS: CHECK_CMDWIN; win_goto_hor(TRUE, Prenum1); break; // cursor to right window case 'l': case K_RIGHT: case Ctrl_L: CHECK_CMDWIN; win_goto_hor(FALSE, Prenum1); break; // move window to new tab page case 'T': CHECK_CMDWIN; if (one_window()) msg(_(m_onlyone)); else { tabpage_T *oldtab = curtab; tabpage_T *newtab; // First create a new tab with the window, then go back to // the old tab and close the window there. wp = curwin; if (win_new_tabpage((int)Prenum) == OK && valid_tabpage(oldtab)) { newtab = curtab; goto_tabpage_tp(oldtab, TRUE, TRUE); if (curwin == wp) win_close(curwin, FALSE); if (valid_tabpage(newtab)) goto_tabpage_tp(newtab, TRUE, TRUE); } } break; // cursor to top-left window case 't': case Ctrl_T: win_goto(firstwin); break; // cursor to bottom-right window case 'b': case Ctrl_B: win_goto(lastwin); break; // cursor to last accessed (previous) window case 'p': case Ctrl_P: if (!win_valid(prevwin)) beep_flush(); else win_goto(prevwin); break; // exchange current and next window case 'x': case Ctrl_X: CHECK_CMDWIN; win_exchange(Prenum); break; // rotate windows downwards case Ctrl_R: case 'r': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode win_rotate(FALSE, (int)Prenum1); // downwards break; // rotate windows upwards case 'R': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode win_rotate(TRUE, (int)Prenum1); // upwards break; // move window to the very top/bottom/left/right case 'K': case 'J': case 'H': case 'L': CHECK_CMDWIN; win_totop((int)Prenum, ((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0) | ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT)); break; // make all windows the same height case '=': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_equal(NULL, FALSE, 'b'); break; // increase current window height case '+': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setheight(curwin->w_height + (int)Prenum1); break; // decrease current window height case '-': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setheight(curwin->w_height - (int)Prenum1); break; // set current window height case Ctrl__: case '_': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setheight(Prenum ? (int)Prenum : 9999); break; // increase current window width case '>': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setwidth(curwin->w_width + (int)Prenum1); break; // decrease current window width case '<': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setwidth(curwin->w_width - (int)Prenum1); break; // set current window width case '|': #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setwidth(Prenum != 0 ? (int)Prenum : 9999); break; // jump to tag and split window if tag exists (in preview window) #if defined(FEAT_QUICKFIX) case '}': CHECK_CMDWIN; if (Prenum) g_do_tagpreview = Prenum; else g_do_tagpreview = p_pvh; #endif // FALLTHROUGH case ']': case Ctrl_RSB: CHECK_CMDWIN; // keep Visual mode, can select words to use as a tag if (Prenum) postponed_split = Prenum; else postponed_split = -1; #ifdef FEAT_QUICKFIX if (nchar != '}') g_do_tagpreview = 0; #endif // Execute the command right here, required when "wincmd ]" // was used in a function. do_nv_ident(Ctrl_RSB, NUL); break; #ifdef FEAT_SEARCHPATH // edit file name under cursor in a new window case 'f': case 'F': case Ctrl_F: wingotofile: CHECK_CMDWIN; ptr = grab_file_name(Prenum1, &lnum); if (ptr != NULL) { tabpage_T *oldtab = curtab; win_T *oldwin = curwin; # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif setpcmark(); if (win_split(0, 0) == OK) { RESET_BINDING(curwin); if (do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL, ECMD_HIDE, NULL) == FAIL) { // Failed to open the file, close the window // opened for it. win_close(curwin, FALSE); goto_tabpage_win(oldtab, oldwin); } else if (nchar == 'F' && lnum >= 0) { curwin->w_cursor.lnum = lnum; check_cursor_lnum(); beginline(BL_SOL | BL_FIX); } } vim_free(ptr); } break; #endif #ifdef FEAT_FIND_ID // Go to the first occurrence of the identifier under cursor along path in a // new window -- webb case 'i': // Go to any match case Ctrl_I: type = FIND_ANY; // FALLTHROUGH case 'd': // Go to definition, using 'define' case Ctrl_D: CHECK_CMDWIN; if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) break; find_pattern_in_path(ptr, 0, len, TRUE, Prenum == 0 ? TRUE : FALSE, type, Prenum1, ACTION_SPLIT, (linenr_T)1, (linenr_T)MAXLNUM); curwin->w_set_curswant = TRUE; break; #endif // Quickfix window only: view the result under the cursor in a new split. #if defined(FEAT_QUICKFIX) case K_KENTER: case CAR: if (bt_quickfix(curbuf)) qf_view_result(TRUE); break; #endif // CTRL-W g extended commands case 'g': case Ctrl_G: CHECK_CMDWIN; #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; // disallow scrolling here #endif ++no_mapping; ++allow_keys; // no mapping for xchar, but allow key codes if (xchar == NUL) xchar = plain_vgetc(); LANGMAP_ADJUST(xchar, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO (void)add_to_showcmd(xchar); #endif switch (xchar) { #if defined(FEAT_QUICKFIX) case '}': xchar = Ctrl_RSB; if (Prenum) g_do_tagpreview = Prenum; else g_do_tagpreview = p_pvh; #endif // FALLTHROUGH case ']': case Ctrl_RSB: // keep Visual mode, can select words to use as a tag if (Prenum) postponed_split = Prenum; else postponed_split = -1; // Execute the command right here, required when // "wincmd g}" was used in a function. do_nv_ident('g', xchar); break; #ifdef FEAT_SEARCHPATH case 'f': // CTRL-W gf: "gf" in a new tab page case 'F': // CTRL-W gF: "gF" in a new tab page cmdmod.cmod_tab = tabpage_index(curtab) + 1; nchar = xchar; goto wingotofile; #endif case 't': // CTRL-W gt: go to next tab page goto_tabpage((int)Prenum); break; case 'T': // CTRL-W gT: go to previous tab page goto_tabpage(-(int)Prenum1); break; case TAB: // CTRL-W g<Tab>: go to last used tab page if (goto_tabpage_lastused() == FAIL) beep_flush(); break; default: beep_flush(); break; } break; default: beep_flush(); break; } }
null
null
204,069
40601062791344847116382130508151483298
537
patch 8.2.4979: accessing freed memory when line is flushed Problem: Accessing freed memory when line is flushed. Solution: Make a copy of the pattern to search for.
other
openldap
3539fc33212b528c56b716584f2c2994af7c30b0
1
issuerAndThisUpdateCheck( struct berval *in, struct berval *is, struct berval *tu, void *ctx ) { int numdquotes = 0; struct berval x = *in; struct berval ni = BER_BVNULL; /* Parse GSER format */ enum { HAVE_NONE = 0x0, HAVE_ISSUER = 0x1, HAVE_THISUPDATE = 0x2, HAVE_ALL = ( HAVE_ISSUER | HAVE_THISUPDATE ) } have = HAVE_NONE; if ( in->bv_len < STRLENOF( "{issuer \"\",thisUpdate \"YYMMDDhhmmssZ\"}" ) ) return LDAP_INVALID_SYNTAX; if ( in->bv_val[0] != '{' || in->bv_val[in->bv_len-1] != '}' ) { return LDAP_INVALID_SYNTAX; } x.bv_val++; x.bv_len -= STRLENOF("{}"); do { /* eat leading spaces */ for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) { /* empty */; } /* should be at issuer or thisUpdate */ if ( strncasecmp( x.bv_val, "issuer", STRLENOF("issuer") ) == 0 ) { if ( have & HAVE_ISSUER ) return LDAP_INVALID_SYNTAX; /* parse issuer */ x.bv_val += STRLENOF("issuer"); x.bv_len -= STRLENOF("issuer"); if ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX; x.bv_val++; x.bv_len--; /* eat leading spaces */ for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) { /* empty */; } /* For backward compatibility, this part is optional */ if ( strncasecmp( x.bv_val, "rdnSequence:", STRLENOF("rdnSequence:") ) != 0 ) { return LDAP_INVALID_SYNTAX; } x.bv_val += STRLENOF("rdnSequence:"); x.bv_len -= STRLENOF("rdnSequence:"); if ( x.bv_val[0] != '"' ) return LDAP_INVALID_SYNTAX; x.bv_val++; x.bv_len--; is->bv_val = x.bv_val; is->bv_len = 0; for ( ; is->bv_len < x.bv_len; ) { if ( is->bv_val[is->bv_len] != '"' ) { is->bv_len++; continue; } if ( is->bv_val[is->bv_len+1] == '"' ) { /* double dquote */ numdquotes++; is->bv_len += 2; continue; } break; } x.bv_val += is->bv_len + 1; x.bv_len -= is->bv_len + 1; have |= HAVE_ISSUER; } else if ( strncasecmp( x.bv_val, "thisUpdate", STRLENOF("thisUpdate") ) == 0 ) { if ( have & HAVE_THISUPDATE ) return LDAP_INVALID_SYNTAX; /* parse thisUpdate */ x.bv_val += STRLENOF("thisUpdate"); x.bv_len -= STRLENOF("thisUpdate"); if ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX; x.bv_val++; x.bv_len--; /* eat leading spaces */ for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) { /* empty */; } if ( !x.bv_len || x.bv_val[0] != '"' ) return LDAP_INVALID_SYNTAX; x.bv_val++; x.bv_len--; tu->bv_val = x.bv_val; tu->bv_len = 0; for ( ; tu->bv_len < x.bv_len; tu->bv_len++ ) { if ( tu->bv_val[tu->bv_len] == '"' ) { break; } } x.bv_val += tu->bv_len + 1; x.bv_len -= tu->bv_len + 1; have |= HAVE_THISUPDATE; } else { return LDAP_INVALID_SYNTAX; } /* eat leading spaces */ for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) { /* empty */; } if ( have == HAVE_ALL ) { break; } if ( x.bv_val[0] != ',' ) { return LDAP_INVALID_SYNTAX; } x.bv_val++; x.bv_len--; } while ( 1 ); /* should have no characters left... */ if ( x.bv_len ) return LDAP_INVALID_SYNTAX; if ( numdquotes == 0 ) { ber_dupbv_x( &ni, is, ctx ); } else { ber_len_t src, dst; ni.bv_len = is->bv_len - numdquotes; ni.bv_val = slap_sl_malloc( ni.bv_len + 1, ctx ); for ( src = 0, dst = 0; src < is->bv_len; src++, dst++ ) { if ( is->bv_val[src] == '"' ) { src++; } ni.bv_val[dst] = is->bv_val[src]; } ni.bv_val[dst] = '\0'; } *is = ni; return 0; }
null
null
204,115
296580747977289517542159030414767300564
161
ITS#9454 fix issuerAndThisUpdateCheck
other
pjproject
8b621f192cae14456ee0b0ade52ce6c6f258af1e
1
static void parse_rtcp_bye(pjmedia_rtcp_session *sess, const void *pkt, pj_size_t size) { pj_str_t reason = {"-", 1}; /* Check and get BYE reason */ if (size > 8) { reason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_), *((pj_uint8_t*)pkt+8)); pj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9), reason.slen); reason.ptr = sess->stat.peer_sdes_buf_; } /* Just print RTCP BYE log */ PJ_LOG(5, (sess->name, "Received RTCP BYE, reason: %.*s", reason.slen, reason.ptr)); }
null
null
204,195
116381620827139969116334270652816885980
19
Merge pull request from GHSA-3qx3-cg72-wrh9
other
lldpd
73d42680fce8598324364dbb31b9bc3b8320adf7
1
sonmp_decode(struct lldpd *cfg, char *frame, int s, struct lldpd_hardware *hardware, struct lldpd_chassis **newchassis, struct lldpd_port **newport) { const u_int8_t mcastaddr[] = SONMP_MULTICAST_ADDR; struct lldpd_chassis *chassis; struct lldpd_port *port; struct lldpd_mgmt *mgmt; int length, i; u_int8_t *pos; u_int8_t seg[3], rchassis; struct in_addr address; log_debug("sonmp", "decode SONMP PDU from %s", hardware->h_ifname); if ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) { log_warn("sonmp", "failed to allocate remote chassis"); return -1; } TAILQ_INIT(&chassis->c_mgmt); if ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) { log_warn("sonmp", "failed to allocate remote port"); free(chassis); return -1; } #ifdef ENABLE_DOT1 TAILQ_INIT(&port->p_vlans); #endif length = s; pos = (u_int8_t*)frame; if (length < SONMP_SIZE) { log_warnx("sonmp", "too short SONMP frame received on %s", hardware->h_ifname); goto malformed; } if (PEEK_CMP(mcastaddr, sizeof(mcastaddr)) != 0) /* There is two multicast address. We just handle only one of * them. */ goto malformed; /* We skip to LLC PID */ PEEK_DISCARD(ETHER_ADDR_LEN); PEEK_DISCARD_UINT16; PEEK_DISCARD(6); if (PEEK_UINT16 != LLC_PID_SONMP_HELLO) { log_debug("sonmp", "incorrect LLC protocol ID received for SONMP on %s", hardware->h_ifname); goto malformed; } chassis->c_id_subtype = LLDP_CHASSISID_SUBTYPE_ADDR; if ((chassis->c_id = calloc(1, sizeof(struct in_addr) + 1)) == NULL) { log_warn("sonmp", "unable to allocate memory for chassis id on %s", hardware->h_ifname); goto malformed; } chassis->c_id_len = sizeof(struct in_addr) + 1; chassis->c_id[0] = 1; PEEK_BYTES(&address, sizeof(struct in_addr)); memcpy(chassis->c_id + 1, &address, sizeof(struct in_addr)); if (asprintf(&chassis->c_name, "%s", inet_ntoa(address)) == -1) { log_warnx("sonmp", "unable to write chassis name for %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(seg, sizeof(seg)); rchassis = PEEK_UINT8; for (i=0; sonmp_chassis_types[i].type != 0; i++) { if (sonmp_chassis_types[i].type == rchassis) break; } if (asprintf(&chassis->c_descr, "%s", sonmp_chassis_types[i].description) == -1) { log_warnx("sonmp", "unable to write chassis description for %s", hardware->h_ifname); goto malformed; } mgmt = lldpd_alloc_mgmt(LLDPD_AF_IPV4, &address, sizeof(struct in_addr), 0); if (mgmt == NULL) { if (errno == ENOMEM) log_warn("sonmp", "unable to allocate memory for management address"); else log_warn("sonmp", "too large management address received on %s", hardware->h_ifname); goto malformed; } TAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries); port->p_ttl = cfg?(cfg->g_config.c_tx_interval * cfg->g_config.c_tx_hold): LLDPD_TTL; port->p_ttl = (port->p_ttl + 999) / 1000; port->p_id_subtype = LLDP_PORTID_SUBTYPE_LOCAL; if (asprintf(&port->p_id, "%02x-%02x-%02x", seg[0], seg[1], seg[2]) == -1) { log_warn("sonmp", "unable to allocate memory for port id on %s", hardware->h_ifname); goto malformed; } port->p_id_len = strlen(port->p_id); /* Port description depend on the number of segments */ if ((seg[0] == 0) && (seg[1] == 0)) { if (asprintf(&port->p_descr, "port %d", seg[2]) == -1) { log_warnx("sonmp", "unable to write port description for %s", hardware->h_ifname); goto malformed; } } else if (seg[0] == 0) { if (asprintf(&port->p_descr, "port %d/%d", seg[1], seg[2]) == -1) { log_warnx("sonmp", "unable to write port description for %s", hardware->h_ifname); goto malformed; } } else { if (asprintf(&port->p_descr, "port %x:%x:%x", seg[0], seg[1], seg[2]) == -1) { log_warnx("sonmp", "unable to write port description for %s", hardware->h_ifname); goto malformed; } } *newchassis = chassis; *newport = port; return 1; malformed: lldpd_chassis_cleanup(chassis, 1); lldpd_port_cleanup(port, 1); free(port); return -1; }
null
null
204,378
433540116442967903483329906084914417
132
sonmp: fix heap overflow when reading SONMP packets By sending short SONMP packets, an attacker can make the decoder crash by reading too much data on the heap. SONMP packets are fixed in size, just ensure we get the enough bytes to contain a SONMP packet. CVE-2021-43612
other
php-src
259057b2a484747a6c73ce54c4fa0f5acbd56179
1
SPL_METHOD(SplDoublyLinkedList, unserialize) { spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *flags, *elem; char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Serialized string cannot be empty"); return; } s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); /* flags */ ALLOC_INIT_ZVAL(flags); if (!php_var_unserialize(&flags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(flags) != IS_LONG) { zval_ptr_dtor(&flags); goto error; } var_push_dtor(&var_hash, &flags); intern->flags = Z_LVAL_P(flags); zval_ptr_dtor(&flags); /* elements */ while(*p == ':') { ++p; ALLOC_INIT_ZVAL(elem); if (!php_var_unserialize(&elem, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&elem); goto error; } spl_ptr_llist_push(intern->llist, elem TSRMLS_CC); } if (*p != '\0') { goto error; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; error: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */
null
null
204,545
175570379904229409444093217226892836618
56
Fix bug #70366 - use-after-free vulnerability in unserialize() with SplDoublyLinkedList
other
samba
34383981a0c40860f71a4451ff8fd752e1b67666
1
static int ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; /* * At this point we know cnk.length <= val.length as * otherwise there could be no match */ if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ /* * haystack is a valid pointer in val * because the memmem() can only * succeed if the needle (cnk.length) * is <= haystacklen * * p will be a pointer at least * cnk.length from the end of haystack */ uint8_t *haystack = p + cnk.length; size_t haystacklen = end - (haystack); g = memmem(haystack, haystacklen, (const uint8_t *)cnk.data, cnk.length); if (g) { p = g; } } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; }
null
null
204,711
264293216438188529998910258908439139604
126
CVE-2019-3824 ldb: wildcard_match check tree operation Check the operation type of the passed parse tree, and return LDB_INAPPROPRIATE_MATCH if the operation is not LDB_OP_SUBSTRING. A query of "attribute=*" gets parsed as LDB_OP_PRESENT, checking the operation and failing ldb_wildcard_match should help prevent confusion writing tests. BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773 Signed-off-by: Gary Lockyer <[email protected]> Reviewed-by: Andrew Bartlett <[email protected]>
other
vim
adce965162dd89bf29ee0e5baf53652e7515762c
1
do_tag( char_u *tag, // tag (pattern) to jump to int type, int count, int forceit, // :ta with ! int verbose) // print "tag not found" message { taggy_T *tagstack = curwin->w_tagstack; int tagstackidx = curwin->w_tagstackidx; int tagstacklen = curwin->w_tagstacklen; int cur_match = 0; int cur_fnum = curbuf->b_fnum; int oldtagstackidx = tagstackidx; int prevtagstackidx = tagstackidx; int prev_num_matches; int new_tag = FALSE; int i; int ic; int no_regexp = FALSE; int error_cur_match = 0; int save_pos = FALSE; fmark_T saved_fmark; #ifdef FEAT_CSCOPE int jumped_to_tag = FALSE; #endif int new_num_matches; char_u **new_matches; int use_tagstack; int skip_msg = FALSE; char_u *buf_ffname = curbuf->b_ffname; // name to use for // priority computation int use_tfu = 1; // remember the matches for the last used tag static int num_matches = 0; static int max_num_matches = 0; // limit used for match search static char_u **matches = NULL; static int flags; #ifdef FEAT_EVAL if (tfu_in_use) { emsg(_(e_cannot_modify_tag_stack_within_tagfunc)); return FALSE; } #endif #ifdef EXITFREE if (type == DT_FREE) { // remove the list of matches FreeWild(num_matches, matches); # ifdef FEAT_CSCOPE cs_free_tags(); # endif num_matches = 0; return FALSE; } #endif if (type == DT_HELP) { type = DT_TAG; no_regexp = TRUE; use_tfu = 0; } prev_num_matches = num_matches; free_string_option(nofile_fname); nofile_fname = NULL; CLEAR_POS(&saved_fmark.mark); // shutup gcc 4.0 saved_fmark.fnum = 0; /* * Don't add a tag to the tagstack if 'tagstack' has been reset. */ if ((!p_tgst && *tag != NUL)) { use_tagstack = FALSE; new_tag = TRUE; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } #endif } else { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) use_tagstack = FALSE; else #endif use_tagstack = TRUE; // new pattern, add to the tag stack if (*tag != NUL && (type == DT_TAG || type == DT_SELECT || type == DT_JUMP #ifdef FEAT_QUICKFIX || type == DT_LTAG #endif #ifdef FEAT_CSCOPE || type == DT_CSCOPE #endif )) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (ptag_entry.tagname != NULL && STRCMP(ptag_entry.tagname, tag) == 0) { // Jumping to same tag: keep the current match, so that // the CursorHold autocommand example works. cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } } else #endif { /* * If the last used entry is not at the top, delete all tag * stack entries above it. */ while (tagstackidx < tagstacklen) tagstack_clear_entry(&tagstack[--tagstacklen]); // if the tagstack is full: remove oldest entry if (++tagstacklen > TAGSTACKSIZE) { tagstacklen = TAGSTACKSIZE; tagstack_clear_entry(&tagstack[0]); for (i = 1; i < tagstacklen; ++i) tagstack[i - 1] = tagstack[i]; --tagstackidx; } /* * put the tag name in the tag stack */ if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL) { curwin->w_tagstacklen = tagstacklen - 1; goto end_do_tag; } curwin->w_tagstacklen = tagstacklen; save_pos = TRUE; // save the cursor position below } new_tag = TRUE; } else { if ( #if defined(FEAT_QUICKFIX) g_do_tagpreview != 0 ? ptag_entry.tagname == NULL : #endif tagstacklen == 0) { // empty stack emsg(_(e_tag_stack_empty)); goto end_do_tag; } if (type == DT_POP) // go to older position { #ifdef FEAT_FOLDING int old_KeyTyped = KeyTyped; #endif if ((tagstackidx -= count) < 0) { emsg(_(e_at_bottom_of_tag_stack)); if (tagstackidx + count == 0) { // We did [num]^T from the bottom of the stack tagstackidx = 0; goto end_do_tag; } // We weren't at the bottom of the stack, so jump all the // way to the bottom now. tagstackidx = 0; } else if (tagstackidx >= tagstacklen) // count == 0? { emsg(_(e_at_top_of_tag_stack)); goto end_do_tag; } // Make a copy of the fmark, autocommands may invalidate the // tagstack before it's used. saved_fmark = tagstack[tagstackidx].fmark; if (saved_fmark.fnum != curbuf->b_fnum) { /* * Jump to other file. If this fails (e.g. because the * file was changed) keep original position in tag stack. */ if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum, GETF_SETMARK, forceit) == FAIL) { tagstackidx = oldtagstackidx; // back to old posn goto end_do_tag; } // An BufReadPost autocommand may jump to the '" mark, but // we don't what that here. curwin->w_cursor.lnum = saved_fmark.mark.lnum; } else { setpcmark(); curwin->w_cursor.lnum = saved_fmark.mark.lnum; } curwin->w_cursor.col = saved_fmark.mark.col; curwin->w_set_curswant = TRUE; check_cursor(); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_TAG) && old_KeyTyped) foldOpenCursor(); #endif // remove the old list of matches FreeWild(num_matches, matches); #ifdef FEAT_CSCOPE cs_free_tags(); #endif num_matches = 0; tag_freematch(); goto end_do_tag; } if (type == DT_TAG #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { // ":tag" (no argument): go to newer pattern save_pos = TRUE; // save the cursor position below if ((tagstackidx += count - 1) >= tagstacklen) { /* * Beyond the last one, just give an error message and * go to the last one. Don't store the cursor * position. */ tagstackidx = tagstacklen - 1; emsg(_(e_at_top_of_tag_stack)); save_pos = FALSE; } else if (tagstackidx < 0) // must have been count == 0 { emsg(_(e_at_bottom_of_tag_stack)); tagstackidx = 0; goto end_do_tag; } cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } new_tag = TRUE; } else // go to other matching tag { // Save index for when selection is cancelled. prevtagstackidx = tagstackidx; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { if (--tagstackidx < 0) tagstackidx = 0; cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } switch (type) { case DT_FIRST: cur_match = count - 1; break; case DT_SELECT: case DT_JUMP: #ifdef FEAT_CSCOPE case DT_CSCOPE: #endif case DT_LAST: cur_match = MAXCOL - 1; break; case DT_NEXT: cur_match += count; break; case DT_PREV: cur_match -= count; break; } if (cur_match >= MAXCOL) cur_match = MAXCOL - 1; else if (cur_match < 0) { emsg(_(e_cannot_go_before_first_matching_tag)); skip_msg = TRUE; cur_match = 0; cur_fnum = curbuf->b_fnum; } } } #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (type != DT_SELECT && type != DT_JUMP) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } } else #endif { /* * For ":tag [arg]" or ":tselect" remember position before the jump. */ saved_fmark = tagstack[tagstackidx].fmark; if (save_pos) { tagstack[tagstackidx].fmark.mark = curwin->w_cursor; tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum; } // Curwin will change in the call to jumpto_tag() if ":stag" was // used or an autocommand jumps to another window; store value of // tagstackidx now. curwin->w_tagstackidx = tagstackidx; if (type != DT_SELECT && type != DT_JUMP) { curwin->w_tagstack[tagstackidx].cur_match = cur_match; curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum; } } } // When not using the current buffer get the name of buffer "cur_fnum". // Makes sure that the tag order doesn't change when using a remembered // position for "cur_match". if (cur_fnum != curbuf->b_fnum) { buf_T *buf = buflist_findnr(cur_fnum); if (buf != NULL) buf_ffname = buf->b_ffname; } /* * Repeat searching for tags, when a file has not been found. */ for (;;) { int other_name; char_u *name; /* * When desired match not found yet, try to find it (and others). */ if (use_tagstack) name = tagstack[tagstackidx].tagname; #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) name = ptag_entry.tagname; #endif else name = tag; other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0); if (new_tag || (cur_match >= num_matches && max_num_matches != MAXCOL) || other_name) { if (other_name) { vim_free(tagmatchname); tagmatchname = vim_strsave(name); } if (type == DT_SELECT || type == DT_JUMP #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) cur_match = MAXCOL - 1; if (type == DT_TAG) max_num_matches = MAXCOL; else max_num_matches = cur_match + 1; // when the argument starts with '/', use it as a regexp if (!no_regexp && *name == '/') { flags = TAG_REGEXP; ++name; } else flags = TAG_NOIC; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE) flags = TAG_CSCOPE; #endif if (verbose) flags |= TAG_VERBOSE; if (!use_tfu) flags |= TAG_NO_TAGFUNC; if (find_tags(name, &new_num_matches, &new_matches, flags, max_num_matches, buf_ffname) == OK && new_num_matches < max_num_matches) max_num_matches = MAXCOL; // If less than max_num_matches // found: all matches found. // If there already were some matches for the same name, move them // to the start. Avoids that the order changes when using // ":tnext" and jumping to another file. if (!new_tag && !other_name) { int j, k; int idx = 0; tagptrs_T tagp, tagp2; // Find the position of each old match in the new list. Need // to use parse_match() to find the tag line. for (j = 0; j < num_matches; ++j) { parse_match(matches[j], &tagp); for (i = idx; i < new_num_matches; ++i) { parse_match(new_matches[i], &tagp2); if (STRCMP(tagp.tagname, tagp2.tagname) == 0) { char_u *p = new_matches[i]; for (k = i; k > idx; --k) new_matches[k] = new_matches[k - 1]; new_matches[idx++] = p; break; } } } } FreeWild(num_matches, matches); num_matches = new_num_matches; matches = new_matches; } if (num_matches <= 0) { if (verbose) semsg(_(e_tag_not_found_str), name); #if defined(FEAT_QUICKFIX) g_do_tagpreview = 0; #endif } else { int ask_for_selection = FALSE; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE && num_matches > 1) { cs_print_tags(); ask_for_selection = TRUE; } else #endif if (type == DT_TAG && *tag != NUL) // If a count is supplied to the ":tag <name>" command, then // jump to count'th matching tag. cur_match = count > 0 ? count - 1 : 0; else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) { print_tag_list(new_tag, use_tagstack, num_matches, matches); ask_for_selection = TRUE; } #if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL) else if (type == DT_LTAG) { if (add_llist_tags(tag, num_matches, matches) == FAIL) goto end_do_tag; cur_match = 0; // Jump to the first tag } #endif if (ask_for_selection == TRUE) { /* * Ask to select a tag from the list. */ i = prompt_for_number(NULL); if (i <= 0 || i > num_matches || got_int) { // no valid choice: don't change anything if (use_tagstack) { tagstack[tagstackidx].fmark = saved_fmark; tagstackidx = prevtagstackidx; } #ifdef FEAT_CSCOPE cs_free_tags(); jumped_to_tag = TRUE; #endif break; } cur_match = i - 1; } if (cur_match >= num_matches) { // Avoid giving this error when a file wasn't found and we're // looking for a match in another file, which wasn't found. // There will be an emsg("file doesn't exist") below then. if ((type == DT_NEXT || type == DT_FIRST) && nofile_fname == NULL) { if (num_matches == 1) emsg(_(e_there_is_only_one_matching_tag)); else emsg(_(e_cannot_go_beyond_last_matching_tag)); skip_msg = TRUE; } cur_match = num_matches - 1; } if (use_tagstack) { tagptrs_T tagp; tagstack[tagstackidx].cur_match = cur_match; tagstack[tagstackidx].cur_fnum = cur_fnum; // store user-provided data originating from tagfunc if (use_tfu && parse_match(matches[cur_match], &tagp) == OK && tagp.user_data) { VIM_CLEAR(tagstack[tagstackidx].user_data); tagstack[tagstackidx].user_data = vim_strnsave( tagp.user_data, tagp.user_data_end - tagp.user_data); } ++tagstackidx; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } #endif /* * Only when going to try the next match, report that the previous * file didn't exist. Otherwise an emsg() is given below. */ if (nofile_fname != NULL && error_cur_match != cur_match) smsg(_("File \"%s\" does not exist"), nofile_fname); ic = (matches[cur_match][0] & MT_IC_OFF); if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP #ifdef FEAT_CSCOPE && type != DT_CSCOPE #endif && (num_matches > 1 || ic) && !skip_msg) { // Give an indication of the number of matching tags sprintf((char *)IObuff, _("tag %d of %d%s"), cur_match + 1, num_matches, max_num_matches != MAXCOL ? _(" or more") : ""); if (ic) STRCAT(IObuff, _(" Using tag with different case!")); if ((num_matches > prev_num_matches || new_tag) && num_matches > 1) { if (ic) msg_attr((char *)IObuff, HL_ATTR(HLF_W)); else msg((char *)IObuff); msg_scroll = TRUE; // don't overwrite this message } else give_warning(IObuff, ic); if (ic && !msg_scrolled && msg_silent == 0) { out_flush(); ui_delay(1007L, TRUE); } } #if defined(FEAT_EVAL) // Let the SwapExists event know what tag we are jumping to. vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name); set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1); #endif /* * Jump to the desired match. */ i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE); #if defined(FEAT_EVAL) set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); #endif if (i == NOTAGFILE) { // File not found: try again with another matching tag if ((type == DT_PREV && cur_match > 0) || ((type == DT_TAG || type == DT_NEXT || type == DT_FIRST) && (max_num_matches != MAXCOL || cur_match < num_matches - 1))) { error_cur_match = cur_match; if (use_tagstack) --tagstackidx; if (type == DT_PREV) --cur_match; else { type = DT_NEXT; ++cur_match; } continue; } semsg(_(e_file_str_does_not_exist), nofile_fname); } else { // We may have jumped to another window, check that // tagstackidx is still valid. if (use_tagstack && tagstackidx > curwin->w_tagstacklen) tagstackidx = curwin->w_tagstackidx; #ifdef FEAT_CSCOPE jumped_to_tag = TRUE; #endif } } break; } end_do_tag: // Only store the new index when using the tagstack and it's valid. if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) curwin->w_tagstackidx = tagstackidx; postponed_split = 0; // don't split next time # ifdef FEAT_QUICKFIX g_do_tagpreview = 0; // don't do tag preview next time # endif #ifdef FEAT_CSCOPE return jumped_to_tag; #else return FALSE; #endif }
null
null
204,751
126478621754533124439278167196869287849
679
patch 9.0.0246: using freed memory when 'tagfunc' deletes the buffer Problem: Using freed memory when 'tagfunc' deletes the buffer. Solution: Make a copy of the tag name.
other
evolution-data-server
5d8b92c622f6927b253762ff9310479dd3ac627d
1
gpg_ctx_add_recipient (struct _GpgCtx *gpg, const gchar *keyid) { if (gpg->mode != GPG_CTX_MODE_ENCRYPT && gpg->mode != GPG_CTX_MODE_EXPORT) return; if (!gpg->recipients) gpg->recipients = g_ptr_array_new (); g_ptr_array_add (gpg->recipients, g_strdup (keyid)); }
null
null
206,025
141933283002790613862782726205564754266
11
CamelGpgContext: Enclose email addresses in brackets. The recipient list for encrypting can be specified by either key ID or email address. Enclose email addresses in brackets to ensure an exact match, as per the gpg man page: HOW TO SPECIFY A USER ID ... By exact match on an email address. This is indicated by enclosing the email address in the usual way with left and right angles. <[email protected]> Without the brackets gpg uses a substring match, which risks selecting the wrong recipient.
other
vim
c6fdb15d423df22e1776844811d082322475e48a
1
parse_command_modifiers( exarg_T *eap, char **errormsg, cmdmod_T *cmod, int skip_only) { char_u *orig_cmd = eap->cmd; char_u *cmd_start = NULL; int use_plus_cmd = FALSE; int starts_with_colon = FALSE; int vim9script = in_vim9script(); int has_visual_range = FALSE; CLEAR_POINTER(cmod); cmod->cmod_flags = sticky_cmdmod_flags; if (STRNCMP(eap->cmd, "'<,'>", 5) == 0) { // The automatically inserted Visual area range is skipped, so that // typing ":cmdmod cmd" in Visual mode works without having to move the // range to after the modififiers. The command will be // "'<,'>cmdmod cmd", parse "cmdmod cmd" and then put back "'<,'>" // before "cmd" below. eap->cmd += 5; cmd_start = eap->cmd; has_visual_range = TRUE; } // Repeat until no more command modifiers are found. for (;;) { char_u *p; while (*eap->cmd == ' ' || *eap->cmd == '\t' || *eap->cmd == ':') { if (*eap->cmd == ':') starts_with_colon = TRUE; ++eap->cmd; } // in ex mode, an empty command (after modifiers) works like :+ if (*eap->cmd == NUL && exmode_active && (getline_equal(eap->getline, eap->cookie, getexmodeline) || getline_equal(eap->getline, eap->cookie, getexline)) && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { use_plus_cmd = TRUE; if (!skip_only) ex_pressedreturn = TRUE; break; // no modifiers following } // ignore comment and empty lines if (comment_start(eap->cmd, starts_with_colon)) { // a comment ends at a NL if (eap->nextcmd == NULL) { eap->nextcmd = vim_strchr(eap->cmd, '\n'); if (eap->nextcmd != NULL) ++eap->nextcmd; } if (vim9script && has_cmdmod(cmod, FALSE)) *errormsg = _(e_command_modifier_without_command); return FAIL; } if (*eap->cmd == NUL) { if (!skip_only) { ex_pressedreturn = TRUE; if (vim9script && has_cmdmod(cmod, FALSE)) *errormsg = _(e_command_modifier_without_command); } return FAIL; } p = skip_range(eap->cmd, TRUE, NULL); // In Vim9 script a variable can shadow a command modifier: // verbose = 123 // verbose += 123 // silent! verbose = func() // verbose.member = 2 // verbose[expr] = 2 // But not: // verbose [a, b] = list if (vim9script) { char_u *s, *n; for (s = eap->cmd; ASCII_ISALPHA(*s); ++s) ; n = skipwhite(s); if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=') || *s == '[') break; } switch (*p) { // When adding an entry, also modify cmd_exists(). case 'a': if (!checkforcmd_noparen(&eap->cmd, "aboveleft", 3)) break; cmod->cmod_split |= WSP_ABOVE; continue; case 'b': if (checkforcmd_noparen(&eap->cmd, "belowright", 3)) { cmod->cmod_split |= WSP_BELOW; continue; } if (checkforcmd_opt(&eap->cmd, "browse", 3, TRUE)) { #ifdef FEAT_BROWSE_CMD cmod->cmod_flags |= CMOD_BROWSE; #endif continue; } if (!checkforcmd_noparen(&eap->cmd, "botright", 2)) break; cmod->cmod_split |= WSP_BOT; continue; case 'c': if (!checkforcmd_opt(&eap->cmd, "confirm", 4, TRUE)) break; #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) cmod->cmod_flags |= CMOD_CONFIRM; #endif continue; case 'k': if (checkforcmd_noparen(&eap->cmd, "keepmarks", 3)) { cmod->cmod_flags |= CMOD_KEEPMARKS; continue; } if (checkforcmd_noparen(&eap->cmd, "keepalt", 5)) { cmod->cmod_flags |= CMOD_KEEPALT; continue; } if (checkforcmd_noparen(&eap->cmd, "keeppatterns", 5)) { cmod->cmod_flags |= CMOD_KEEPPATTERNS; continue; } if (!checkforcmd_noparen(&eap->cmd, "keepjumps", 5)) break; cmod->cmod_flags |= CMOD_KEEPJUMPS; continue; case 'f': // only accept ":filter {pat} cmd" { char_u *reg_pat; char_u *nulp = NULL; int c = 0; if (!checkforcmd_noparen(&p, "filter", 4) || *p == NUL || (ends_excmd(*p) #ifdef FEAT_EVAL // in ":filter #pat# cmd" # does not // start a comment && (!vim9script || VIM_ISWHITE(p[1])) #endif )) break; if (*p == '!') { cmod->cmod_filter_force = TRUE; p = skipwhite(p + 1); if (*p == NUL || ends_excmd(*p)) break; } #ifdef FEAT_EVAL // Avoid that "filter(arg)" is recognized. if (vim9script && !VIM_ISWHITE(p[-1])) break; #endif if (skip_only) p = skip_vimgrep_pat(p, NULL, NULL); else // NOTE: This puts a NUL after the pattern. p = skip_vimgrep_pat_ext(p, &reg_pat, NULL, &nulp, &c); if (p == NULL || *p == NUL) break; if (!skip_only) { cmod->cmod_filter_regmatch.regprog = vim_regcomp(reg_pat, RE_MAGIC); if (cmod->cmod_filter_regmatch.regprog == NULL) break; // restore the character overwritten by NUL if (nulp != NULL) *nulp = c; } eap->cmd = p; continue; } // ":hide" and ":hide | cmd" are not modifiers case 'h': if (p != eap->cmd || !checkforcmd_noparen(&p, "hide", 3) || *p == NUL || ends_excmd(*p)) break; eap->cmd = p; cmod->cmod_flags |= CMOD_HIDE; continue; case 'l': if (checkforcmd_noparen(&eap->cmd, "lockmarks", 3)) { cmod->cmod_flags |= CMOD_LOCKMARKS; continue; } if (checkforcmd_noparen(&eap->cmd, "legacy", 3)) { if (ends_excmd2(p, eap->cmd)) { *errormsg = _(e_legacy_must_be_followed_by_command); return FAIL; } cmod->cmod_flags |= CMOD_LEGACY; continue; } if (!checkforcmd_noparen(&eap->cmd, "leftabove", 5)) break; cmod->cmod_split |= WSP_ABOVE; continue; case 'n': if (checkforcmd_noparen(&eap->cmd, "noautocmd", 3)) { cmod->cmod_flags |= CMOD_NOAUTOCMD; continue; } if (!checkforcmd_noparen(&eap->cmd, "noswapfile", 3)) break; cmod->cmod_flags |= CMOD_NOSWAPFILE; continue; case 'r': if (!checkforcmd_noparen(&eap->cmd, "rightbelow", 6)) break; cmod->cmod_split |= WSP_BELOW; continue; case 's': if (checkforcmd_noparen(&eap->cmd, "sandbox", 3)) { cmod->cmod_flags |= CMOD_SANDBOX; continue; } if (!checkforcmd_noparen(&eap->cmd, "silent", 3)) break; cmod->cmod_flags |= CMOD_SILENT; if (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1])) { // ":silent!", but not "silent !cmd" eap->cmd = skipwhite(eap->cmd + 1); cmod->cmod_flags |= CMOD_ERRSILENT; } continue; case 't': if (checkforcmd_noparen(&p, "tab", 3)) { if (!skip_only) { long tabnr = get_address(eap, &eap->cmd, ADDR_TABS, eap->skip, skip_only, FALSE, 1); if (tabnr == MAXLNUM) cmod->cmod_tab = tabpage_index(curtab) + 1; else { if (tabnr < 0 || tabnr > LAST_TAB_NR) { *errormsg = _(e_invalid_range); return FAIL; } cmod->cmod_tab = tabnr + 1; } } eap->cmd = p; continue; } if (!checkforcmd_noparen(&eap->cmd, "topleft", 2)) break; cmod->cmod_split |= WSP_TOP; continue; case 'u': if (!checkforcmd_noparen(&eap->cmd, "unsilent", 3)) break; cmod->cmod_flags |= CMOD_UNSILENT; continue; case 'v': if (checkforcmd_noparen(&eap->cmd, "vertical", 4)) { cmod->cmod_split |= WSP_VERT; continue; } if (checkforcmd_noparen(&eap->cmd, "vim9cmd", 4)) { if (ends_excmd2(p, eap->cmd)) { *errormsg = _(e_vim9cmd_must_be_followed_by_command); return FAIL; } cmod->cmod_flags |= CMOD_VIM9CMD; continue; } if (!checkforcmd_noparen(&p, "verbose", 4)) break; if (vim_isdigit(*eap->cmd)) { // zero means not set, one is verbose == 0, etc. cmod->cmod_verbose = atoi((char *)eap->cmd) + 1; } else cmod->cmod_verbose = 2; // default: verbose == 1 eap->cmd = p; continue; } break; } if (has_visual_range) { if (eap->cmd > cmd_start) { // Move the '<,'> range to after the modifiers and insert a colon. // Since the modifiers have been parsed put the colon on top of the // space: "'<,'>mod cmd" -> "mod:'<,'>cmd // Put eap->cmd after the colon. if (use_plus_cmd) { size_t len = STRLEN(cmd_start); // Special case: empty command uses "+": // "'<,'>mods" -> "mods'<,'>+ mch_memmove(orig_cmd, cmd_start, len); STRCPY(orig_cmd + len, "'<,'>+"); } else { mch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start); eap->cmd -= 5; mch_memmove(eap->cmd - 1, ":'<,'>", 6); } } else // No modifiers, move the pointer back. // Special case: change empty command to "+". if (use_plus_cmd) eap->cmd = (char_u *)"'<,'>+"; else eap->cmd = orig_cmd; } else if (use_plus_cmd) eap->cmd = (char_u *)"+"; return OK; }
null
null
206,262
23783941848142444822455321328938674747
362
patch 9.0.0025: accessing beyond allocated memory with the cmdline window Problem: Accessing beyond allocated memory when using the cmdline window in Ex mode. Solution: Use "*" instead of "'<,'>" for Visual mode.
other
vim
6456fae9ba8e72c74b2c0c499eaf09974604ff30
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 --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 }
null
null
206,921
14507096832468276355973161027739212088
1,481
patch 8.2.4440: crash with specific regexp pattern and string Problem: Crash with specific regexp pattern and string. Solution: Stop at the start of the string.
other
flatpak
fb473cad801c6b61706353256cab32330557374a
1
apply_extra_data (FlatpakDir *self, GFile *checkoutdir, GCancellable *cancellable, GError **error) { g_autoptr(GFile) metadata = NULL; g_autofree char *metadata_contents = NULL; gsize metadata_size; g_autoptr(GKeyFile) metakey = NULL; g_autofree char *id = NULL; g_autofree char *runtime_pref = NULL; g_autoptr(FlatpakDecomposed) runtime_ref = NULL; g_autoptr(FlatpakDeploy) runtime_deploy = NULL; g_autoptr(FlatpakBwrap) bwrap = NULL; g_autoptr(GFile) app_files = NULL; g_autoptr(GFile) apply_extra_file = NULL; g_autoptr(GFile) app_export_file = NULL; g_autoptr(GFile) extra_export_file = NULL; g_autoptr(GFile) extra_files = NULL; g_autoptr(GFile) runtime_files = NULL; g_autoptr(FlatpakContext) app_context = NULL; g_auto(GStrv) minimal_envp = NULL; g_autofree char *runtime_arch = NULL; int exit_status; const char *group = FLATPAK_METADATA_GROUP_APPLICATION; g_autoptr(GError) local_error = NULL; apply_extra_file = g_file_resolve_relative_path (checkoutdir, "files/bin/apply_extra"); if (!g_file_query_exists (apply_extra_file, cancellable)) return TRUE; metadata = g_file_get_child (checkoutdir, "metadata"); if (!g_file_load_contents (metadata, cancellable, &metadata_contents, &metadata_size, NULL, error)) return FALSE; metakey = g_key_file_new (); if (!g_key_file_load_from_data (metakey, metadata_contents, metadata_size, 0, error)) return FALSE; id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME, &local_error); if (id == NULL) { group = FLATPAK_METADATA_GROUP_RUNTIME; id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME, NULL); if (id == NULL) { g_propagate_error (error, g_steal_pointer (&local_error)); return FALSE; } g_clear_error (&local_error); } runtime_pref = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_RUNTIME, error); if (runtime_pref == NULL) runtime_pref = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_EXTENSION_OF, FLATPAK_METADATA_KEY_RUNTIME, NULL); if (runtime_pref == NULL) return FALSE; runtime_ref = flatpak_decomposed_new_from_pref (FLATPAK_KINDS_RUNTIME, runtime_pref, error); if (runtime_ref == NULL) return FALSE; runtime_arch = flatpak_decomposed_dup_arch (runtime_ref); if (!g_key_file_get_boolean (metakey, FLATPAK_METADATA_GROUP_EXTRA_DATA, FLATPAK_METADATA_KEY_NO_RUNTIME, NULL)) { /* We pass in self here so that we ensure that we find the runtime in case it only exists in this installation (which might be custom) */ runtime_deploy = flatpak_find_deploy_for_ref (flatpak_decomposed_get_ref (runtime_ref), NULL, self, cancellable, error); if (runtime_deploy == NULL) return FALSE; runtime_files = flatpak_deploy_get_files (runtime_deploy); } app_files = g_file_get_child (checkoutdir, "files"); app_export_file = g_file_get_child (checkoutdir, "export"); extra_files = g_file_get_child (app_files, "extra"); extra_export_file = g_file_get_child (extra_files, "export"); minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE); bwrap = flatpak_bwrap_new (minimal_envp); flatpak_bwrap_add_args (bwrap, flatpak_get_bwrap (), NULL); if (runtime_files) flatpak_bwrap_add_args (bwrap, "--ro-bind", flatpak_file_get_path_cached (runtime_files), "/usr", "--lock-file", "/usr/.ref", NULL); flatpak_bwrap_add_args (bwrap, "--ro-bind", flatpak_file_get_path_cached (app_files), "/app", "--bind", flatpak_file_get_path_cached (extra_files), "/app/extra", "--chdir", "/app/extra", /* We run as root in the system-helper case, so drop all caps */ "--cap-drop", "ALL", NULL); if (!flatpak_run_setup_base_argv (bwrap, runtime_files, NULL, runtime_arch, /* Might need multiarch in apply_extra (see e.g. #3742). Should be pretty safe in this limited context */ FLATPAK_RUN_FLAG_MULTIARCH | FLATPAK_RUN_FLAG_NO_SESSION_HELPER | FLATPAK_RUN_FLAG_NO_PROC, error)) return FALSE; app_context = flatpak_context_new (); if (!flatpak_run_add_environment_args (bwrap, NULL, FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY | FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY | FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY, id, app_context, NULL, NULL, NULL, cancellable, error)) return FALSE; flatpak_bwrap_add_arg (bwrap, "/app/bin/apply_extra"); flatpak_bwrap_finish (bwrap); g_debug ("Running /app/bin/apply_extra "); /* We run the sandbox without caps, but it can still create files owned by itself with * arbitrary permissions, including setuid myself. This is extra risky in the case where * this runs as root in the system helper case. We canonicalize the permissions at the * end, but to avoid non-canonical permissions leaking out before then we make the * toplevel dir only accessible to the user */ if (chmod (flatpak_file_get_path_cached (extra_files), 0700) != 0) { glnx_set_error_from_errno (error); return FALSE; } if (!g_spawn_sync (NULL, (char **) bwrap->argv->pdata, bwrap->envp, G_SPAWN_SEARCH_PATH, child_setup, bwrap->fds, NULL, NULL, &exit_status, error)) return FALSE; if (!flatpak_canonicalize_permissions (AT_FDCWD, flatpak_file_get_path_cached (extra_files), getuid () == 0 ? 0 : -1, getuid () == 0 ? 0 : -1, error)) return FALSE; if (exit_status != 0) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, _("apply_extra script failed, exit status %d"), exit_status); return FALSE; } if (g_file_query_exists (extra_export_file, cancellable)) { if (!flatpak_mkdir_p (app_export_file, cancellable, error)) return FALSE; if (!flatpak_cp_a (extra_export_file, app_export_file, FLATPAK_CP_FLAGS_MERGE, cancellable, error)) return FALSE; } return TRUE; }
null
null
206,989
62902606532827421827792118702945647615
172
dir: Pass environment via bwrap --setenv when running apply_extra This means we can systematically pass the environment variables through bwrap(1), even if it is setuid and thus is filtering out security-sensitive environment variables. bwrap ends up being run with an empty environment instead. As with the previous commit, this regressed while fixing CVE-2021-21261. Fixes: 6d1773d2 "run: Convert all environment variables into bwrap arguments" Signed-off-by: Simon McVittie <[email protected]>
other
linux
054aa8d439b9185d4f5eb9a90282d1ce74772969
1
static struct file *__fget_files(struct files_struct *files, unsigned int fd, fmode_t mask, unsigned int refs) { struct file *file; rcu_read_lock(); loop: file = files_lookup_fd_rcu(files, fd); if (file) { /* File object ref couldn't be taken. * dup2() atomicity guarantee is the reason * we loop to catch the new file (or NULL pointer) */ if (file->f_mode & mask) file = NULL; else if (!get_file_rcu_many(file, refs)) goto loop; } rcu_read_unlock(); return file; }
null
null
208,085
236448832030969755251234701523533614254
22
fget: check that the fd still exists after getting a ref to it Jann Horn points out that there is another possible race wrt Unix domain socket garbage collection, somewhat reminiscent of the one fixed in commit cbcf01128d0a ("af_unix: fix garbage collect vs MSG_PEEK"). See the extended comment about the garbage collection requirements added to unix_peek_fds() by that commit for details. The race comes from how we can locklessly look up a file descriptor just as it is in the process of being closed, and with the right artificial timing (Jann added a few strategic 'mdelay(500)' calls to do that), the Unix domain socket garbage collector could see the reference count decrement of the close() happen before fget() took its reference to the file and the file was attached onto a new file descriptor. This is all (intentionally) correct on the 'struct file *' side, with RCU lookups and lockless reference counting very much part of the design. Getting that reference count out of order isn't a problem per se. But the garbage collector can get confused by seeing this situation of having seen a file not having any remaining external references and then seeing it being attached to an fd. In commit cbcf01128d0a ("af_unix: fix garbage collect vs MSG_PEEK") the fix was to serialize the file descriptor install with the garbage collector by taking and releasing the unix_gc_lock. That's not really an option here, but since this all happens when we are in the process of looking up a file descriptor, we can instead simply just re-check that the file hasn't been closed in the meantime, and just re-do the lookup if we raced with a concurrent close() of the same file descriptor. Reported-and-tested-by: Jann Horn <[email protected]> Acked-by: Miklos Szeredi <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
other
vim
27efc62f5d86afcb2ecb7565587fe8dea4b036fe
1
check_termcode( int max_offset, char_u *buf, int bufsize, int *buflen) { char_u *tp; char_u *p; int slen = 0; // init for GCC int modslen; int len; int retval = 0; int offset; char_u key_name[2]; int modifiers; char_u *modifiers_start = NULL; int key; int new_slen; // Length of what will replace the termcode char_u string[MAX_KEY_CODE_LEN + 1]; int i, j; int idx = 0; int cpo_koffset; cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL); /* * Speed up the checks for terminal codes by gathering all first bytes * used in termleader[]. Often this is just a single <Esc>. */ if (need_gather) gather_termleader(); /* * Check at several positions in typebuf.tb_buf[], to catch something like * "x<Up>" that can be mapped. Stop at max_offset, because characters * after that cannot be used for mapping, and with @r commands * typebuf.tb_buf[] can become very long. * This is used often, KEEP IT FAST! */ for (offset = 0; offset < max_offset; ++offset) { if (buf == NULL) { if (offset >= typebuf.tb_len) break; tp = typebuf.tb_buf + typebuf.tb_off + offset; len = typebuf.tb_len - offset; // length of the input } else { if (offset >= *buflen) break; tp = buf + offset; len = *buflen - offset; } /* * Don't check characters after K_SPECIAL, those are already * translated terminal chars (avoid translating ~@^Hx). */ if (*tp == K_SPECIAL) { offset += 2; // there are always 2 extra characters continue; } /* * Skip this position if the character does not appear as the first * character in term_strings. This speeds up a lot, since most * termcodes start with the same character (ESC or CSI). */ i = *tp; for (p = termleader; *p && *p != i; ++p) ; if (*p == NUL) continue; /* * Skip this position if p_ek is not set and tp[0] is an ESC and we * are in Insert mode. */ if (*tp == ESC && !p_ek && (State & MODE_INSERT)) continue; key_name[0] = NUL; // no key name found yet key_name[1] = NUL; // no key name found yet modifiers = 0; // no modifiers yet #ifdef FEAT_GUI if (gui.in_use) { /* * GUI special key codes are all of the form [CSI xx]. */ if (*tp == CSI) // Special key from GUI { if (len < 3) return -1; // Shouldn't happen slen = 3; key_name[0] = tp[1]; key_name[1] = tp[2]; } } else #endif // FEAT_GUI { int mouse_index_found = -1; for (idx = 0; idx < tc_len; ++idx) { /* * Ignore the entry if we are not at the start of * typebuf.tb_buf[] * and there are not enough characters to make a match. * But only when the 'K' flag is in 'cpoptions'. */ slen = termcodes[idx].len; modifiers_start = NULL; if (cpo_koffset && offset && len < slen) continue; if (STRNCMP(termcodes[idx].code, tp, (size_t)(slen > len ? len : slen)) == 0) { int looks_like_mouse_start = FALSE; if (len < slen) // got a partial sequence return -1; // need to get more chars /* * When found a keypad key, check if there is another key * that matches and use that one. This makes <Home> to be * found instead of <kHome> when they produce the same * key code. */ if (termcodes[idx].name[0] == 'K' && VIM_ISDIGIT(termcodes[idx].name[1])) { for (j = idx + 1; j < tc_len; ++j) if (termcodes[j].len == slen && STRNCMP(termcodes[idx].code, termcodes[j].code, slen) == 0) { idx = j; break; } } if (slen == 2 && len > 2 && termcodes[idx].code[0] == ESC && termcodes[idx].code[1] == '[') { // The mouse termcode "ESC [" is also the prefix of // "ESC [ I" (focus gained) and other keys. Check some // more bytes to find out. if (!isdigit(tp[2])) { // ESC [ without number following: Only use it when // there is no other match. looks_like_mouse_start = TRUE; } else if (termcodes[idx].name[0] == KS_DEC_MOUSE) { char_u *nr = tp + 2; int count = 0; // If a digit is following it could be a key with // modifier, e.g., ESC [ 1;2P. Can be confused // with DEC_MOUSE, which requires four numbers // following. If not then it can't be a DEC_MOUSE // code. for (;;) { ++count; (void)getdigits(&nr); if (nr >= tp + len) return -1; // partial sequence if (*nr != ';') break; ++nr; if (nr >= tp + len) return -1; // partial sequence } if (count < 4) continue; // no match } } if (looks_like_mouse_start) { // Only use it when there is no other match. if (mouse_index_found < 0) mouse_index_found = idx; } else { key_name[0] = termcodes[idx].name[0]; key_name[1] = termcodes[idx].name[1]; break; } } /* * Check for code with modifier, like xterm uses: * <Esc>[123;*X (modslen == slen - 3) * <Esc>[@;*X (matches <Esc>[X and <Esc>[1;9X ) * Also <Esc>O*X and <M-O>*X (modslen == slen - 2). * When there is a modifier the * matches a number. * When there is no modifier the ;* or * is omitted. */ if (termcodes[idx].modlen > 0 && mouse_index_found < 0) { int at_code; modslen = termcodes[idx].modlen; if (cpo_koffset && offset && len < modslen) continue; at_code = termcodes[idx].code[modslen] == '@'; if (STRNCMP(termcodes[idx].code, tp, (size_t)(modslen > len ? len : modslen)) == 0) { int n; if (len <= modslen) // got a partial sequence return -1; // need to get more chars if (tp[modslen] == termcodes[idx].code[slen - 1]) // no modifiers slen = modslen + 1; else if (tp[modslen] != ';' && modslen == slen - 3) // no match for "code;*X" with "code;" continue; else if (at_code && tp[modslen] != '1') // no match for "<Esc>[@" with "<Esc>[1" continue; else { // Skip over the digits, the final char must // follow. URXVT can use a negative value, thus // also accept '-'. for (j = slen - 2; j < len && (isdigit(tp[j]) || tp[j] == '-' || tp[j] == ';'); ++j) ; ++j; if (len < j) // got a partial sequence return -1; // need to get more chars if (tp[j - 1] != termcodes[idx].code[slen - 1]) continue; // no match modifiers_start = tp + slen - 2; // Match! Convert modifier bits. n = atoi((char *)modifiers_start); modifiers |= decode_modifiers(n); slen = j; } key_name[0] = termcodes[idx].name[0]; key_name[1] = termcodes[idx].name[1]; break; } } } if (idx == tc_len && mouse_index_found >= 0) { key_name[0] = termcodes[mouse_index_found].name[0]; key_name[1] = termcodes[mouse_index_found].name[1]; } } #ifdef FEAT_TERMRESPONSE if (key_name[0] == NUL // Mouse codes of DEC and pterm start with <ESC>[. When // detecting the start of these mouse codes they might as well be // another key code or terminal response. # ifdef FEAT_MOUSE_DEC || key_name[0] == KS_DEC_MOUSE # endif # ifdef FEAT_MOUSE_PTERM || key_name[0] == KS_PTERM_MOUSE # endif ) { char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1; /* * Check for responses from the terminal starting with {lead}: * "<Esc>[" or CSI followed by [0-9>?] * * - Xterm version string: {lead}>{x};{vers};{y}c * Also eat other possible responses to t_RV, rxvt returns * "{lead}?1;2c". * * - Cursor position report: {lead}{row};{col}R * The final byte must be 'R'. It is used for checking the * ambiguous-width character state. * * - window position reply: {lead}3;{x};{y}t * * - key with modifiers when modifyOtherKeys is enabled: * {lead}27;{modifier};{key}~ * {lead}{key};{modifier}u */ if (((tp[0] == ESC && len >= 3 && tp[1] == '[') || (tp[0] == CSI && len >= 2)) && (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?')) { int resp = handle_csi(tp, len, argp, offset, buf, bufsize, buflen, key_name, &slen); if (resp != 0) { # ifdef DEBUG_TERMRESPONSE if (resp == -1) LOG_TR(("Not enough characters for CSI sequence")); # endif return resp; } } // Check for fore/background color response from the terminal, // starting} with <Esc>] or OSC else if ((*T_RBG != NUL || *T_RFG != NUL) && ((tp[0] == ESC && len >= 2 && tp[1] == ']') || tp[0] == OSC)) { if (handle_osc(tp, argp, len, key_name, &slen) == FAIL) return -1; } // Check for key code response from xterm, // starting with <Esc>P or DCS else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT) && ((tp[0] == ESC && len >= 2 && tp[1] == 'P') || tp[0] == DCS)) { if (handle_dcs(tp, argp, len, key_name, &slen) == FAIL) return -1; } } #endif if (key_name[0] == NUL) continue; // No match at this position, try next one // We only get here when we have a complete termcode match #ifdef FEAT_GUI /* * Only in the GUI: Fetch the pointer coordinates of the scroll event * so that we know which window to scroll later. */ if (gui.in_use && key_name[0] == (int)KS_EXTRA && (key_name[1] == (int)KE_X1MOUSE || key_name[1] == (int)KE_X2MOUSE || key_name[1] == (int)KE_MOUSEMOVE_XY || key_name[1] == (int)KE_MOUSELEFT || key_name[1] == (int)KE_MOUSERIGHT || key_name[1] == (int)KE_MOUSEDOWN || key_name[1] == (int)KE_MOUSEUP)) { char_u bytes[6]; int num_bytes = get_bytes_from_buf(tp + slen, bytes, 4); if (num_bytes == -1) // not enough coordinates return -1; mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1; mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1; slen += num_bytes; // equal to K_MOUSEMOVE if (key_name[1] == (int)KE_MOUSEMOVE_XY) key_name[1] = (int)KE_MOUSEMOVE; } else #endif /* * If it is a mouse click, get the coordinates. */ if (key_name[0] == KS_MOUSE #ifdef FEAT_MOUSE_GPM || key_name[0] == KS_GPM_MOUSE #endif #ifdef FEAT_MOUSE_JSB || key_name[0] == KS_JSBTERM_MOUSE #endif #ifdef FEAT_MOUSE_NET || key_name[0] == KS_NETTERM_MOUSE #endif #ifdef FEAT_MOUSE_DEC || key_name[0] == KS_DEC_MOUSE #endif #ifdef FEAT_MOUSE_PTERM || key_name[0] == KS_PTERM_MOUSE #endif #ifdef FEAT_MOUSE_URXVT || key_name[0] == KS_URXVT_MOUSE #endif || key_name[0] == KS_SGR_MOUSE || key_name[0] == KS_SGR_MOUSE_RELEASE) { if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx, &modifiers) == -1) return -1; } #ifdef FEAT_GUI /* * If using the GUI, then we get menu and scrollbar events. * * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by * four bytes which are to be taken as a pointer to the vimmenu_T * structure. * * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr" * is one byte with the tab index. * * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed * by one byte representing the scrollbar number, and then four bytes * representing a long_u which is the new value of the scrollbar. * * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR, * KE_FILLER followed by four bytes representing a long_u which is the * new value of the scrollbar. */ # ifdef FEAT_MENU else if (key_name[0] == (int)KS_MENU) { long_u val; int num_bytes = get_long_from_buf(tp + slen, &val); if (num_bytes == -1) return -1; current_menu = (vimmenu_T *)val; slen += num_bytes; // The menu may have been deleted right after it was used, check // for that. if (check_menu_pointer(root_menu, current_menu) == FAIL) { key_name[0] = KS_EXTRA; key_name[1] = (int)KE_IGNORE; } } # endif # ifdef FEAT_GUI_TABLINE else if (key_name[0] == (int)KS_TABLINE) { // Selecting tabline tab or using its menu. char_u bytes[6]; int num_bytes = get_bytes_from_buf(tp + slen, bytes, 1); if (num_bytes == -1) return -1; current_tab = (int)bytes[0]; if (current_tab == 255) // -1 in a byte gives 255 current_tab = -1; slen += num_bytes; } else if (key_name[0] == (int)KS_TABMENU) { // Selecting tabline tab or using its menu. char_u bytes[6]; int num_bytes = get_bytes_from_buf(tp + slen, bytes, 2); if (num_bytes == -1) return -1; current_tab = (int)bytes[0]; current_tabmenu = (int)bytes[1]; slen += num_bytes; } # endif # ifndef USE_ON_FLY_SCROLL else if (key_name[0] == (int)KS_VER_SCROLLBAR) { long_u val; char_u bytes[6]; int num_bytes; // Get the last scrollbar event in the queue of the same type j = 0; for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR && tp[j + 2] != NUL; ++i) { j += 3; num_bytes = get_bytes_from_buf(tp + j, bytes, 1); if (num_bytes == -1) break; if (i == 0) current_scrollbar = (int)bytes[0]; else if (current_scrollbar != (int)bytes[0]) break; j += num_bytes; num_bytes = get_long_from_buf(tp + j, &val); if (num_bytes == -1) break; scrollbar_value = val; j += num_bytes; slen = j; } if (i == 0) // not enough characters to make one return -1; } else if (key_name[0] == (int)KS_HOR_SCROLLBAR) { long_u val; int num_bytes; // Get the last horiz. scrollbar event in the queue j = 0; for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR && tp[j + 2] != NUL; ++i) { j += 3; num_bytes = get_long_from_buf(tp + j, &val); if (num_bytes == -1) break; scrollbar_value = val; j += num_bytes; slen = j; } if (i == 0) // not enough characters to make one return -1; } # endif // !USE_ON_FLY_SCROLL #endif // FEAT_GUI #if (defined(UNIX) || defined(VMS)) /* * Handle FocusIn/FocusOut event sequences reported by XTerm. * (CSI I/CSI O) */ if (key_name[0] == KS_EXTRA # ifdef FEAT_GUI && !gui.in_use # endif ) { if (key_name[1] == KE_FOCUSGAINED) { if (!focus_state) { ui_focus_change(TRUE); did_cursorhold = TRUE; focus_state = TRUE; } key_name[1] = (int)KE_IGNORE; } else if (key_name[1] == KE_FOCUSLOST) { if (focus_state) { ui_focus_change(FALSE); did_cursorhold = TRUE; focus_state = FALSE; } key_name[1] = (int)KE_IGNORE; } } #endif /* * Change <xHome> to <Home>, <xUp> to <Up>, etc. */ key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1])); /* * Add any modifier codes to our string. */ new_slen = modifiers2keycode(modifiers, &key, string); // Finally, add the special key code to our string key_name[0] = KEY2TERMCAP0(key); key_name[1] = KEY2TERMCAP1(key); if (key_name[0] == KS_KEY) { // from ":set <M-b>=xx" if (has_mbyte) new_slen += (*mb_char2bytes)(key_name[1], string + new_slen); else string[new_slen++] = key_name[1]; } else if (new_slen == 0 && key_name[0] == KS_EXTRA && key_name[1] == KE_IGNORE) { // Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED // to indicate what happened. retval = KEYLEN_REMOVED; } else { string[new_slen++] = K_SPECIAL; string[new_slen++] = key_name[0]; string[new_slen++] = key_name[1]; } if (put_string_in_typebuf(offset, slen, string, new_slen, buf, bufsize, buflen) == FAIL) return -1; return retval == 0 ? (len + new_slen - slen + offset) : retval; } #ifdef FEAT_TERMRESPONSE LOG_TR(("normal character")); #endif return 0; // no match found }
null
null
208,411
141177609605865586721920240131748064761
604
patch 9.0.0018: going over the end of the typahead Problem: Going over the end of the typahead. Solution: Put a NUL after the typeahead.
other
linux
717adfdaf14704fd3ec7fa2c04520c0723247eac
1
static ssize_t hid_debug_events_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct hid_debug_list *list = file->private_data; int ret = 0, len; DECLARE_WAITQUEUE(wait, current); mutex_lock(&list->read_mutex); while (ret == 0) { if (list->head == list->tail) { add_wait_queue(&list->hdev->debug_wait, &wait); set_current_state(TASK_INTERRUPTIBLE); while (list->head == list->tail) { if (file->f_flags & O_NONBLOCK) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = -ERESTARTSYS; break; } if (!list->hdev || !list->hdev->debug) { ret = -EIO; set_current_state(TASK_RUNNING); goto out; } /* allow O_NONBLOCK from other threads */ mutex_unlock(&list->read_mutex); schedule(); mutex_lock(&list->read_mutex); set_current_state(TASK_INTERRUPTIBLE); } set_current_state(TASK_RUNNING); remove_wait_queue(&list->hdev->debug_wait, &wait); } if (ret) goto out; /* pass the ringbuffer contents to userspace */ copy_rest: if (list->tail == list->head) goto out; if (list->tail > list->head) { len = list->tail - list->head; if (copy_to_user(buffer + ret, &list->hid_debug_buf[list->head], len)) { ret = -EFAULT; goto out; } ret += len; list->head += len; } else { len = HID_DEBUG_BUFSIZE - list->head; if (copy_to_user(buffer, &list->hid_debug_buf[list->head], len)) { ret = -EFAULT; goto out; } list->head = 0; ret += len; goto copy_rest; } } out: mutex_unlock(&list->read_mutex); return ret; }
null
null
208,430
155206844330449950846334904452225854896
73
HID: debug: check length before copy_to_user() If our length is greater than the size of the buffer, we overflow the buffer Cc: [email protected] Signed-off-by: Daniel Rosenberg <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]>
other
tor
57e35ad3d91724882c345ac709666a551a977f0f
1
networkstatus_parse_vote_from_string(const char *s, const char **eos_out, networkstatus_type_t ns_type) { smartlist_t *tokens = smartlist_create(); smartlist_t *rs_tokens = NULL, *footer_tokens = NULL; networkstatus_voter_info_t *voter = NULL; networkstatus_t *ns = NULL; digests_t ns_digests; const char *cert, *end_of_header, *end_of_footer, *s_dup = s; directory_token_t *tok; int ok; struct in_addr in; int i, inorder, n_signatures = 0; memarea_t *area = NULL, *rs_area = NULL; consensus_flavor_t flav = FLAV_NS; tor_assert(s); if (eos_out) *eos_out = NULL; if (router_get_networkstatus_v3_hashes(s, &ns_digests)) { log_warn(LD_DIR, "Unable to compute digest of network-status"); goto err; } area = memarea_new(); end_of_header = find_start_of_next_routerstatus(s); if (tokenize_string(area, s, end_of_header, tokens, (ns_type == NS_TYPE_CONSENSUS) ? networkstatus_consensus_token_table : networkstatus_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing network-status vote header"); goto err; } ns = tor_malloc_zero(sizeof(networkstatus_t)); memcpy(&ns->digests, &ns_digests, sizeof(ns_digests)); tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION); tor_assert(tok); if (tok->n_args > 1) { int flavor = networkstatus_parse_flavor_name(tok->args[1]); if (flavor < 0) { log_warn(LD_DIR, "Can't parse document with unknown flavor %s", escaped(tok->args[2])); goto err; } ns->flavor = flav = flavor; } if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) { log_warn(LD_DIR, "Flavor found on non-consensus networkstatus."); goto err; } if (ns_type != NS_TYPE_CONSENSUS) { const char *end_of_cert = NULL; if (!(cert = strstr(s, "\ndir-key-certificate-version"))) goto err; ++cert; ns->cert = authority_cert_parse_from_string(cert, &end_of_cert); if (!ns->cert || !end_of_cert || end_of_cert > end_of_header) goto err; } tok = find_by_keyword(tokens, K_VOTE_STATUS); tor_assert(tok->n_args); if (!strcmp(tok->args[0], "vote")) { ns->type = NS_TYPE_VOTE; } else if (!strcmp(tok->args[0], "consensus")) { ns->type = NS_TYPE_CONSENSUS; } else if (!strcmp(tok->args[0], "opinion")) { ns->type = NS_TYPE_OPINION; } else { log_warn(LD_DIR, "Unrecognized vote status %s in network-status", escaped(tok->args[0])); goto err; } if (ns_type != ns->type) { log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus."); goto err; } if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) { tok = find_by_keyword(tokens, K_PUBLISHED); if (parse_iso_time(tok->args[0], &ns->published)) goto err; ns->supported_methods = smartlist_create(); tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS); if (tok) { for (i=0; i < tok->n_args; ++i) smartlist_add(ns->supported_methods, tor_strdup(tok->args[i])); } else { smartlist_add(ns->supported_methods, tor_strdup("1")); } } else { tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD); if (tok) { ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX, &ok, NULL); if (!ok) goto err; } else { ns->consensus_method = 1; } } tok = find_by_keyword(tokens, K_VALID_AFTER); if (parse_iso_time(tok->args[0], &ns->valid_after)) goto err; tok = find_by_keyword(tokens, K_FRESH_UNTIL); if (parse_iso_time(tok->args[0], &ns->fresh_until)) goto err; tok = find_by_keyword(tokens, K_VALID_UNTIL); if (parse_iso_time(tok->args[0], &ns->valid_until)) goto err; tok = find_by_keyword(tokens, K_VOTING_DELAY); tor_assert(tok->n_args >= 2); ns->vote_seconds = (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL); if (!ok) goto err; ns->dist_seconds = (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL); if (!ok) goto err; if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) { log_warn(LD_DIR, "Vote/consensus freshness interval is too short"); goto err; } if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) { log_warn(LD_DIR, "Vote/consensus liveness interval is too short"); goto err; } if (ns->vote_seconds < MIN_VOTE_SECONDS) { log_warn(LD_DIR, "Vote seconds is too short"); goto err; } if (ns->dist_seconds < MIN_DIST_SECONDS) { log_warn(LD_DIR, "Dist seconds is too short"); goto err; } if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) { ns->client_versions = tor_strdup(tok->args[0]); } if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) { ns->server_versions = tor_strdup(tok->args[0]); } tok = find_by_keyword(tokens, K_KNOWN_FLAGS); ns->known_flags = smartlist_create(); inorder = 1; for (i = 0; i < tok->n_args; ++i) { smartlist_add(ns->known_flags, tor_strdup(tok->args[i])); if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) { log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]); inorder = 0; } } if (!inorder) { log_warn(LD_DIR, "known-flags not in order"); goto err; } tok = find_opt_by_keyword(tokens, K_PARAMS); if (tok) { inorder = 1; ns->net_params = smartlist_create(); for (i = 0; i < tok->n_args; ++i) { int ok=0; char *eq = strchr(tok->args[i], '='); if (!eq) { log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i])); goto err; } tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL); if (!ok) { log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i])); goto err; } if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) { log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]); inorder = 0; } smartlist_add(ns->net_params, tor_strdup(tok->args[i])); } if (!inorder) { log_warn(LD_DIR, "params not in order"); goto err; } } ns->voters = smartlist_create(); SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) { tok = _tok; if (tok->tp == K_DIR_SOURCE) { tor_assert(tok->n_args >= 6); if (voter) smartlist_add(ns->voters, voter); voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t)); voter->sigs = smartlist_create(); if (ns->type != NS_TYPE_CONSENSUS) memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN); voter->nickname = tor_strdup(tok->args[0]); if (strlen(tok->args[1]) != HEX_DIGEST_LEN || base16_decode(voter->identity_digest, sizeof(voter->identity_digest), tok->args[1], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding identity digest %s in " "network-status vote.", escaped(tok->args[1])); goto err; } if (ns->type != NS_TYPE_CONSENSUS && tor_memneq(ns->cert->cache_info.identity_digest, voter->identity_digest, DIGEST_LEN)) { log_warn(LD_DIR,"Mismatch between identities in certificate and vote"); goto err; } voter->address = tor_strdup(tok->args[2]); if (!tor_inet_aton(tok->args[3], &in)) { log_warn(LD_DIR, "Error decoding IP address %s in network-status.", escaped(tok->args[3])); goto err; } voter->addr = ntohl(in.s_addr); voter->dir_port = (uint16_t) tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL); if (!ok) goto err; voter->or_port = (uint16_t) tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL); if (!ok) goto err; } else if (tok->tp == K_CONTACT) { if (!voter || voter->contact) { log_warn(LD_DIR, "contact element is out of place."); goto err; } voter->contact = tor_strdup(tok->args[0]); } else if (tok->tp == K_VOTE_DIGEST) { tor_assert(ns->type == NS_TYPE_CONSENSUS); tor_assert(tok->n_args >= 1); if (!voter || ! tor_digest_is_zero(voter->vote_digest)) { log_warn(LD_DIR, "vote-digest element is out of place."); goto err; } if (strlen(tok->args[0]) != HEX_DIGEST_LEN || base16_decode(voter->vote_digest, sizeof(voter->vote_digest), tok->args[0], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding vote digest %s in " "network-status consensus.", escaped(tok->args[0])); goto err; } } } SMARTLIST_FOREACH_END(_tok); if (voter) { smartlist_add(ns->voters, voter); voter = NULL; } if (smartlist_len(ns->voters) == 0) { log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus."); goto err; } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) { log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus."); goto err; } if (ns->type != NS_TYPE_CONSENSUS && (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) { int bad = 1; if (strlen(tok->args[0]) == HEX_DIGEST_LEN) { networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0); if (base16_decode(voter->legacy_id_digest, DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN)<0) bad = 1; else bad = 0; } if (bad) { log_warn(LD_DIR, "Invalid legacy key digest %s on vote.", escaped(tok->args[0])); } } /* Parse routerstatus lines. */ rs_tokens = smartlist_create(); rs_area = memarea_new(); s = end_of_header; ns->routerstatus_list = smartlist_create(); while (!strcmpstart(s, "r ")) { if (ns->type != NS_TYPE_CONSENSUS) { vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t)); if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns, rs, 0, 0)) smartlist_add(ns->routerstatus_list, rs); else { tor_free(rs->version); tor_free(rs); } } else { routerstatus_t *rs; if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, NULL, NULL, ns->consensus_method, flav))) smartlist_add(ns->routerstatus_list, rs); } } for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) { routerstatus_t *rs1, *rs2; if (ns->type != NS_TYPE_CONSENSUS) { vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1); vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i); rs1 = &a->status; rs2 = &b->status; } else { rs1 = smartlist_get(ns->routerstatus_list, i-1); rs2 = smartlist_get(ns->routerstatus_list, i); } if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) { log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity " "digest"); goto err; } } /* Parse footer; check signature. */ footer_tokens = smartlist_create(); if ((end_of_footer = strstr(s, "\nnetwork-status-version "))) ++end_of_footer; else end_of_footer = s + strlen(s); if (tokenize_string(area,s, end_of_footer, footer_tokens, networkstatus_vote_footer_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing network-status vote footer."); goto err; } { int found_sig = 0; SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) { tok = _tok; if (tok->tp == K_DIRECTORY_SIGNATURE) found_sig = 1; else if (found_sig) { log_warn(LD_DIR, "Extraneous token after first directory-signature"); goto err; } } SMARTLIST_FOREACH_END(_tok); } if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) { if (tok != smartlist_get(footer_tokens, 0)) { log_warn(LD_DIR, "Misplaced directory-footer token"); goto err; } } tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS); if (tok) { ns->weight_params = smartlist_create(); for (i = 0; i < tok->n_args; ++i) { int ok=0; char *eq = strchr(tok->args[i], '='); if (!eq) { log_warn(LD_DIR, "Bad element '%s' in weight params", escaped(tok->args[i])); goto err; } tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL); if (!ok) { log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i])); goto err; } smartlist_add(ns->weight_params, tor_strdup(tok->args[i])); } } SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) { char declared_identity[DIGEST_LEN]; networkstatus_voter_info_t *v; document_signature_t *sig; const char *id_hexdigest = NULL; const char *sk_hexdigest = NULL; digest_algorithm_t alg = DIGEST_SHA1; tok = _tok; if (tok->tp != K_DIRECTORY_SIGNATURE) continue; tor_assert(tok->n_args >= 2); if (tok->n_args == 2) { id_hexdigest = tok->args[0]; sk_hexdigest = tok->args[1]; } else { const char *algname = tok->args[0]; int a; id_hexdigest = tok->args[1]; sk_hexdigest = tok->args[2]; a = crypto_digest_algorithm_parse_name(algname); if (a<0) { log_warn(LD_DIR, "Unknown digest algorithm %s; skipping", escaped(algname)); continue; } alg = a; } if (!tok->object_type || strcmp(tok->object_type, "SIGNATURE") || tok->object_size < 128 || tok->object_size > 512) { log_warn(LD_DIR, "Bad object type or length on directory-signature"); goto err; } if (strlen(id_hexdigest) != HEX_DIGEST_LEN || base16_decode(declared_identity, sizeof(declared_identity), id_hexdigest, HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared identity %s in " "network-status vote.", escaped(id_hexdigest)); goto err; } if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) { log_warn(LD_DIR, "ID on signature on network-status vote does not match " "any declared directory source."); goto err; } sig = tor_malloc_zero(sizeof(document_signature_t)); memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN); sig->alg = alg; if (strlen(sk_hexdigest) != HEX_DIGEST_LEN || base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest), sk_hexdigest, HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared signing key digest %s in " "network-status vote.", escaped(sk_hexdigest)); tor_free(sig); goto err; } if (ns->type != NS_TYPE_CONSENSUS) { if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest, DIGEST_LEN)) { log_warn(LD_DIR, "Digest mismatch between declared and actual on " "network-status vote."); tor_free(sig); goto err; } } if (voter_get_sig_by_algorithm(v, sig->alg)) { /* We already parsed a vote with this algorithm from this voter. Use the first one. */ log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus " "that contains two votes from the same voter with the same " "algorithm. Ignoring the second vote."); tor_free(sig); continue; } if (ns->type != NS_TYPE_CONSENSUS) { if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN, tok, ns->cert->signing_key, 0, "network-status vote")) { tor_free(sig); goto err; } sig->good_signature = 1; } else { if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) { tor_free(sig); goto err; } sig->signature = tor_memdup(tok->object_body, tok->object_size); sig->signature_len = (int) tok->object_size; } smartlist_add(v->sigs, sig); ++n_signatures; } SMARTLIST_FOREACH_END(_tok); if (! n_signatures) { log_warn(LD_DIR, "No signatures on networkstatus vote."); goto err; } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) { log_warn(LD_DIR, "Received more than one signature on a " "network-status vote."); goto err; } if (eos_out) *eos_out = end_of_footer; goto done; err: dump_desc(s_dup, "v3 networkstatus"); networkstatus_vote_free(ns); ns = NULL; done: if (tokens) { SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t)); smartlist_free(tokens); } if (voter) { if (voter->sigs) { SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig, document_signature_free(sig)); smartlist_free(voter->sigs); } tor_free(voter->nickname); tor_free(voter->address); tor_free(voter->contact); tor_free(voter); } if (rs_tokens) { SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t)); smartlist_free(rs_tokens); } if (footer_tokens) { SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t)); smartlist_free(footer_tokens); } if (area) { DUMP_AREA(area, "v3 networkstatus"); memarea_drop_all(area); } if (rs_area) memarea_drop_all(rs_area); return ns; }
null
null
208,505
320303562647980943317783282141447596021
536
Avoid possible segfault when handling networkstatus vote with bad flavor Fix for 6530; fix on 0.2.2.6-alpha.
other
heimdal
04171147948d0a3636bc6374181926f0fb2ec83a
1
tgs_build_reply(astgs_request_t priv, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, const krb5_keyblock *replykey, int rk_is_subkey, krb5_ticket *ticket, const char **e_text, AuthorizationData **auth_data, const struct sockaddr *from_addr) { krb5_context context = priv->context; krb5_kdc_configuration *config = priv->config; KDC_REQ *req = &priv->req; KDC_REQ_BODY *b = &priv->req.req_body; const char *from = priv->from; krb5_error_code ret, ret2; krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL; krb5_principal krbtgt_out_principal = NULL; char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL; hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL; HDB *clientdb, *s4u2self_impersonated_clientdb; krb5_realm ref_realm = NULL; EncTicketPart *tgt = &ticket->ticket; krb5_principals spp = NULL; const EncryptionKey *ekey; krb5_keyblock sessionkey; krb5_kvno kvno; krb5_data rspac; const char *tgt_realm = /* Realm of TGT issuer */ krb5_principal_get_realm(context, krbtgt->entry.principal); const char *our_realm = /* Realm of this KDC */ krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1); char **capath = NULL; size_t num_capath = 0; hdb_entry_ex *krbtgt_out = NULL; METHOD_DATA enc_pa_data; PrincipalName *s; Realm r; EncTicketPart adtkt; char opt_str[128]; int signedpath = 0; Key *tkey_check; Key *tkey_sign; int flags = HDB_F_FOR_TGS_REQ; memset(&sessionkey, 0, sizeof(sessionkey)); memset(&adtkt, 0, sizeof(adtkt)); krb5_data_zero(&rspac); memset(&enc_pa_data, 0, sizeof(enc_pa_data)); s = b->sname; r = b->realm; /* * The canonicalize KDC option is passed as a hint to the backend, but * can typically be ignored. Per RFC 6806, names are not canonicalized * in response to a TGS request (although we make an exception, see * force-canonicalize below). */ if (b->kdc_options.canonicalize) flags |= HDB_F_CANON; if(b->kdc_options.enc_tkt_in_skey){ Ticket *t; hdb_entry_ex *uu; krb5_principal p; Key *uukey; krb5uint32 second_kvno = 0; krb5uint32 *kvno_ptr = NULL; if(b->additional_tickets == NULL || b->additional_tickets->len == 0){ ret = KRB5KDC_ERR_BADOPTION; /* ? */ kdc_log(context, config, 4, "No second ticket present in user-to-user request"); _kdc_audit_addreason((kdc_request_t)priv, "No second ticket present in user-to-user request"); goto out; } t = &b->additional_tickets->val[0]; if(!get_krbtgt_realm(&t->sname)){ kdc_log(context, config, 4, "Additional ticket is not a ticket-granting ticket"); _kdc_audit_addreason((kdc_request_t)priv, "Additional ticket is not a ticket-granting ticket"); ret = KRB5KDC_ERR_POLICY; goto out; } _krb5_principalname2krb5_principal(context, &p, t->sname, t->realm); ret = krb5_unparse_name(context, p, &tpn); if (ret) goto out; if(t->enc_part.kvno){ second_kvno = *t->enc_part.kvno; kvno_ptr = &second_kvno; } ret = _kdc_db_fetch(context, config, p, HDB_F_GET_KRBTGT, kvno_ptr, NULL, &uu); krb5_free_principal(context, p); if(ret){ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_audit_addreason((kdc_request_t)priv, "User-to-user service principal (TGS) unknown"); goto out; } ret = hdb_enctype2key(context, &uu->entry, NULL, t->enc_part.etype, &uukey); if(ret){ _kdc_free_ent(context, uu); ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ _kdc_audit_addreason((kdc_request_t)priv, "User-to-user enctype not supported"); goto out; } ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0); _kdc_free_ent(context, uu); if(ret) { _kdc_audit_addreason((kdc_request_t)priv, "User-to-user TGT decrypt failure"); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "User-to-user TGT expired or invalid"); goto out; } s = &adtkt.cname; r = adtkt.crealm; } _krb5_principalname2krb5_principal(context, &sp, *s, r); ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm); ret = krb5_unparse_name(context, cp, &priv->cname); if (ret) goto out; cpn = priv->cname; unparse_flags (KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), opt_str, sizeof(opt_str)); if(*opt_str) kdc_log(context, config, 4, "TGS-REQ %s from %s for %s [%s]", cpn, from, spn, opt_str); else kdc_log(context, config, 4, "TGS-REQ %s from %s for %s", cpn, from, spn); /* * Fetch server */ server_lookup: ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags, NULL, NULL, &server); priv->server = server; if (ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", spn); _kdc_audit_addreason((kdc_request_t)priv, "Target not found here"); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { free(ref_realm); ref_realm = strdup(server->entry.principal->realm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } kdc_log(context, config, 4, "Returning a referral to realm %s for " "server %s.", ref_realm, spn); krb5_free_principal(context, sp); sp = NULL; ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); if (ret) goto out; free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; goto server_lookup; } else if (ret) { const char *new_rlm, *msg; Realm req_rlm; krb5_realm *realms; if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) { if (capath == NULL) { /* With referalls, hierarchical capaths are always enabled */ ret2 = _krb5_find_capath(context, tgt->crealm, our_realm, req_rlm, TRUE, &capath, &num_capath); if (ret2) { ret = ret2; _kdc_audit_addreason((kdc_request_t)priv, "No trusted path from client realm to ours"); goto out; } } new_rlm = num_capath > 0 ? capath[--num_capath] : NULL; if (new_rlm) { kdc_log(context, config, 5, "krbtgt from %s via %s for " "realm %s not found, trying %s", tgt->crealm, our_realm, req_rlm, new_rlm); free(ref_realm); ref_realm = strdup(new_rlm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; goto server_lookup; } } else if (need_referral(context, config, &b->kdc_options, sp, &realms)) { if (strcmp(realms[0], sp->realm) != 0) { kdc_log(context, config, 4, "Returning a referral to realm %s for " "server %s that was not found", realms[0], spn); krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, realms[0], NULL); free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) { krb5_free_host_realm(context, realms); goto out; } spn = priv->sname; free(ref_realm); ref_realm = strdup(realms[0]); krb5_free_host_realm(context, realms); goto server_lookup; } krb5_free_host_realm(context, realms); } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 3, "Server not found in database: %s: %s", spn, msg); krb5_free_error_message(context, msg); if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_audit_addreason((kdc_request_t)priv, "Service principal unknown"); goto out; } /* * RFC 6806 notes that names MUST NOT be changed in the response to * a TGS request. Hence we ignore the setting of the canonicalize * KDC option. However, for legacy interoperability we do allow the * backend to override this by setting the force-canonicalize HDB * flag in the server entry. */ if (server->entry.flags.force_canonicalize) rsp = server->entry.principal; else rsp = sp; /* * Select enctype, return key and kvno. */ { krb5_enctype etype; if(b->kdc_options.enc_tkt_in_skey) { size_t i; ekey = &adtkt.key; for(i = 0; i < b->etype.len; i++) if (b->etype.val[i] == adtkt.key.keytype) break; if(i == b->etype.len) { kdc_log(context, config, 4, "Addition ticket have not matching etypes"); krb5_clear_error_message(context); ret = KRB5KDC_ERR_ETYPE_NOSUPP; _kdc_audit_addreason((kdc_request_t)priv, "No matching enctypes for 2nd ticket"); goto out; } etype = b->etype.val[i]; kvno = 0; } else { Key *skey; ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp) ? KFE_IS_TGS : 0, b->etype.val, b->etype.len, &etype, NULL, NULL); if(ret) { kdc_log(context, config, 4, "Server (%s) has no support for etypes", spn); _kdc_audit_addreason((kdc_request_t)priv, "Enctype not supported"); goto out; } ret = _kdc_get_preferred_key(context, config, server, spn, NULL, &skey); if(ret) { kdc_log(context, config, 4, "Server (%s) has no supported etypes", spn); _kdc_audit_addreason((kdc_request_t)priv, "Enctype not supported"); goto out; } ekey = &skey->key; kvno = server->entry.kvno; } ret = krb5_generate_random_keyblock(context, etype, &sessionkey); if (ret) goto out; } /* * Check that service is in the same realm as the krbtgt. If it's * not the same, it's someone that is using a uni-directional trust * backward. */ /* * Validate authorization data */ ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */ krbtgt_etype, &tkey_check); if(ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC check"); _kdc_audit_addreason((kdc_request_t)priv, "No key for krbtgt PAC check"); goto out; } /* * Now refetch the primary krbtgt, and get the current kvno (the * sign check may have been on an old kvno, and the server may * have been an incoming trust) */ ret = krb5_make_principal(context, &krbtgt_out_principal, our_realm, KRB5_TGS_NAME, our_realm, NULL); if (ret) { kdc_log(context, config, 4, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n); if (ret) { kdc_log(context, config, 4, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = _kdc_db_fetch(context, config, krbtgt_out_principal, HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out); if (ret) { char *ktpn = NULL; ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn); kdc_log(context, config, 4, "No such principal %s (needed for authz-data signature keys) " "while processing TGS-REQ for service %s with krbtg %s", krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>"); free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } /* * The first realm is the realm of the service, the second is * krbtgt/<this>/@REALM component of the krbtgt DN the request was * encrypted to. The redirection via the krbtgt_out entry allows * the DB to possibly correct the case of the realm (Samba4 does * this) before the strcmp() */ if (strcmp(krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) { char *ktpn; ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn); kdc_log(context, config, 4, "Request with wrong krbtgt: %s", (ret == 0) ? ktpn : "<unknown>"); if(ret == 0) free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; _kdc_audit_addreason((kdc_request_t)priv, "Request with wrong TGT"); goto out; } ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n, NULL, &tkey_sign); if (ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC signature"); _kdc_audit_addreason((kdc_request_t)priv, "Failed to find key for krbtgt PAC signature"); goto out; } ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL, tkey_sign->key.keytype, &tkey_sign); if(ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC signature"); _kdc_audit_addreason((kdc_request_t)priv, "Failed to find key for krbtgt PAC signature"); goto out; } { krb5_data verified_cas; /* * If the client doesn't exist in the HDB but has a TGT and it's * obtained with PKINIT then we assume it's a synthetic client -- that * is, a client whose name was vouched for by a CA using a PKINIT SAN, * but which doesn't exist in the HDB proper. We'll allow such a * client to do TGT requests even though normally we'd reject all * clients that don't exist in the HDB. */ ret = krb5_ticket_get_authorization_data_type(context, ticket, KRB5_AUTHDATA_INITIAL_VERIFIED_CAS, &verified_cas); if (ret == 0) { krb5_data_free(&verified_cas); flags |= HDB_F_SYNTHETIC_OK; } } ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags, NULL, &clientdb, &client); flags &= ~HDB_F_SYNTHETIC_OK; priv->client = client; if(ret == HDB_ERR_NOT_FOUND_HERE) { /* This is OK, we are just trying to find out if they have * been disabled or deleted in the meantime, missing secrets * is OK */ } else if(ret){ const char *krbtgt_realm, *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal); if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) { if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; kdc_log(context, config, 4, "Client no longer in database: %s", cpn); _kdc_audit_addreason((kdc_request_t)priv, "Client no longer in HDB"); goto out; } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 4, "Client not found in database: %s", msg); _kdc_audit_addreason((kdc_request_t)priv, "Client does not exist"); krb5_free_error_message(context, msg); } else if (ret == 0 && (client->entry.flags.invalid || !client->entry.flags.client)) { _kdc_audit_addreason((kdc_request_t)priv, "Client has invalid bit set"); kdc_log(context, config, 4, "Client has invalid bit set"); ret = KRB5KDC_ERR_POLICY; goto out; } ret = check_PAC(context, config, cp, NULL, client, server, krbtgt, &tkey_check->key, ekey, &tkey_sign->key, tgt, &rspac, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "PAC check failed"); kdc_log(context, config, 4, "Verify PAC failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* also check the krbtgt for signature */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, tgt, &spp, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed"); kdc_log(context, config, 4, "KRB5SignedPath check failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Process request */ /* by default the tgt principal matches the client principal */ tp = cp; tpn = cpn; if (client) { const PA_DATA *sdata; int i = 0; sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER); if (sdata) { struct astgs_request_desc imp_req; krb5_crypto crypto; krb5_data datack; PA_S4U2Self self; const char *str; ret = decode_PA_S4U2Self(sdata->padata_value.data, sdata->padata_value.length, &self, NULL); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Failed to decode PA-S4U2Self"); kdc_log(context, config, 4, "Failed to decode PA-S4U2Self"); goto out; } if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) { free_PA_S4U2Self(&self); _kdc_audit_addreason((kdc_request_t)priv, "PA-S4U2Self with unkeyed checksum"); kdc_log(context, config, 4, "Reject PA-S4U2Self with unkeyed checksum"); ret = KRB5KRB_AP_ERR_INAPP_CKSUM; goto out; } ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack); if (ret) goto out; ret = krb5_crypto_init(context, &tgt->key, 0, &crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); krb5_data_free(&datack); kdc_log(context, config, 4, "krb5_crypto_init failed: %s", msg); krb5_free_error_message(context, msg); goto out; } /* Allow HMAC_MD5 checksum with any key type */ if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) { struct krb5_crypto_iov iov; unsigned char csdata[16]; Checksum cs; cs.checksum.length = sizeof(csdata); cs.checksum.data = &csdata; iov.data.data = datack.data; iov.data.length = datack.length; iov.flags = KRB5_CRYPTO_TYPE_DATA; ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key, KRB5_KU_OTHER_CKSUM, &iov, 1, &cs); if (ret == 0 && krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0) ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; } else { ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, datack.data, datack.length, &self.cksum); } krb5_data_free(&datack); krb5_crypto_destroy(context, crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); _kdc_audit_addreason((kdc_request_t)priv, "S4U2Self checksum failed"); kdc_log(context, config, 4, "krb5_verify_checksum failed for S4U2Self: %s", msg); krb5_free_error_message(context, msg); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, self.name, self.realm); free_PA_S4U2Self(&self); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; /* * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients * is probably not desirable! */ ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags, NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client); if (ret) { const char *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "S4U2Self principal to impersonate not found"); kdc_log(context, config, 2, "S4U2Self principal to impersonate %s not found in database: %s", tpn, msg); krb5_free_error_message(context, msg); goto out; } /* Ignore require_pwchange and pw_end attributes (as Windows does), * since S4U2Self is not password authentication. */ s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE; free(s4u2self_impersonated_client->entry.pw_end); s4u2self_impersonated_client->entry.pw_end = NULL; imp_req = *priv; imp_req.client = s4u2self_impersonated_client; imp_req.client_princ = tp; ret = kdc_check_flags(&imp_req, FALSE); if (ret) goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */ /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */ if(rspac.data) { krb5_pac p = NULL; krb5_data_free(&rspac); ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing"); kdc_log(context, config, 4, "PAC generation failed for -- %s", tpn); goto out; } if (p != NULL) { ret = _krb5_pac_sign(context, p, ticket->ticket.authtime, s4u2self_impersonated_client->entry.principal, ekey, &tkey_sign->key, &rspac); krb5_pac_free(context, p); if (ret) { kdc_log(context, config, 4, "PAC signing failed for -- %s", tpn); goto out; } } } /* * Check that service doing the impersonating is * requesting a ticket to it-self. */ ret = check_s4u2self(context, config, clientdb, client, sp); if (ret) { kdc_log(context, config, 4, "S4U2Self: %s is not allowed " "to impersonate to service " "(tried for user %s to service %s)", cpn, tpn, spn); goto out; } /* * If the service isn't trusted for authentication to * delegation or if the impersonate client is disallowed * forwardable, remove the forwardable flag. */ if (client->entry.flags.trusted_for_delegation && s4u2self_impersonated_client->entry.flags.forwardable) { str = "[forwardable]"; } else { b->kdc_options.forwardable = 0; str = ""; } kdc_log(context, config, 4, "s4u2self %s impersonating %s to " "service %s %s", cpn, tpn, spn, str); } } /* * Constrained delegation */ if (client != NULL && b->additional_tickets != NULL && b->additional_tickets->len != 0 && b->kdc_options.cname_in_addl_tkt && b->kdc_options.enc_tkt_in_skey == 0) { int ad_signedpath = 0; Key *clientkey; Ticket *t; /* * Require that the KDC have issued the service's krbtgt (not * self-issued ticket with kimpersonate(1). */ if (!signedpath) { ret = KRB5KDC_ERR_BADOPTION; _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing"); kdc_log(context, config, 4, "Constrained delegation done on service ticket %s/%s", cpn, spn); goto out; } t = &b->additional_tickets->val[0]; ret = hdb_enctype2key(context, &client->entry, hdb_kvno2keys(context, &client->entry, t->enc_part.kvno ? * t->enc_part.kvno : 0), t->enc_part.etype, &clientkey); if(ret){ ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Failed to decrypt constrained delegation ticket"); kdc_log(context, config, 4, "failed to decrypt ticket for " "constrained delegation from %s to %s ", cpn, spn); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, adtkt.cname, adtkt.crealm); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; _kdc_audit_addkv((kdc_request_t)priv, 0, "impersonatee", "%s", tpn); ret = _krb5_principalname2krb5_principal(context, &dp, t->sname, t->realm); if (ret) goto out; ret = krb5_unparse_name(context, dp, &dpn); if (ret) goto out; /* check that ticket is valid */ if (adtkt.flags.forwardable == 0) { _kdc_audit_addreason((kdc_request_t)priv, "Missing forwardable flag on ticket for constrained delegation"); kdc_log(context, config, 4, "Missing forwardable flag on ticket for " "constrained delegation from %s (%s) as %s to %s ", cpn, dpn, tpn, spn); ret = KRB5KDC_ERR_BADOPTION; goto out; } ret = check_constrained_delegation(context, config, clientdb, client, server, sp); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation not allowed"); kdc_log(context, config, 4, "constrained delegation from %s (%s) as %s to %s not allowed", cpn, dpn, tpn, spn); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket expired or invalid"); goto out; } krb5_data_free(&rspac); /* * generate the PAC for the user. * * TODO: pass in t->sname and t->realm and build * a S4U_DELEGATION_INFO blob to the PAC. */ ret = check_PAC(context, config, tp, dp, client, server, krbtgt, &clientkey->key, ekey, &tkey_sign->key, &adtkt, &rspac, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket PAC check failed"); kdc_log(context, config, 4, "Verify delegated PAC failed to %s for client" "%s (%s) as %s from %s with %s", spn, cpn, dpn, tpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Check that the KDC issued the user's ticket. */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, &adtkt, NULL, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 4, "KRB5SignedPath check from service %s failed " "for delegation to %s for client %s (%s)" "from %s failed with %s", spn, tpn, dpn, cpn, from, msg); krb5_free_error_message(context, msg); _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed"); goto out; } if (!ad_signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 4, "Ticket not signed with PAC nor SignedPath service %s failed " "for delegation to %s for client %s (%s)" "from %s", spn, tpn, dpn, cpn, from); _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket not signed"); goto out; } kdc_log(context, config, 4, "constrained delegation for %s " "from %s (%s) to %s", tpn, cpn, dpn, spn); } /* * Check flags */ ret = kdc_check_flags(priv, FALSE); if(ret) goto out; if((b->kdc_options.validate || b->kdc_options.renew) && !krb5_principal_compare(context, krbtgt->entry.principal, server->entry.principal)){ _kdc_audit_addreason((kdc_request_t)priv, "Inconsistent request"); kdc_log(context, config, 4, "Inconsistent request."); ret = KRB5KDC_ERR_SERVER_NOMATCH; goto out; } /* check for valid set of addresses */ if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) { if (config->check_ticket_addresses) { ret = KRB5KRB_AP_ERR_BADADDR; _kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes"); kdc_log(context, config, 4, "Request from wrong address"); _kdc_audit_addreason((kdc_request_t)priv, "Request from wrong address"); goto out; } else if (config->warn_ticket_addresses) { _kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes"); } } /* check local and per-principal anonymous ticket issuance policy */ if (is_anon_tgs_request_p(b, tgt)) { ret = _kdc_check_anon_policy(priv); if (ret) goto out; } /* * If this is an referral, add server referral data to the * auth_data reply . */ if (ref_realm) { PA_DATA pa; krb5_crypto crypto; kdc_log(context, config, 3, "Adding server referral to %s", ref_realm); ret = krb5_crypto_init(context, &sessionkey, 0, &crypto); if (ret) goto out; ret = build_server_referral(context, config, crypto, ref_realm, NULL, s, &pa.padata_value); krb5_crypto_destroy(context, crypto); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Referral build failed"); kdc_log(context, config, 4, "Failed building server referral"); goto out; } pa.padata_type = KRB5_PADATA_SERVER_REFERRAL; ret = add_METHOD_DATA(&enc_pa_data, &pa); krb5_data_free(&pa.padata_value); if (ret) { kdc_log(context, config, 4, "Add server referral METHOD-DATA failed"); goto out; } } /* * */ ret = tgs_make_reply(priv, tp, tgt, replykey, rk_is_subkey, ekey, &sessionkey, kvno, *auth_data, server, rsp, client, cp, tgt_realm, krbtgt_out, tkey_sign->key.keytype, spp, &rspac, &enc_pa_data); out: if (tpn != cpn) free(tpn); free(dpn); free(krbtgt_out_n); _krb5_free_capath(context, capath); krb5_data_free(&rspac); krb5_free_keyblock_contents(context, &sessionkey); if(krbtgt_out) _kdc_free_ent(context, krbtgt_out); if(server) _kdc_free_ent(context, server); if(client) _kdc_free_ent(context, client); if(s4u2self_impersonated_client) _kdc_free_ent(context, s4u2self_impersonated_client); if (tp && tp != cp) krb5_free_principal(context, tp); krb5_free_principal(context, cp); krb5_free_principal(context, dp); krb5_free_principal(context, sp); krb5_free_principal(context, krbtgt_out_principal); free(ref_realm); free_METHOD_DATA(&enc_pa_data); free_EncTicketPart(&adtkt); return ret; }
null
null
208,506
172674879650950329667725116403393224452
1,038
kdc: validate sname in TGS-REQ In tgs_build_reply(), validate the server name in the TGS-REQ is present before dereferencing.
other
libxml2
b1d34de46a11323fccffa9fadeb33be670d602f5
1
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; size_t buffer_size = 0; size_t nbchars = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); }
null
null
208,533
301710766906450297101615067146831788109
164
Fix inappropriate fetch of entities content For https://bugzilla.gnome.org/show_bug.cgi?id=761430 libfuzzer regression testing exposed another case where the parser would fetch content of an external entity while not in validating mode. Plug that hole
other
dpdk
af74f7db384ed149fe42b21dbd7975f8a54ef227
1
vhost_user_get_inflight_fd(struct virtio_net **pdev, struct vhu_msg_context *ctx, int main_fd __rte_unused) { struct rte_vhost_inflight_info_packed *inflight_packed; uint64_t pervq_inflight_size, mmap_size; uint16_t num_queues, queue_size; struct virtio_net *dev = *pdev; int fd, i, j; int numa_node = SOCKET_ID_ANY; void *addr; if (ctx->msg.size != sizeof(ctx->msg.payload.inflight)) { VHOST_LOG_CONFIG(ERR, "(%s) invalid get_inflight_fd message size is %d\n", dev->ifname, ctx->msg.size); return RTE_VHOST_MSG_RESULT_ERR; } /* * If VQ 0 has already been allocated, try to allocate on the same * NUMA node. It can be reallocated later in numa_realloc(). */ if (dev->nr_vring > 0) numa_node = dev->virtqueue[0]->numa_node; if (dev->inflight_info == NULL) { dev->inflight_info = rte_zmalloc_socket("inflight_info", sizeof(struct inflight_mem_info), 0, numa_node); if (!dev->inflight_info) { VHOST_LOG_CONFIG(ERR, "(%s) failed to alloc dev inflight area\n", dev->ifname); return RTE_VHOST_MSG_RESULT_ERR; } dev->inflight_info->fd = -1; } num_queues = ctx->msg.payload.inflight.num_queues; queue_size = ctx->msg.payload.inflight.queue_size; VHOST_LOG_CONFIG(INFO, "(%s) get_inflight_fd num_queues: %u\n", dev->ifname, ctx->msg.payload.inflight.num_queues); VHOST_LOG_CONFIG(INFO, "(%s) get_inflight_fd queue_size: %u\n", dev->ifname, ctx->msg.payload.inflight.queue_size); if (vq_is_packed(dev)) pervq_inflight_size = get_pervq_shm_size_packed(queue_size); else pervq_inflight_size = get_pervq_shm_size_split(queue_size); mmap_size = num_queues * pervq_inflight_size; addr = inflight_mem_alloc(dev, "vhost-inflight", mmap_size, &fd); if (!addr) { VHOST_LOG_CONFIG(ERR, "(%s) failed to alloc vhost inflight area\n", dev->ifname); ctx->msg.payload.inflight.mmap_size = 0; return RTE_VHOST_MSG_RESULT_ERR; } memset(addr, 0, mmap_size); if (dev->inflight_info->addr) { munmap(dev->inflight_info->addr, dev->inflight_info->size); dev->inflight_info->addr = NULL; } if (dev->inflight_info->fd >= 0) { close(dev->inflight_info->fd); dev->inflight_info->fd = -1; } dev->inflight_info->addr = addr; dev->inflight_info->size = ctx->msg.payload.inflight.mmap_size = mmap_size; dev->inflight_info->fd = ctx->fds[0] = fd; ctx->msg.payload.inflight.mmap_offset = 0; ctx->fd_num = 1; if (vq_is_packed(dev)) { for (i = 0; i < num_queues; i++) { inflight_packed = (struct rte_vhost_inflight_info_packed *)addr; inflight_packed->used_wrap_counter = 1; inflight_packed->old_used_wrap_counter = 1; for (j = 0; j < queue_size; j++) inflight_packed->desc[j].next = j + 1; addr = (void *)((char *)addr + pervq_inflight_size); } } VHOST_LOG_CONFIG(INFO, "(%s) send inflight mmap_size: %"PRIu64"\n", dev->ifname, ctx->msg.payload.inflight.mmap_size); VHOST_LOG_CONFIG(INFO, "(%s) send inflight mmap_offset: %"PRIu64"\n", dev->ifname, ctx->msg.payload.inflight.mmap_offset); VHOST_LOG_CONFIG(INFO, "(%s) send inflight fd: %d\n", dev->ifname, ctx->fds[0]); return RTE_VHOST_MSG_RESULT_REPLY; }
null
null
210,284
33623247974536318315256615866397928606
94
vhost: fix FD leak with inflight messages Even if unlikely, a buggy vhost-user master might attach fds to inflight messages. Add checks like for other types of vhost-user messages. Fixes: d87f1a1cb7b6 ("vhost: support inflight info sharing") Cc: [email protected] Signed-off-by: David Marchand <[email protected]> Reviewed-by: Maxime Coquelin <[email protected]>
other
linux
89c2b3b74918200e46699338d7bcc19b1ea12110
1
static int io_read(struct io_kiocb *req, unsigned int issue_flags) { struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs; struct kiocb *kiocb = &req->rw.kiocb; struct iov_iter __iter, *iter = &__iter; struct io_async_rw *rw = req->async_data; ssize_t io_size, ret, ret2; bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK; if (rw) { iter = &rw->iter; iovec = NULL; } else { ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock); if (ret < 0) return ret; } io_size = iov_iter_count(iter); req->result = io_size; /* Ensure we clear previously set non-block flag */ if (!force_nonblock) kiocb->ki_flags &= ~IOCB_NOWAIT; else kiocb->ki_flags |= IOCB_NOWAIT; /* If the file doesn't support async, just async punt */ if (force_nonblock && !io_file_supports_async(req, READ)) { ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true); return ret ?: -EAGAIN; } ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size); if (unlikely(ret)) { kfree(iovec); return ret; } ret = io_iter_do_read(req, iter); if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) { req->flags &= ~REQ_F_REISSUE; /* IOPOLL retry should happen for io-wq threads */ if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL)) goto done; /* no retry on NONBLOCK nor RWF_NOWAIT */ if (req->flags & REQ_F_NOWAIT) goto done; /* some cases will consume bytes even on error returns */ iov_iter_revert(iter, io_size - iov_iter_count(iter)); ret = 0; } else if (ret == -EIOCBQUEUED) { goto out_free; } else if (ret <= 0 || ret == io_size || !force_nonblock || (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) { /* read all, failed, already did sync or don't want to retry */ goto done; } ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true); if (ret2) return ret2; iovec = NULL; rw = req->async_data; /* now use our persistent iterator, if we aren't already */ iter = &rw->iter; do { io_size -= ret; rw->bytes_done += ret; /* if we can retry, do so with the callbacks armed */ if (!io_rw_should_retry(req)) { kiocb->ki_flags &= ~IOCB_WAITQ; return -EAGAIN; } /* * Now retry read with the IOCB_WAITQ parts set in the iocb. If * we get -EIOCBQUEUED, then we'll get a notification when the * desired page gets unlocked. We can also get a partial read * here, and if we do, then just retry at the new offset. */ ret = io_iter_do_read(req, iter); if (ret == -EIOCBQUEUED) return 0; /* we got some bytes, but not all. retry. */ kiocb->ki_flags &= ~IOCB_WAITQ; } while (ret > 0 && ret < io_size); done: kiocb_done(kiocb, ret, issue_flags); out_free: /* it's faster to check here then delegate to kfree */ if (iovec) kfree(iovec); return 0; }
null
null
210,484
9767670992332379490534176378394297980
97
io_uring: reexpand under-reexpanded iters [ 74.211232] BUG: KASAN: stack-out-of-bounds in iov_iter_revert+0x809/0x900 [ 74.212778] Read of size 8 at addr ffff888025dc78b8 by task syz-executor.0/828 [ 74.214756] CPU: 0 PID: 828 Comm: syz-executor.0 Not tainted 5.14.0-rc3-next-20210730 #1 [ 74.216525] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.14.0-0-g155821a1990b-prebuilt.qemu.org 04/01/2014 [ 74.219033] Call Trace: [ 74.219683] dump_stack_lvl+0x8b/0xb3 [ 74.220706] print_address_description.constprop.0+0x1f/0x140 [ 74.224226] kasan_report.cold+0x7f/0x11b [ 74.226085] iov_iter_revert+0x809/0x900 [ 74.227960] io_write+0x57d/0xe40 [ 74.232647] io_issue_sqe+0x4da/0x6a80 [ 74.242578] __io_queue_sqe+0x1ac/0xe60 [ 74.245358] io_submit_sqes+0x3f6e/0x76a0 [ 74.248207] __do_sys_io_uring_enter+0x90c/0x1a20 [ 74.257167] do_syscall_64+0x3b/0x90 [ 74.257984] entry_SYSCALL_64_after_hwframe+0x44/0xae old_size = iov_iter_count(); ... iov_iter_revert(old_size - iov_iter_count()); If iov_iter_revert() is done base on the initial size as above, and the iter is truncated and not reexpanded in the middle, it miscalculates borders causing problems. This trace is due to no one reexpanding after generic_write_checks(). Now iters store how many bytes has been truncated, so reexpand them to the initial state right before reverting. Cc: [email protected] Reported-by: Palash Oswal <[email protected]> Reported-by: Sudip Mukherjee <[email protected]> Reported-and-tested-by: [email protected] Signed-off-by: Pavel Begunkov <[email protected]> Signed-off-by: Al Viro <[email protected]>
other
squashfs-tools
79b5a555058eef4e1e7ff220c344d39f8cd09646
1
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_3 dirh; char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer; long long start; int bytes; int dir_count, size; struct dir_ent *new_dir; struct dir *dir; TRACE("squashfs_opendir: inode start block %d, offset %d\n", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) EXIT_UNSQUASH("squashfs_opendir: malloc failed!\n"); dir->dir_count = 0; dir->cur_entry = 0; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 3) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; bytes = lookup_entry(directory_table_hash, start); if(bytes == -1) EXIT_UNSQUASH("squashfs_opendir: directory block %d not " "found!\n", block_start); bytes += (*i)->offset; size = (*i)->data + bytes - 3; while(bytes < size) { if(swap) { squashfs_dir_header_3 sdirh; memcpy(&sdirh, directory_table + bytes, sizeof(sdirh)); SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh); } else memcpy(&dirh, directory_table + bytes, sizeof(dirh)); dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header @ byte position " "%d, %d directory entries\n", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR("File system corrupted: too many entries in directory\n"); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_3 sdire; memcpy(&sdire, directory_table + bytes, sizeof(sdire)); SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire); } else memcpy(dire, directory_table + bytes, sizeof(*dire)); bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR("File system corrupted: filename too long\n"); goto corrupted; } memcpy(dire->name, directory_table + bytes, dire->size + 1); dire->name[dire->size + 1] = '\0'; TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); if((dir->dir_count % DIR_ENT_SIZE) == 0) { new_dir = realloc(dir->dirs, (dir->dir_count + DIR_ENT_SIZE) * sizeof(struct dir_ent)); if(new_dir == NULL) EXIT_UNSQUASH("squashfs_opendir: " "realloc failed!\n"); dir->dirs = new_dir; } strcpy(dir->dirs[dir->dir_count].name, dire->name); dir->dirs[dir->dir_count].start_block = dirh.start_block; dir->dirs[dir->dir_count].offset = dire->offset; dir->dirs[dir->dir_count].type = dire->type; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: free(dir->dirs); free(dir); return NULL; }
null
null
210,701
84788405315542553885310338439631637350
117
Unsquashfs: fix write outside destination directory exploit An issue on Github (https://github.com/plougher/squashfs-tools/issues/72) shows how some specially crafted Squashfs filesystems containing invalid file names (with '/' and ..) can cause Unsquashfs to write files outside of the destination directory. This commit fixes this exploit by checking all names for validity. In doing so I have also added checks for '.' and for names that are shorter than they should be (names in the file system should not have '\0' terminators). Signed-off-by: Phillip Lougher <[email protected]>
other
file-roller
b147281293a8307808475e102a14857055f81631
1
extract_archive_thread (GSimpleAsyncResult *result, GObject *object, GCancellable *cancellable) { ExtractData *extract_data; LoadData *load_data; GHashTable *checked_folders; struct archive *a; struct archive_entry *entry; int r; extract_data = g_simple_async_result_get_op_res_gpointer (result); load_data = LOAD_DATA (extract_data); checked_folders = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL); fr_archive_progress_set_total_files (load_data->archive, extract_data->n_files_to_extract); a = archive_read_new (); archive_read_support_filter_all (a); archive_read_support_format_all (a); archive_read_open (a, load_data, load_data_open, load_data_read, load_data_close); while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) { const char *pathname; char *fullpath; GFile *file; GFile *parent; GOutputStream *ostream; const void *buffer; size_t buffer_size; int64_t offset; GError *local_error = NULL; __LA_MODE_T filetype; if (g_cancellable_is_cancelled (cancellable)) break; pathname = archive_entry_pathname (entry); if (! extract_data_get_extraction_requested (extract_data, pathname)) { archive_read_data_skip (a); continue; } fullpath = (*pathname == '/') ? g_strdup (pathname) : g_strconcat ("/", pathname, NULL); file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (fullpath, extract_data->base_dir, extract_data->junk_paths)); /* honor the skip_older and overwrite options */ if (extract_data->skip_older || ! extract_data->overwrite) { GFileInfo *info; info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, cancellable, &local_error); if (info != NULL) { gboolean skip = FALSE; if (! extract_data->overwrite) { skip = TRUE; } else if (extract_data->skip_older) { GTimeVal modification_time; g_file_info_get_modification_time (info, &modification_time); if (archive_entry_mtime (entry) < modification_time.tv_sec) skip = TRUE; } g_object_unref (info); if (skip) { g_object_unref (file); archive_read_data_skip (a); fr_archive_progress_inc_completed_bytes (load_data->archive, archive_entry_size_is_set (entry) ? archive_entry_size (entry) : 0); if ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) { r = ARCHIVE_EOF; break; } continue; } } else { if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { load_data->error = local_error; g_object_unref (info); break; } g_error_free (local_error); } } fr_archive_progress_inc_completed_files (load_data->archive, 1); /* create the file parents */ parent = g_file_get_parent (file); if ((parent != NULL) && (g_hash_table_lookup (checked_folders, parent) == NULL) && ! g_file_query_exists (parent, cancellable)) { if (g_file_make_directory_with_parents (parent, cancellable, &load_data->error)) { GFile *grandparent; grandparent = g_object_ref (parent); while (grandparent != NULL) { if (g_hash_table_lookup (checked_folders, grandparent) == NULL) g_hash_table_insert (checked_folders, grandparent, GINT_TO_POINTER (1)); grandparent = g_file_get_parent (grandparent); } } } g_object_unref (parent); /* create the file */ filetype = archive_entry_filetype (entry); if (load_data->error == NULL) { const char *linkname; linkname = archive_entry_hardlink (entry); if (linkname != NULL) { char *link_fullpath; GFile *link_file; char *oldname; char *newname; int r; link_fullpath = (*linkname == '/') ? g_strdup (linkname) : g_strconcat ("/", linkname, NULL); link_file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (link_fullpath, extract_data->base_dir, extract_data->junk_paths)); oldname = g_file_get_path (link_file); newname = g_file_get_path (file); if ((oldname != NULL) && (newname != NULL)) r = link (oldname, newname); else r = -1; if (r == 0) { __LA_INT64_T filesize; if (archive_entry_size_is_set (entry)) filesize = archive_entry_size (entry); else filesize = -1; if (filesize > 0) filetype = AE_IFREG; /* treat as a regular file to save the data */ } else { char *uri; char *msg; uri = g_file_get_uri (file); msg = g_strdup_printf ("Could not create the hard link %s", uri); load_data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, msg); g_free (msg); g_free (uri); } g_free (newname); g_free (oldname); g_object_unref (link_file); g_free (link_fullpath); } } if (load_data->error == NULL) { switch (filetype) { case AE_IFDIR: if (! g_file_make_directory (file, cancellable, &local_error)) { if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS)) load_data->error = g_error_copy (local_error); g_error_free (local_error); } else _g_file_set_attributes_from_entry (file, entry, extract_data, cancellable); archive_read_data_skip (a); break; case AE_IFREG: ostream = (GOutputStream *) g_file_replace (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, &load_data->error); if (ostream == NULL) break; while ((r = archive_read_data_block (a, &buffer, &buffer_size, &offset)) == ARCHIVE_OK) { if (g_output_stream_write (ostream, buffer, buffer_size, cancellable, &load_data->error) == -1) break; fr_archive_progress_inc_completed_bytes (load_data->archive, buffer_size); } _g_object_unref (ostream); if (r != ARCHIVE_EOF) load_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a)); else _g_file_set_attributes_from_entry (file, entry, extract_data, cancellable); break; case AE_IFLNK: if (! g_file_make_symbolic_link (file, archive_entry_symlink (entry), cancellable, &local_error)) { if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS)) load_data->error = g_error_copy (local_error); g_error_free (local_error); } archive_read_data_skip (a); break; default: archive_read_data_skip (a); break; } } g_object_unref (file); g_free (fullpath); if (load_data->error != NULL) break; if ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) { r = ARCHIVE_EOF; break; } } if ((load_data->error == NULL) && (r != ARCHIVE_EOF)) load_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a)); if (load_data->error == NULL) g_cancellable_set_error_if_cancelled (cancellable, &load_data->error); if (load_data->error != NULL) g_simple_async_result_set_from_error (result, load_data->error); g_hash_table_unref (checked_folders); archive_read_free (a); extract_data_free (extract_data); }
null
null
211,102
146521485464683242231569868140802651647
242
libarchive: sanitize filenames before extracting
other
linux
7fd25e6fc035f4b04b75bca6d7e8daa069603a76
1
static void atusb_disconnect(struct usb_interface *interface) { struct atusb *atusb = usb_get_intfdata(interface); dev_dbg(&atusb->usb_dev->dev, "%s\n", __func__); atusb->shutdown = 1; cancel_delayed_work_sync(&atusb->work); usb_kill_anchored_urbs(&atusb->rx_urbs); atusb_free_urbs(atusb); usb_kill_urb(atusb->tx_urb); usb_free_urb(atusb->tx_urb); ieee802154_unregister_hw(atusb->hw); ieee802154_free_hw(atusb->hw); usb_set_intfdata(interface, NULL); usb_put_dev(atusb->usb_dev); pr_debug("%s done\n", __func__); }
null
null
211,113
267064650077885177982562711259078440803
23
ieee802154: atusb: fix use-after-free at disconnect The disconnect callback was accessing the hardware-descriptor private data after having having freed it. Fixes: 7490b008d123 ("ieee802154: add support for atusb transceiver") Cc: stable <[email protected]> # 4.2 Cc: Alexander Aring <[email protected]> Reported-by: [email protected] Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Stefan Schmidt <[email protected]>
other
gdk-pixbuf
4f0f465f991cd454d03189497f923eb40c170c22
1
read_bitmap_file_data (FILE *fstream, guint *width, guint *height, guchar **data, int *x_hot, int *y_hot) { guchar *bits = NULL; /* working variable */ char line[MAX_SIZE]; /* input line from file */ int size; /* number of bytes of data */ char name_and_type[MAX_SIZE]; /* an input line */ char *type; /* for parsing */ int value; /* from an input line */ int version10p; /* boolean, old format */ int padding; /* to handle alignment */ int bytes_per_line; /* per scanline of data */ guint ww = 0; /* width */ guint hh = 0; /* height */ int hx = -1; /* x hotspot */ int hy = -1; /* y hotspot */ /* first time initialization */ if (!initialized) { init_hex_table (); } /* error cleanup and return macro */ #define RETURN(code) { g_free (bits); return code; } while (fgets (line, MAX_SIZE, fstream)) { if (strlen (line) == MAX_SIZE-1) RETURN (FALSE); if (sscanf (line,"#define %s %d",name_and_type,&value) == 2) { if (!(type = strrchr (name_and_type, '_'))) type = name_and_type; else { type++; } if (!strcmp ("width", type)) ww = (unsigned int) value; if (!strcmp ("height", type)) hh = (unsigned int) value; if (!strcmp ("hot", type)) { if (type-- == name_and_type || type-- == name_and_type) continue; if (!strcmp ("x_hot", type)) hx = value; if (!strcmp ("y_hot", type)) hy = value; } continue; } if (sscanf (line, "static short %s = {", name_and_type) == 1) version10p = 1; else if (sscanf (line,"static const unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf (line,"static unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf (line, "static const char %s = {", name_and_type) == 1) version10p = 0; else if (sscanf (line, "static char %s = {", name_and_type) == 1) version10p = 0; else continue; if (!(type = strrchr (name_and_type, '_'))) type = name_and_type; else type++; if (strcmp ("bits[]", type)) continue; if (!ww || !hh) RETURN (FALSE); if ((ww % 16) && ((ww % 16) < 9) && version10p) padding = 1; else padding = 0; bytes_per_line = (ww+7)/8 + padding; size = bytes_per_line * hh; bits = g_malloc (size); if (version10p) { unsigned char *ptr; int bytes; for (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) { if ((value = next_int (fstream)) < 0) RETURN (FALSE); *(ptr++) = value; if (!padding || ((bytes+2) % bytes_per_line)) *(ptr++) = value >> 8; } } else { unsigned char *ptr; int bytes; for (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) { if ((value = next_int (fstream)) < 0) RETURN (FALSE); *ptr=value; } } break; } if (!bits) RETURN (FALSE); *data = bits; *width = ww; *height = hh; if (x_hot) *x_hot = hx; if (y_hot) *y_hot = hy; return TRUE; }
null
null
211,473
70165411011067571586761169769193194588
126
Avoid an integer overflow in the xbm loader At the same time, reject some silly input, such as negative width or height. https://bugzilla.gnome.org/show_bug.cgi?id=672811
other
linux
89f3594d0de58e8a57d92d497dea9fee3d4b9cda
1
dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct dev_data *dev = fd->private_data; ssize_t value, length = len; unsigned total; u32 tag; char *kbuf; spin_lock_irq(&dev->lock); if (dev->state > STATE_DEV_OPENED) { value = ep0_write(fd, buf, len, ptr); spin_unlock_irq(&dev->lock); return value; } spin_unlock_irq(&dev->lock); if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) || (len > PAGE_SIZE * 4)) return -EINVAL; /* we might need to change message format someday */ if (copy_from_user (&tag, buf, 4)) return -EFAULT; if (tag != 0) return -EINVAL; buf += 4; length -= 4; kbuf = memdup_user(buf, length); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); spin_lock_irq (&dev->lock); value = -EINVAL; if (dev->buf) { kfree(kbuf); goto fail; } dev->buf = kbuf; /* full or low speed config */ dev->config = (void *) kbuf; total = le16_to_cpu(dev->config->wTotalLength); if (!is_valid_config(dev->config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; /* optional high speed config */ if (kbuf [1] == USB_DT_CONFIG) { dev->hs_config = (void *) kbuf; total = le16_to_cpu(dev->hs_config->wTotalLength); if (!is_valid_config(dev->hs_config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; } else { dev->hs_config = NULL; } /* could support multiple configs, using another encoding! */ /* device descriptor (tweaked for paranoia) */ if (length != USB_DT_DEVICE_SIZE) goto fail; dev->dev = (void *)kbuf; if (dev->dev->bLength != USB_DT_DEVICE_SIZE || dev->dev->bDescriptorType != USB_DT_DEVICE || dev->dev->bNumConfigurations != 1) goto fail; dev->dev->bcdUSB = cpu_to_le16 (0x0200); /* triggers gadgetfs_bind(); then we can enumerate. */ spin_unlock_irq (&dev->lock); if (dev->hs_config) gadgetfs_driver.max_speed = USB_SPEED_HIGH; else gadgetfs_driver.max_speed = USB_SPEED_FULL; value = usb_gadget_probe_driver(&gadgetfs_driver); if (value != 0) { kfree (dev->buf); dev->buf = NULL; } else { /* at this point "good" hardware has for the first time * let the USB the host see us. alternatively, if users * unplug/replug that will clear all the error state. * * note: everything running before here was guaranteed * to choke driver model style diagnostics. from here * on, they can work ... except in cleanup paths that * kick in after the ep0 descriptor is closed. */ value = len; dev->gadget_registered = true; } return value; fail: spin_unlock_irq (&dev->lock); pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev); kfree (dev->buf); dev->buf = NULL; return value; }
null
null
211,650
182318114915089365572042937695601411290
107
usb: gadget: don't release an existing dev->buf dev->buf does not need to be released if it already exists before executing dev_config. Acked-by: Alan Stern <[email protected]> Signed-off-by: Hangyu Hua <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
other
jasper
4cd52b5daac62b00a0a328451544807ddecf775f
1
static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image) { jpc_enc_cp_t *cp; jas_tvparser_t *tvp; int ret; int numilyrrates; double *ilyrrates; int i; int tagid; jpc_enc_tcp_t *tcp; jpc_enc_tccp_t *tccp; jpc_enc_ccp_t *ccp; uint_fast16_t rlvlno; uint_fast16_t prcwidthexpn; uint_fast16_t prcheightexpn; bool enablemct; uint_fast32_t jp2overhead; uint_fast16_t lyrno; uint_fast32_t hsteplcm; uint_fast32_t vsteplcm; bool mctvalid; tvp = 0; cp = 0; ilyrrates = 0; numilyrrates = 0; if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { goto error; } prcwidthexpn = 15; prcheightexpn = 15; enablemct = true; jp2overhead = 0; cp->ccps = 0; cp->debug = 0; cp->imgareatlx = UINT_FAST32_MAX; cp->imgareatly = UINT_FAST32_MAX; cp->refgrdwidth = 0; cp->refgrdheight = 0; cp->tilegrdoffx = UINT_FAST32_MAX; cp->tilegrdoffy = UINT_FAST32_MAX; cp->tilewidth = 0; cp->tileheight = 0; cp->numcmpts = jas_image_numcmpts(image); hsteplcm = 1; vsteplcm = 1; for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { jas_eprintf("unsupported image type\n"); goto error; } /* Note: We ought to be calculating the LCMs here. Fix some day. */ hsteplcm *= jas_image_cmpthstep(image, cmptno); vsteplcm *= jas_image_cmptvstep(image, cmptno); } if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) { goto error; } unsigned cmptno; for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno, ++ccp) { ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); /* XXX - this isn't quite correct for more general image */ ccp->sampgrdsubstepx = 0; ccp->sampgrdsubstepx = 0; ccp->prec = jas_image_cmptprec(image, cmptno); ccp->sgnd = jas_image_cmptsgnd(image, cmptno); ccp->numstepsizes = 0; memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); } cp->rawsize = jas_image_rawsize(image); if (cp->rawsize == 0) { /* prevent division by zero in cp_create() */ goto error; } cp->totalsize = UINT_FAST32_MAX; tcp = &cp->tcp; tcp->csty = 0; tcp->intmode = true; tcp->prg = JPC_COD_LRCPPRG; tcp->numlyrs = 1; tcp->ilyrrates = 0; tccp = &cp->tccp; tccp->csty = 0; tccp->maxrlvls = 6; tccp->cblkwidthexpn = 6; tccp->cblkheightexpn = 6; tccp->cblksty = 0; tccp->numgbits = 2; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!(ret = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, jas_tvparser_gettag(tvp)))->id) { case OPT_DEBUG: cp->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFX: cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFY: cp->imgareatly = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFX: cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFY: cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEWIDTH: cp->tilewidth = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEHEIGHT: cp->tileheight = atoi(jas_tvparser_getval(tvp)); break; case OPT_PRCWIDTH: prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_PRCHEIGHT: prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKWIDTH: tccp->cblkwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKHEIGHT: tccp->cblkheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_MODE: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid mode %s\n", jas_tvparser_getval(tvp)); } else { tcp->intmode = (tagid == MODE_INT); } break; case OPT_PRG: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid progression order %s\n", jas_tvparser_getval(tvp)); } else { tcp->prg = tagid; } break; case OPT_NOMCT: enablemct = false; break; case OPT_MAXRLVLS: tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); break; case OPT_SOP: cp->tcp.csty |= JPC_COD_SOP; break; case OPT_EPH: cp->tcp.csty |= JPC_COD_EPH; break; case OPT_LAZY: tccp->cblksty |= JPC_COX_LAZY; break; case OPT_TERMALL: tccp->cblksty |= JPC_COX_TERMALL; break; case OPT_SEGSYM: tccp->cblksty |= JPC_COX_SEGSYM; break; case OPT_VCAUSAL: tccp->cblksty |= JPC_COX_VSC; break; case OPT_RESET: tccp->cblksty |= JPC_COX_RESET; break; case OPT_PTERM: tccp->cblksty |= JPC_COX_PTERM; break; case OPT_NUMGBITS: cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); break; case OPT_RATE: if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, &cp->totalsize)) { jas_eprintf("ignoring bad rate specifier %s\n", jas_tvparser_getval(tvp)); } break; case OPT_ILYRRATES: if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, &ilyrrates)) { jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n", jas_tvparser_getval(tvp)); } break; case OPT_JP2OVERHEAD: jp2overhead = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); tvp = 0; if (cp->totalsize != UINT_FAST32_MAX) { cp->totalsize = (cp->totalsize > jp2overhead) ? (cp->totalsize - jp2overhead) : 0; } if (cp->imgareatlx == UINT_FAST32_MAX) { cp->imgareatlx = 0; } else { if (hsteplcm != 1) { jas_eprintf("warning: overriding imgareatlx value\n"); } cp->imgareatlx *= hsteplcm; } if (cp->imgareatly == UINT_FAST32_MAX) { cp->imgareatly = 0; } else { if (vsteplcm != 1) { jas_eprintf("warning: overriding imgareatly value\n"); } cp->imgareatly *= vsteplcm; } cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); cp->refgrdheight = cp->imgareatly + jas_image_height(image); if (cp->tilegrdoffx == UINT_FAST32_MAX) { cp->tilegrdoffx = cp->imgareatlx; } if (cp->tilegrdoffy == UINT_FAST32_MAX) { cp->tilegrdoffy = cp->imgareatly; } if (!cp->tilewidth) { cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; } if (!cp->tileheight) { cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; } if (cp->numcmpts == 3) { mctvalid = true; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { mctvalid = false; } } } else { mctvalid = false; } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { jas_eprintf("warning: color space apparently not RGB\n"); } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); } else { tcp->mctid = JPC_MCT_NONE; } tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { tccp->prcwidthexpns[rlvlno] = prcwidthexpn; tccp->prcheightexpns[rlvlno] = prcheightexpn; } if (prcwidthexpn != 15 || prcheightexpn != 15) { tccp->csty |= JPC_COX_PRT; } /* Ensure that the tile width and height is valid. */ if (!cp->tilewidth) { jas_eprintf("invalid tile width %lu\n", (unsigned long) cp->tilewidth); goto error; } if (!cp->tileheight) { jas_eprintf("invalid tile height %lu\n", (unsigned long) cp->tileheight); goto error; } /* Ensure that the tile grid offset is valid. */ if (cp->tilegrdoffx > cp->imgareatlx || cp->tilegrdoffy > cp->imgareatly || cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { jas_eprintf("invalid tile grid offset (%lu, %lu)\n", (unsigned long) cp->tilegrdoffx, (unsigned long) cp->tilegrdoffy); goto error; } cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, cp->tilewidth); cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, cp->tileheight); cp->numtiles = cp->numhtiles * cp->numvtiles; if (ilyrrates && numilyrrates > 0) { tcp->numlyrs = numilyrrates + 1; if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1), sizeof(jpc_fix_t)))) { goto error; } for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); } } /* Ensure that the integer mode is used in the case of lossless coding. */ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { jas_eprintf("cannot use real mode for lossless coding\n"); goto error; } /* Ensure that the precinct width is valid. */ if (prcwidthexpn > 15) { jas_eprintf("invalid precinct width\n"); goto error; } /* Ensure that the precinct height is valid. */ if (prcheightexpn > 15) { jas_eprintf("invalid precinct height\n"); goto error; } /* Ensure that the code block width is valid. */ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { jas_eprintf("invalid code block width %d\n", JPC_POW2(cp->tccp.cblkwidthexpn)); goto error; } /* Ensure that the code block height is valid. */ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { jas_eprintf("invalid code block height %d\n", JPC_POW2(cp->tccp.cblkheightexpn)); goto error; } /* Ensure that the code block size is not too large. */ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { jas_eprintf("code block size too large\n"); goto error; } /* Ensure that the number of layers is valid. */ if (cp->tcp.numlyrs > 16384) { jas_eprintf("too many layers\n"); goto error; } /* There must be at least one resolution level. */ if (cp->tccp.maxrlvls < 1) { jas_eprintf("must be at least one resolution level\n"); goto error; } /* Ensure that the number of guard bits is valid. */ if (cp->tccp.numgbits > 8) { jas_eprintf("invalid number of guard bits\n"); goto error; } /* Ensure that the rate is within the legal range. */ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); } /* Ensure that the intermediate layer rates are valid. */ if (tcp->numlyrs > 1) { /* The intermediate layers rates must increase monotonically. */ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { jas_eprintf("intermediate layer rates must increase monotonically\n"); goto error; } } /* The intermediate layer rates must be less than the overall rate. */ if (cp->totalsize != UINT_FAST32_MAX) { for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) / cp->rawsize) { jas_eprintf("warning: intermediate layer rates must be less than overall rate\n"); goto error; } } } } if (ilyrrates) { jas_free(ilyrrates); } return cp; error: if (ilyrrates) { jas_free(ilyrrates); } if (tvp) { jas_tvparser_destroy(tvp); } if (cp) { jpc_enc_cp_destroy(cp); } return 0; }
null
null
211,785
181232699919937488567474720086554483482
431
Avoid maxrlvls more than upper bound to cause heap-buffer-overflow
other
vim
e3537aec2f8d6470010547af28dcbd83d41461b8
1
do_buffer_ext( int action, int start, int dir, // FORWARD or BACKWARD int count, // buffer number or number of buffers int flags) // DOBUF_FORCEIT etc. { buf_T *buf; buf_T *bp; int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL || action == DOBUF_WIPE || action == DOBUF_WIPE_REUSE); switch (start) { case DOBUF_FIRST: buf = firstbuf; break; case DOBUF_LAST: buf = lastbuf; break; default: buf = curbuf; break; } if (start == DOBUF_MOD) // find next modified buffer { while (count-- > 0) { do { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } while (buf != curbuf && !bufIsChanged(buf)); } if (!bufIsChanged(buf)) { emsg(_(e_no_modified_buffer_found)); return FAIL; } } else if (start == DOBUF_FIRST && count) // find specified buffer number { while (buf != NULL && buf->b_fnum != count) buf = buf->b_next; } else { bp = NULL; while (count > 0 || (!unload && !buf->b_p_bl && bp != buf)) { // remember the buffer where we start, we come back there when all // buffers are unlisted. if (bp == NULL) bp = buf; if (dir == FORWARD) { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } else { buf = buf->b_prev; if (buf == NULL) buf = lastbuf; } // don't count unlisted buffers if (unload || buf->b_p_bl) { --count; bp = NULL; // use this buffer as new starting point } if (bp == buf) { // back where we started, didn't find anything. emsg(_(e_there_is_no_listed_buffer)); return FAIL; } } } if (buf == NULL) // could not find it { if (start == DOBUF_FIRST) { // don't warn when deleting if (!unload) semsg(_(e_buffer_nr_does_not_exist), count); } else if (dir == FORWARD) emsg(_(e_cannot_go_beyond_last_buffer)); else emsg(_(e_cannot_go_before_first_buffer)); return FAIL; } #ifdef FEAT_PROP_POPUP if ((flags & DOBUF_NOPOPUP) && bt_popup(buf) # ifdef FEAT_TERMINAL && !bt_terminal(buf) #endif ) return OK; #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * delete buffer "buf" from memory and/or the list */ if (unload) { int forward; bufref_T bufref; if (!can_unload_buffer(buf)) return FAIL; set_bufref(&bufref, buf); // When unloading or deleting a buffer that's already unloaded and // unlisted: fail silently. if (action != DOBUF_WIPE && action != DOBUF_WIPE_REUSE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl) return FAIL; if ((flags & DOBUF_FORCEIT) == 0 && bufIsChanged(buf)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) { dialog_changed(buf, FALSE); if (!bufref_valid(&bufref)) // Autocommand deleted buffer, oops! It's not changed // now. return FAIL; // If it's still changed fail silently, the dialog already // mentioned why it fails. if (bufIsChanged(buf)) return FAIL; } else #endif { semsg(_(e_no_write_since_last_change_for_buffer_nr_add_bang_to_override), buf->b_fnum); return FAIL; } } // When closing the current buffer stop Visual mode. if (buf == curbuf && VIsual_active) end_visual_mode(); // If deleting the last (listed) buffer, make it empty. // The last (listed) buffer cannot be unloaded. FOR_ALL_BUFFERS(bp) if (bp->b_p_bl && bp != buf) break; if (bp == NULL && buf == curbuf) return empty_curbuf(TRUE, (flags & DOBUF_FORCEIT), action); // If the deleted buffer is the current one, close the current window // (unless it's the only window). Repeat this so long as we end up in // a window with this buffer. while (buf == curbuf && !(curwin->w_closing || curwin->w_buffer->b_locked > 0) && (!ONE_WINDOW || first_tabpage->tp_next != NULL)) { if (win_close(curwin, FALSE) == FAIL) break; } // If the buffer to be deleted is not the current one, delete it here. if (buf != curbuf) { close_windows(buf, FALSE); if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows <= 0) close_buffer(NULL, buf, action, FALSE, FALSE); return OK; } /* * Deleting the current buffer: Need to find another buffer to go to. * There should be another, otherwise it would have been handled * above. However, autocommands may have deleted all buffers. * First use au_new_curbuf.br_buf, if it is valid. * Then prefer the buffer we most recently visited. * Else try to find one that is loaded, after the current buffer, * then before the current buffer. * Finally use any buffer. */ buf = NULL; // selected buffer bp = NULL; // used when no loaded buffer found if (au_new_curbuf.br_buf != NULL && bufref_valid(&au_new_curbuf)) buf = au_new_curbuf.br_buf; else if (curwin->w_jumplistlen > 0) { int jumpidx; jumpidx = curwin->w_jumplistidx - 1; if (jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; forward = jumpidx; while (jumpidx != curwin->w_jumplistidx) { buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum); if (buf != NULL) { if (buf == curbuf || !buf->b_p_bl) buf = NULL; // skip current and unlisted bufs else if (buf->b_ml.ml_mfp == NULL) { // skip unloaded buf, but may keep it for later if (bp == NULL) bp = buf; buf = NULL; } } if (buf != NULL) // found a valid buffer: stop searching break; // advance to older entry in jump list if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen) break; if (--jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; if (jumpidx == forward) // List exhausted for sure break; } } if (buf == NULL) // No previous buffer, Try 2'nd approach { forward = TRUE; buf = curbuf->b_next; for (;;) { if (buf == NULL) { if (!forward) // tried both directions break; buf = curbuf->b_prev; forward = FALSE; continue; } // in non-help buffer, try to skip help buffers, and vv if (buf->b_help == curbuf->b_help && buf->b_p_bl) { if (buf->b_ml.ml_mfp != NULL) // found loaded buffer break; if (bp == NULL) // remember unloaded buf for later bp = buf; } if (forward) buf = buf->b_next; else buf = buf->b_prev; } } if (buf == NULL) // No loaded buffer, use unloaded one buf = bp; if (buf == NULL) // No loaded buffer, find listed one { FOR_ALL_BUFFERS(buf) if (buf->b_p_bl && buf != curbuf) break; } if (buf == NULL) // Still no buffer, just take one { if (curbuf->b_next != NULL) buf = curbuf->b_next; else buf = curbuf->b_prev; } } if (buf == NULL) { // Autocommands must have wiped out all other buffers. Only option // now is to make the current buffer empty. return empty_curbuf(FALSE, (flags & DOBUF_FORCEIT), action); } /* * make "buf" the current buffer */ if (action == DOBUF_SPLIT) // split window first { // If 'switchbuf' contains "useopen": jump to first window containing // "buf" if one exists if ((swb_flags & SWB_USEOPEN) && buf_jump_open_win(buf)) return OK; // If 'switchbuf' contains "usetab": jump to first window in any tab // page containing "buf" if one exists if ((swb_flags & SWB_USETAB) && buf_jump_open_tab(buf)) return OK; if (win_split(0, 0) == FAIL) return FAIL; } // go to current buffer - nothing to do if (buf == curbuf) return OK; // Check if the current buffer may be abandoned. if (action == DOBUF_GOTO && !can_abandon(curbuf, (flags & DOBUF_FORCEIT))) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) { bufref_T bufref; set_bufref(&bufref, buf); dialog_changed(curbuf, FALSE); if (!bufref_valid(&bufref)) // Autocommand deleted buffer, oops! return FAIL; } if (bufIsChanged(curbuf)) #endif { no_write_message(); return FAIL; } } // Go to the other buffer. set_curbuf(buf, action); if (action == DOBUF_SPLIT) RESET_BINDING(curwin); // reset 'scrollbind' and 'cursorbind' #if defined(FEAT_EVAL) if (aborting()) // autocmds may abort script processing return FAIL; #endif return OK; }
null
null
211,839
216423663569045638499778463707888891660
337
patch 8.2.4327: may end up with no current buffer Problem: May end up with no current buffer. Solution: When deleting the current buffer to not pick a quickfix buffer as the new current buffer.
other
linux
690b2549b19563ec5ad53e5c82f6a944d910086e
1
static int ismt_access(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data) { int ret; unsigned long time_left; dma_addr_t dma_addr = 0; /* address of the data buffer */ u8 dma_size = 0; enum dma_data_direction dma_direction = 0; struct ismt_desc *desc; struct ismt_priv *priv = i2c_get_adapdata(adap); struct device *dev = &priv->pci_dev->dev; u8 *dma_buffer = PTR_ALIGN(&priv->buffer[0], 16); desc = &priv->hw[priv->head]; /* Initialize the DMA buffer */ memset(priv->buffer, 0, sizeof(priv->buffer)); /* Initialize the descriptor */ memset(desc, 0, sizeof(struct ismt_desc)); desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write); /* Always clear the log entries */ memset(priv->log, 0, ISMT_LOG_ENTRIES * sizeof(u32)); /* Initialize common control bits */ if (likely(pci_dev_msi_enabled(priv->pci_dev))) desc->control = ISMT_DESC_INT | ISMT_DESC_FAIR; else desc->control = ISMT_DESC_FAIR; if ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK) && (size != I2C_SMBUS_I2C_BLOCK_DATA)) desc->control |= ISMT_DESC_PEC; switch (size) { case I2C_SMBUS_QUICK: dev_dbg(dev, "I2C_SMBUS_QUICK\n"); break; case I2C_SMBUS_BYTE: if (read_write == I2C_SMBUS_WRITE) { /* * Send Byte * The command field contains the write data */ dev_dbg(dev, "I2C_SMBUS_BYTE: WRITE\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; } else { /* Receive Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE: READ\n"); dma_size = 1; dma_direction = DMA_FROM_DEVICE; desc->rd_len = 1; } break; case I2C_SMBUS_BYTE_DATA: if (read_write == I2C_SMBUS_WRITE) { /* * Write Byte * Command plus 1 data byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: WRITE\n"); desc->wr_len_cmd = 2; dma_size = 2; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->byte; } else { /* Read Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: READ\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; desc->rd_len = 1; dma_size = 1; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_WORD_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Write Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: WRITE\n"); desc->wr_len_cmd = 3; dma_size = 3; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; } else { /* Read Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: READ\n"); desc->wr_len_cmd = command; desc->control |= ISMT_DESC_CWRL; desc->rd_len = 2; dma_size = 2; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_PROC_CALL\n"); desc->wr_len_cmd = 3; desc->rd_len = 2; dma_size = 3; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; break; case I2C_SMBUS_BLOCK_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Block Write */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_BLK; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* Block Read */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: READ\n"); dma_size = I2C_SMBUS_BLOCK_MAX; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL); } break; case I2C_SMBUS_BLOCK_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_BLOCK_PROC_CALL\n"); dma_size = I2C_SMBUS_BLOCK_MAX; desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 1); desc->wr_len_cmd = data->block[0] + 1; desc->rd_len = dma_size; desc->control |= ISMT_DESC_BLK; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], data->block[0]); break; case I2C_SMBUS_I2C_BLOCK_DATA: /* Make sure the length is valid */ if (data->block[0] < 1) data->block[0] = 1; if (data->block[0] > I2C_SMBUS_BLOCK_MAX) data->block[0] = I2C_SMBUS_BLOCK_MAX; if (read_write == I2C_SMBUS_WRITE) { /* i2c Block Write */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_I2C; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* i2c Block Read */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: READ\n"); dma_size = data->block[0]; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL); /* * Per the "Table 15-15. I2C Commands", * in the External Design Specification (EDS), * (Document Number: 508084, Revision: 2.0), * the _rw bit must be 0 */ desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0); } break; default: dev_err(dev, "Unsupported transaction %d\n", size); return -EOPNOTSUPP; } /* map the data buffer */ if (dma_size != 0) { dev_dbg(dev, " dev=%p\n", dev); dev_dbg(dev, " data=%p\n", data); dev_dbg(dev, " dma_buffer=%p\n", dma_buffer); dev_dbg(dev, " dma_size=%d\n", dma_size); dev_dbg(dev, " dma_direction=%d\n", dma_direction); dma_addr = dma_map_single(dev, dma_buffer, dma_size, dma_direction); if (dma_mapping_error(dev, dma_addr)) { dev_err(dev, "Error in mapping dma buffer %p\n", dma_buffer); return -EIO; } dev_dbg(dev, " dma_addr = %pad\n", &dma_addr); desc->dptr_low = lower_32_bits(dma_addr); desc->dptr_high = upper_32_bits(dma_addr); } reinit_completion(&priv->cmp); /* Add the descriptor */ ismt_submit_desc(priv); /* Now we wait for interrupt completion, 1s */ time_left = wait_for_completion_timeout(&priv->cmp, HZ*1); /* unmap the data buffer */ if (dma_size != 0) dma_unmap_single(dev, dma_addr, dma_size, dma_direction); if (unlikely(!time_left)) { dev_err(dev, "completion wait timed out\n"); ret = -ETIMEDOUT; goto out; } /* do any post processing of the descriptor here */ ret = ismt_process_desc(desc, data, priv, size, read_write); out: /* Update the ring pointer */ priv->head++; priv->head %= ISMT_DESC_ENTRIES; return ret; }
null
null
212,083
218082028726825778448502302966621907044
241
i2c: ismt: prevent memory corruption in ismt_access() The "data->block[0]" variable comes from the user and is a number between 0-255. It needs to be capped to prevent writing beyond the end of dma_buffer[]. Fixes: 5e9a97b1f449 ("i2c: ismt: Adding support for I2C_SMBUS_BLOCK_PROC_CALL") Reported-and-tested-by: Zheyu Ma <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Mika Westerberg <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
other
varnish-cache
c5fd097e5cce8b461c6443af02b3448baef2491d
1
http_isfiltered(const struct http *fm, unsigned u, unsigned how) { const char *e; const struct http_hdrflg *f; if (fm->hdf[u] & HDF_FILTER) return (1); e = strchr(fm->hd[u].b, ':'); if (e == NULL) return (0); f = http_hdr_flags(fm->hd[u].b, e); return (f != NULL && f->flag & how); }
null
null
212,407
122529399994073188542433561825721278627
13
Do not call http_hdr_flags() on pseudo-headers In http_EstimateWS(), all headers are passed to the http_isfiltered() function to calculate how many bytes is needed to serialize the entire struct http. http_isfiltered() will check the headers for whether they are going to be filtered out later and if so skip them. However http_isfiltered() would attempt to treat all elements of struct http as regular headers with an implicit structure. That does not hold for the first three pseudo-header entries, which would lead to asserts in later steps. This patch skips the filter step for pseudo-headers. Fixes: #3830
other
atril
f4291fd62f7dfe6460d2406a979ccfac0c68dd59
1
extract_argv (EvDocument *document, gint page) { ComicsDocument *comics_document = COMICS_DOCUMENT (document); char **argv; char *command_line, *quoted_archive, *quoted_filename; GError *err = NULL; if (page >= comics_document->page_names->len) return NULL; if (comics_document->regex_arg) { quoted_archive = g_shell_quote (comics_document->archive); quoted_filename = comics_regex_quote (comics_document->page_names->pdata[page]); } else { quoted_archive = g_shell_quote (comics_document->archive); quoted_filename = g_shell_quote (comics_document->page_names->pdata[page]); } command_line = g_strdup_printf ("%s %s %s", comics_document->extract_command, quoted_archive, quoted_filename); g_free (quoted_archive); g_free (quoted_filename); g_shell_parse_argv (command_line, NULL, &argv, &err); g_free (command_line); if (err) { g_warning (_("Error %s"), err->message); g_error_free (err); return NULL; } return argv; }
null
null
212,917
5221502165965543150113388489824773188
37
comics: make the files containing "--checkpoint-action=" unsupported Fixes #257
other
qemu
8c92060d3c0248bd4d515719a35922cd2391b9b4
1
static void sungem_send_packet(SunGEMState *s, const uint8_t *buf, int size) { NetClientState *nc = qemu_get_queue(s->nic); if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) { nc->info->receive(nc, buf, size); } else { qemu_send_packet(nc, buf, size); } }
null
null
212,927
22164789416916763534513212272225664326
11
sungem: switch to use qemu_receive_packet() for loopback This patch switches to use qemu_receive_packet() which can detect reentrancy and return early. This is intended to address CVE-2021-3416. Cc: Prasad J Pandit <[email protected]> Cc: [email protected] Reviewed-by: Mark Cave-Ayland <[email protected]> Reviewed-by: Philippe Mathieu-Daudé <[email protected]> Reviewed-by: Alistair Francis <[email protected]> Signed-off-by: Jason Wang <[email protected]>
other
w3m
67be73b03a5ad581e331ec97cb275cd8a52719ed
1
process_button(struct parsed_tag *tag) { Str tmp = NULL; char *p, *q, *r, *qq = ""; int qlen, v; if (cur_form_id < 0) { char *s = "<form_int method=internal action=none>"; tmp = process_form(parse_tag(&s, TRUE)); } if (tmp == NULL) tmp = Strnew(); p = "submit"; parsedtag_get_value(tag, ATTR_TYPE, &p); q = NULL; parsedtag_get_value(tag, ATTR_VALUE, &q); r = ""; parsedtag_get_value(tag, ATTR_NAME, &r); v = formtype(p); if (v == FORM_UNKNOWN) return NULL; if (!q) { switch (v) { case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: q = "SUBMIT"; break; case FORM_INPUT_RESET: q = "RESET"; break; } } if (q) { qq = html_quote(q); qlen = strlen(q); } /* Strcat_charp(tmp, "<pre_int>"); */ Strcat(tmp, Sprintf("<input_alt hseq=\"%d\" fid=\"%d\" type=\"%s\" " "name=\"%s\" value=\"%s\">", cur_hseq++, cur_form_id, html_quote(p), html_quote(r), qq)); return tmp; }
null
null
213,589
325224422713155790624329814808410593768
47
Prevent segfault with incorrect button type Bug-Debian: https://github.com/tats/w3m/issues/17
other
libtpms
ea62fd9679f8c6fc5e79471b33cfbd8227bfed72
1
FindEmptyObjectSlot( TPMI_DH_OBJECT *handle // OUT: (optional) ) { UINT32 i; OBJECT *object; for(i = 0; i < MAX_LOADED_OBJECTS; i++) { object = &s_objects[i]; if(object->attributes.occupied == CLEAR) { if(handle) *handle = i + TRANSIENT_FIRST; // Initialize the object attributes MemorySet(&object->attributes, 0, sizeof(OBJECT_ATTRIBUTES)); return object; } } return NULL; }
null
null
213,998
277852716912471259753395033097358636489
20
tpm2: Initialize a whole OBJECT before using it Initialize a whole OBJECT before using it. This is necessary since an OBJECT may also be used as a HASH_OBJECT via the ANY_OBJECT union and that HASH_OBJECT can leave bad size inidicators in TPM2B buffer in the OBJECT. To get rid of this problem we reset the whole OBJECT to 0 before using it. This is as if the memory for the OBJECT was just initialized. Signed-off-by: Stefan Berger <[email protected]>
other
liblouis
2e4772befb2b1c37cb4b9d6572945115ee28630a
1
compileRule(FileInfo *file, TranslationTableHeader **table, DisplayTableHeader **displayTable, const MacroList **inScopeMacros) { CharsString token; TranslationTableOpcode opcode; CharsString ruleChars; CharsString ruleDots; CharsString cells; CharsString scratchPad; CharsString emphClass; TranslationTableCharacterAttributes after = 0; TranslationTableCharacterAttributes before = 0; int noback, nofor, nocross; noback = nofor = nocross = 0; doOpcode: if (!getToken(file, &token, NULL)) return 1; /* blank line */ if (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */ if (file->lineNumber == 1 && (eqasc2uni((unsigned char *)"ISO", token.chars, 3) || eqasc2uni((unsigned char *)"UTF-8", token.chars, 5))) { if (table) compileHyphenation(file, &token, table); else /* ignore the whole file */ while (_lou_getALine(file)) ; return 1; } opcode = getOpcode(file, &token); switch (opcode) { case CTO_Macro: { const Macro *macro; #ifdef ENABLE_MACROS if (!inScopeMacros) { compileError(file, "Defining macros only allowed in table files."); return 0; } if (compileMacro(file, &macro)) { *inScopeMacros = cons_macro(macro, *inScopeMacros); return 1; } return 0; #else compileError(file, "Macro feature is disabled."); return 0; #endif } case CTO_IncludeFile: { CharsString includedFile; if (!getToken(file, &token, "include file name")) return 0; if (!parseChars(file, &includedFile, &token)) return 0; return includeFile(file, &includedFile, table, displayTable); } case CTO_NoBack: if (nofor) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoFor)); return 0; } noback = 1; goto doOpcode; case CTO_NoFor: if (noback) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoBack)); return 0; } nofor = 1; goto doOpcode; case CTO_Space: return compileCharDef( file, opcode, CTC_Space, noback, nofor, table, displayTable); case CTO_Digit: return compileCharDef( file, opcode, CTC_Digit, noback, nofor, table, displayTable); case CTO_LitDigit: return compileCharDef( file, opcode, CTC_LitDigit, noback, nofor, table, displayTable); case CTO_Punctuation: return compileCharDef( file, opcode, CTC_Punctuation, noback, nofor, table, displayTable); case CTO_Math: return compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable); case CTO_Sign: return compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable); case CTO_Letter: return compileCharDef( file, opcode, CTC_Letter, noback, nofor, table, displayTable); case CTO_UpperCase: return compileCharDef( file, opcode, CTC_UpperCase, noback, nofor, table, displayTable); case CTO_LowerCase: return compileCharDef( file, opcode, CTC_LowerCase, noback, nofor, table, displayTable); case CTO_Grouping: return compileGrouping(file, noback, nofor, table, displayTable); case CTO_Display: if (!displayTable) return 1; // ignore if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length != 1) { compileError(file, "Exactly one character and one cell are required."); return 0; } return putCharDotsMapping( file, ruleChars.chars[0], ruleDots.chars[0], displayTable); case CTO_UpLow: case CTO_None: { // check if token is a macro name if (inScopeMacros) { const MacroList *macros = *inScopeMacros; while (macros) { const Macro *m = macros->head; if (token.length == strlen(m->name) && eqasc2uni((unsigned char *)m->name, token.chars, token.length)) { if (!inScopeMacros) { compileError(file, "Calling macros only allowed in table files."); return 0; } FileInfo tmpFile; memset(&tmpFile, 0, sizeof(tmpFile)); tmpFile.fileName = file->fileName; tmpFile.sourceFile = file->sourceFile; tmpFile.lineNumber = file->lineNumber; tmpFile.encoding = noEncoding; tmpFile.status = 0; tmpFile.linepos = 0; tmpFile.linelen = 0; int argument_count = 0; CharsString *arguments = malloc(m->argument_count * sizeof(CharsString)); while (argument_count < m->argument_count) { if (getToken(file, &token, "macro argument")) arguments[argument_count++] = token; else break; } if (argument_count < m->argument_count) { compileError(file, "Expected %d arguments", m->argument_count); return 0; } int i = 0; int subst = 0; int next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; for (;;) { while (i < next) { widechar c = m->definition[i++]; if (c == '\n') { if (!compileRule(&tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } tmpFile.linepos = 0; tmpFile.linelen = 0; } else if (tmpFile.linelen >= MAXSTRING) { compileError(file, "Line exceeds %d characters (post macro " "expansion)", MAXSTRING); return 0; } else tmpFile.line[tmpFile.linelen++] = c; } if (subst < m->substitution_count) { CharsString arg = arguments[m->substitutions[2 * subst + 1] - 1]; for (int j = 0; j < arg.length; j++) tmpFile.line[tmpFile.linelen++] = arg.chars[j]; subst++; next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; } else { if (!compileRule( &tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } break; } } return 1; } macros = macros->tail; } } if (opcode == CTO_UpLow) { compileError(file, "The uplow opcode is deprecated."); return 0; } compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } /* now only opcodes follow that don't modify the display table */ default: if (!table) return 1; switch (opcode) { case CTO_Locale: compileWarning(file, "The locale opcode is not implemented. Use the locale meta data " "instead."); return 1; case CTO_Undefined: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->undefined; if (!compileBrailleIndicator(file, "undefined character opcode", CTO_Undefined, &ruleOffset, noback, nofor, table)) return 0; (*table)->undefined = ruleOffset; return 1; } case CTO_Match: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternsOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); noback = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, &rule, noback, nofor, table)) goto CTO_Match_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_Match_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_Match_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternsOffset, len * sizeof(widechar), table)) goto CTO_Match_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar)); rule->patterns = patternsOffset; ok = 1; CTO_Match_cleanup: free(patterns); return ok; } case CTO_BackMatch: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); nofor = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule, noback, nofor, table)) goto CTO_BackMatch_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternOffset, len * sizeof(widechar), table)) goto CTO_BackMatch_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar)); rule->patterns = patternOffset; ok = 1; CTO_BackMatch_cleanup: free(patterns); return ok; } case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: /* these 8 general purpose opcodes are compiled further down to more specific * internal opcodes: * - modeletter * - begmodeword * - endmodeword * - begmode * - endmode * - begmodephrase * - endmodephrase * - lenmodephrase */ case CTO_ModeLetter: case CTO_BegModeWord: case CTO_EndModeWord: case CTO_BegMode: case CTO_EndMode: case CTO_BegModePhrase: case CTO_EndModePhrase: case CTO_LenModePhrase: { TranslationTableCharacterAttributes mode; int i; switch (opcode) { case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: mode = CTC_UpperCase; i = 0; opcode += (CTO_ModeLetter - CTO_CapsLetter); break; default: if (!getToken(file, &token, "attribute name")) return 0; if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *characterClass = findCharacterClass(&token, *table); if (!characterClass) { characterClass = addCharacterClass(file, token.chars, token.length, *table, 1); if (!characterClass) return 0; } mode = characterClass->attribute; if (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space && mode <= CTC_LitDigit) { compileError(file, "mode must be \"uppercase\", \"digit\", or a custom " "attribute name."); return 0; } /* check if this mode is already defined and if the number of modes does * not exceed the maximal number */ if (mode == CTC_UpperCase) i = 0; else { for (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) { if ((*table)->modes[i].mode == mode) { break; } } if (i == MAX_MODES) { compileError(file, "Max number of modes (%i) reached", MAX_MODES); return 0; } } } if (!(*table)->modes[i].value) (*table)->modes[i] = (EmphasisClass){ plain_text, mode, 0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i }; switch (opcode) { case CTO_BegModePhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word capital sign", CTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset; return 1; } case CTO_EndModePhrase: { TranslationTableOffset ruleOffset; switch (compileBeforeAfter(file)) { case 1: // before if ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) { compileError( file, "Capital sign after last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "capital sign before last word", CTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] = ruleOffset; return 1; case 2: // after if ((*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]) { compileError( file, "Capital sign before last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "capital sign after last word", CTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] = ruleOffset; return 1; default: // error compileError(file, "Invalid lastword indicator location."); return 0; } return 0; } case CTO_BegMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset]; if (!compileBrailleIndicator(file, "first letter capital sign", CTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset; return 1; } case CTO_EndMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset]; if (!compileBrailleIndicator(file, "last letter capital sign", CTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset; return 1; } case CTO_ModeLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset]; if (!compileBrailleIndicator(file, "single letter capital sign", CTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset; return 1; } case CTO_BegModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset]; if (!compileBrailleIndicator(file, "capital word", CTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset; return 1; } case CTO_EndModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset]; if (!compileBrailleIndicator(file, "capital word stop", CTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset; return 1; } case CTO_LenModePhrase: return (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] = compileNumber(file); default: break; } break; } /* these 8 general purpose emphasis opcodes are compiled further down to more * specific internal opcodes: * - emphletter * - begemphword * - endemphword * - begemph * - endemph * - begemphphrase * - endemphphrase * - lenemphphrase */ case CTO_EmphClass: if (!getToken(file, &emphClass, "emphasis class")) { compileError(file, "emphclass must be followed by a valid class name."); return 0; } int k, i; char *s = malloc(sizeof(char) * (emphClass.length + 1)); for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) { _lou_logMessage(LOU_LOG_WARN, "Duplicate emphasis class: %s", s); warningCount++; free(s); return 1; } if (i == MAX_EMPH_CLASSES) { _lou_logMessage(LOU_LOG_ERROR, "Max number of emphasis classes (%i) reached", MAX_EMPH_CLASSES); errorCount++; free(s); return 0; } switch (i) { /* For backwards compatibility (i.e. because programs will assume * the first 3 typeform bits are `italic', `underline' and `bold') * we require that the first 3 emphclass definitions are (in that * order): * * emphclass italic * emphclass underline * emphclass bold * * While it would be possible to use the emphclass opcode only for * defining _additional_ classes (not allowing for them to be called * italic, underline or bold), thereby reducing the amount of * boilerplate, we deliberately choose not to do that in order to * not give italic, underline and bold any special status. The * hope is that eventually all programs will use liblouis for * emphasis the recommended way (i.e. by looking up the supported * typeforms in the documentation or API) so that we can drop this * restriction. */ case 0: if (strcmp(s, "italic") != 0) { _lou_logMessage(LOU_LOG_ERROR, "First emphasis class must be \"italic\" but got " "%s", s); errorCount++; free(s); return 0; } break; case 1: if (strcmp(s, "underline") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Second emphasis class must be \"underline\" but " "got " "%s", s); errorCount++; free(s); return 0; } break; case 2: if (strcmp(s, "bold") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Third emphasis class must be \"bold\" but got " "%s", s); errorCount++; free(s); return 0; } break; } (*table)->emphClassNames[i] = s; (*table)->emphClasses[i] = (EmphasisClass){ emph_1 << i, /* relies on the order of typeforms emph_1..emph_10 */ 0, 0x1 << i, i }; return 1; case CTO_EmphLetter: case CTO_BegEmphWord: case CTO_EndEmphWord: case CTO_BegEmph: case CTO_EndEmph: case CTO_BegEmphPhrase: case CTO_EndEmphPhrase: case CTO_LenEmphPhrase: case CTO_EmphModeChars: case CTO_NoEmphChars: { if (!getToken(file, &token, "emphasis class")) return 0; if (!parseChars(file, &emphClass, &token)) return 0; char *s = malloc(sizeof(char) * (emphClass.length + 1)); int k, i; for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) break; if (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) { _lou_logMessage(LOU_LOG_ERROR, "Emphasis class %s not declared", s); errorCount++; free(s); return 0; } int ok = 0; switch (opcode) { case CTO_EmphLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset]; if (!compileBrailleIndicator(file, "single letter", CTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][letterOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset]; if (!compileBrailleIndicator(file, "word", CTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begWordOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset]; if (!compileBrailleIndicator(file, "word stop", CTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endWordOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmph: { /* fail if both begemph and any of begemphphrase or begemphword are * defined */ if ((*table)->emphRules[i][begWordOffset] || (*table)->emphRules[i][begPhraseOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both begemph and " "begemphword or begemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset]; if (!compileBrailleIndicator(file, "first letter", CTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmph: { if ((*table)->emphRules[i][endWordOffset] || (*table)->emphRules[i][endPhraseBeforeOffset] || (*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both endemph and " "endemphword or endemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset]; if (!compileBrailleIndicator(file, "last letter", CTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphPhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word", CTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begPhraseOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphPhrase: switch (compileBeforeAfter(file)) { case 1: { // before if ((*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "last word after already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "last word before", CTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset; ok = 1; break; } case 2: { // after if ((*table)->emphRules[i][endPhraseBeforeOffset]) { compileError(file, "last word before already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "last word after", CTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset; ok = 1; break; } default: // error compileError(file, "Invalid lastword indicator location."); break; } break; case CTO_LenEmphPhrase: if (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file))) ok = 1; break; case CTO_EmphModeChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *emphmodechars = (*table)->emphModeChars[i]; int len; for (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++) ; if (len + ruleChars.length > EMPHMODECHARSSIZE) { compileError(file, "More than %d characters", EMPHMODECHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Emphasis mode character undefined"); ok = 0; break; } emphmodechars[len++] = ruleChars.chars[k]; } break; } case CTO_NoEmphChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *noemphchars = (*table)->noEmphChars[i]; int len; for (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++) ; if (len + ruleChars.length > NOEMPHCHARSSIZE) { compileError(file, "More than %d characters", NOEMPHCHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Character undefined"); ok = 0; break; } noemphchars[len++] = ruleChars.chars[k]; } break; } default: break; } free(s); return ok; } case CTO_LetterSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->letterSign; if (!compileBrailleIndicator(file, "letter sign", CTO_LetterRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->letterSign = ruleOffset; return 1; } case CTO_NoLetsignBefore: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) { compileError(file, "More than %d characters", LETSIGNBEFORESIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsign: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) { compileError(file, "More than %d characters", LETSIGNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsignAfter: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) { compileError(file, "More than %d characters", LETSIGNAFTERSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] = ruleChars.chars[k]; return 1; case CTO_NumberSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->numberSign; if (!compileBrailleIndicator(file, "number sign", CTO_NumberRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->numberSign = ruleOffset; return 1; } case CTO_NumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric mode character undefined: %s", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } c->attributes |= CTC_NumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_MidEndNumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Midendnumeric mode character undefined"); return 0; } c->attributes |= CTC_MidEndNumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_NumericNoContractChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric no contraction character undefined"); return 0; } c->attributes |= CTC_NumericNoContract; (*table)->usesNumericMode = 1; } return 1; case CTO_NoContractSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->noContractSign; if (!compileBrailleIndicator(file, "no contractions sign", CTO_NoContractRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->noContractSign = ruleOffset; return 1; } case CTO_SeqDelimiter: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence delimiter character undefined"); return 0; } c->attributes |= CTC_SeqDelimiter; (*table)->usesSequences = 1; } return 1; case CTO_SeqBeforeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence before character undefined"); return 0; } c->attributes |= CTC_SeqBefore; } return 1; case CTO_SeqAfterChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence after character undefined"); return 0; } c->attributes |= CTC_SeqAfter; } return 1; case CTO_SeqAfterPattern: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) { compileError(file, "More than %d characters", SEQPATTERNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k]; (*table)->seqPatterns[(*table)->seqPatternsCount++] = 0; return 1; case CTO_SeqAfterExpression: if (!getRuleCharsText(file, &ruleChars)) return 0; for ((*table)->seqAfterExpressionLength = 0; (*table)->seqAfterExpressionLength < ruleChars.length; (*table)->seqAfterExpressionLength++) (*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = ruleChars.chars[(*table)->seqAfterExpressionLength]; (*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = 0; return 1; case CTO_CapsModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Capital mode character undefined"); return 0; } c->attributes |= CTC_CapsMode; (*table)->hasCapsModeChars = 1; } return 1; case CTO_BegComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->begComp; if (!compileBrailleIndicator(file, "begin computer braille", CTO_BegCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->begComp = ruleOffset; return 1; } case CTO_EndComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->endComp; if (!compileBrailleIndicator(file, "end computer braslle", CTO_EndCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->endComp = ruleOffset; return 1; } case CTO_NoCross: if (nocross) { compileError( file, "%s already specified.", _lou_findOpcodeName(CTO_NoCross)); return 0; } nocross = 1; goto doOpcode; case CTO_Syllable: (*table)->syllables = 1; case CTO_Always: case CTO_LargeSign: case CTO_WholeWord: case CTO_PartWord: case CTO_JoinNum: case CTO_JoinableWord: case CTO_LowWord: case CTO_SuffixableWord: case CTO_PrefixableWord: case CTO_BegWord: case CTO_BegMidWord: case CTO_MidWord: case CTO_MidEndWord: case CTO_EndWord: case CTO_PrePunc: case CTO_PostPunc: case CTO_BegNum: case CTO_MidNum: case CTO_EndNum: case CTO_Repeated: case CTO_RepWord: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleDots.length == 0) // check that all characters in a rule with `=` as second operand are // defined (or based on another character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } TranslationTableRule *r; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r, noback, nofor, table)) return 0; if (nocross) r->nocross = 1; return 1; // if (opcode == CTO_MidNum) // { // TranslationTableCharacter *c = getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } case CTO_RepEndWord: if (!getRuleCharsText(file, &ruleChars)) return 0; CharsString dots; if (!getToken(file, &dots, "dots,dots operand")) return 0; int len = dots.length; for (int k = 0; k < len - 1; k++) { if (dots.chars[k] == ',') { dots.length = k; if (!parseDots(file, &ruleDots, &dots)) return 0; ruleDots.chars[ruleDots.length++] = ','; k++; if (k == len - 1 && dots.chars[k] == '=') { // check that all characters are defined (or based on another // character) for (int l = 0; l < ruleChars.length; l++) { TranslationTableCharacter *c = getChar(ruleChars.chars[l], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[l], 1, 0)); return 0; } } } else { CharsString x, y; x.length = 0; while (k < len) x.chars[x.length++] = dots.chars[k++]; if (parseDots(file, &y, &x)) for (int l = 0; l < y.length; l++) ruleDots.chars[ruleDots.length++] = y.chars[l]; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); } } return 0; case CTO_CompDots: case CTO_Comp6: { TranslationTableOffset ruleOffset; if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.length != 1) { compileError(file, "first operand must be 1 character"); return 0; } if (nofor || noback) { compileWarning(file, "nofor and noback not allowed on comp6 rules"); } if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; return 1; } case CTO_ExactDots: if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.chars[0] != '@') { compileError(file, "The operand must begin with an at sign (@)"); return 0; } for (int k = 1; k < ruleChars.length; k++) scratchPad.chars[k - 1] = ruleChars.chars[k]; scratchPad.length = ruleChars.length - 1; if (!parseDots(file, &ruleDots, &scratchPad)) return 0; return addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL, noback, nofor, table); case CTO_CapsNoCont: { TranslationTableOffset ruleOffset; ruleChars.length = 1; ruleChars.chars[0] = 'a'; if (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; (*table)->capsNoCont = ruleOffset; return 1; } case CTO_Replace: if (getRuleCharsText(file, &ruleChars)) { if (atEndOfLine(file)) ruleDots.length = ruleDots.chars[0] = 0; else { getRuleDotsText(file, &ruleDots); if (ruleDots.chars[0] == '#') ruleDots.length = ruleDots.chars[0] = 0; else if (ruleDots.chars[0] == '\\' && ruleDots.chars[1] == '#') memmove(&ruleDots.chars[0], &ruleDots.chars[1], ruleDots.length-- * CHARSIZE); } } for (int k = 0; k < ruleChars.length; k++) putChar(file, ruleChars.chars[k], table, NULL); for (int k = 0; k < ruleDots.length; k++) putChar(file, ruleDots.chars[k], table, NULL); return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); case CTO_Correct: (*table)->corrections = 1; goto doPass; case CTO_Pass2: if ((*table)->numPasses < 2) (*table)->numPasses = 2; goto doPass; case CTO_Pass3: if ((*table)->numPasses < 3) (*table)->numPasses = 3; goto doPass; case CTO_Pass4: if ((*table)->numPasses < 4) (*table)->numPasses = 4; doPass: case CTO_Context: if (!(nofor || noback)) { compileError(file, "%s or %s must be specified.", _lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack)); return 0; } return compilePassOpcode(file, opcode, noback, nofor, table); case CTO_Contraction: case CTO_NoCont: case CTO_CompBrl: case CTO_Literal: if (!getRuleCharsText(file, &ruleChars)) return 0; // check that all characters in a compbrl, contraction, // nocont or literal rule are defined (or based on another // character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } return addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL, noback, nofor, table); case CTO_MultInd: { ruleChars.length = 0; if (!getToken(file, &token, "multiple braille indicators") || !parseDots(file, &cells, &token)) return 0; while (getToken(file, &token, "multind opcodes")) { opcode = getOpcode(file, &token); if (opcode == CTO_None) { compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } if (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) { compileError(file, "Not a braille indicator opcode."); return 0; } ruleChars.chars[ruleChars.length++] = (widechar)opcode; if (atEndOfLine(file)) break; } return addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL, NULL, noback, nofor, table); } case CTO_Class: compileWarning(file, "class is deprecated, use attribute instead"); case CTO_Attribute: { if (nofor || noback) { compileWarning( file, "nofor and noback not allowed before class/attribute"); } if ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) || (opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) { compileError(file, "attribute and class rules must not be both present in a table"); return 0; } if (opcode == CTO_Class) (*table)->usesAttributeOrClass = 2; else (*table)->usesAttributeOrClass = 1; if (!getToken(file, &token, "attribute name")) { compileError(file, "Expected %s", "attribute name"); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } TranslationTableCharacterAttributes attribute = 0; { int attrNumber = -1; switch (token.chars[0]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': attrNumber = token.chars[0] - '0'; break; } if (attrNumber >= 0) { if (opcode == CTO_Class) { compileError(file, "Invalid class name: may not contain digits, use " "attribute instead of class"); return 0; } if (token.length > 1 || attrNumber > 7) { compileError(file, "Invalid attribute name: must be a digit between 0 and 7 " "or a word containing only letters"); return 0; } if (!(*table)->numberedAttributes[attrNumber]) // attribute not used before yet: assign it a value (*table)->numberedAttributes[attrNumber] = getNextNumberedAttribute(*table); attribute = (*table)->numberedAttributes[attrNumber]; } else { const CharacterClass *namedAttr = findCharacterClass(&token, *table); if (!namedAttr) { // no class with that name: create one namedAttr = addCharacterClass( file, &token.chars[0], token.length, *table, 1); if (!namedAttr) return 0; } // there is a class with that name or a new class was successfully // created attribute = namedAttr->attribute; if (attribute == CTC_UpperCase || attribute == CTC_LowerCase) attribute |= CTC_Letter; } } CharsString characters; if (!getCharacters(file, &characters)) return 0; for (int i = 0; i < characters.length; i++) { // get the character from the table, or if it is not defined yet, // define it TranslationTableCharacter *character = putChar(file, characters.chars[i], table, NULL); // set the attribute character->attributes |= attribute; // also set the attribute on the associated dots (if any) if (character->basechar) character = (TranslationTableCharacter *)&(*table) ->ruleArea[character->basechar]; if (character->definitionRule) { TranslationTableRule *defRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; if (defRule->dotslen == 1) { TranslationTableCharacter *dots = getDots(defRule->charsdots[defRule->charslen], *table); if (dots) dots->attributes |= attribute; } } } return 1; } { TranslationTableCharacterAttributes *attributes; const CharacterClass *class; case CTO_After: attributes = &after; goto doBeforeAfter; case CTO_Before: attributes = &before; doBeforeAfter: if (!(*table)->characterClasses) { if (!allocateCharacterClasses(*table)) return 0; } if (!getToken(file, &token, "attribute name")) return 0; if (!(class = findCharacterClass(&token, *table))) { compileError(file, "attribute not defined"); return 0; } *attributes |= class->attribute; goto doOpcode; } case CTO_Base: if (nofor || noback) { compileWarning(file, "nofor and noback not allowed before base"); } if (!getToken(file, &token, "attribute name")) { compileError( file, "base opcode must be followed by a valid attribute name."); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *mode = findCharacterClass(&token, *table); if (!mode) { mode = addCharacterClass(file, token.chars, token.length, *table, 1); if (!mode) return 0; } if (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) && mode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) { compileError(file, "base opcode must be followed by \"uppercase\", \"digit\", or a " "custom attribute name."); return 0; } if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one character followed by one base character is " "required."); return 0; } TranslationTableOffset characterOffset; TranslationTableCharacter *character = putChar(file, token.chars[0], table, &characterOffset); if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one base character is required."); return 0; } if (character->definitionRule) { TranslationTableRule *prevRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Character already defined (%s). The base rule will take " "precedence.", file->fileName, file->lineNumber, printSource(file, prevRule->sourceFile, prevRule->sourceLine)); character->definitionRule = 0; } TranslationTableOffset basechar; putChar(file, token.chars[0], table, &basechar); // putChar may have moved table, so make sure character is still valid character = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset]; if (character->basechar) { if (character->basechar == basechar && character->mode == mode->attribute) { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Duplicate base rule.", file->fileName, file->lineNumber); } else { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: A different base rule already exists for this " "character (%s). The new rule will take precedence.", file->fileName, file->lineNumber, printSource( file, character->sourceFile, character->sourceLine)); } } character->basechar = basechar; character->mode = mode->attribute; character->sourceFile = file->sourceFile; character->sourceLine = file->lineNumber; /* some other processing is done at the end of the compilation, in * finalizeTable() */ return 1; case CTO_EmpMatchBefore: before |= CTC_EmpMatch; goto doOpcode; case CTO_EmpMatchAfter: after |= CTC_EmpMatch; goto doOpcode; case CTO_SwapCc: case CTO_SwapCd: case CTO_SwapDd: return compileSwap(file, opcode, noback, nofor, table); case CTO_Hyphen: case CTO_DecPoint: // case CTO_Apostrophe: // case CTO_Initial: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length < 1) { compileError(file, "One Unicode character and at least one cell are " "required."); return 0; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); // if (opcode == CTO_DecPoint) // { // TranslationTableCharacter *c = // getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } default: compileError(file, "unimplemented opcode."); return 0; } } return 0; }
null
null
214,997
50388777807644470054179765540034197016
1,462
Prevent an invalid memory writes in compileRule Thanks to Han Zheng for reporting it Fixes #1214
other
linux-2.6
efc7ffcb4237f8cb9938909041c4ed38f6e1bf40
1
int hfsplus_find_cat(struct super_block *sb, u32 cnid, struct hfs_find_data *fd) { hfsplus_cat_entry tmp; int err; u16 type; hfsplus_cat_build_key(sb, fd->search_key, cnid, NULL); err = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry)); if (err) return err; type = be16_to_cpu(tmp.type); if (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) { printk(KERN_ERR "hfs: found bad thread record in catalog\n"); return -EIO; } hfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID), &tmp.thread.nodeName); return hfs_brec_find(fd); }
CWE-119
null
215,399
256655408888579656518249099852758355696
22
hfsplus: fix Buffer overflow with a corrupted image When an hfsplus image gets corrupted it might happen that the catalog namelength field gets b0rked. If we mount such an image the memcpy() in hfsplus_cat_build_key_uni() writes more than the 255 that fit in the name field. Depending on the size of the overwritten data, we either only get memory corruption or also trigger an oops like this: [ 221.628020] BUG: unable to handle kernel paging request at c82b0000 [ 221.629066] IP: [<c022d4b1>] hfsplus_find_cat+0x10d/0x151 [ 221.629066] *pde = 0ea29163 *pte = 082b0160 [ 221.629066] Oops: 0002 [#1] PREEMPT DEBUG_PAGEALLOC [ 221.629066] Modules linked in: [ 221.629066] [ 221.629066] Pid: 4845, comm: mount Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #28) [ 221.629066] EIP: 0060:[<c022d4b1>] EFLAGS: 00010206 CPU: 0 [ 221.629066] EIP is at hfsplus_find_cat+0x10d/0x151 [ 221.629066] EAX: 00000029 EBX: 00016210 ECX: 000042c2 EDX: 00000002 [ 221.629066] ESI: c82d70ca EDI: c82b0000 EBP: c82d1bcc ESP: c82d199c [ 221.629066] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068 [ 221.629066] Process mount (pid: 4845, ti=c82d1000 task=c8224060 task.ti=c82d1000) [ 221.629066] Stack: c080b3c4 c82aa8f8 c82d19c2 00016210 c080b3be c82d1bd4 c82aa8f0 00000300 [ 221.629066] 01000000 750008b1 74006e00 74006900 65006c00 c82d6400 c013bd35 c8224060 [ 221.629066] 00000036 00000046 c82d19f0 00000082 c8224548 c8224060 00000036 c0d653cc [ 221.629066] Call Trace: [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c01302d2>] ? __kernel_text_address+0x1b/0x27 [ 221.629066] [<c010487a>] ? dump_trace+0xca/0xd6 [ 221.629066] [<c0109e32>] ? save_stack_address+0x0/0x2c [ 221.629066] [<c0109eaf>] ? save_stack_trace+0x1c/0x3a [ 221.629066] [<c013b571>] ? save_trace+0x37/0x8d [ 221.629066] [<c013b62e>] ? add_lock_to_list+0x67/0x8d [ 221.629066] [<c013ea1c>] ? validate_chain+0x8a4/0x9f4 [ 221.629066] [<c013553d>] ? down+0xc/0x2f [ 221.629066] [<c013f1f6>] ? __lock_acquire+0x68a/0x6e0 [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c013da5d>] ? mark_held_locks+0x43/0x5a [ 221.629066] [<c013dc3a>] ? trace_hardirqs_on+0xb/0xd [ 221.629066] [<c013dbf4>] ? trace_hardirqs_on_caller+0xf4/0x12f [ 221.629066] [<c06abec8>] ? _spin_unlock_irqrestore+0x42/0x58 [ 221.629066] [<c013555c>] ? down+0x2b/0x2f [ 221.629066] [<c022aa68>] ? hfsplus_iget+0xa0/0x154 [ 221.629066] [<c022b0b9>] ? hfsplus_fill_super+0x280/0x447 [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013f1f6>] ? __lock_acquire+0x68a/0x6e0 [ 221.629066] [<c041c9e4>] ? string+0x2b/0x74 [ 221.629066] [<c041cd16>] ? vsnprintf+0x2e9/0x512 [ 221.629066] [<c010487a>] ? dump_trace+0xca/0xd6 [ 221.629066] [<c0109eaf>] ? save_stack_trace+0x1c/0x3a [ 221.629066] [<c0109eaf>] ? save_stack_trace+0x1c/0x3a [ 221.629066] [<c013b571>] ? save_trace+0x37/0x8d [ 221.629066] [<c013b62e>] ? add_lock_to_list+0x67/0x8d [ 221.629066] [<c013ea1c>] ? validate_chain+0x8a4/0x9f4 [ 221.629066] [<c01354d3>] ? up+0xc/0x2f [ 221.629066] [<c013f1f6>] ? __lock_acquire+0x68a/0x6e0 [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c041cfb7>] ? snprintf+0x1b/0x1d [ 221.629066] [<c01ba466>] ? disk_name+0x25/0x67 [ 221.629066] [<c0183960>] ? get_sb_bdev+0xcd/0x10b [ 221.629066] [<c016ad92>] ? kstrdup+0x2a/0x4c [ 221.629066] [<c022a7b3>] ? hfsplus_get_sb+0x13/0x15 [ 221.629066] [<c022ae39>] ? hfsplus_fill_super+0x0/0x447 [ 221.629066] [<c0183583>] ? vfs_kern_mount+0x3b/0x76 [ 221.629066] [<c0183602>] ? do_kern_mount+0x32/0xba [ 221.629066] [<c01960d4>] ? do_new_mount+0x46/0x74 [ 221.629066] [<c0196277>] ? do_mount+0x175/0x193 [ 221.629066] [<c013dbf4>] ? trace_hardirqs_on_caller+0xf4/0x12f [ 221.629066] [<c01663b2>] ? __get_free_pages+0x1e/0x24 [ 221.629066] [<c06ac07b>] ? lock_kernel+0x19/0x8c [ 221.629066] [<c01962e6>] ? sys_mount+0x51/0x9b [ 221.629066] [<c01962f9>] ? sys_mount+0x64/0x9b [ 221.629066] [<c01038bd>] ? sysenter_do_call+0x12/0x31 [ 221.629066] ======================= [ 221.629066] Code: 89 c2 c1 e2 08 c1 e8 08 09 c2 8b 85 e8 fd ff ff 66 89 50 06 89 c7 53 83 c7 08 56 57 68 c4 b3 80 c0 e8 8c 5c ef ff 89 d9 c1 e9 02 <f3> a5 89 d9 83 e1 03 74 02 f3 a4 83 c3 06 8b 95 e8 fd ff ff 0f [ 221.629066] EIP: [<c022d4b1>] hfsplus_find_cat+0x10d/0x151 SS:ESP 0068:c82d199c [ 221.629066] ---[ end trace e417a1d67f0d0066 ]--- Since hfsplus_cat_build_key_uni() returns void and only has one callsite, the check is performed at the callsite. Signed-off-by: Eric Sesterhenn <[email protected]> Reviewed-by: Pekka Enberg <[email protected]> Cc: Roman Zippel <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
other
linux-2.6
649f1ee6c705aab644035a7998d7b574193a598a
1
int hfsplus_block_allocate(struct super_block *sb, u32 size, u32 offset, u32 *max) { struct page *page; struct address_space *mapping; __be32 *pptr, *curr, *end; u32 mask, start, len, n; __be32 val; int i; len = *max; if (!len) return size; dprint(DBG_BITMAP, "block_allocate: %u,%u,%u\n", size, offset, len); mutex_lock(&HFSPLUS_SB(sb).alloc_file->i_mutex); mapping = HFSPLUS_SB(sb).alloc_file->i_mapping; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); pptr = kmap(page); curr = pptr + (offset & (PAGE_CACHE_BITS - 1)) / 32; i = offset % 32; offset &= ~(PAGE_CACHE_BITS - 1); if ((size ^ offset) / PAGE_CACHE_BITS) end = pptr + PAGE_CACHE_BITS / 32; else end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32; /* scan the first partial u32 for zero bits */ val = *curr; if (~val) { n = be32_to_cpu(val); mask = (1U << 31) >> i; for (; i < 32; mask >>= 1, i++) { if (!(n & mask)) goto found; } } curr++; /* scan complete u32s for the first zero bit */ while (1) { while (curr < end) { val = *curr; if (~val) { n = be32_to_cpu(val); mask = 1 << 31; for (i = 0; i < 32; mask >>= 1, i++) { if (!(n & mask)) goto found; } } curr++; } kunmap(page); offset += PAGE_CACHE_BITS; if (offset >= size) break; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); curr = pptr = kmap(page); if ((size ^ offset) / PAGE_CACHE_BITS) end = pptr + PAGE_CACHE_BITS / 32; else end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32; } dprint(DBG_BITMAP, "bitmap full\n"); start = size; goto out; found: start = offset + (curr - pptr) * 32 + i; if (start >= size) { dprint(DBG_BITMAP, "bitmap full\n"); goto out; } /* do any partial u32 at the start */ len = min(size - start, len); while (1) { n |= mask; if (++i >= 32) break; mask >>= 1; if (!--len || n & mask) goto done; } if (!--len) goto done; *curr++ = cpu_to_be32(n); /* do full u32s */ while (1) { while (curr < end) { n = be32_to_cpu(*curr); if (len < 32) goto last; if (n) { len = 32; goto last; } *curr++ = cpu_to_be32(0xffffffff); len -= 32; } set_page_dirty(page); kunmap(page); offset += PAGE_CACHE_BITS; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); pptr = kmap(page); curr = pptr; end = pptr + PAGE_CACHE_BITS / 32; } last: /* do any partial u32 at end */ mask = 1U << 31; for (i = 0; i < len; i++) { if (n & mask) break; n |= mask; mask >>= 1; } done: *curr = cpu_to_be32(n); set_page_dirty(page); kunmap(page); *max = offset + (curr - pptr) * 32 + i - start; HFSPLUS_SB(sb).free_blocks -= *max; sb->s_dirt = 1; dprint(DBG_BITMAP, "-> %u,%u\n", start, *max); out: mutex_unlock(&HFSPLUS_SB(sb).alloc_file->i_mutex); return start; }
CWE-20
null
215,400
162883961593441362505774058247214968119
130
hfsplus: check read_mapping_page() return value While testing more corrupted images with hfsplus, i came across one which triggered the following bug: [15840.675016] BUG: unable to handle kernel paging request at fffffffb [15840.675016] IP: [<c0116a4f>] kmap+0x15/0x56 [15840.675016] *pde = 00008067 *pte = 00000000 [15840.675016] Oops: 0000 [#1] PREEMPT DEBUG_PAGEALLOC [15840.675016] Modules linked in: [15840.675016] [15840.675016] Pid: 11575, comm: ln Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #29) [15840.675016] EIP: 0060:[<c0116a4f>] EFLAGS: 00010202 CPU: 0 [15840.675016] EIP is at kmap+0x15/0x56 [15840.675016] EAX: 00000246 EBX: fffffffb ECX: 00000000 EDX: cab919c0 [15840.675016] ESI: 000007dd EDI: cab0bcf4 EBP: cab0bc98 ESP: cab0bc94 [15840.675016] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068 [15840.675016] Process ln (pid: 11575, ti=cab0b000 task=cab919c0 task.ti=cab0b000) [15840.675016] Stack: 00000000 cab0bcdc c0231cfb 00000000 cab0bce0 00000800 ca9290c0 fffffffb [15840.675016] cab145d0 cab919c0 cab15998 22222222 22222222 22222222 00000001 cab15960 [15840.675016] 000007dd cab0bcf4 cab0bd04 c022cb3a cab0bcf4 cab15a6c ca9290c0 00000000 [15840.675016] Call Trace: [15840.675016] [<c0231cfb>] ? hfsplus_block_allocate+0x6f/0x2d3 [15840.675016] [<c022cb3a>] ? hfsplus_file_extend+0xc4/0x1db [15840.675016] [<c022ce41>] ? hfsplus_get_block+0x8c/0x19d [15840.675016] [<c06adde4>] ? sub_preempt_count+0x9d/0xab [15840.675016] [<c019ece6>] ? __block_prepare_write+0x147/0x311 [15840.675016] [<c0161934>] ? __grab_cache_page+0x52/0x73 [15840.675016] [<c019ef4f>] ? block_write_begin+0x79/0xd5 [15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d [15840.675016] [<c019f22a>] ? cont_write_begin+0x27f/0x2af [15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d [15840.675016] [<c0139ebe>] ? tick_program_event+0x28/0x4c [15840.675016] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [15840.675016] [<c022b723>] ? hfsplus_write_begin+0x2d/0x32 [15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d [15840.675016] [<c0161988>] ? pagecache_write_begin+0x33/0x107 [15840.675016] [<c01879e5>] ? __page_symlink+0x3c/0xae [15840.675016] [<c019ad34>] ? __mark_inode_dirty+0x12f/0x137 [15840.675016] [<c0187a70>] ? page_symlink+0x19/0x1e [15840.675016] [<c022e6eb>] ? hfsplus_symlink+0x41/0xa6 [15840.675016] [<c01886a9>] ? vfs_symlink+0x99/0x101 [15840.675016] [<c018a2f6>] ? sys_symlinkat+0x6b/0xad [15840.675016] [<c018a348>] ? sys_symlink+0x10/0x12 [15840.675016] [<c01038bd>] ? sysenter_do_call+0x12/0x31 [15840.675016] ======================= [15840.675016] Code: 00 00 75 10 83 3d 88 2f ec c0 02 75 07 89 d0 e8 12 56 05 00 5d c3 55 ba 06 00 00 00 89 e5 53 89 c3 b8 3d eb 7e c0 e8 16 74 00 00 <8b> 03 c1 e8 1e 69 c0 d8 02 00 00 05 b8 69 8e c0 2b 80 c4 02 00 [15840.675016] EIP: [<c0116a4f>] kmap+0x15/0x56 SS:ESP 0068:cab0bc94 [15840.675016] ---[ end trace 4fea40dad6b70e5f ]--- This happens because the return value of read_mapping_page() is passed on to kmap unchecked. The bug is triggered after the first read_mapping_page() in hfsplus_block_allocate(), this patch fixes all three usages in this functions but leaves the ones further down in the file unchanged. Signed-off-by: Eric Sesterhenn <[email protected]> Cc: Roman Zippel <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
other
nettle
c71d2c9d20eeebb985e3872e4550137209e3ce4d
1
ecc_256_modp (const struct ecc_modulo *p, mp_limb_t *rp) { mp_limb_t u1, u0; mp_size_t n; n = 2*p->size; u1 = rp[--n]; u0 = rp[n-1]; /* This is not particularly fast, but should work well with assembly implementation. */ for (; n >= p->size; n--) { mp_limb_t q2, q1, q0, t, cy; /* <q2, q1, q0> = v * u1 + <u1,u0>, with v = 2^32 - 1: +---+---+ | u1| u0| +---+---+ |-u1| +-+-+-+ | u1| +---+-+-+-+-+ | q2| q1| q0| +---+---+---+ */ q1 = u1 - (u1 > u0); q0 = u0 - u1; t = u1 << 32; q0 += t; t = (u1 >> 32) + (q0 < t) + 1; q1 += t; q2 = q1 < t; /* Compute candidate remainder */ u1 = u0 + (q1 << 32) - q1; t = -(mp_limb_t) (u1 > q0); u1 -= t & 0xffffffff; q1 += t; q2 += t + (q1 < t); assert (q2 < 2); /* We multiply by two low limbs of p, 2^96 - 1, so we could use shifts rather than mul. */ t = mpn_submul_1 (rp + n - 4, p->m, 2, q1); t += cnd_sub_n (q2, rp + n - 3, p->m, 1); t += (-q2) & 0xffffffff; u0 = rp[n-2]; cy = (u0 < t); u0 -= t; t = (u1 < cy); u1 -= cy; u1 += cnd_add_n (t, rp + n - 4, p->m, 3); u1 -= (-t) & 0xffffffff; } rp[2] = u0; rp[3] = u1; }
CWE-310
null
215,948
177459790284134415640388177650830838743
60
Fixed miscomputation bugs in secp-256r1 modulo functions.
other
openssl
cca1cd9a3447dd067503e4a85ebd1679ee78a48e
1
kssl_keytab_is_available(KSSL_CTX *kssl_ctx) { krb5_context krb5context = NULL; krb5_keytab krb5keytab = NULL; krb5_keytab_entry entry; krb5_principal princ = NULL; krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC; int rc = 0; if ((krb5rc = krb5_init_context(&krb5context))) return(0); /* kssl_ctx->keytab_file == NULL ==> use Kerberos default */ if (kssl_ctx->keytab_file) { krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file, &krb5keytab); if (krb5rc) goto exit; } else { krb5rc = krb5_kt_default(krb5context,&krb5keytab); if (krb5rc) goto exit; } /* the host key we are looking for */ krb5rc = krb5_sname_to_principal(krb5context, NULL, kssl_ctx->service_name ? kssl_ctx->service_name: KRB5SVC, KRB5_NT_SRV_HST, &princ); krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, princ, 0 /* IGNORE_VNO */, 0 /* IGNORE_ENCTYPE */, &entry); if ( krb5rc == KRB5_KT_NOTFOUND ) { rc = 1; goto exit; } else if ( krb5rc ) goto exit; krb5_kt_free_entry(krb5context, &entry); rc = 1; exit: if (krb5keytab) krb5_kt_close(krb5context, krb5keytab); if (princ) krb5_free_principal(krb5context, princ); if (krb5context) krb5_free_context(krb5context); return(rc); }
CWE-20
null
216,126
270879083228272962991952045442860437006
53
Submitted by: Tomas Hoger <[email protected]> Fix for CVE-2010-0433 where some kerberos enabled versions of OpenSSL could be crashed if the relevant tables were not present (e.g. chrooted).
other
libssh
4d8420f3282ed07fc99fc5e930c17df27ef1e9b2
1
int sftp_mkdir(sftp_session sftp, const char *directory, mode_t mode) { sftp_status_message status = NULL; sftp_message msg = NULL; sftp_attributes errno_attr = NULL; struct sftp_attributes_struct attr; ssh_buffer buffer; ssh_string path; uint32_t id; buffer = ssh_buffer_new(); if (buffer == NULL) { ssh_set_error_oom(sftp->session); return -1; } path = ssh_string_from_char(directory); if (path == NULL) { ssh_set_error_oom(sftp->session); ssh_buffer_free(buffer); return -1; } ZERO_STRUCT(attr); attr.permissions = mode; attr.flags = SSH_FILEXFER_ATTR_PERMISSIONS; id = sftp_get_new_id(sftp); if (buffer_add_u32(buffer, id) < 0 || buffer_add_ssh_string(buffer, path) < 0 || buffer_add_attributes(buffer, &attr) < 0 || sftp_packet_write(sftp, SSH_FXP_MKDIR, buffer) < 0) { ssh_buffer_free(buffer); ssh_string_free(path); } ssh_buffer_free(buffer); ssh_string_free(path); while (msg == NULL) { if (sftp_read_and_dispatch(sftp) < 0) { return -1; } msg = sftp_dequeue(sftp, id); } /* By specification, this command only returns SSH_FXP_STATUS */ if (msg->packet_type == SSH_FXP_STATUS) { status = parse_status_msg(msg); sftp_message_free(msg); if (status == NULL) { return -1; } sftp_set_error(sftp, status->status); switch (status->status) { case SSH_FX_FAILURE: /* * mkdir always returns a failure, even if the path already exists. * To be POSIX conform and to be able to map it to EEXIST a stat * call is needed here. */ errno_attr = sftp_lstat(sftp, directory); if (errno_attr != NULL) { SAFE_FREE(errno_attr); sftp_set_error(sftp, SSH_FX_FILE_ALREADY_EXISTS); } break; case SSH_FX_OK: status_msg_free(status); return 0; break; default: break; } /* * The status should be SSH_FX_OK if the command was successful, if it * didn't, then there was an error */ ssh_set_error(sftp->session, SSH_REQUEST_DENIED, "SFTP server: %s", status->errormsg); status_msg_free(status); return -1; } else { ssh_set_error(sftp->session, SSH_FATAL, "Received message %d when attempting to make directory", msg->packet_type); sftp_message_free(msg); } return -1; }
null
216,202
59555850448704507002572255109645975811
89
sftp: Fix bug in sftp_mkdir not returning on error. resolves: #84 (cherry picked from commit a92c97b2e17715c1b3cdd693d14af6c3311d8e44)
other
server
9e2c26b0f6d91b3b6b0deaf9bc82f6e6ebf9a90b
1
int maria_create(const char *name, enum data_file_type datafile_type, uint keys,MARIA_KEYDEF *keydefs, uint columns, MARIA_COLUMNDEF *columndef, uint uniques, MARIA_UNIQUEDEF *uniquedefs, MARIA_CREATE_INFO *ci,uint flags) { register uint i,j; File UNINIT_VAR(dfile), UNINIT_VAR(file); int errpos,save_errno, create_mode= O_RDWR | O_TRUNC, res; myf create_flag; uint length,max_key_length,packed,pack_bytes,pointer,real_length_diff, key_length,info_length,key_segs,options,min_key_length, base_pos,long_varchar_count, unique_key_parts,fulltext_keys,offset, not_block_record_extra_length; uint max_field_lengths, extra_header_size, column_nr; uint internal_table= flags & HA_CREATE_INTERNAL_TABLE; ulong reclength, real_reclength,min_pack_length; char kfilename[FN_REFLEN], klinkname[FN_REFLEN], *klinkname_ptr= NullS; char dfilename[FN_REFLEN], dlinkname[FN_REFLEN], *dlinkname_ptr= 0; ulong pack_reclength; ulonglong tot_length,max_rows, tmp; enum en_fieldtype type; enum data_file_type org_datafile_type= datafile_type; MARIA_SHARE share; MARIA_KEYDEF *keydef,tmp_keydef; MARIA_UNIQUEDEF *uniquedef; HA_KEYSEG *keyseg,tmp_keyseg; MARIA_COLUMNDEF *column, *end_column; double *rec_per_key_part; ulong *nulls_per_key_part; uint16 *column_array; my_off_t key_root[HA_MAX_POSSIBLE_KEY], kfile_size_before_extension; MARIA_CREATE_INFO tmp_create_info; my_bool tmp_table= FALSE; /* cache for presence of HA_OPTION_TMP_TABLE */ my_bool forced_packed; myf sync_dir= 0; uchar *log_data= NULL; my_bool encrypted= maria_encrypt_tables && datafile_type == BLOCK_RECORD; my_bool insert_order= MY_TEST(flags & HA_PRESERVE_INSERT_ORDER); uint crypt_page_header_space= 0; DBUG_ENTER("maria_create"); DBUG_PRINT("enter", ("keys: %u columns: %u uniques: %u flags: %u", keys, columns, uniques, flags)); DBUG_ASSERT(maria_inited); if (!ci) { bzero((char*) &tmp_create_info,sizeof(tmp_create_info)); ci=&tmp_create_info; } if (keys + uniques > MARIA_MAX_KEY) { DBUG_RETURN(my_errno=HA_WRONG_CREATE_OPTION); } errpos=0; options=0; bzero((uchar*) &share,sizeof(share)); if (flags & HA_DONT_TOUCH_DATA) { /* We come here from recreate table */ org_datafile_type= ci->org_data_file_type; if (!(ci->old_options & HA_OPTION_TEMP_COMPRESS_RECORD)) options= (ci->old_options & (HA_OPTION_COMPRESS_RECORD | HA_OPTION_PACK_RECORD | HA_OPTION_READ_ONLY_DATA | HA_OPTION_CHECKSUM | HA_OPTION_TMP_TABLE | HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_LONG_BLOB_PTR | HA_OPTION_PAGE_CHECKSUM)); else { /* Uncompressing rows */ options= (ci->old_options & (HA_OPTION_CHECKSUM | HA_OPTION_TMP_TABLE | HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_LONG_BLOB_PTR | HA_OPTION_PAGE_CHECKSUM)); } } else { /* Transactional tables must be of type BLOCK_RECORD */ if (ci->transactional) datafile_type= BLOCK_RECORD; } if (!(rec_per_key_part= (double*) my_malloc((keys + uniques)*HA_MAX_KEY_SEG*sizeof(double) + (keys + uniques)*HA_MAX_KEY_SEG*sizeof(ulong) + sizeof(uint16) * columns, MYF(MY_WME | MY_ZEROFILL)))) DBUG_RETURN(my_errno); nulls_per_key_part= (ulong*) (rec_per_key_part + (keys + uniques) * HA_MAX_KEY_SEG); column_array= (uint16*) (nulls_per_key_part + (keys + uniques) * HA_MAX_KEY_SEG); /* Start by checking fields and field-types used */ long_varchar_count=packed= not_block_record_extra_length= pack_reclength= max_field_lengths= 0; reclength= min_pack_length= ci->null_bytes; forced_packed= 0; column_nr= 0; if (encrypted) { DBUG_ASSERT(datafile_type == BLOCK_RECORD); crypt_page_header_space= ma_crypt_get_data_page_header_space(); } for (column= columndef, end_column= column + columns ; column != end_column ; column++) { /* Fill in not used struct parts */ column->column_nr= column_nr++; column->offset= reclength; column->empty_pos= 0; column->empty_bit= 0; column->fill_length= column->length; if (column->null_bit) options|= HA_OPTION_NULL_FIELDS; reclength+= column->length; type= column->type; if (datafile_type == BLOCK_RECORD) { if (type == FIELD_SKIP_PRESPACE) type= column->type= FIELD_NORMAL; /* SKIP_PRESPACE not supported */ if (type == FIELD_NORMAL && column->length > FULL_PAGE_SIZE2(maria_block_size, crypt_page_header_space)) { /* FIELD_NORMAL can't be split over many blocks, convert to a CHAR */ type= column->type= FIELD_SKIP_ENDSPACE; } } if (type != FIELD_NORMAL && type != FIELD_CHECK) { column->empty_pos= packed/8; column->empty_bit= (1 << (packed & 7)); if (type == FIELD_BLOB) { forced_packed= 1; packed++; share.base.blobs++; if (pack_reclength != INT_MAX32) { if (column->length == 4+portable_sizeof_char_ptr) pack_reclength= INT_MAX32; else { /* Add max possible blob length */ pack_reclength+= (1 << ((column->length- portable_sizeof_char_ptr)*8)); } } max_field_lengths+= (column->length - portable_sizeof_char_ptr); } else if (type == FIELD_SKIP_PRESPACE || type == FIELD_SKIP_ENDSPACE) { forced_packed= 1; max_field_lengths+= column->length > 255 ? 2 : 1; not_block_record_extra_length++; packed++; } else if (type == FIELD_VARCHAR) { pack_reclength++; not_block_record_extra_length++; max_field_lengths++; if (datafile_type != DYNAMIC_RECORD) packed++; column->fill_length= 1; options|= HA_OPTION_NULL_FIELDS; /* Use ma_checksum() */ /* We must test for 257 as length includes pack-length */ if (MY_TEST(column->length >= 257)) { long_varchar_count++; max_field_lengths++; column->fill_length= 2; } } else if (type == FIELD_SKIP_ZERO) packed++; else { if (!column->null_bit) min_pack_length+= column->length; else { /* Only BLOCK_RECORD skips NULL fields for all field values */ not_block_record_extra_length+= column->length; } column->empty_pos= 0; column->empty_bit= 0; } } else /* FIELD_NORMAL */ { if (!column->null_bit) { min_pack_length+= column->length; share.base.fixed_not_null_fields++; share.base.fixed_not_null_fields_length+= column->length; } else not_block_record_extra_length+= column->length; } } if (datafile_type == STATIC_RECORD && forced_packed) { /* Can't use fixed length records, revert to block records */ datafile_type= BLOCK_RECORD; } if (datafile_type == NO_RECORD && uniques) { /* Can't do unique without data, revert to block records */ datafile_type= BLOCK_RECORD; } if (encrypted) { /* datafile_type is set (finally?) update encryption that is only supported for BLOCK_RECORD */ if (datafile_type != BLOCK_RECORD) { encrypted= FALSE; crypt_page_header_space= 0; } } if (datafile_type == DYNAMIC_RECORD) options|= HA_OPTION_PACK_RECORD; /* Must use packed records */ if (datafile_type == STATIC_RECORD || datafile_type == NO_RECORD) { /* We can't use checksum with static length rows */ flags&= ~HA_CREATE_CHECKSUM; options&= ~HA_OPTION_CHECKSUM; min_pack_length= reclength; packed= 0; } else if (datafile_type != BLOCK_RECORD) min_pack_length+= not_block_record_extra_length; else min_pack_length+= 5; /* Min row overhead */ if (flags & HA_CREATE_TMP_TABLE) { options|= HA_OPTION_TMP_TABLE; tmp_table= TRUE; create_mode|= O_NOFOLLOW | (internal_table ? 0 : O_EXCL); /* "CREATE TEMPORARY" tables are not crash-safe (dropped at restart) */ ci->transactional= FALSE; flags&= ~HA_CREATE_PAGE_CHECKSUM; } share.base.null_bytes= ci->null_bytes; share.base.original_null_bytes= ci->null_bytes; share.base.born_transactional= ci->transactional; share.base.max_field_lengths= max_field_lengths; share.base.field_offsets= 0; /* for future */ if (flags & HA_CREATE_CHECKSUM || (options & HA_OPTION_CHECKSUM)) { options|= HA_OPTION_CHECKSUM; min_pack_length++; pack_reclength++; } if (pack_reclength < INT_MAX32) pack_reclength+= max_field_lengths + long_varchar_count; else pack_reclength= INT_MAX32; if (flags & HA_CREATE_DELAY_KEY_WRITE) options|= HA_OPTION_DELAY_KEY_WRITE; if (flags & HA_CREATE_RELIES_ON_SQL_LAYER) options|= HA_OPTION_RELIES_ON_SQL_LAYER; if (flags & HA_CREATE_PAGE_CHECKSUM) options|= HA_OPTION_PAGE_CHECKSUM; pack_bytes= (packed + 7) / 8; if (pack_reclength != INT_MAX32) pack_reclength+= reclength+pack_bytes + MY_TEST(test_all_bits(options, HA_OPTION_CHECKSUM | HA_OPTION_PACK_RECORD)); min_pack_length+= pack_bytes; /* Calculate min possible row length for rows-in-block */ extra_header_size= MAX_FIXED_HEADER_SIZE; if (ci->transactional) { extra_header_size= TRANS_MAX_FIXED_HEADER_SIZE; DBUG_PRINT("info",("creating a transactional table")); } share.base.min_block_length= (extra_header_size + share.base.null_bytes + pack_bytes); if (!ci->data_file_length && ci->max_rows) { set_if_bigger(ci->max_rows, ci->reloc_rows); if (pack_reclength == INT_MAX32 || (~(ulonglong) 0)/ci->max_rows < (ulonglong) pack_reclength) ci->data_file_length= ~(ulonglong) 0; else { ci->data_file_length= _ma_safe_mul(ci->max_rows, pack_reclength); if (datafile_type == BLOCK_RECORD) { /* Assume that blocks are only half full (very pessimistic!) */ ci->data_file_length= _ma_safe_mul(ci->data_file_length, 2); set_if_bigger(ci->data_file_length, maria_block_size*2); } } } else if (!ci->max_rows) { if (datafile_type == BLOCK_RECORD) { uint rows_per_page= ((maria_block_size - PAGE_OVERHEAD_SIZE_RAW - crypt_page_header_space) / (min_pack_length + extra_header_size + DIR_ENTRY_SIZE)); ulonglong data_file_length= ci->data_file_length; if (!data_file_length) data_file_length= ((((ulonglong) 1 << ((BLOCK_RECORD_POINTER_SIZE-1) * 8))/2 -1) * maria_block_size); if (rows_per_page > 0) { set_if_smaller(rows_per_page, MAX_ROWS_PER_PAGE); ci->max_rows= (data_file_length / maria_block_size+1) * rows_per_page; } else ci->max_rows= data_file_length / (min_pack_length + extra_header_size + DIR_ENTRY_SIZE); } else ci->max_rows=(ha_rows) (ci->data_file_length/(min_pack_length + ((options & HA_OPTION_PACK_RECORD) ? 3 : 0))); set_if_smaller(ci->reloc_rows, ci->max_rows); } max_rows= (ulonglong) ci->max_rows; if (datafile_type == BLOCK_RECORD) { /* The + 1 is for record position withing page The * 2 is because we need one bit for knowing if there is transid's after the row pointer */ pointer= maria_get_pointer_length((ci->data_file_length / maria_block_size) * 2, 4) + 1; set_if_smaller(pointer, BLOCK_RECORD_POINTER_SIZE); if (!max_rows) max_rows= (((((ulonglong) 1 << ((pointer-1)*8)) -1) * maria_block_size) / min_pack_length / 2); } else { if (datafile_type == NO_RECORD) pointer= 0; else if (datafile_type != STATIC_RECORD) pointer= maria_get_pointer_length(ci->data_file_length, maria_data_pointer_size); else pointer= maria_get_pointer_length(ci->max_rows, maria_data_pointer_size); if (!max_rows) max_rows= ((((ulonglong) 1 << (pointer*8)) -1) / min_pack_length); } real_reclength=reclength; if (datafile_type == STATIC_RECORD) { if (reclength <= pointer) reclength=pointer+1; /* reserve place for delete link */ } else reclength+= long_varchar_count; /* We need space for varchar! */ max_key_length=0; tot_length=0 ; key_segs=0; fulltext_keys=0; share.state.rec_per_key_part= rec_per_key_part; share.state.nulls_per_key_part= nulls_per_key_part; share.state.key_root=key_root; share.state.key_del= HA_OFFSET_ERROR; if (uniques) max_key_length= MARIA_UNIQUE_HASH_LENGTH + pointer; for (i=0, keydef=keydefs ; i < keys ; i++ , keydef++) { share.state.key_root[i]= HA_OFFSET_ERROR; length= real_length_diff= 0; min_key_length= key_length= pointer; if (keydef->key_alg == HA_KEY_ALG_RTREE) keydef->flag|= HA_RTREE_INDEX; /* For easier tests */ if (keydef->flag & HA_SPATIAL) { #ifdef HAVE_SPATIAL /* BAR TODO to support 3D and more dimensions in the future */ uint sp_segs=SPDIMS*2; keydef->flag=HA_SPATIAL; if (flags & HA_DONT_TOUCH_DATA) { /* Called by maria_chk - i.e. table structure was taken from MYI file and SPATIAL key *does have* additional sp_segs keysegs. keydef->seg here points right at the GEOMETRY segment, so we only need to decrease keydef->keysegs. (see maria_recreate_table() in _ma_check.c) */ keydef->keysegs-=sp_segs-1; } for (j=0, keyseg=keydef->seg ; (int) j < keydef->keysegs ; j++, keyseg++) { if (keyseg->type != HA_KEYTYPE_BINARY && keyseg->type != HA_KEYTYPE_VARBINARY1 && keyseg->type != HA_KEYTYPE_VARBINARY2) { my_errno=HA_WRONG_CREATE_OPTION; goto err_no_lock; } } keydef->keysegs+=sp_segs; key_length+=SPLEN*sp_segs; length++; /* At least one length uchar */ min_key_length++; #else my_errno= HA_ERR_UNSUPPORTED; goto err_no_lock; #endif /*HAVE_SPATIAL*/ } else if (keydef->flag & HA_FULLTEXT) { keydef->flag=HA_FULLTEXT | HA_PACK_KEY | HA_VAR_LENGTH_KEY; options|=HA_OPTION_PACK_KEYS; /* Using packed keys */ for (j=0, keyseg=keydef->seg ; (int) j < keydef->keysegs ; j++, keyseg++) { if (keyseg->type != HA_KEYTYPE_TEXT && keyseg->type != HA_KEYTYPE_VARTEXT1 && keyseg->type != HA_KEYTYPE_VARTEXT2) { my_errno=HA_WRONG_CREATE_OPTION; goto err_no_lock; } if (!(keyseg->flag & HA_BLOB_PART) && (keyseg->type == HA_KEYTYPE_VARTEXT1 || keyseg->type == HA_KEYTYPE_VARTEXT2)) { /* Make a flag that this is a VARCHAR */ keyseg->flag|= HA_VAR_LENGTH_PART; /* Store in bit_start number of bytes used to pack the length */ keyseg->bit_start= ((keyseg->type == HA_KEYTYPE_VARTEXT1)? 1 : 2); } } fulltext_keys++; key_length+= HA_FT_MAXBYTELEN+HA_FT_WLEN; length++; /* At least one length uchar */ min_key_length+= 1 + HA_FT_WLEN; real_length_diff=HA_FT_MAXBYTELEN-FT_MAX_WORD_LEN_FOR_SORT; } else { /* Test if prefix compression */ if (keydef->flag & HA_PACK_KEY) { /* Can't use space_compression on number keys */ if ((keydef->seg[0].flag & HA_SPACE_PACK) && keydef->seg[0].type == (int) HA_KEYTYPE_NUM) keydef->seg[0].flag&= ~HA_SPACE_PACK; /* Only use HA_PACK_KEY when first segment is a variable length key */ if (!(keydef->seg[0].flag & (HA_SPACE_PACK | HA_BLOB_PART | HA_VAR_LENGTH_PART))) { /* pack relative to previous key */ keydef->flag&= ~HA_PACK_KEY; keydef->flag|= HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; } else { keydef->seg[0].flag|=HA_PACK_KEY; /* for easyer intern test */ keydef->flag|=HA_VAR_LENGTH_KEY; options|=HA_OPTION_PACK_KEYS; /* Using packed keys */ } } if (keydef->flag & HA_BINARY_PACK_KEY) options|=HA_OPTION_PACK_KEYS; /* Using packed keys */ if (keydef->flag & HA_AUTO_KEY && ci->with_auto_increment) share.base.auto_key=i+1; for (j=0, keyseg=keydef->seg ; j < keydef->keysegs ; j++, keyseg++) { /* numbers are stored with high by first to make compression easier */ switch (keyseg->type) { case HA_KEYTYPE_SHORT_INT: case HA_KEYTYPE_LONG_INT: case HA_KEYTYPE_FLOAT: case HA_KEYTYPE_DOUBLE: case HA_KEYTYPE_USHORT_INT: case HA_KEYTYPE_ULONG_INT: case HA_KEYTYPE_LONGLONG: case HA_KEYTYPE_ULONGLONG: case HA_KEYTYPE_INT24: case HA_KEYTYPE_UINT24: case HA_KEYTYPE_INT8: keyseg->flag|= HA_SWAP_KEY; break; case HA_KEYTYPE_VARTEXT1: case HA_KEYTYPE_VARTEXT2: case HA_KEYTYPE_VARBINARY1: case HA_KEYTYPE_VARBINARY2: if (!(keyseg->flag & HA_BLOB_PART)) { /* Make a flag that this is a VARCHAR */ keyseg->flag|= HA_VAR_LENGTH_PART; /* Store in bit_start number of bytes used to pack the length */ keyseg->bit_start= ((keyseg->type == HA_KEYTYPE_VARTEXT1 || keyseg->type == HA_KEYTYPE_VARBINARY1) ? 1 : 2); } break; default: break; } if (keyseg->flag & HA_SPACE_PACK) { DBUG_ASSERT(!(keyseg->flag & (HA_VAR_LENGTH_PART | HA_BLOB_PART))); keydef->flag |= HA_SPACE_PACK_USED | HA_VAR_LENGTH_KEY; options|=HA_OPTION_PACK_KEYS; /* Using packed keys */ length++; /* At least one length uchar */ if (!keyseg->null_bit) min_key_length++; key_length+= keyseg->length; if (keyseg->length >= 255) { /* prefix may be 3 bytes */ length+= 2; } } else if (keyseg->flag & (HA_VAR_LENGTH_PART | HA_BLOB_PART)) { DBUG_ASSERT(!test_all_bits(keyseg->flag, (HA_VAR_LENGTH_PART | HA_BLOB_PART))); keydef->flag|=HA_VAR_LENGTH_KEY; length++; /* At least one length uchar */ if (!keyseg->null_bit) min_key_length++; options|=HA_OPTION_PACK_KEYS; /* Using packed keys */ key_length+= keyseg->length; if (keyseg->length >= 255) { /* prefix may be 3 bytes */ length+= 2; } } else { key_length+= keyseg->length; if (!keyseg->null_bit) min_key_length+= keyseg->length; } if (keyseg->null_bit) { key_length++; /* min key part is 1 byte */ min_key_length++; options|=HA_OPTION_PACK_KEYS; keyseg->flag|=HA_NULL_PART; keydef->flag|=HA_VAR_LENGTH_KEY | HA_NULL_PART_KEY; } } } /* if HA_FULLTEXT */ key_segs+=keydef->keysegs; if (keydef->keysegs > HA_MAX_KEY_SEG) { my_errno=HA_WRONG_CREATE_OPTION; goto err_no_lock; } /* key_segs may be 0 in the case when we only want to be able to add on row into the table. This can happen with some DISTINCT queries in MySQL */ if ((keydef->flag & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME && key_segs) share.state.rec_per_key_part[key_segs-1]=1L; length+=key_length; /* A key can't be longer than than half a index block (as we have to be able to put at least 2 keys on an index block for the key algorithms to work). */ if (length > _ma_max_key_length()) { my_errno=HA_WRONG_CREATE_OPTION; goto err_no_lock; } keydef->block_length= (uint16) maria_block_size; keydef->keylength= (uint16) key_length; keydef->minlength= (uint16) min_key_length; keydef->maxlength= (uint16) length; if (length > max_key_length) max_key_length= length; tot_length= update_tot_length(tot_length, max_rows, length); } unique_key_parts=0; for (i=0, uniquedef=uniquedefs ; i < uniques ; i++ , uniquedef++) { uniquedef->key=keys+i; unique_key_parts+=uniquedef->keysegs; share.state.key_root[keys+i]= HA_OFFSET_ERROR; tot_length= update_tot_length(tot_length, max_rows, MARIA_UNIQUE_HASH_LENGTH + pointer); } keys+=uniques; /* Each unique has 1 key */ key_segs+=uniques; /* Each unique has 1 key seg */ base_pos=(MARIA_STATE_INFO_SIZE + keys * MARIA_STATE_KEY_SIZE + key_segs * MARIA_STATE_KEYSEG_SIZE); info_length= base_pos+(uint) (MARIA_BASE_INFO_SIZE+ keys * MARIA_KEYDEF_SIZE+ uniques * MARIA_UNIQUEDEF_SIZE + (key_segs + unique_key_parts)*HA_KEYSEG_SIZE+ columns*(MARIA_COLUMNDEF_SIZE + 2)); if (encrypted) { share.base.extra_options|= MA_EXTRA_OPTIONS_ENCRYPTED; /* store crypt data in info */ info_length+= ma_crypt_get_file_length(); } if (insert_order) { share.base.extra_options|= MA_EXTRA_OPTIONS_INSERT_ORDER; } DBUG_PRINT("info", ("info_length: %u", info_length)); /* There are only 16 bits for the total header length. */ if (info_length > 65535) { my_printf_error(HA_WRONG_CREATE_OPTION, "Aria table '%s' has too many columns and/or " "indexes and/or unique constraints.", MYF(0), name + dirname_length(name)); my_errno= HA_WRONG_CREATE_OPTION; goto err_no_lock; } bmove(share.state.header.file_version, maria_file_magic, 4); ci->old_options=options | (ci->old_options & HA_OPTION_TEMP_COMPRESS_RECORD ? HA_OPTION_COMPRESS_RECORD | HA_OPTION_TEMP_COMPRESS_RECORD: 0); mi_int2store(share.state.header.options,ci->old_options); mi_int2store(share.state.header.header_length,info_length); mi_int2store(share.state.header.state_info_length,MARIA_STATE_INFO_SIZE); mi_int2store(share.state.header.base_info_length,MARIA_BASE_INFO_SIZE); mi_int2store(share.state.header.base_pos,base_pos); share.state.header.data_file_type= share.data_file_type= datafile_type; share.state.header.org_data_file_type= org_datafile_type; share.state.header.not_used= 0; share.state.dellink = HA_OFFSET_ERROR; share.state.first_bitmap_with_space= 0; #ifdef MARIA_EXTERNAL_LOCKING share.state.process= (ulong) getpid(); #endif share.state.version= (ulong) time((time_t*) 0); share.state.sortkey= (ushort) ~0; share.state.auto_increment=ci->auto_increment; share.options=options; share.base.rec_reflength=pointer; share.base.block_size= maria_block_size; share.base.language= (ci->language ? ci->language : default_charset_info->number); /* Get estimate for index file length (this may be wrong for FT keys) This is used for pointers to other key pages. */ tmp= (tot_length / maria_block_size + keys * MARIA_INDEX_BLOCK_MARGIN); /* use maximum of key_file_length we calculated and key_file_length value we got from MAI file header (see also mariapack.c:save_state) */ share.base.key_reflength= maria_get_pointer_length(MY_MAX(ci->key_file_length,tmp),3); share.base.keys= share.state.header.keys= keys; share.state.header.uniques= uniques; share.state.header.fulltext_keys= fulltext_keys; mi_int2store(share.state.header.key_parts,key_segs); mi_int2store(share.state.header.unique_key_parts,unique_key_parts); maria_set_all_keys_active(share.state.key_map, keys); share.base.keystart = share.state.state.key_file_length= MY_ALIGN(info_length, maria_block_size); share.base.max_key_block_length= maria_block_size; share.base.max_key_length=ALIGN_SIZE(max_key_length+4); share.base.records=ci->max_rows; share.base.reloc= ci->reloc_rows; share.base.reclength=real_reclength; share.base.pack_reclength= reclength + MY_TEST(options & HA_OPTION_CHECKSUM); share.base.max_pack_length=pack_reclength; share.base.min_pack_length=min_pack_length; share.base.pack_bytes= pack_bytes; share.base.fields= columns; share.base.pack_fields= packed; if (share.data_file_type == BLOCK_RECORD) { /* we are going to create a first bitmap page, set data_file_length to reflect this, before the state goes to disk */ share.state.state.data_file_length= maria_block_size; /* Add length of packed fields + length */ share.base.pack_reclength+= share.base.max_field_lengths+3; share.base.max_pack_length= share.base.pack_reclength; /* Adjust max_pack_length, to be used if we have short rows */ if (share.base.max_pack_length < maria_block_size) { share.base.max_pack_length+= FLAG_SIZE; if (ci->transactional) share.base.max_pack_length+= TRANSID_SIZE * 2; } } /* max_data_file_length and max_key_file_length are recalculated on open */ if (tmp_table) share.base.max_data_file_length= (my_off_t) ci->data_file_length; else if (ci->transactional && translog_status == TRANSLOG_OK && !maria_in_recovery) { /* we have checked translog_inited above, because maria_chk may call us (via maria_recreate_table()) and it does not have a log. */ sync_dir= MY_SYNC_DIR; /* If crash between _ma_state_info_write_sub() and _ma_update_state__lsns_sub(), table should be ignored by Recovery (or old REDOs would fail), so we cannot let LSNs be 0: */ share.state.skip_redo_lsn= share.state.is_of_horizon= share.state.create_rename_lsn= LSN_MAX; } if (datafile_type == DYNAMIC_RECORD) { share.base.min_block_length= (share.base.pack_reclength+3 < MARIA_EXTEND_BLOCK_LENGTH && ! share.base.blobs) ? MY_MAX(share.base.pack_reclength,MARIA_MIN_BLOCK_LENGTH) : MARIA_EXTEND_BLOCK_LENGTH; } else if (datafile_type == STATIC_RECORD) share.base.min_block_length= share.base.pack_reclength; if (! (flags & HA_DONT_TOUCH_DATA)) share.state.create_time= time((time_t*) 0); if (!internal_table) mysql_mutex_lock(&THR_LOCK_maria); /* NOTE: For test_if_reopen() we need a real path name. Hence we need MY_RETURN_REAL_PATH for every fn_format(filename, ...). */ if (ci->index_file_name) { char *iext= strrchr(ci->index_file_name, '.'); int have_iext= iext && !strcmp(iext, MARIA_NAME_IEXT); if (tmp_table) { char *path; /* chop off the table name, tempory tables use generated name */ if ((path= strrchr(ci->index_file_name, FN_LIBCHAR))) *path= '\0'; fn_format(kfilename, name, ci->index_file_name, MARIA_NAME_IEXT, MY_REPLACE_DIR | MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH | MY_APPEND_EXT); } else { fn_format(kfilename, ci->index_file_name, "", MARIA_NAME_IEXT, MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH | (have_iext ? MY_REPLACE_EXT : MY_APPEND_EXT)); } fn_format(klinkname, name, "", MARIA_NAME_IEXT, MY_UNPACK_FILENAME|MY_APPEND_EXT); klinkname_ptr= klinkname; /* Don't create the table if the link or file exists to ensure that one doesn't accidently destroy another table. Don't sync dir now if the data file has the same path. */ create_flag= (ci->data_file_name && !strcmp(ci->index_file_name, ci->data_file_name)) ? 0 : sync_dir; } else { char *iext= strrchr(name, '.'); int have_iext= iext && !strcmp(iext, MARIA_NAME_IEXT); fn_format(kfilename, name, "", MARIA_NAME_IEXT, MY_UNPACK_FILENAME | (internal_table ? 0 : MY_RETURN_REAL_PATH) | (have_iext ? MY_REPLACE_EXT : MY_APPEND_EXT)); /* Replace the current file. Don't sync dir now if the data file has the same path. */ create_flag= (flags & HA_CREATE_KEEP_FILES) ? 0 : MY_DELETE_OLD; create_flag|= (!ci->data_file_name ? 0 : sync_dir); } /* If a MRG_MARIA table is in use, the mapped MARIA tables are open, but no entry is made in the table cache for them. A TRUNCATE command checks for the table in the cache only and could be fooled to believe, the table is not open. Pull the emergency brake in this situation. (Bug #8306) NOTE: The filename is compared against unique_file_name of every open table. Hence we need a real path here. */ if (!internal_table && _ma_test_if_reopen(kfilename)) { my_printf_error(HA_ERR_TABLE_EXIST, "Aria table '%s' is in use " "(most likely by a MERGE table). Try FLUSH TABLES.", MYF(0), name + dirname_length(name)); my_errno= HA_ERR_TABLE_EXIST; goto err; } if ((file= mysql_file_create_with_symlink(key_file_kfile, klinkname_ptr, kfilename, 0, create_mode, MYF(MY_WME|create_flag))) < 0) goto err; errpos=1; DBUG_PRINT("info", ("write state info and base info")); if (_ma_state_info_write_sub(file, &share.state, MA_STATE_INFO_WRITE_FULL_INFO) || _ma_base_info_write(file, &share.base)) goto err; DBUG_PRINT("info", ("base_pos: %d base_info_size: %d", base_pos, MARIA_BASE_INFO_SIZE)); DBUG_ASSERT(mysql_file_tell(file,MYF(0)) == base_pos+ MARIA_BASE_INFO_SIZE); /* Write key and keyseg definitions */ DBUG_PRINT("info", ("write key and keyseg definitions")); for (i=0 ; i < share.base.keys - uniques; i++) { uint sp_segs=(keydefs[i].flag & HA_SPATIAL) ? 2*SPDIMS : 0; if (_ma_keydef_write(file, &keydefs[i])) goto err; for (j=0 ; j < keydefs[i].keysegs-sp_segs ; j++) if (_ma_keyseg_write(file, &keydefs[i].seg[j])) goto err; #ifdef HAVE_SPATIAL for (j=0 ; j < sp_segs ; j++) { HA_KEYSEG sseg; sseg.type=SPTYPE; sseg.language= 7; /* Binary */ sseg.null_bit=0; sseg.bit_start=0; sseg.bit_length= 0; sseg.bit_pos= 0; sseg.length=SPLEN; sseg.null_pos=0; sseg.start=j*SPLEN; sseg.flag= HA_SWAP_KEY; if (_ma_keyseg_write(file, &sseg)) goto err; } #endif } /* Create extra keys for unique definitions */ offset= real_reclength - uniques*MARIA_UNIQUE_HASH_LENGTH; bzero((char*) &tmp_keydef,sizeof(tmp_keydef)); bzero((char*) &tmp_keyseg,sizeof(tmp_keyseg)); for (i=0; i < uniques ; i++) { tmp_keydef.keysegs=1; tmp_keydef.flag= HA_UNIQUE_CHECK; tmp_keydef.block_length= (uint16) maria_block_size; tmp_keydef.keylength= MARIA_UNIQUE_HASH_LENGTH + pointer; tmp_keydef.minlength=tmp_keydef.maxlength=tmp_keydef.keylength; tmp_keyseg.type= MARIA_UNIQUE_HASH_TYPE; tmp_keyseg.length= MARIA_UNIQUE_HASH_LENGTH; tmp_keyseg.start= offset; offset+= MARIA_UNIQUE_HASH_LENGTH; if (_ma_keydef_write(file,&tmp_keydef) || _ma_keyseg_write(file,(&tmp_keyseg))) goto err; } /* Save unique definition */ DBUG_PRINT("info", ("write unique definitions")); for (i=0 ; i < share.state.header.uniques ; i++) { HA_KEYSEG *keyseg_end; keyseg= uniquedefs[i].seg; if (_ma_uniquedef_write(file, &uniquedefs[i])) goto err; for (keyseg= uniquedefs[i].seg, keyseg_end= keyseg+ uniquedefs[i].keysegs; keyseg < keyseg_end; keyseg++) { switch (keyseg->type) { case HA_KEYTYPE_VARTEXT1: case HA_KEYTYPE_VARTEXT2: case HA_KEYTYPE_VARBINARY1: case HA_KEYTYPE_VARBINARY2: if (!(keyseg->flag & HA_BLOB_PART)) { keyseg->flag|= HA_VAR_LENGTH_PART; keyseg->bit_start= ((keyseg->type == HA_KEYTYPE_VARTEXT1 || keyseg->type == HA_KEYTYPE_VARBINARY1) ? 1 : 2); } break; default: DBUG_ASSERT((keyseg->flag & HA_VAR_LENGTH_PART) == 0); break; } if (_ma_keyseg_write(file, keyseg)) goto err; } } DBUG_PRINT("info", ("write field definitions")); if (datafile_type == BLOCK_RECORD) { /* Store columns in a more efficent order */ MARIA_COLUMNDEF **col_order, **pos; if (!(col_order= (MARIA_COLUMNDEF**) my_malloc(share.base.fields * sizeof(MARIA_COLUMNDEF*), MYF(MY_WME)))) goto err; for (column= columndef, pos= col_order ; column != end_column ; column++, pos++) *pos= column; qsort(col_order, share.base.fields, sizeof(*col_order), (qsort_cmp) compare_columns); for (i=0 ; i < share.base.fields ; i++) { column_array[col_order[i]->column_nr]= i; if (_ma_columndef_write(file, col_order[i])) { my_free(col_order); goto err; } } my_free(col_order); } else { for (i=0 ; i < share.base.fields ; i++) { column_array[i]= (uint16) i; if (_ma_columndef_write(file, &columndef[i])) goto err; } } if (_ma_column_nr_write(file, column_array, columns)) goto err; if (encrypted) { if (ma_crypt_create(&share) || ma_crypt_write(&share, file)) goto err; } if ((kfile_size_before_extension= mysql_file_tell(file,MYF(0))) == MY_FILEPOS_ERROR) goto err; #ifndef DBUG_OFF if (kfile_size_before_extension != info_length) DBUG_PRINT("warning",("info_length: %u != used_length: %u", info_length, (uint)kfile_size_before_extension)); #endif if (sync_dir) { /* we log the first bytes and then the size to which we extend; this is not log 1 KB of mostly zeroes if this is a small table. */ char empty_string[]= ""; LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 4]; translog_size_t total_rec_length= 0; uint k; LSN lsn; log_array[TRANSLOG_INTERNAL_PARTS + 1].length= 1 + 2 + 2 + (uint) kfile_size_before_extension; /* we are needing maybe 64 kB, so don't use the stack */ log_data= my_malloc(log_array[TRANSLOG_INTERNAL_PARTS + 1].length, MYF(0)); if ((log_data == NULL) || mysql_file_pread(file, 1 + 2 + 2 + log_data, (size_t) kfile_size_before_extension, 0, MYF(MY_NABP))) goto err; /* remember if the data file was created or not, to know if Recovery can do it or not, in the future */ log_data[0]= MY_TEST(flags & HA_DONT_TOUCH_DATA); int2store(log_data + 1, kfile_size_before_extension); int2store(log_data + 1 + 2, share.base.keystart); log_array[TRANSLOG_INTERNAL_PARTS + 0].str= (uchar *)name; /* we store the end-zero, for Recovery to just pass it to my_create() */ log_array[TRANSLOG_INTERNAL_PARTS + 0].length= strlen(name) + 1; log_array[TRANSLOG_INTERNAL_PARTS + 1].str= log_data; /* symlink description is also needed for re-creation by Recovery: */ { const char *s= ci->data_file_name ? ci->data_file_name : empty_string; log_array[TRANSLOG_INTERNAL_PARTS + 2].str= (uchar*)s; log_array[TRANSLOG_INTERNAL_PARTS + 2].length= strlen(s) + 1; s= ci->index_file_name ? ci->index_file_name : empty_string; log_array[TRANSLOG_INTERNAL_PARTS + 3].str= (uchar*)s; log_array[TRANSLOG_INTERNAL_PARTS + 3].length= strlen(s) + 1; } for (k= TRANSLOG_INTERNAL_PARTS; k < (sizeof(log_array)/sizeof(log_array[0])); k++) total_rec_length+= (translog_size_t) log_array[k].length; /** For this record to be of any use for Recovery, we need the upper MySQL layer to be crash-safe, which it is not now (that would require work using the ddl_log of sql/sql_table.cc); when it is, we should reconsider the moment of writing this log record (before or after op, under THR_LOCK_maria or not...), how to use it in Recovery. For now this record can serve when we apply logs to a backup, so we sync it. This happens before the data file is created. If the data file was created before, and we crashed before writing the log record, at restart the table may be used, so we would not have a trustable history in the log (impossible to apply this log to a backup). The way we do it, if we crash before writing the log record then there is no data file and the table cannot be used. @todo Note that in case of TRUNCATE TABLE we also come here; for Recovery to be able to finish TRUNCATE TABLE, instead of leaving a half-truncated table, we should log the record at start of maria_create(); for that we shouldn't write to the index file but to a buffer (DYNAMIC_STRING), put the buffer into the record, then put the buffer into the index file (so, change _ma_keydef_write() etc). That would also enable Recovery to finish a CREATE TABLE. The final result would be that we would be able to finish what the SQL layer has asked for: it would be atomic. When in CREATE/TRUNCATE (or DROP or RENAME or REPAIR) we have not called external_lock(), so have no TRN. It does not matter, as all these operations are non-transactional and sync their files. */ if (unlikely(translog_write_record(&lsn, LOGREC_REDO_CREATE_TABLE, &dummy_transaction_object, NULL, total_rec_length, sizeof(log_array)/sizeof(log_array[0]), log_array, NULL, NULL) || translog_flush(lsn))) goto err; share.kfile.file= file; DBUG_EXECUTE_IF("maria_flush_whole_log", { DBUG_PRINT("maria_flush_whole_log", ("now")); translog_flush(translog_get_horizon()); }); DBUG_EXECUTE_IF("maria_crash_create_table", { DBUG_PRINT("maria_crash_create_table", ("now")); DBUG_ABORT(); }); /* store LSN into file, needed for Recovery to not be confused if a DROP+CREATE happened (applying REDOs to the wrong table). */ if (_ma_update_state_lsns_sub(&share, lsn, trnman_get_min_safe_trid(), FALSE, TRUE)) goto err; my_free(log_data); } if (!(flags & HA_DONT_TOUCH_DATA)) { if (ci->data_file_name) { char *dext= strrchr(ci->data_file_name, '.'); int have_dext= dext && !strcmp(dext, MARIA_NAME_DEXT); if (tmp_table) { char *path; /* chop off the table name, tempory tables use generated name */ if ((path= strrchr(ci->data_file_name, FN_LIBCHAR))) *path= '\0'; fn_format(dfilename, name, ci->data_file_name, MARIA_NAME_DEXT, MY_REPLACE_DIR | MY_UNPACK_FILENAME | MY_APPEND_EXT); } else { fn_format(dfilename, ci->data_file_name, "", MARIA_NAME_DEXT, MY_UNPACK_FILENAME | (have_dext ? MY_REPLACE_EXT : MY_APPEND_EXT)); } fn_format(dlinkname, name, "",MARIA_NAME_DEXT, MY_UNPACK_FILENAME | MY_APPEND_EXT); dlinkname_ptr= dlinkname; create_flag=0; } else { fn_format(dfilename,name,"", MARIA_NAME_DEXT, MY_UNPACK_FILENAME | MY_APPEND_EXT); create_flag= (flags & HA_CREATE_KEEP_FILES) ? 0 : MY_DELETE_OLD; } if ((dfile= mysql_file_create_with_symlink(key_file_dfile, dlinkname_ptr, dfilename, 0, create_mode, MYF(MY_WME | create_flag | sync_dir))) < 0) goto err; errpos=3; if (_ma_initialize_data_file(&share, dfile)) goto err; } /* Enlarge files */ DBUG_PRINT("info", ("enlarge to keystart: %lu", (ulong) share.base.keystart)); if (mysql_file_chsize(file,(ulong) share.base.keystart,0,MYF(0))) goto err; if (!internal_table && sync_dir && mysql_file_sync(file, MYF(0))) goto err; if (! (flags & HA_DONT_TOUCH_DATA)) { #ifdef USE_RELOC if (mysql_file_chsize(key_file_dfile, dfile, share.base.min_pack_length*ci->reloc_rows,0,MYF(0))) goto err; #endif if (!internal_table && sync_dir && mysql_file_sync(dfile, MYF(0))) goto err; if (mysql_file_close(dfile,MYF(0))) goto err; } if (!internal_table) mysql_mutex_unlock(&THR_LOCK_maria); res= 0; my_free((char*) rec_per_key_part); ma_crypt_free(&share); errpos=0; if (mysql_file_close(file,MYF(0))) res= my_errno; DBUG_RETURN(res); err: if (!internal_table) mysql_mutex_unlock(&THR_LOCK_maria); err_no_lock: save_errno=my_errno; switch (errpos) { case 3: mysql_file_close(dfile, MYF(0)); if (! (flags & HA_DONT_TOUCH_DATA)) { mysql_file_delete(key_file_dfile, dfilename, MYF(sync_dir)); if (dlinkname_ptr) mysql_file_delete(key_file_dfile, dlinkname_ptr, MYF(sync_dir)); } /* fall through */ case 1: mysql_file_close(file, MYF(0)); if (! (flags & HA_DONT_TOUCH_DATA)) { mysql_file_delete(key_file_kfile, kfilename, MYF(sync_dir)); if (klinkname_ptr) mysql_file_delete(key_file_kfile, klinkname_ptr, MYF(sync_dir)); } } ma_crypt_free(&share); my_free(log_data); my_free(rec_per_key_part); DBUG_RETURN(my_errno=save_errno); /* return the fatal errno */ }
null
216,901
108363512210404851146521651556770149401
1,212
MDEV-26351 segfault - (MARIA_HA *) 0x0 in ha_maria::extra don't let Aria create a table that it cannot open
other