target
int64
func
string
cwe_id_cleaned
string
label
int64
0
static void red_channel_client_set_migration_seamless(RedChannelClient *rcc) { spice_assert(rcc->client->during_target_migrate && rcc->client->seamless_migrate); if (rcc->channel->migration_flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) { rcc->wait_migrate_data = TRUE; rcc->client->num_migrated_channels++; } spice_debug("channel type %d id %d rcc %p wait data %d", rcc->channel->type, rcc->channel->id, rcc, rcc->wait_migrate_data); }
none
24
0
static int ciedefgrange(i_ctx_t * i_ctx_p, ref *space, float *ptr) { int code; ref CIEdict, *tempref; code = array_get(imemory, space, 1, &CIEdict); if (code < 0) return code; /* If we have a RangeDEFG, get the values from that */ code = dict_find_string(&CIEdict, "RangeDEFG", &tempref); if (code > 0 && !r_has_type(tempref, t_null)) { code = get_cie_param_array(imemory, tempref, 8, ptr); if (code < 0) return code; } else { /* Default values for a CIEBasedDEFG */ memcpy(ptr, default_0_1, 8*sizeof(float)); } return 0; }
none
24
1
int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index) { struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table; int i, err = 0; int free = -1; mutex_lock(&table->mutex); for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) { if (free < 0 && (table->refs[i] == 0)) { free = i; continue; } if (table->refs[i] && (vlan == (MLX4_VLAN_MASK & be32_to_cpu(table->entries[i])))) { /* Vlan already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (table->total == table->max) { /* No free vlan entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID); err = mlx4_set_port_vlan_table(dev, port, table->entries); if (unlikely(err)) { mlx4_warn(dev, "Failed adding vlan: %u\n", vlan); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; }
CWE-119
0
0
pch_says_nonexistent (bool which) { return p_says_nonexistent[which]; }
none
24
1
ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; }
CWE-119
0
0
static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *alg1, X509_ALGOR *alg2, ASN1_BIT_STRING *sig) { int pad_mode; EVP_PKEY_CTX *pkctx = ctx->pctx; if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; if (pad_mode == RSA_PKCS1_PADDING) return 2; if (pad_mode == RSA_PKCS1_PSS_PADDING) { const EVP_MD *sigmd, *mgf1md; RSA_PSS_PARAMS *pss = NULL; X509_ALGOR *mgf1alg = NULL; ASN1_STRING *os1 = NULL, *os2 = NULL; EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx); int saltlen, rv = 0; sigmd = EVP_MD_CTX_md(ctx); if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) goto err; if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen)) goto err; if (saltlen == -1) saltlen = EVP_MD_size(sigmd); else if (saltlen == -2) { saltlen = EVP_PKEY_size(pk) - EVP_MD_size(sigmd) - 2; if (((EVP_PKEY_bits(pk) - 1) & 0x7) == 0) saltlen--; } pss = RSA_PSS_PARAMS_new(); if (!pss) goto err; if (saltlen != 20) { pss->saltLength = ASN1_INTEGER_new(); if (!pss->saltLength) goto err; if (!ASN1_INTEGER_set(pss->saltLength, saltlen)) goto err; } if (EVP_MD_type(sigmd) != NID_sha1) { pss->hashAlgorithm = X509_ALGOR_new(); if (!pss->hashAlgorithm) goto err; X509_ALGOR_set_md(pss->hashAlgorithm, sigmd); } if (EVP_MD_type(mgf1md) != NID_sha1) { ASN1_STRING *stmp = NULL; /* need to embed algorithm ID inside another */ mgf1alg = X509_ALGOR_new(); X509_ALGOR_set_md(mgf1alg, mgf1md); if (!ASN1_item_pack(mgf1alg, ASN1_ITEM_rptr(X509_ALGOR), &stmp)) goto err; pss->maskGenAlgorithm = X509_ALGOR_new(); if (!pss->maskGenAlgorithm) goto err; X509_ALGOR_set0(pss->maskGenAlgorithm, OBJ_nid2obj(NID_mgf1), V_ASN1_SEQUENCE, stmp); } /* Finally create string with pss parameter encoding. */ if (!ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), &os1)) goto err; if (alg2) { os2 = ASN1_STRING_dup(os1); if (!os2) goto err; X509_ALGOR_set0(alg2, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os2); } X509_ALGOR_set0(alg1, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os1); os1 = os2 = NULL; rv = 3; err: if (mgf1alg) X509_ALGOR_free(mgf1alg); if (pss) RSA_PSS_PARAMS_free(pss); if (os1) ASN1_STRING_free(os1); return rv; } return 2; }
none
24
0
static int patterncomponent(i_ctx_t * i_ctx_p, ref *space, int *n) { os_ptr op = osp; int n_comps, code; const gs_color_space * pcs = gs_currentcolorspace(igs); gs_client_color cc; /* check for a pattern color space */ if ((n_comps = cs_num_components(pcs)) < 0) { n_comps = -n_comps; if (r_has_type(op, t_dictionary)) { ref *pImpl, pPatInst; code = dict_find_string(op, "Implementation", &pImpl); if (code > 0) { code = array_get(imemory, pImpl, 0, &pPatInst); if (code < 0) return code; cc.pattern = r_ptr(&pPatInst, gs_pattern_instance_t); if (pattern_instance_uses_base_space(cc.pattern)) *n = n_comps; else *n = 1; } else *n = 1; } else *n = 1; } else return_error(gs_error_typecheck); return 0; }
none
24
0
static char *addr_to_string(const char *format, struct sockaddr_storage *sa, socklen_t salen) { char *addr; char host[NI_MAXHOST]; char serv[NI_MAXSERV]; int err; size_t addrlen; if ((err = getnameinfo((struct sockaddr *)sa, salen, host, sizeof(host), serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV)) != 0) { spice_warning("Cannot resolve address %d: %s", err, gai_strerror(err)); return NULL; } /* Enough for the existing format + the 2 vars we're * substituting in. */ addrlen = strlen(format) + strlen(host) + strlen(serv); addr = spice_malloc(addrlen + 1); snprintf(addr, addrlen, format, host, serv); addr[addrlen] = '\0'; return addr; }
none
24
1
static int raw_getname(struct socket *sock, struct sockaddr *uaddr, int *len, int peer) { struct sockaddr_can *addr = (struct sockaddr_can *)uaddr; struct sock *sk = sock->sk; struct raw_sock *ro = raw_sk(sk); if (peer) return -EOPNOTSUPP; addr->can_family = AF_CAN; addr->can_ifindex = ro->ifindex; *len = sizeof(*addr); return 0; }
CWE-200
4
1
static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt = (struct rt6_info *)dst; if (!dst) goto out; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) { dst_release(dst); dst = NULL; } out: return dst; }
CWE-20
3
0
static int cieabccompareproc(i_ctx_t *i_ctx_p, ref *space, ref *testspace) { int code = 0; ref CIEdict1, CIEdict2; code = array_get(imemory, space, 1, &CIEdict1); if (code < 0) return 0; code = array_get(imemory, testspace, 1, &CIEdict2); if (code < 0) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"WhitePoint")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"BlackPoint")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"RangeABC")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"DecodeABC")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"MatrixABC")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"RangeLMN")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"DecodeLMN")) return 0; if (!comparedictkey(i_ctx_p, &CIEdict1, &CIEdict2, (char *)"MatrixMN")) return 0; return 1; }
none
24
1
static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int bandno; int rlvlno; jpc_dec_band_t *band; jpc_dec_rlvl_t *rlvl; int prcno; jpc_dec_prc_t *prc; jpc_dec_seg_t *seg; jpc_dec_cblk_t *cblk; int cblkno; if (tile->tcomps) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (band->prcs) { for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { if (!prc->cblks) { continue; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { while (cblk->segs.head) { seg = cblk->segs.head; jpc_seglist_remove(&cblk->segs, seg); jpc_seg_destroy(seg); } jas_matrix_destroy(cblk->data); if (cblk->mqdec) { jpc_mqdec_destroy(cblk->mqdec); } if (cblk->nulldec) { jpc_bitstream_close(cblk->nulldec); } if (cblk->flags) { jas_matrix_destroy(cblk->flags); } } if (prc->incltagtree) { jpc_tagtree_destroy(prc->incltagtree); } if (prc->numimsbstagtree) { jpc_tagtree_destroy(prc->numimsbstagtree); } if (prc->cblks) { jas_free(prc->cblks); } } } if (band->data) { jas_matrix_destroy(band->data); } if (band->prcs) { jas_free(band->prcs); } } if (rlvl->bands) { jas_free(rlvl->bands); } } if (tcomp->rlvls) { jas_free(tcomp->rlvls); } if (tcomp->data) { jas_matrix_destroy(tcomp->data); } if (tcomp->tsfb) { jpc_tsfb_destroy(tcomp->tsfb); } } } if (tile->cp) { jpc_dec_cp_destroy(tile->cp); tile->cp = 0; } if (tile->tcomps) { jas_free(tile->tcomps); tile->tcomps = 0; } if (tile->pi) { jpc_pi_destroy(tile->pi); tile->pi = 0; } if (tile->pkthdrstream) { jas_stream_close(tile->pkthdrstream); tile->pkthdrstream = 0; } if (tile->pptstab) { jpc_ppxstab_destroy(tile->pptstab); tile->pptstab = 0; } tile->state = JPC_TILE_DONE; return 0; }
CWE-476
12
0
void Splash::fillGlyph(SplashCoord x, SplashCoord y, SplashGlyphBitmap *glyph) { SplashCoord xt, yt; int x0, y0; transform(state->matrix, x, y, &xt, &yt); x0 = splashFloor(xt); y0 = splashFloor(yt); SplashClipResult clipRes = state->clip->testRect(x0 - glyph->x, y0 - glyph->y, x0 - glyph->x + glyph->w - 1, y0 - glyph->y + glyph->h - 1); if (clipRes != splashClipAllOutside) { fillGlyph2(x0, y0, glyph, clipRes == splashClipAllInside); } opClipRes = clipRes; }
none
24
1
static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q), exception),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); }
CWE-125
1
1
static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=NULL; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; #ifdef EXIF_DEBUG char *dump_data; int dump_free; #endif /* EXIF_DEBUG */ /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached"); return FALSE; } ImageInfo->ifd_nesting_level++; tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components); return FALSE; } byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format]; if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC)); return FALSE; } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; /* dir_entry is ImageInfo->file.list[sn].data+2+i*12 offset_base is ImageInfo->file.list[sn].data-dir_offset dir_entry - offset_base is dir_offset+2+i*12 */ if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* It is important to check for IMAGE_FILETYPE_TIFF * JPEG does not use absolute pointers instead its pointers are * relative to the start of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength); } return FALSE; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = safe_emalloc(byte_count, 1, 0); outside = value_ptr; } else { /* In most cases we only access a small range so * it is faster to use a static buffer there * BUT it offers also the possibility to have * pointers read without the need to free them * explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = php_stream_tell(ImageInfo->infile); php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val); return FALSE; } fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count); php_stream_seek(ImageInfo->infile, fpos, SEEK_SET); if (fgot<byte_count) { EFREE_IF(outside); EXIF_ERRLOG_FILEEOF(ImageInfo) return FALSE; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; #ifdef EXIF_DEBUG dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data); if (dump_free) { efree(dump_data); } #endif if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ ImageInfo->CopyrightPhotographer = estrdup(value_ptr); ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { ImageInfo->Copyright = estrndup(value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC); break; case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD"); } break; case TAG_MAKE: ImageInfo->make = estrndup(value_ptr, byte_count); break; case TAG_MODEL: ImageInfo->model = estrndup(value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF"); #endif ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS"); #endif ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY"); #endif ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer"); return FALSE; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index)); #endif } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC); EFREE_IF(outside); return TRUE; }
CWE-119
0
1
static int mxf_parse_structural_metadata(MXFContext *mxf) { MXFPackage *material_package = NULL; int i, j, k, ret; av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count); /* TODO: handle multiple material packages (OP3x) */ for (i = 0; i < mxf->packages_count; i++) { material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); if (material_package) break; } if (!material_package) { av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n"); return AVERROR_INVALIDDATA; } mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package); if (material_package->name && material_package->name[0]) av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0); mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); for (i = 0; i < material_package->tracks_count; i++) { MXFPackage *source_package = NULL; MXFTrack *material_track = NULL; MXFTrack *source_track = NULL; MXFTrack *temp_track = NULL; MXFDescriptor *descriptor = NULL; MXFStructuralComponent *component = NULL; MXFTimecodeComponent *mxf_tc = NULL; UID *essence_container_ul = NULL; const MXFCodecUL *codec_ul = NULL; const MXFCodecUL *container_ul = NULL; const MXFCodecUL *pix_fmt_ul = NULL; AVStream *st; AVTimecode tc; int flags; if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n"); continue; } if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc); } } if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n"); continue; } for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); if (!component) continue; mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc); break; } } /* TODO: handle multiple source clips, only finds first valid source clip */ if(material_track->sequence->structural_components_count > 1) av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n", material_track->track_id, material_track->sequence->structural_components_count); for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); if (!component) continue; source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid); if (!source_package) { av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id); continue; } for (k = 0; k < source_package->tracks_count; k++) { if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n"); ret = AVERROR_INVALIDDATA; goto fail_and_free; } if (temp_track->track_id == component->source_track_id) { source_track = temp_track; break; } } if (!source_track) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id); break; } for (k = 0; k < mxf->essence_container_data_count; k++) { MXFEssenceContainerData *essence_data; if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) { av_log(mxf, AV_LOG_TRACE, "could not resolve essence container data strong ref\n"); continue; } if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) { source_track->body_sid = essence_data->body_sid; source_track->index_sid = essence_data->index_sid; break; } } if(source_track && component) break; } if (!source_track || !component || !source_package) { if((ret = mxf_add_metadata_stream(mxf, material_track))) goto fail_and_free; continue; } if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n"); ret = AVERROR_INVALIDDATA; goto fail_and_free; } /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id); continue; } st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n"); ret = AVERROR(ENOMEM); goto fail_and_free; } st->id = material_track->track_id; st->priv_data = source_track; source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ if (descriptor && descriptor->duration != AV_NOPTS_VALUE) source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); else source_track->original_duration = st->duration = component->duration; if (st->duration == -1) st->duration = AV_NOPTS_VALUE; st->start_time = component->start_position; if (material_track->edit_rate.num <= 0 || material_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "Invalid edit rate (%d/%d) found on stream #%d, " "defaulting to 25/1\n", material_track->edit_rate.num, material_track->edit_rate.den, st->index); material_track->edit_rate = (AVRational){25, 1}; } avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); /* ensure SourceTrack EditRate == MaterialTrack EditRate since only * the former is accessible via st->priv_data */ source_track->edit_rate = material_track->edit_rate; PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); st->codecpar->codec_type = codec_ul->id; if (!descriptor) { av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index); continue; } PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul); PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul); essence_container_ul = &descriptor->essence_container_ul; source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul); if (source_track->wrapping == UnknownWrapped) av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index); /* HACK: replacing the original key with mxf_encrypted_essence_container * is not allowed according to s429-6, try to find correct information anyway */ if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n"); for (k = 0; k < mxf->metadata_sets_count; k++) { MXFMetadataSet *metadata = mxf->metadata_sets[k]; if (metadata->type == CryptoContext) { essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; break; } } } /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; } av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ", avcodec_get_name(st->codecpar->codec_id)); for (k = 0; k < 16; k++) { av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x", descriptor->essence_codec_ul[k]); if (!(k+1 & 19) || k == 5) av_log(mxf->fc, AV_LOG_VERBOSE, "."); } av_log(mxf->fc, AV_LOG_VERBOSE, "\n"); mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package); if (source_package->name && source_package->name[0]) av_dict_set(&st->metadata, "file_package_name", source_package->name, 0); if (material_track->name && material_track->name[0]) av_dict_set(&st->metadata, "track_name", material_track->name, 0); mxf_parse_physical_source_package(mxf, source_track, st); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { source_track->intra_only = mxf_is_intra_only(descriptor); container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; st->codecpar->width = descriptor->width; st->codecpar->height = descriptor->height; /* Field height, not frame height */ switch (descriptor->frame_layout) { case FullFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; break; case OneField: /* Every other line is stored and needs to be duplicated. */ av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n"); break; /* The correct thing to do here is fall through, but by breaking we might be able to decode some streams at half the vertical resolution, rather than not al all. It's also for compatibility with the old behavior. */ case MixedFields: break; case SegmentedFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; case SeparateFields: av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n", descriptor->video_line_map[0], descriptor->video_line_map[1], descriptor->field_dominance); if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { /* Detect coded field order from VideoLineMap: * (even, even) => bottom field coded first * (even, odd) => top field coded first * (odd, even) => top field coded first * (odd, odd) => bottom field coded first */ if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_TT; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_TB; break; default: avpriv_request_sample(mxf->fc, "Field dominance %d support", descriptor->field_dominance); } } else { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_BB; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_BT; break; default: avpriv_request_sample(mxf->fc, "Field dominance %d support", descriptor->field_dominance); } } } /* Turn field height into frame height. */ st->codecpar->height *= 2; break; default: av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout); } if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { st->codecpar->format = descriptor->pix_fmt; if (st->codecpar->format == AV_PIX_FMT_NONE) { pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, &descriptor->essence_codec_ul); st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; if (st->codecpar->format== AV_PIX_FMT_NONE) { st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, &descriptor->essence_codec_ul)->id; if (!st->codecpar->codec_tag) { /* support files created before RP224v10 by defaulting to UYVY422 if subsampling is 4:2:2 and component depth is 8-bit */ if (descriptor->horiz_subsampling == 2 && descriptor->vert_subsampling == 1 && descriptor->component_depth == 8) { st->codecpar->format = AV_PIX_FMT_UYVY422; } } } } } st->need_parsing = AVSTREAM_PARSE_HEADERS; if (material_track->sequence->origin) { av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0); } if (source_track->sequence->origin) { av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0); } if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) st->display_aspect_ratio = descriptor->aspect_ratio; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) st->codecpar->codec_id = (enum AVCodecID)container_ul->id; st->codecpar->channels = descriptor->channels; st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; if (descriptor->sample_rate.den > 0) { st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); } else { av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) " "found for stream #%d, time base forced to 1/48000\n", descriptor->sample_rate.num, descriptor->sample_rate.den, st->index); avpriv_set_pts_info(st, 64, 1, 48000); } /* if duration is set, rescale it from EditRate to SampleRate */ if (st->duration != AV_NOPTS_VALUE) st->duration = av_rescale_q(st->duration, av_inv_q(material_track->edit_rate), st->time_base); /* TODO: implement AV_CODEC_ID_RAWAUDIO */ if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { st->need_parsing = AVSTREAM_PARSE_FULL; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { enum AVMediaType type; container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; type = avcodec_get_type(st->codecpar->codec_id); if (type == AVMEDIA_TYPE_SUBTITLE) st->codecpar->codec_type = type; if (container_ul->desc) av_dict_set(&st->metadata, "data_type", container_ul->desc, 0); } if (descriptor->extradata) { if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); } } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, &descriptor->essence_codec_ul)->id; if (coded_width) st->codecpar->width = coded_width; ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) { /* TODO: decode timestamps */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; } } ret = 0; fail_and_free: return ret; }
CWE-125
1
1
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; }
CWE-20
3
0
GfxPattern::GfxPattern(int typeA) { type = typeA; }
none
24
1
static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = chan->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = cpu_to_le16(chan->dcid); } else { la->l2_psm = chan->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = cpu_to_le16(chan->scid); } return 0; }
CWE-200
4
1
static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image) { CompressionType compression; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; MemoryInfo *pixel_info; SGIInfo iris_info; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t imageListLength; ssize_t y, z; unsigned char *pixels, *packets; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { /* Initialize SGI raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace); (void) memset(&iris_info,0,sizeof(iris_info)); iris_info.magic=0x01DA; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (image->depth > 8) compression=NoCompression; if (compression == NoCompression) iris_info.storage=(unsigned char) 0x00; else iris_info.storage=(unsigned char) 0x01; iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1); iris_info.dimension=3; iris_info.columns=(unsigned short) image->columns; iris_info.rows=(unsigned short) image->rows; if (image->matte != MagickFalse) iris_info.depth=4; else { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { iris_info.dimension=2; iris_info.depth=1; } else iris_info.depth=3; } iris_info.minimum_value=0; iris_info.maximum_value=(size_t) (image->depth <= 8 ? 1UL*ScaleQuantumToChar(QuantumRange) : 1UL*ScaleQuantumToShort(QuantumRange)); /* Write SGI header. */ (void) WriteBlobMSBShort(image,iris_info.magic); (void) WriteBlobByte(image,iris_info.storage); (void) WriteBlobByte(image,iris_info.bytes_per_pixel); (void) WriteBlobMSBShort(image,iris_info.dimension); (void) WriteBlobMSBShort(image,iris_info.columns); (void) WriteBlobMSBShort(image,iris_info.rows); (void) WriteBlobMSBShort(image,iris_info.depth); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name)); (void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format); (void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler); /* Allocate SGI pixels. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*iris_info.bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory((size_t) number_pixels,4* iris_info.bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Convert image pixels to uncompressed SGI pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (image->depth <= 8) for (x=0; x < (ssize_t) image->columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelAlpha(p)); p++; } else for (x=0; x < (ssize_t) image->columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToShort(GetPixelRed(p)); *q++=ScaleQuantumToShort(GetPixelGreen(p)); *q++=ScaleQuantumToShort(GetPixelBlue(p)); *q++=ScaleQuantumToShort(GetPixelAlpha(p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } switch (compression) { case NoCompression: { /* Write uncompressed SGI pixels. */ for (z=0; z < (ssize_t) iris_info.depth; z++) { for (y=0; y < (ssize_t) iris_info.rows; y++) { if (image->depth <= 8) for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobByte(image,*q); } else for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobMSBShort(image,*q); } } } break; } default: { MemoryInfo *packet_info; size_t length, number_packets, *runlength; ssize_t offset, *offsets; /* Convert SGI uncompressed pixels. */ offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)* image->rows,4*sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets != (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength != (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info != (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth); number_packets=0; q=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { length=SGIEncode(q+z,(size_t) iris_info.columns,packets+ number_packets); number_packets+=length; offsets[y+z*iris_info.rows]=offset; runlength[y+z*iris_info.rows]=(size_t) length; offset+=(ssize_t) length; } q+=(iris_info.columns*4); } /* Write out line start and length tables and runlength-encoded pixels. */ for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) offsets[i]); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) runlength[i]); (void) WriteBlob(image,number_packets,packets); /* Relinquish resources. */ offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
CWE-787
16
1
ast_for_arguments(struct compiling *c, const node *n) { /* This function handles both typedargslist (function definition) and varargslist (lambda definition). parameters: '(' [typedargslist] ')' typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [ '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']]] | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']) tfpdef: NAME [':' test] varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] | '**' vfpdef [',']]] | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] | '**' vfpdef [','] ) vfpdef: NAME */ int i, j, k, nposargs = 0, nkwonlyargs = 0; int nposdefaults = 0, found_default = 0; asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults; arg_ty vararg = NULL, kwarg = NULL; arg_ty arg; node *ch; if (TYPE(n) == parameters) { if (NCH(n) == 2) /* () as argument list */ return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); n = CHILD(n, 1); } assert(TYPE(n) == typedargslist || TYPE(n) == varargslist); /* First count the number of positional args & defaults. The variable i is the loop index for this for loop and the next. The next loop picks up where the first leaves off. */ for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == STAR) { /* skip star */ i++; if (i < NCH(n) && /* skip argument following star */ (TYPE(CHILD(n, i)) == tfpdef || TYPE(CHILD(n, i)) == vfpdef)) { i++; } break; } if (TYPE(ch) == DOUBLESTAR) break; if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } /* count the number of keyword only args & defaults for keyword only args */ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); if (TYPE(ch) == DOUBLESTAR) break; if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++; } posargs = (nposargs ? _Py_asdl_seq_new(nposargs, c->c_arena) : NULL); if (!posargs && nposargs) return NULL; kwonlyargs = (nkwonlyargs ? _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) return NULL; posdefaults = (nposdefaults ? _Py_asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) return NULL; /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ kwdefaults = (nkwonlyargs ? _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwdefaults && nkwonlyargs) return NULL; /* tfpdef: NAME [':' test] vfpdef: NAME */ i = 0; j = 0; /* index for defaults */ k = 0; /* index for args */ while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case tfpdef: case vfpdef: /* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is anything other than EQUAL or a comma? */ /* XXX Should NCH(n) check be made a separate check? */ if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expr_ty expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) return NULL; assert(posdefaults != NULL); asdl_seq_SET(posdefaults, j++, expression); i += 2; found_default = 1; } else if (found_default) { ast_error(c, n, "non-default argument follows default argument"); return NULL; } arg = ast_for_arg(c, ch); if (!arg) return NULL; asdl_seq_SET(posargs, k++, arg); i += 2; /* the name and the comma */ break; case STAR: if (i+1 >= NCH(n) || (i+2 == NCH(n) && TYPE(CHILD(n, i+1)) == COMMA)) { ast_error(c, CHILD(n, i), "named arguments must follow bare *"); return NULL; } ch = CHILD(n, i+1); /* tfpdef or COMMA */ if (TYPE(ch) == COMMA) { int res = 0; i += 2; /* now follows keyword only arguments */ res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) return NULL; i = res; /* res has new position to process */ } else { vararg = ast_for_arg(c, ch); if (!vararg) return NULL; i += 3; if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef || TYPE(CHILD(n, i)) == vfpdef)) { int res = 0; res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) return NULL; i = res; /* res has new position to process */ } } break; case DOUBLESTAR: ch = CHILD(n, i+1); /* tfpdef */ assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef); kwarg = ast_for_arg(c, ch); if (!kwarg) return NULL; i += 3; break; default: PyErr_Format(PyExc_SystemError, "unexpected node in varargslist: %d @ %d", TYPE(ch), i); return NULL; } } return arguments(posargs, vararg, kwonlyargs, kwdefaults, kwarg, posdefaults, c->c_arena); }
CWE-125
1
1
static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) { #define SIZEOF_FILE_NAME 255 int i = 0; const char* basename; if (!dbg_data) { return 0; } switch (dbg_dir_entry->Type) { case IMAGE_DEBUG_TYPE_CODEVIEW: if (!strncmp ((char*) dbg_data, "RSDS", 4)) { SCV_RSDS_HEADER rsds_hdr; init_rsdr_hdr (&rsds_hdr); if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) { bprintf ("Warning: Cannot read PE debug info\n"); return 0; } snprintf (res->guidstr, GUIDSTR_LEN, "%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x", rsds_hdr.guid.data1, rsds_hdr.guid.data2, rsds_hdr.guid.data3, rsds_hdr.guid.data4[0], rsds_hdr.guid.data4[1], rsds_hdr.guid.data4[2], rsds_hdr.guid.data4[3], rsds_hdr.guid.data4[4], rsds_hdr.guid.data4[5], rsds_hdr.guid.data4[6], rsds_hdr.guid.data4[7], rsds_hdr.age); basename = r_file_basename ((char*) rsds_hdr.file_name); strncpy (res->file_name, (const char*) basename, sizeof (res->file_name)); res->file_name[sizeof (res->file_name) - 1] = 0; rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr); } else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) { SCV_NB10_HEADER nb10_hdr; init_cv_nb10_header (&nb10_hdr); get_nb10 (dbg_data, &nb10_hdr); snprintf (res->guidstr, sizeof (res->guidstr), "%x%x", nb10_hdr.timestamp, nb10_hdr.age); strncpy (res->file_name, (const char*) nb10_hdr.file_name, sizeof(res->file_name) - 1); res->file_name[sizeof (res->file_name) - 1] = 0; nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr); } else { bprintf ("CodeView section not NB10 or RSDS\n"); return 0; } break; default: return 0; } while (i < 33) { res->guidstr[i] = toupper ((int) res->guidstr[i]); i++; } return 1; }
CWE-125
1
1
ExtensionNavigationThrottle::WillStartOrRedirectRequest() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::WebContents* web_contents = navigation_handle()->GetWebContents(); ExtensionRegistry* registry = ExtensionRegistry::Get(web_contents->GetBrowserContext()); const GURL& url = navigation_handle()->GetURL(); bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme); url::Origin target_origin = url::Origin::Create(url); const Extension* target_extension = nullptr; if (url_has_extension_scheme) { target_extension = registry->enabled_extensions().GetExtensionOrAppByURL(url); } else if (target_origin.scheme() == kExtensionScheme) { DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob()); target_extension = registry->enabled_extensions().GetByID(target_origin.host()); } else { return content::NavigationThrottle::PROCEED; } if (!target_extension) { return content::NavigationThrottle::BLOCK_REQUEST; } if (target_extension->is_hosted_app()) { base::StringPiece resource_root_relative_path = url.path_piece().empty() ? base::StringPiece() : url.path_piece().substr(1); if (!IconsInfo::GetIcons(target_extension) .ContainsPath(resource_root_relative_path)) { return content::NavigationThrottle::BLOCK_REQUEST; } } if (navigation_handle()->IsInMainFrame()) { bool current_frame_is_extension_process = !!registry->enabled_extensions().GetExtensionOrAppByURL( navigation_handle()->GetStartingSiteInstance()->GetSiteURL()); if (!url_has_extension_scheme && !current_frame_is_extension_process) { if (target_origin.scheme() == kExtensionScheme && navigation_handle()->GetSuggestedFilename().has_value()) { return content::NavigationThrottle::PROCEED; } bool has_webview_permission = target_extension->permissions_data()->HasAPIPermission( APIPermission::kWebView); if (!has_webview_permission) return content::NavigationThrottle::CANCEL; } guest_view::GuestViewBase* guest = guest_view::GuestViewBase::FromWebContents(web_contents); if (url_has_extension_scheme && guest) { const std::string& owner_extension_id = guest->owner_host(); const Extension* owner_extension = registry->enabled_extensions().GetByID(owner_extension_id); std::string partition_domain; std::string partition_id; bool in_memory = false; bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite( navigation_handle()->GetStartingSiteInstance()->GetSiteURL(), &partition_domain, &partition_id, &in_memory); bool allowed = true; url_request_util::AllowCrossRendererResourceLoadHelper( is_guest, target_extension, owner_extension, partition_id, url.path(), navigation_handle()->GetPageTransition(), &allowed); if (!allowed) return content::NavigationThrottle::BLOCK_REQUEST; } return content::NavigationThrottle::PROCEED; } content::RenderFrameHost* parent = navigation_handle()->GetParentFrame(); bool external_ancestor = false; for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) { if (ancestor->GetLastCommittedOrigin() == target_origin) continue; if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin) continue; if (ancestor->GetLastCommittedURL().SchemeIs( content::kChromeDevToolsScheme)) continue; external_ancestor = true; break; } if (external_ancestor) { if (!url_has_extension_scheme) return content::NavigationThrottle::CANCEL; if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension, url.path())) return content::NavigationThrottle::BLOCK_REQUEST; if (target_extension->is_platform_app()) return content::NavigationThrottle::CANCEL; const Extension* parent_extension = registry->enabled_extensions().GetExtensionOrAppByURL( parent->GetSiteInstance()->GetSiteURL()); if (parent_extension && parent_extension->is_platform_app()) return content::NavigationThrottle::BLOCK_REQUEST; } return content::NavigationThrottle::PROCEED; }
CWE-20
3
1
void EventBindings::AttachFilteredEvent( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsString()); CHECK(args[1]->IsObject()); std::string event_name = *v8::String::Utf8Value(args[0]); if (!context()->HasAccessOrThrowError(event_name)) return; std::unique_ptr<base::DictionaryValue> filter; { std::unique_ptr<content::V8ValueConverter> converter( content::V8ValueConverter::create()); std::unique_ptr<base::Value> filter_value(converter->FromV8Value( v8::Local<v8::Object>::Cast(args[1]), context()->v8_context())); if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) { args.GetReturnValue().Set(static_cast<int32_t>(-1)); return; } filter = base::DictionaryValue::From(std::move(filter_value)); } base::DictionaryValue* filter_weak = filter.get(); int id = g_event_filter.Get().AddEventMatcher( event_name, ParseEventMatcher(std::move(filter))); attached_matcher_ids_.insert(id); std::string extension_id = context()->GetExtensionID(); if (AddFilter(event_name, extension_id, *filter_weak)) { bool lazy = ExtensionFrameHelper::IsContextForEventPage(context()); content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener( extension_id, event_name, *filter_weak, lazy)); } args.GetReturnValue().Set(static_cast<int32_t>(id)); }
CWE-416
10
0
void *vfs_fetch_fsp_extension(vfs_handle_struct *handle, files_struct *fsp) { struct vfs_fsp_data *head; head = (struct vfs_fsp_data *)vfs_memctx_fsp_extension(handle, fsp); if (head != NULL) { return EXT_DATA_AREA(head); } return NULL; }
none
24
1
static irqreturn_t sunkbd_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct sunkbd *sunkbd = serio_get_drvdata(serio); if (sunkbd->reset <= -1) { /* * If cp[i] is 0xff, sunkbd->reset will stay -1. * The keyboard sends 0xff 0xff 0xID on powerup. */ sunkbd->reset = data; wake_up_interruptible(&sunkbd->wait); goto out; } if (sunkbd->layout == -1) { sunkbd->layout = data; wake_up_interruptible(&sunkbd->wait); goto out; } switch (data) { case SUNKBD_RET_RESET: schedule_work(&sunkbd->tq); sunkbd->reset = -1; break; case SUNKBD_RET_LAYOUT: sunkbd->layout = -1; break; case SUNKBD_RET_ALLUP: /* All keys released */ break; default: if (!sunkbd->enabled) break; if (sunkbd->keycode[data & SUNKBD_KEY]) { input_report_key(sunkbd->dev, sunkbd->keycode[data & SUNKBD_KEY], !(data & SUNKBD_RELEASE)); input_sync(sunkbd->dev); } else { printk(KERN_WARNING "sunkbd.c: Unknown key (scancode %#x) %s.\n", data & SUNKBD_KEY, data & SUNKBD_RELEASE ? "released" : "pressed"); } } out: return IRQ_HANDLED; }
CWE-416
10
1
crypto_recv( struct peer *peer, /* peer structure pointer */ struct recvbuf *rbufp /* packet buffer pointer */ ) { const EVP_MD *dp; /* message digest algorithm */ u_int32 *pkt; /* receive packet pointer */ struct autokey *ap, *bp; /* autokey pointer */ struct exten *ep, *fp; /* extension pointers */ struct cert_info *xinfo; /* certificate info pointer */ int has_mac; /* length of MAC field */ int authlen; /* offset of MAC field */ associd_t associd; /* association ID */ tstamp_t fstamp = 0; /* filestamp */ u_int len; /* extension field length */ u_int code; /* extension field opcode */ u_int vallen = 0; /* value length */ X509 *cert; /* X509 certificate */ char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ keyid_t cookie; /* crumbles */ int hismode; /* packet mode */ int rval = XEVNT_OK; const u_char *puch; u_int32 temp32; /* * Initialize. Note that the packet has already been checked for * valid format and extension field lengths. First extract the * field length, command code and association ID in host byte * order. These are used with all commands and modes. Then check * the version number, which must be 2, and length, which must * be at least 8 for requests and VALUE_LEN (24) for responses. * Packets that fail either test sink without a trace. The * association ID is saved only if nonzero. */ authlen = LEN_PKT_NOMAC; hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode); while ((has_mac = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) { pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4; ep = (struct exten *)pkt; code = ntohl(ep->opcode) & 0xffff0000; len = ntohl(ep->opcode) & 0x0000ffff; // HMS: Why pkt[1] instead of ep->associd ? associd = (associd_t)ntohl(pkt[1]); rval = XEVNT_OK; DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n", peer->crypto, authlen, len, code >> 16, associd)); /* * Check version number and field length. If bad, * quietly ignore the packet. */ if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) { sys_badlength++; code |= CRYPTO_ERROR; } if (len >= VALUE_LEN) { fstamp = ntohl(ep->fstamp); vallen = ntohl(ep->vallen); /* * Bug 2761: I hope this isn't too early... */ if ( vallen == 0 || len - VALUE_LEN < vallen) return XEVNT_LEN; } switch (code) { /* * Install status word, host name, signature scheme and * association ID. In OpenSSL the signature algorithm is * bound to the digest algorithm, so the NID completely * defines the signature scheme. Note the request and * response are identical, but neither is validated by * signature. The request is processed here only in * symmetric modes. The server name field might be * useful to implement access controls in future. */ case CRYPTO_ASSOC: /* * If our state machine is running when this * message arrives, the other fellow might have * restarted. However, this could be an * intruder, so just clamp the poll interval and * find out for ourselves. Otherwise, pass the * extension field to the transmit side. */ if (peer->crypto & CRYPTO_FLAG_CERT) { rval = XEVNT_ERR; break; } if (peer->cmmd) { if (peer->assoc != associd) { rval = XEVNT_ERR; break; } } fp = emalloc(len); memcpy(fp, ep, len); fp->associd = htonl(peer->associd); peer->cmmd = fp; /* fall through */ case CRYPTO_ASSOC | CRYPTO_RESP: /* * Discard the message if it has already been * stored or the message has been amputated. */ if (peer->crypto) { if (peer->assoc != associd) rval = XEVNT_ERR; break; } INSIST(len >= VALUE_LEN); if (vallen == 0 || vallen > MAXHOSTNAME || len - VALUE_LEN < vallen) { rval = XEVNT_LEN; break; } DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n", crypto_flags, peer->associd, fstamp, peer->assoc)); temp32 = crypto_flags & CRYPTO_FLAG_MASK; /* * If the client scheme is PC, the server scheme * must be PC. The public key and identity are * presumed valid, so we skip the certificate * and identity exchanges and move immediately * to the cookie exchange which confirms the * server signature. */ if (crypto_flags & CRYPTO_FLAG_PRIV) { if (!(fstamp & CRYPTO_FLAG_PRIV)) { rval = XEVNT_KEY; break; } fstamp |= CRYPTO_FLAG_CERT | CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN; /* * It is an error if either peer supports * identity, but the other does not. */ } else if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE) { if ((temp32 && !(fstamp & CRYPTO_FLAG_MASK)) || (!temp32 && (fstamp & CRYPTO_FLAG_MASK))) { rval = XEVNT_KEY; break; } } /* * Discard the message if the signature digest * NID is not supported. */ temp32 = (fstamp >> 16) & 0xffff; dp = (const EVP_MD *)EVP_get_digestbynid(temp32); if (dp == NULL) { rval = XEVNT_MD; break; } /* * Save status word, host name and message * digest/signature type. If this is from a * broadcast and the association ID has changed, * request the autokey values. */ peer->assoc = associd; if (hismode == MODE_SERVER) fstamp |= CRYPTO_FLAG_AUTO; if (!(fstamp & CRYPTO_FLAG_TAI)) fstamp |= CRYPTO_FLAG_LEAP; RAND_bytes((u_char *)&peer->hcookie, 4); peer->crypto = fstamp; peer->digest = dp; if (peer->subject != NULL) free(peer->subject); peer->subject = emalloc(vallen + 1); memcpy(peer->subject, ep->pkt, vallen); peer->subject[vallen] = '\0'; if (peer->issuer != NULL) free(peer->issuer); peer->issuer = estrdup(peer->subject); snprintf(statstr, sizeof(statstr), "assoc %d %d host %s %s", peer->associd, peer->assoc, peer->subject, OBJ_nid2ln(temp32)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Decode X509 certificate in ASN.1 format and extract * the data containing, among other things, subject * name and public key. In the default identification * scheme, the certificate trail is followed to a self * signed trusted certificate. */ case CRYPTO_CERT | CRYPTO_RESP: /* * Discard the message if empty or invalid. */ if (len < VALUE_LEN) break; if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * Scan the certificate list to delete old * versions and link the newest version first on * the list. Then, verify the signature. If the * certificate is bad or missing, just ignore * it. */ if ((xinfo = cert_install(ep, peer)) == NULL) { rval = XEVNT_CRT; break; } if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK) break; /* * We plug in the public key and lifetime from * the first certificate received. However, note * that this certificate might not be signed by * the server, so we can't check the * signature/digest NID. */ if (peer->pkey == NULL) { puch = xinfo->cert.ptr; cert = d2i_X509(NULL, &puch, ntohl(xinfo->cert.vallen)); peer->pkey = X509_get_pubkey(cert); X509_free(cert); } peer->flash &= ~TEST8; temp32 = xinfo->nid; snprintf(statstr, sizeof(statstr), "cert %s %s 0x%x %s (%u) fs %u", xinfo->subject, xinfo->issuer, xinfo->flags, OBJ_nid2ln(temp32), temp32, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Schnorr (IFF) identity scheme. This scheme is * designed for use with shared secret server group keys * and where the certificate may be generated by a third * party. The client sends a challenge to the server, * which performs a calculation and returns the result. * A positive result is possible only if both client and * server contain the same secret group key. */ case CRYPTO_IFF | CRYPTO_RESP: /* * Discard the message if invalid. */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * If the challenge matches the response, the * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further * certificate exchanges and move immediately to * the cookie exchange. */ if ((rval = crypto_iff(ep, peer)) != XEVNT_OK) break; peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "iff %s fs %u", peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Guillou-Quisquater (GQ) identity scheme. This scheme * is designed for use with public certificates carrying * the GQ public key in an extension field. The client * sends a challenge to the server, which performs a * calculation and returns the result. A positive result * is possible only if both client and server contain * the same group key and the server has the matching GQ * private key. */ case CRYPTO_GQ | CRYPTO_RESP: /* * Discard the message if invalid */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * If the challenge matches the response, the * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further * certificate exchanges and move immediately to * the cookie exchange. */ if ((rval = crypto_gq(ep, peer)) != XEVNT_OK) break; peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "gq %s fs %u", peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Mu-Varadharajan (MV) identity scheme. This scheme is * designed for use with three levels of trust, trusted * host, server and client. The trusted host key is * opaque to servers and clients; the server keys are * opaque to clients and each client key is different. * Client keys can be revoked without requiring new key * generations. */ case CRYPTO_MV | CRYPTO_RESP: /* * Discard the message if invalid. */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * If the challenge matches the response, the * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further * certificate exchanges and move immediately to * the cookie exchange. */ if ((rval = crypto_mv(ep, peer)) != XEVNT_OK) break; peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "mv %s fs %u", peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Cookie response in client and symmetric modes. If the * cookie bit is set, the working cookie is the EXOR of * the current and new values. */ case CRYPTO_COOK | CRYPTO_RESP: /* * Discard the message if invalid or signature * not verified with respect to the cookie * values. */ if ((rval = crypto_verify(ep, &peer->cookval, peer)) != XEVNT_OK) break; /* * Decrypt the cookie, hunting all the time for * errors. */ if (vallen == (u_int)EVP_PKEY_size(host_pkey)) { u_int32 *cookiebuf = malloc( RSA_size(host_pkey->pkey.rsa)); if (!cookiebuf) { rval = XEVNT_CKY; break; } if (RSA_private_decrypt(vallen, (u_char *)ep->pkt, (u_char *)cookiebuf, host_pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) != 4) { rval = XEVNT_CKY; free(cookiebuf); break; } else { cookie = ntohl(*cookiebuf); free(cookiebuf); } } else { rval = XEVNT_CKY; break; } /* * Install cookie values and light the cookie * bit. If this is not broadcast client mode, we * are done here. */ key_expire(peer); if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE) peer->pcookie = peer->hcookie ^ cookie; else peer->pcookie = cookie; peer->crypto |= CRYPTO_FLAG_COOK; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "cook %x ts %u fs %u", peer->pcookie, ntohl(ep->tstamp), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Install autokey values in broadcast client and * symmetric modes. We have to do this every time the * sever/peer cookie changes or a new keylist is * rolled. Ordinarily, this is automatic as this message * is piggybacked on the first NTP packet sent upon * either of these events. Note that a broadcast client * or symmetric peer can receive this response without a * matching request. */ case CRYPTO_AUTO | CRYPTO_RESP: /* * Discard the message if invalid or signature * not verified with respect to the receive * autokey values. */ if ((rval = crypto_verify(ep, &peer->recval, peer)) != XEVNT_OK) break; /* * Discard the message if a broadcast client and * the association ID does not match. This might * happen if a broacast server restarts the * protocol. A protocol restart will occur at * the next ASSOC message. */ if ((peer->cast_flags & MDF_BCLNT) && peer->assoc != associd) break; /* * Install autokey values and light the * autokey bit. This is not hard. */ if (ep->tstamp == 0) break; if (peer->recval.ptr == NULL) peer->recval.ptr = emalloc(sizeof(struct autokey)); bp = (struct autokey *)peer->recval.ptr; peer->recval.tstamp = ep->tstamp; peer->recval.fstamp = ep->fstamp; ap = (struct autokey *)ep->pkt; bp->seq = ntohl(ap->seq); bp->key = ntohl(ap->key); peer->pkeyid = bp->key; peer->crypto |= CRYPTO_FLAG_AUTO; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "auto seq %d key %x ts %u fs %u", bp->seq, bp->key, ntohl(ep->tstamp), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * X509 certificate sign response. Validate the * certificate signed by the server and install. Later * this can be provided to clients of this server in * lieu of the self signed certificate in order to * validate the public key. */ case CRYPTO_SIGN | CRYPTO_RESP: /* * Discard the message if invalid. */ if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* * Scan the certificate list to delete old * versions and link the newest version first on * the list. */ if ((xinfo = cert_install(ep, peer)) == NULL) { rval = XEVNT_CRT; break; } peer->crypto |= CRYPTO_FLAG_SIGN; peer->flash &= ~TEST8; temp32 = xinfo->nid; snprintf(statstr, sizeof(statstr), "sign %s %s 0x%x %s (%u) fs %u", xinfo->subject, xinfo->issuer, xinfo->flags, OBJ_nid2ln(temp32), temp32, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * Install leapseconds values. While the leapsecond * values epoch, TAI offset and values expiration epoch * are retained, only the current TAI offset is provided * via the kernel to other applications. */ case CRYPTO_LEAP | CRYPTO_RESP: /* * Discard the message if invalid. We can't * compare the value timestamps here, as they * can be updated by different servers. */ rval = crypto_verify(ep, NULL, peer); if ((rval != XEVNT_OK ) || (vallen != 3*sizeof(uint32_t)) ) break; /* Check if we can update the basic TAI offset * for our current leap frame. This is a hack * and ignores the time stamps in the autokey * message. */ if (sys_leap != LEAP_NOTINSYNC) leapsec_autokey_tai(ntohl(ep->pkt[0]), rbufp->recv_time.l_ui, NULL); tai_leap.tstamp = ep->tstamp; tai_leap.fstamp = ep->fstamp; crypto_update(); mprintf_event(EVNT_TAI, peer, "%d seconds", ntohl(ep->pkt[0])); peer->crypto |= CRYPTO_FLAG_LEAP; peer->flash &= ~TEST8; snprintf(statstr, sizeof(statstr), "leap TAI offset %d at %u expire %u fs %u", ntohl(ep->pkt[0]), ntohl(ep->pkt[1]), ntohl(ep->pkt[2]), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * We come here in symmetric modes for miscellaneous * commands that have value fields but are processed on * the transmit side. All we need do here is check for * valid field length. Note that ASSOC is handled * separately. */ case CRYPTO_CERT: case CRYPTO_IFF: case CRYPTO_GQ: case CRYPTO_MV: case CRYPTO_COOK: case CRYPTO_SIGN: if (len < VALUE_LEN) { rval = XEVNT_LEN; break; } /* fall through */ /* * We come here in symmetric modes for requests * requiring a response (above plus AUTO and LEAP) and * for responses. If a request, save the extension field * for later; invalid requests will be caught on the * transmit side. If an error or invalid response, * declare a protocol error. */ default: if (code & (CRYPTO_RESP | CRYPTO_ERROR)) { rval = XEVNT_ERR; } else if (peer->cmmd == NULL) { fp = emalloc(len); memcpy(fp, ep, len); peer->cmmd = fp; } } /* * The first error found terminates the extension field * scan and we return the laundry to the caller. */ if (rval != XEVNT_OK) { snprintf(statstr, sizeof(statstr), "%04x %d %02x %s", htonl(ep->opcode), associd, rval, eventstr(rval)); record_crypto_stats(&peer->srcadr, statstr); DPRINTF(1, ("crypto_recv: %s\n", statstr)); return (rval); } authlen += (len + 3) / 4 * 4; } return (rval); }
CWE-20
3
1
static int crypto_report_one(struct crypto_alg *alg, struct crypto_user_alg *ualg, struct sk_buff *skb) { strlcpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name)); strlcpy(ualg->cru_driver_name, alg->cra_driver_name, sizeof(ualg->cru_driver_name)); strlcpy(ualg->cru_module_name, module_name(alg->cra_module), sizeof(ualg->cru_module_name)); ualg->cru_type = 0; ualg->cru_mask = 0; ualg->cru_flags = alg->cra_flags; ualg->cru_refcnt = refcount_read(&alg->cra_refcnt); if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority)) goto nla_put_failure; if (alg->cra_flags & CRYPTO_ALG_LARVAL) { struct crypto_report_larval rl; strlcpy(rl.type, "larval", sizeof(rl.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL, sizeof(struct crypto_report_larval), &rl)) goto nla_put_failure; goto out; } if (alg->cra_type && alg->cra_type->report) { if (alg->cra_type->report(skb, alg)) goto nla_put_failure; goto out; } switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) { case CRYPTO_ALG_TYPE_CIPHER: if (crypto_report_cipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_COMPRESS: if (crypto_report_comp(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_ACOMPRESS: if (crypto_report_acomp(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_AKCIPHER: if (crypto_report_akcipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_KPP: if (crypto_report_kpp(skb, alg)) goto nla_put_failure; break; } out: return 0; nla_put_failure: return -EMSGSIZE; }
CWE-200
4
0
ospf_api_typename (int msgtype) { struct nametab NameTab[] = { { MSG_REGISTER_OPAQUETYPE, "Register opaque-type", }, { MSG_UNREGISTER_OPAQUETYPE, "Unregister opaque-type", }, { MSG_REGISTER_EVENT, "Register event", }, { MSG_SYNC_LSDB, "Sync LSDB", }, { MSG_ORIGINATE_REQUEST, "Originate request", }, { MSG_DELETE_REQUEST, "Delete request", }, { MSG_REPLY, "Reply", }, { MSG_READY_NOTIFY, "Ready notify", }, { MSG_LSA_UPDATE_NOTIFY, "LSA update notify", }, { MSG_LSA_DELETE_NOTIFY, "LSA delete notify", }, { MSG_NEW_IF, "New interface", }, { MSG_DEL_IF, "Del interface", }, { MSG_ISM_CHANGE, "ISM change", }, { MSG_NSM_CHANGE, "NSM change", }, }; int i, n = array_size(NameTab); const char *name = NULL; for (i = 0; i < n; i++) { if (NameTab[i].value == msgtype) { name = NameTab[i].name; break; } } return name ? name : "?"; }
none
24
0
static int sepdomain(i_ctx_t * i_ctx_p, ref *space, float *ptr) { ptr[0] = 0; ptr[1] = 1; return 0; }
none
24
1
int ppp_register_net_channel(struct net *net, struct ppp_channel *chan) { struct channel *pch; struct ppp_net *pn; pch = kzalloc(sizeof(struct channel), GFP_KERNEL); if (!pch) return -ENOMEM; pn = ppp_pernet(net); pch->ppp = NULL; pch->chan = chan; pch->chan_net = net; chan->ppp = pch; init_ppp_file(&pch->file, CHANNEL); pch->file.hdrlen = chan->hdrlen; #ifdef CONFIG_PPP_MULTILINK pch->lastseq = -1; #endif /* CONFIG_PPP_MULTILINK */ init_rwsem(&pch->chan_sem); spin_lock_init(&pch->downl); rwlock_init(&pch->upl); spin_lock_bh(&pn->all_channels_lock); pch->file.index = ++pn->last_channel_index; list_add(&pch->list, &pn->new_channels); atomic_inc(&channel_count); spin_unlock_bh(&pn->all_channels_lock); return 0; }
CWE-416
10
1
jio_snprintf(char * str, int n, const char * format, ...) { va_list args; int result; Trc_SC_snprintf_Entry(); va_start(args, format); #if defined(WIN32) && !defined(WIN32_IBMC) result = _vsnprintf( str, n, format, args ); #else result = vsprintf( str, format, args ); #endif va_end(args); Trc_SC_snprintf_Exit(result); return result; }
CWE-119
0
1
do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, descsz); if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, " "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)", file_printable(sbuf, sizeof(sbuf), RCAST(char *, pi.cpi_name)), elf_getu32(swap, (uint32_t)pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, (uint32_t)pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; case OS_STYLE_FREEBSD: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t argoff, pidoff; if (clazz == ELFCLASS32) argoff = 4 + 4 + 17; else argoff = 4 + 4 + 8 + 17; if (file_printf(ms, ", from '%.80s'", nbuf + doff + argoff) == -1) return 1; pidoff = argoff + 81 + 2; if (doff + pidoff + 4 <= size) { if (file_printf(ms, ", pid=%u", elf_getu32(swap, *RCAST(uint32_t *, (nbuf + doff + pidoff)))) == -1) return 1; } *flags |= FLAGS_DID_CORE; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; cp < nbuf + size && *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; }
CWE-125
1
0
BufStream::BufStream(Stream *strA, int bufSizeA): FilterStream(strA) { bufSize = bufSizeA; buf = (int *)gmallocn(bufSize, sizeof(int)); }
none
24
1
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; /*ctxt->sax->fatalError = NULL;*/ #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; }
CWE-200
4
1
String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector<String> sitems; sitems.reserve(size); int len = 0; int lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assert(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assert(p - buffer == len); s.setSize(len); return s; }
CWE-190
2
0
static int ssl_check_srp_ext_ClientHello(SSL *s, int *al) { int ret = SSL_ERROR_NONE; *al = SSL_AD_UNRECOGNIZED_NAME; if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) { if (s->srp_ctx.login == NULL) { /* * RFC 5054 says SHOULD reject, we do so if There is no srp * login name */ ret = SSL3_AL_FATAL; *al = SSL_AD_UNKNOWN_PSK_IDENTITY; } else { ret = SSL_srp_server_param_with_username(s, al); } } return ret; }
none
24
1
static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf) { git_pkt *pkt; const char *line, *line_end; size_t line_len; int error; int reading_from_buf = data_pkt_buf->size > 0; if (reading_from_buf) { /* We had an existing partial packet, so add the new * packet to the buffer and parse the whole thing */ git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len); line = data_pkt_buf->ptr; line_len = data_pkt_buf->size; } else { line = data_pkt->data; line_len = data_pkt->len; } while (line_len > 0) { error = git_pkt_parse_line(&pkt, line, &line_end, line_len); if (error == GIT_EBUFS) { /* Buffer the data when the inner packet is split * across multiple sideband packets */ if (!reading_from_buf) git_buf_put(data_pkt_buf, line, line_len); error = 0; goto done; } else if (error < 0) goto done; /* Advance in the buffer */ line_len -= (line_end - line); line = line_end; /* When a valid packet with no content has been * read, git_pkt_parse_line does not report an * error, but the pkt pointer has not been set. * Handle this by skipping over empty packets. */ if (pkt == NULL) continue; error = add_push_report_pkt(push, pkt); git_pkt_free(pkt); if (error < 0 && error != GIT_ITEROVER) goto done; } error = 0; done: if (reading_from_buf) git_buf_consume(data_pkt_buf, line_end); return error; }
CWE-476
12
0
void reds_release_agent_data_buffer(uint8_t *buf) { VDIPortState *dev_state = &reds->agent_state; if (!dev_state->recv_from_client_buf) { free(buf); return; } spice_assert(buf == dev_state->recv_from_client_buf->buf + sizeof(VDIChunkHeader)); if (!dev_state->recv_from_client_buf_pushed) { spice_char_device_write_buffer_release(reds->agent_state.base, dev_state->recv_from_client_buf); } dev_state->recv_from_client_buf = NULL; dev_state->recv_from_client_buf_pushed = FALSE; }
none
24
1
bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter, param_type* r) { const char *data; int data_size = 0; bool result = m->ReadData(iter, &data, &data_size); if (result && data_size == sizeof(LOGFONT)) { memcpy(r, data, sizeof(LOGFONT)); } else { result = false; NOTREACHED(); } return result; }
CWE-20
3
1
BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize) : bufferSize_(bufferSize), buffer_(new unsigned char[bufferSize]), ptr_(buffer_.get() + bufferSize) { // refill on first use }
CWE-787
16
0
saml2md::MetadataProvider* SHIBSP_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e) { return new DynamicMetadataProvider(e); }
none
24
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) { regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], FALSE); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_RANGE_EXC, B) { regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], TRUE); 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); }
CWE-200
4
1
static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; int i, j, codebook_index; s->avctx = avctx; avctx->pix_fmt = PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, " VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE); return -1; } /* load up the VQA parameters from the header */ s->vqa_version = s->avctx->extradata[0]; s->width = AV_RL16(&s->avctx->extradata[6]); s->height = AV_RL16(&s->avctx->extradata[8]); if(av_image_check_size(s->width, s->height, 0, avctx)){ s->width= s->height= 0; return -1; } s->vector_width = s->avctx->extradata[10]; s->vector_height = s->avctx->extradata[11]; s->partial_count = s->partial_countdown = s->avctx->extradata[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return -1; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); if (!s->codebook) goto fail; s->next_codebook_buffer = av_malloc(s->codebook_size); if (!s->next_codebook_buffer) goto fail; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_malloc(s->decode_buffer_size); if (!s->decode_buffer) goto fail; /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; s->frame.data[0] = NULL; return 0; fail: av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return AVERROR(ENOMEM); }
CWE-119
0
1
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }
CWE-125
1
1
std::string queueloader::get_filename(const std::string& str) { std::string fn = ctrl->get_dlpath(); if (fn[fn.length()-1] != NEWSBEUTER_PATH_SEP[0]) fn.append(NEWSBEUTER_PATH_SEP); char buf[1024]; snprintf(buf, sizeof(buf), "%s", str.c_str()); char * base = basename(buf); if (!base || strlen(base) == 0) { char lbuf[128]; time_t t = time(NULL); strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t)); fn.append(lbuf); } else { fn.append(base); } return fn; }
CWE-78
15
0
nm_setting_vpn_error_quark (void) { static GQuark quark; if (G_UNLIKELY (!quark)) quark = g_quark_from_static_string ("nm-setting-vpn-error-quark"); return quark; }
none
24
1
static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice("Image has corrupt COM section: some software set " "wrong length information"); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning("To many padding bytes"); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning("File structure corrupted"); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning("Error reading from file: " "got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning("Unexpected end of file reached"); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning("No image in jpeg!"); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; }
CWE-125
1
1
int treeRead(struct READER *reader, struct DATAOBJECT *data) { int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy, szy; char *input, *output; uint8_t node_type, node_level; uint16_t entries_used; uint32_t size_of_chunk; uint32_t filter_mask; uint64_t address_of_left_sibling, address_of_right_sibling, start[4], child_pointer, key, store; char buf[4]; UNUSED(node_level); UNUSED(address_of_right_sibling); UNUSED(address_of_left_sibling); UNUSED(key); if (data->ds.dimensionality > 3) { log("TREE dimensions > 3"); return MYSOFA_INVALID_FORMAT; } /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) { log("cannot read signature of TREE\n"); return MYSOFA_INVALID_FORMAT; } log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); node_type = (uint8_t)fgetc(reader->fhd); node_level = (uint8_t)fgetc(reader->fhd); entries_used = (uint16_t)readValue(reader, 2); if(entries_used>0x1000) return MYSOFA_UNSUPPORTED_FORMAT; address_of_left_sibling = readValue(reader, reader->superblock.size_of_offsets); address_of_right_sibling = readValue(reader, reader->superblock.size_of_offsets); elements = 1; for (j = 0; j < data->ds.dimensionality; j++) elements *= data->datalayout_chunk[j]; dy = data->datalayout_chunk[1]; dz = data->datalayout_chunk[2]; sx = data->ds.dimension_size[0]; sy = data->ds.dimension_size[1]; sz = data->ds.dimension_size[2]; dzy = dz * dy; szy = sz * sy; size = data->datalayout_chunk[data->ds.dimensionality]; log("elements %d size %d\n",elements,size); if (!(output = malloc(elements * size))) { return MYSOFA_NO_MEMORY; } for (e = 0; e < entries_used * 2; e++) { if (node_type == 0) { key = readValue(reader, reader->superblock.size_of_lengths); } else { size_of_chunk = (uint32_t)readValue(reader, 4); filter_mask = (uint32_t)readValue(reader, 4); if (filter_mask) { log("TREE all filters must be enabled\n"); free(output); return MYSOFA_INVALID_FORMAT; } for (j = 0; j < data->ds.dimensionality; j++) { start[j] = readValue(reader, 8); log("start %d %lu\n",j,start[j]); } if (readValue(reader, 8)) { break; } child_pointer = readValue(reader, reader->superblock.size_of_offsets); log(" data at %lX len %u\n", child_pointer, size_of_chunk); /* read data */ store = ftell(reader->fhd); if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) { free(output); return errno; } if (!(input = malloc(size_of_chunk))) { free(output); return MYSOFA_NO_MEMORY; } if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) { free(output); free(input); return MYSOFA_INVALID_FORMAT; } olen = elements * size; err = gunzip(size_of_chunk, input, &olen, output); free(input); log(" gunzip %d %d %d\n",err, olen, elements*size); if (err || olen != elements * size) { free(output); return MYSOFA_INVALID_FORMAT; } switch (data->ds.dimensionality) { case 1: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements + start[0]; if (x < sx) { j = x * size + b; ((char*)data->data)[j] = output[i]; } } break; case 2: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; y = x % dy + start[1]; x = x / dy + start[0]; if (y < sy && x < sx) { j = ((x * sy + y) * size) + b; ((char*)data->data)[j] = output[i]; } } break; case 3: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; z = x % dz + start[2]; y = (x / dz) % dy + start[1]; x = (x / dzy) + start[0]; if (z < sz && y < sy && x < sx) { j = (x * szy + y * sz + z) * size + b; ((char*)data->data)[j] = output[i]; } } break; default: log("invalid dim\n"); return MYSOFA_INTERNAL_ERROR; } if(fseek(reader->fhd, store, SEEK_SET)<0) { free(output); return errno; } } } free(output); if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */ return errno; return MYSOFA_OK; }
CWE-20
3
0
const struct ldb_val *ldb_dn_get_rdn_val(struct ldb_dn *dn) { if ( ! ldb_dn_validate(dn)) { return NULL; } if (dn->comp_num == 0) return NULL; return &dn->components[0].value; }
none
24
1
bool IsBlacklistedArg(const base::CommandLine::CharType* arg) { #if defined(OS_WIN) const auto converted = base::WideToUTF8(arg); const char* a = converted.c_str(); #else const char* a = arg; #endif static const char* prefixes[] = {"--", "-", "/"}; int prefix_length = 0; for (auto& prefix : prefixes) { if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) { prefix_length = strlen(prefix); break; } } if (prefix_length > 0) { a += prefix_length; std::string switch_name(a, strcspn(a, "=")); auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist), switch_name); if (iter != std::end(kBlacklist) && switch_name == *iter) { return true; } } return false; }
CWE-200
4
0
_dbus_geteuid (void) { return geteuid (); }
none
24
1
configure_zone_ssutable(const cfg_obj_t *zconfig, dns_zone_t *zone, const char *zname) { const cfg_obj_t *updatepolicy = NULL; const cfg_listelt_t *element, *element2; dns_ssutable_t *table = NULL; isc_mem_t *mctx = dns_zone_getmctx(zone); bool autoddns = false; isc_result_t result; (void)cfg_map_get(zconfig, "update-policy", &updatepolicy); if (updatepolicy == NULL) { dns_zone_setssutable(zone, NULL); return (ISC_R_SUCCESS); } if (cfg_obj_isstring(updatepolicy) && strcmp("local", cfg_obj_asstring(updatepolicy)) == 0) { autoddns = true; updatepolicy = NULL; } result = dns_ssutable_create(mctx, &table); if (result != ISC_R_SUCCESS) return (result); for (element = cfg_list_first(updatepolicy); element != NULL; element = cfg_list_next(element)) { const cfg_obj_t *stmt = cfg_listelt_value(element); const cfg_obj_t *mode = cfg_tuple_get(stmt, "mode"); const cfg_obj_t *identity = cfg_tuple_get(stmt, "identity"); const cfg_obj_t *matchtype = cfg_tuple_get(stmt, "matchtype"); const cfg_obj_t *dname = cfg_tuple_get(stmt, "name"); const cfg_obj_t *typelist = cfg_tuple_get(stmt, "types"); const char *str; bool grant = false; bool usezone = false; dns_ssumatchtype_t mtype = DNS_SSUMATCHTYPE_NAME; dns_fixedname_t fname, fident; isc_buffer_t b; dns_rdatatype_t *types; unsigned int i, n; str = cfg_obj_asstring(mode); if (strcasecmp(str, "grant") == 0) { grant = true; } else if (strcasecmp(str, "deny") == 0) { grant = false; } else { INSIST(0); ISC_UNREACHABLE(); } str = cfg_obj_asstring(matchtype); CHECK(dns_ssu_mtypefromstring(str, &mtype)); if (mtype == dns_ssumatchtype_subdomain) { usezone = true; } dns_fixedname_init(&fident); str = cfg_obj_asstring(identity); isc_buffer_constinit(&b, str, strlen(str)); isc_buffer_add(&b, strlen(str)); result = dns_name_fromtext(dns_fixedname_name(&fident), &b, dns_rootname, 0, NULL); if (result != ISC_R_SUCCESS) { cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR, "'%s' is not a valid name", str); goto cleanup; } dns_fixedname_init(&fname); if (usezone) { result = dns_name_copy(dns_zone_getorigin(zone), dns_fixedname_name(&fname), NULL); if (result != ISC_R_SUCCESS) { cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR, "error copying origin: %s", isc_result_totext(result)); goto cleanup; } } else { str = cfg_obj_asstring(dname); isc_buffer_constinit(&b, str, strlen(str)); isc_buffer_add(&b, strlen(str)); result = dns_name_fromtext(dns_fixedname_name(&fname), &b, dns_rootname, 0, NULL); if (result != ISC_R_SUCCESS) { cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR, "'%s' is not a valid name", str); goto cleanup; } } n = ns_config_listcount(typelist); if (n == 0) types = NULL; else { types = isc_mem_get(mctx, n * sizeof(dns_rdatatype_t)); if (types == NULL) { result = ISC_R_NOMEMORY; goto cleanup; } } i = 0; for (element2 = cfg_list_first(typelist); element2 != NULL; element2 = cfg_list_next(element2)) { const cfg_obj_t *typeobj; isc_textregion_t r; INSIST(i < n); typeobj = cfg_listelt_value(element2); str = cfg_obj_asstring(typeobj); DE_CONST(str, r.base); r.length = strlen(str); result = dns_rdatatype_fromtext(&types[i++], &r); if (result != ISC_R_SUCCESS) { cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR, "'%s' is not a valid type", str); isc_mem_put(mctx, types, n * sizeof(dns_rdatatype_t)); goto cleanup; } } INSIST(i == n); result = dns_ssutable_addrule(table, grant, dns_fixedname_name(&fident), mtype, dns_fixedname_name(&fname), n, types); if (types != NULL) isc_mem_put(mctx, types, n * sizeof(dns_rdatatype_t)); if (result != ISC_R_SUCCESS) { goto cleanup; } } /* * If "update-policy local;" and a session key exists, * then use the default policy, which is equivalent to: * update-policy { grant <session-keyname> zonesub any; }; */ if (autoddns) { dns_rdatatype_t any = dns_rdatatype_any; if (ns_g_server->session_keyname == NULL) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "failed to enable auto DDNS policy " "for zone %s: session key not found", zname); result = ISC_R_NOTFOUND; goto cleanup; } result = dns_ssutable_addrule(table, true, ns_g_server->session_keyname, DNS_SSUMATCHTYPE_LOCAL, dns_zone_getorigin(zone), 1, &any); if (result != ISC_R_SUCCESS) goto cleanup; } result = ISC_R_SUCCESS; dns_zone_setssutable(zone, table); cleanup: dns_ssutable_detach(&table); return (result); }
CWE-269
6
0
_dbus_listen_systemd_sockets (int **fds, DBusError *error) { int r, n; unsigned fd; int *new_fds; _DBUS_ASSERT_ERROR_IS_CLEAR (error); n = sd_listen_fds (TRUE); if (n < 0) { dbus_set_error (error, _dbus_error_from_errno (-n), "Failed to acquire systemd socket: %s", _dbus_strerror (-n)); return -1; } if (n <= 0) { dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS, "No socket received."); return -1; } for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++) { r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1); if (r < 0) { dbus_set_error (error, _dbus_error_from_errno (-r), "Failed to verify systemd socket type: %s", _dbus_strerror (-r)); return -1; } if (!r) { dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS, "Passed socket has wrong type."); return -1; } } /* OK, the file descriptors are all good, so let's take posession of them then. */ new_fds = dbus_new (int, n); if (!new_fds) { dbus_set_error (error, DBUS_ERROR_NO_MEMORY, "Failed to allocate file handle array."); goto fail; } for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++) { if (!_dbus_set_local_creds (fd, TRUE)) { dbus_set_error (error, _dbus_error_from_errno (errno), "Failed to enable LOCAL_CREDS on systemd socket: %s", _dbus_strerror (errno)); goto fail; } if (!_dbus_set_fd_nonblocking (fd, error)) { _DBUS_ASSERT_ERROR_IS_SET (error); goto fail; } new_fds[fd - SD_LISTEN_FDS_START] = fd; } *fds = new_fds; return n; fail: for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++) { _dbus_close (fd, NULL); } dbus_free (new_fds); return -1; }
none
24
1
walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); }
CWE-125
1
0
void CairoImageOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap) { cairo_t *cr; cairo_surface_t *surface; double x1, y1, x2, y2; double *ctm; double mat[6]; CairoImage *image; ctm = state->getCTM(); mat[0] = ctm[0]; mat[1] = ctm[1]; mat[2] = -ctm[2]; mat[3] = -ctm[3]; mat[4] = ctm[2] + ctm[4]; mat[5] = ctm[3] + ctm[5]; x1 = mat[4]; y1 = mat[5]; x2 = x1 + width; y2 = y1 + height; image = new CairoImage (x1, y1, x2, y2); saveImage (image); if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) { surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); cr = cairo_create (surface); setCairo (cr); cairo_translate (cr, 0, height); cairo_scale (cr, width, -height); CairoOutputDev::drawSoftMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskColorMap); image->setImage (surface); setCairo (NULL); cairo_surface_destroy (surface); cairo_destroy (cr); } }
none
24
1
init_state(struct posix_acl_state *state, int cnt) { int alloc; memset(state, 0, sizeof(struct posix_acl_state)); state->empty = 1; /* * In the worst case, each individual acl could be for a distinct * named user or group, but we don't no which, so we allocate * enough space for either: */ alloc = sizeof(struct posix_ace_state_array) + cnt*sizeof(struct posix_ace_state); state->users = kzalloc(alloc, GFP_KERNEL); if (!state->users) return -ENOMEM; state->groups = kzalloc(alloc, GFP_KERNEL); if (!state->groups) { kfree(state->users); return -ENOMEM; } return 0; }
CWE-119
0
1
static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; int chan = sa->rc_channel; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } write_lock(&rfcomm_sk_list.lock); if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = chan; sk->sk_state = BT_BOUND; } write_unlock(&rfcomm_sk_list.lock); done: release_sock(sk); return err; }
CWE-476
12
1
int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; }
CWE-119
0
1
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; }
CWE-476
12
0
int ASCII85Stream::lookChar() { int k; Gulong t; if (index >= n) { if (eof) return EOF; index = 0; do { c[0] = str->getChar(); } while (Lexer::isSpace(c[0])); if (c[0] == '~' || c[0] == EOF) { eof = gTrue; n = 0; return EOF; } else if (c[0] == 'z') { b[0] = b[1] = b[2] = b[3] = 0; n = 4; } else { for (k = 1; k < 5; ++k) { do { c[k] = str->getChar(); } while (Lexer::isSpace(c[k])); if (c[k] == '~' || c[k] == EOF) break; } n = k - 1; if (k < 5 && (c[k] == '~' || c[k] == EOF)) { for (++k; k < 5; ++k) c[k] = 0x21 + 84; eof = gTrue; } t = 0; for (k = 0; k < 5; ++k) t = t * 85 + (c[k] - 0x21); for (k = 3; k >= 0; --k) { b[k] = (int)(t & 0xff); t >>= 8; } } } return b[index]; }
none
24
0
NTSTATUS smb1cli_session_protect_session_key(struct smbXcli_session *session) { if (session->smb1.protected_key) { /* already protected */ return NT_STATUS_OK; } if (session->smb1.application_key.length != 16) { return NT_STATUS_INVALID_PARAMETER_MIX; } smb_key_derivation(session->smb1.application_key.data, session->smb1.application_key.length, session->smb1.application_key.data); session->smb1.protected_key = true; return NT_STATUS_OK; }
none
24
0
GfxColorSpace *GfxLabColorSpace::copy() { GfxLabColorSpace *cs; cs = new GfxLabColorSpace(); cs->whiteX = whiteX; cs->whiteY = whiteY; cs->whiteZ = whiteZ; cs->blackX = blackX; cs->blackY = blackY; cs->blackZ = blackZ; cs->aMin = aMin; cs->aMax = aMax; cs->bMin = bMin; cs->bMax = bMax; cs->kr = kr; cs->kg = kg; cs->kb = kb; return cs; }
none
24
0
pdf_drop_cmap(fz_context *ctx, pdf_cmap *cmap) { fz_drop_storable(ctx, &cmap->storable); }
none
24
1
void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } }
CWE-119
0
0
void GfxCalRGBColorSpace::getGray(GfxColor *color, GfxGray *gray) { GfxRGB rgb; #ifdef USE_CMS if (XYZ2DisplayTransform != NULL && displayPixelType == PT_GRAY) { Guchar out[gfxColorMaxComps]; double in[gfxColorMaxComps]; double X, Y, Z; getXYZ(color,&X,&Y,&Z); in[0] = clip01(X); in[1] = clip01(Y); in[2] = clip01(Z); XYZ2DisplayTransform->doTransform(in,out,1); *gray = byteToCol(out[0]); return; } #endif getRGB(color, &rgb); *gray = clip01((GfxColorComp)(0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b + 0.5)); }
none
24
0
static int samldb_rodc_add(struct samldb_ctx *ac) { struct ldb_context *ldb = ldb_module_get_ctx(ac->module); uint32_t krbtgt_number, i_start, i; int ret; char *newpass; struct ldb_val newpass_utf16; /* find a unused msDC-SecondaryKrbTgtNumber */ i_start = generate_random() & 0xFFFF; if (i_start == 0) { i_start = 1; } for (i=i_start; i<=0xFFFF; i++) { if (samldb_krbtgtnumber_available(ac, i)) { krbtgt_number = i; goto found; } } for (i=1; i<i_start; i++) { if (samldb_krbtgtnumber_available(ac, i)) { krbtgt_number = i; goto found; } } ldb_asprintf_errstring(ldb, "%08X: Unable to find available msDS-SecondaryKrbTgtNumber", W_ERROR_V(WERR_NO_SYSTEM_RESOURCES)); return LDB_ERR_OTHER; found: ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber", LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "msDS-SecondaryKrbTgtNumber", krbtgt_number); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u", krbtgt_number); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } newpass = generate_random_password(ac->msg, 128, 255); if (newpass == NULL) { return ldb_operr(ldb); } if (!convert_string_talloc(ac, CH_UNIX, CH_UTF16, newpass, strlen(newpass), (void *)&newpass_utf16.data, &newpass_utf16.length)) { ldb_asprintf_errstring(ldb, "samldb_rodc_add: " "failed to generate UTF16 password from random password"); return LDB_ERR_OPERATIONS_ERROR; } ret = ldb_msg_add_steal_value(ac->msg, "clearTextPassword", &newpass_utf16); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } return samldb_next_step(ac); }
none
24
1
readSampleCountForLineBlock(InputStreamMutex* streamData, DeepScanLineInputFile::Data* data, int lineBlockId) { streamData->is->seekg(data->lineOffsets[lineBlockId]); if (isMultiPart(data->version)) { int partNumber; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, partNumber); if (partNumber != data->partNumber) throw IEX_NAMESPACE::ArgExc("Unexpected part number."); } int minY; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, minY); // // Check the correctness of minY. // if (minY != data->minY + lineBlockId * data->linesInBuffer) throw IEX_NAMESPACE::ArgExc("Unexpected data block y coordinate."); int maxY; maxY = min(minY + data->linesInBuffer - 1, data->maxY); uint64_t sampleCountTableDataSize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, sampleCountTableDataSize); if(sampleCountTableDataSize>static_cast<uint64_t>(data->maxSampleCountTableSize)) { THROW (IEX_NAMESPACE::ArgExc, "Bad sampleCountTableDataSize read from chunk "<< lineBlockId << ": expected " << data->maxSampleCountTableSize << " or less, got "<< sampleCountTableDataSize); } uint64_t packedDataSize; uint64_t unpackedDataSize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, packedDataSize); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, unpackedDataSize); // // We make a check on the data size requirements here. // Whilst we wish to store 64bit sizes on disk, not all the compressors // have been made to work with such data sizes and are still limited to // using signed 32 bit (int) for the data size. As such, this version // insists that we validate that the data size does not exceed the data // type max limit. // @TODO refactor the compressor code to ensure full 64-bit support. // int compressorMaxDataSize = std::numeric_limits<int>::max(); if (sampleCountTableDataSize > uint64_t(compressorMaxDataSize)) { THROW (IEX_NAMESPACE::ArgExc, "This version of the library does not " << "support the allocation of data with size > " << compressorMaxDataSize << " file table size :" << sampleCountTableDataSize << ".\n"); } streamData->is->read(data->sampleCountTableBuffer, static_cast<int>(sampleCountTableDataSize)); const char* readPtr; // // If the sample count table is compressed, we'll uncompress it. // if (sampleCountTableDataSize < static_cast<uint64_t>(data->maxSampleCountTableSize)) { if(!data->sampleCountTableComp) { THROW(IEX_NAMESPACE::ArgExc,"Deep scanline data corrupt at chunk " << lineBlockId << " (sampleCountTableDataSize error)"); } data->sampleCountTableComp->uncompress(data->sampleCountTableBuffer, static_cast<int>(sampleCountTableDataSize), minY, readPtr); } else readPtr = data->sampleCountTableBuffer; char* base = data->sampleCountSliceBase; int xStride = data->sampleCountXStride; int yStride = data->sampleCountYStride; // total number of samples in block: used to check samplecount table doesn't // reference more data than exists size_t cumulative_total_samples=0; for (int y = minY; y <= maxY; y++) { int yInDataWindow = y - data->minY; data->lineSampleCount[yInDataWindow] = 0; int lastAccumulatedCount = 0; for (int x = data->minX; x <= data->maxX; x++) { int accumulatedCount, count; // // Read the sample count for pixel (x, y). // Xdr::read <CharPtrIO> (readPtr, accumulatedCount); // sample count table should always contain monotonically // increasing values. if (accumulatedCount < lastAccumulatedCount) { THROW(IEX_NAMESPACE::ArgExc,"Deep scanline sampleCount data corrupt at chunk " << lineBlockId << " (negative sample count detected)"); } count = accumulatedCount - lastAccumulatedCount; lastAccumulatedCount = accumulatedCount; // // Store the data in both internal and external data structure. // data->sampleCount[yInDataWindow][x - data->minX] = count; data->lineSampleCount[yInDataWindow] += count; sampleCount(base, xStride, yStride, x, y) = count; } cumulative_total_samples+=data->lineSampleCount[yInDataWindow]; if(cumulative_total_samples*data->combinedSampleSize > unpackedDataSize) { THROW(IEX_NAMESPACE::ArgExc,"Deep scanline sampleCount data corrupt at chunk " << lineBlockId << ": pixel data only contains " << unpackedDataSize << " bytes of data but table references at least " << cumulative_total_samples*data->combinedSampleSize << " bytes of sample data" ); } data->gotSampleCount[y - data->minY] = true; } }
CWE-787
16
1
static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = ""; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = ""; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0); sdb_num_set (sdb_version, "idx", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, "file_name", s, 0); free (s); } sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0); vstart += entry->vn_aux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, "idx", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, "name", name, 0); } sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), "vernaux%d", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf ("Invalid vn_next\n"); break; } i += entry->vn_next; snprintf (key, sizeof (key), "version%d", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }
CWE-125
1
1
f_assert_fails(typval_T *argvars, typval_T *rettv) { char_u *cmd; garray_T ga; int save_trylevel = trylevel; int called_emsg_before = called_emsg; char *wrong_arg_msg = NULL; if (check_for_string_or_number_arg(argvars, 0) == FAIL || check_for_opt_string_or_list_arg(argvars, 1) == FAIL || (argvars[1].v_type != VAR_UNKNOWN && (argvars[2].v_type != VAR_UNKNOWN && (check_for_opt_number_arg(argvars, 3) == FAIL || (argvars[3].v_type != VAR_UNKNOWN && check_for_opt_string_arg(argvars, 4) == FAIL))))) return; cmd = tv_get_string_chk(&argvars[0]); // trylevel must be zero for a ":throw" command to be considered failed trylevel = 0; suppress_errthrow = TRUE; in_assert_fails = TRUE; do_cmdline_cmd(cmd); if (called_emsg == called_emsg_before) { prepare_assert_error(&ga); ga_concat(&ga, (char_u *)"command did not fail: "); assert_append_cmd_or_arg(&ga, argvars, cmd); assert_error(&ga); ga_clear(&ga); rettv->vval.v_number = 1; } else if (argvars[1].v_type != VAR_UNKNOWN) { char_u buf[NUMBUFLEN]; char_u *expected; char_u *expected_str = NULL; int error_found = FALSE; int error_found_index = 1; char_u *actual = emsg_assert_fails_msg == NULL ? (char_u *)"[unknown]" : emsg_assert_fails_msg; if (argvars[1].v_type == VAR_STRING) { expected = tv_get_string_buf_chk(&argvars[1], buf); error_found = expected == NULL || strstr((char *)actual, (char *)expected) == NULL; } else if (argvars[1].v_type == VAR_LIST) { list_T *list = argvars[1].vval.v_list; typval_T *tv; if (list == NULL || list->lv_len < 1 || list->lv_len > 2) { wrong_arg_msg = e_assert_fails_second_arg; goto theend; } CHECK_LIST_MATERIALIZE(list); tv = &list->lv_first->li_tv; expected = tv_get_string_buf_chk(tv, buf); if (!pattern_match(expected, actual, FALSE)) { error_found = TRUE; expected_str = expected; } else if (list->lv_len == 2) { tv = &list->lv_u.mat.lv_last->li_tv; actual = get_vim_var_str(VV_ERRMSG); expected = tv_get_string_buf_chk(tv, buf); if (!pattern_match(expected, actual, FALSE)) { error_found = TRUE; expected_str = expected; } } } else { wrong_arg_msg = e_assert_fails_second_arg; goto theend; } if (!error_found && argvars[2].v_type != VAR_UNKNOWN && argvars[3].v_type != VAR_UNKNOWN) { if (argvars[3].v_type != VAR_NUMBER) { wrong_arg_msg = e_assert_fails_fourth_argument; goto theend; } else if (argvars[3].vval.v_number >= 0 && argvars[3].vval.v_number != emsg_assert_fails_lnum) { error_found = TRUE; error_found_index = 3; } if (!error_found && argvars[4].v_type != VAR_UNKNOWN) { if (argvars[4].v_type != VAR_STRING) { wrong_arg_msg = e_assert_fails_fifth_argument; goto theend; } else if (argvars[4].vval.v_string != NULL && !pattern_match(argvars[4].vval.v_string, emsg_assert_fails_context, FALSE)) { error_found = TRUE; error_found_index = 4; } } } if (error_found) { typval_T actual_tv; prepare_assert_error(&ga); if (error_found_index == 3) { actual_tv.v_type = VAR_NUMBER; actual_tv.vval.v_number = emsg_assert_fails_lnum; } else if (error_found_index == 4) { actual_tv.v_type = VAR_STRING; actual_tv.vval.v_string = emsg_assert_fails_context; } else { actual_tv.v_type = VAR_STRING; actual_tv.vval.v_string = actual; } fill_assert_error(&ga, &argvars[2], expected_str, &argvars[error_found_index], &actual_tv, ASSERT_OTHER); ga_concat(&ga, (char_u *)": "); assert_append_cmd_or_arg(&ga, argvars, cmd); assert_error(&ga); ga_clear(&ga); rettv->vval.v_number = 1; } } theend: trylevel = save_trylevel; suppress_errthrow = FALSE; in_assert_fails = FALSE; did_emsg = FALSE; got_int = FALSE; msg_col = 0; need_wait_return = FALSE; emsg_on_display = FALSE; msg_scrolled = 0; lines_left = Rows; VIM_CLEAR(emsg_assert_fails_msg); set_vim_var_string(VV_ERRMSG, NULL, 0); if (wrong_arg_msg != NULL) emsg(_(wrong_arg_msg)); }
CWE-416
10
1
static size_t php_bz2iop_read(php_stream *stream, char *buf, size_t count TSRMLS_DC) { struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *) stream->abstract; size_t ret; ret = BZ2_bzread(self->bz_file, buf, count); if (ret == 0) { stream->eof = 1; } return ret; }
CWE-787
16
1
static int xwd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame *p = data; const uint8_t *buf = avpkt->data; int i, ret, buf_size = avpkt->size; uint32_t version, header_size, vclass, ncolors; uint32_t xoffset, be, bpp, lsize, rsize; uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) return AVERROR_INVALIDDATA; bytestream2_init(&gb, buf, buf_size); header_size = bytestream2_get_be32u(&gb); version = bytestream2_get_be32u(&gb); if (version != XWD_VERSION) { av_log(avctx, AV_LOG_ERROR, "unsupported version\n"); return AVERROR_INVALIDDATA; } if (buf_size < header_size || header_size < XWD_HEADER_SIZE) { av_log(avctx, AV_LOG_ERROR, "invalid header size\n"); return AVERROR_INVALIDDATA; } pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); avctx->width = bytestream2_get_be32u(&gb); avctx->height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); bitorder = bytestream2_get_be32u(&gb); bpad = bytestream2_get_be32u(&gb); bpp = bytestream2_get_be32u(&gb); lsize = bytestream2_get_be32u(&gb); vclass = bytestream2_get_be32u(&gb); rgb[0] = bytestream2_get_be32u(&gb); rgb[1] = bytestream2_get_be32u(&gb); rgb[2] = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, 8); ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); av_log(avctx, AV_LOG_DEBUG, "pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n", pixformat, pixdepth, bunit, bitorder, bpad); av_log(avctx, AV_LOG_DEBUG, "vclass %"PRIu32", ncolors %"PRIu32", bpp %"PRIu32", be %"PRIu32", lsize %"PRIu32", xoffset %"PRIu32"\n", vclass, ncolors, bpp, be, lsize, xoffset); av_log(avctx, AV_LOG_DEBUG, "red %0"PRIx32", green %0"PRIx32", blue %0"PRIx32"\n", rgb[0], rgb[1], rgb[2]); if (pixformat > XWD_Z_PIXMAP) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap format\n"); return AVERROR_INVALIDDATA; } if (pixdepth == 0 || pixdepth > 32) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap depth\n"); return AVERROR_INVALIDDATA; } if (xoffset) { avpriv_request_sample(avctx, "xoffset %"PRIu32"", xoffset); return AVERROR_PATCHWELCOME; } if (be > 1) { av_log(avctx, AV_LOG_ERROR, "invalid byte order\n"); return AVERROR_INVALIDDATA; } if (bitorder > 1) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap bit order\n"); return AVERROR_INVALIDDATA; } if (bunit != 8 && bunit != 16 && bunit != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap unit\n"); return AVERROR_INVALIDDATA; } if (bpad != 8 && bpad != 16 && bpad != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap scan-line pad\n"); return AVERROR_INVALIDDATA; } if (bpp == 0 || bpp > 32) { av_log(avctx, AV_LOG_ERROR, "invalid bits per pixel\n"); return AVERROR_INVALIDDATA; } if (ncolors > 256) { av_log(avctx, AV_LOG_ERROR, "invalid number of entries in colormap\n"); return AVERROR_INVALIDDATA; } if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0) return ret; rsize = FFALIGN(avctx->width * bpp, bpad) / 8; if (lsize < rsize) { av_log(avctx, AV_LOG_ERROR, "invalid bytes per scan-line\n"); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) { av_log(avctx, AV_LOG_ERROR, "input buffer too small\n"); return AVERROR_INVALIDDATA; } if (pixformat != XWD_Z_PIXMAP) { avpriv_report_missing_feature(avctx, "Pixmap format %"PRIu32, pixformat); return AVERROR_PATCHWELCOME; } avctx->pix_fmt = AV_PIX_FMT_NONE; switch (vclass) { case XWD_STATIC_GRAY: case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; if (pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; } else if (pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; case XWD_STATIC_COLOR: case XWD_PSEUDO_COLOR: if (bpp == 8) avctx->pix_fmt = AV_PIX_FMT_PAL8; break; case XWD_TRUE_COLOR: case XWD_DIRECT_COLOR: if (bpp != 16 && bpp != 24 && bpp != 32) return AVERROR_INVALIDDATA; if (bpp == 16 && pixdepth == 15) { if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE; else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00) avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE; } else if (bpp == 16 && pixdepth == 16) { if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE; else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800) avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE; } else if (bpp == 24) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24; } else if (bpp == 32) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA; } bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE); break; default: av_log(avctx, AV_LOG_ERROR, "invalid visual class\n"); return AVERROR_INVALIDDATA; } if (avctx->pix_fmt == AV_PIX_FMT_NONE) { avpriv_request_sample(avctx, "Unknown file: bpp %"PRIu32", pixdepth %"PRIu32", vclass %"PRIu32"", bpp, pixdepth, vclass); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { uint32_t *dst = (uint32_t *)p->data[1]; uint8_t red, green, blue; for (i = 0; i < ncolors; i++) { bytestream2_skipu(&gb, 4); // skip colormap entry number red = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); green = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); blue = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 3); // skip bitmask flag and padding dst[i] = red << 16 | green << 8 | blue; } } ptr = p->data[0]; for (i = 0; i < avctx->height; i++) { bytestream2_get_bufferu(&gb, ptr, rsize); bytestream2_skipu(&gb, lsize - rsize); ptr += p->linesize[0]; } *got_frame = 1; return buf_size; }
CWE-119
0
1
void read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; unsigned fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); }
CWE-119
0
1
static int nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh, char **target) { uint32_t data[1024]; uint32_t *p; uint32_t len; struct packet *nfs_packet; /* * struct READLINK3args { * nfs_fh3 symlink; * }; * * struct READLINK3resok { * post_op_attr symlink_attributes; * nfspath3 data; * }; * * struct READLINK3resfail { * post_op_attr symlink_attributes; * } * * union READLINK3res switch (nfsstat3 status) { * case NFS3_OK: * READLINK3resok resok; * default: * READLINK3resfail resfail; * }; */ p = &(data[0]); p = rpc_add_credentials(p); p = nfs_add_fh3(p, fh); len = p - &(data[0]); nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len); if (IS_ERR(nfs_packet)) return PTR_ERR(nfs_packet); p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4; p = nfs_read_post_op_attr(p, NULL); len = ntoh32(net_read_uint32(p)); /* new path length */ p++; *target = xzalloc(len + 1); return 0; }
CWE-119
0
0
_dbus_append_user_from_current_process (DBusString *str) { dbus_bool_t retval = FALSE; char *sid = NULL; if (!_dbus_getsid(&sid)) return FALSE; retval = _dbus_string_append (str,sid); LocalFree(sid); return retval; }
none
24
1
static void xgmac_enet_send(XgmacState *s) { struct desc bd; int frame_size; int len; uint8_t frame[8192]; uint8_t *ptr; ptr = frame; frame_size = 0; while (1) { xgmac_read_desc(s, &bd, 0); if ((bd.ctl_stat & 0x80000000) == 0) { /* Run out of descriptors to transmit. */ break; } len = (bd.buffer1_size & 0xfff) + (bd.buffer2_size & 0xfff); if ((bd.buffer1_size & 0xfff) > 2048) { DEBUGF_BRK("qemu:%s:ERROR...ERROR...ERROR... -- " "xgmac buffer 1 len on send > 2048 (0x%x)\n", __func__, bd.buffer1_size & 0xfff); } if ((bd.buffer2_size & 0xfff) != 0) { DEBUGF_BRK("qemu:%s:ERROR...ERROR...ERROR... -- " "xgmac buffer 2 len on send != 0 (0x%x)\n", __func__, bd.buffer2_size & 0xfff); } if (len >= sizeof(frame)) { DEBUGF_BRK("qemu:%s: buffer overflow %d read into %zu " "buffer\n" , __func__, len, sizeof(frame)); DEBUGF_BRK("qemu:%s: buffer1.size=%d; buffer2.size=%d\n", __func__, bd.buffer1_size, bd.buffer2_size); } cpu_physical_memory_read(bd.buffer1_addr, ptr, len); ptr += len; frame_size += len; if (bd.ctl_stat & 0x20000000) { /* Last buffer in frame. */ qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->regs[DMA_STATUS] |= DMA_STATUS_TI | DMA_STATUS_NIS; } bd.ctl_stat &= ~0x80000000; /* Write back the modified descriptor. */ xgmac_write_desc(s, &bd, 0); } }
CWE-787
16
1
int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) { op->len = 1; op->op = buf[0]; if (op->op > 0xbf) return 1; // add support for extension opcodes (SIMD + atomics) WasmOpDef *opdef = &opcodes[op->op]; switch (op->op) { case WASM_OP_TRAP: case WASM_OP_NOP: case WASM_OP_ELSE: case WASM_OP_RETURN: case WASM_OP_DROP: case WASM_OP_SELECT: case WASM_OP_I32EQZ: case WASM_OP_I32EQ: case WASM_OP_I32NE: case WASM_OP_I32LTS: case WASM_OP_I32LTU: case WASM_OP_I32GTS: case WASM_OP_I32GTU: case WASM_OP_I32LES: case WASM_OP_I32LEU: case WASM_OP_I32GES: case WASM_OP_I32GEU: case WASM_OP_I64EQZ: case WASM_OP_I64EQ: case WASM_OP_I64NE: case WASM_OP_I64LTS: case WASM_OP_I64LTU: case WASM_OP_I64GTS: case WASM_OP_I64GTU: case WASM_OP_I64LES: case WASM_OP_I64LEU: case WASM_OP_I64GES: case WASM_OP_I64GEU: case WASM_OP_F32EQ: case WASM_OP_F32NE: case WASM_OP_F32LT: case WASM_OP_F32GT: case WASM_OP_F32LE: case WASM_OP_F32GE: case WASM_OP_F64EQ: case WASM_OP_F64NE: case WASM_OP_F64LT: case WASM_OP_F64GT: case WASM_OP_F64LE: case WASM_OP_F64GE: case WASM_OP_I32CLZ: case WASM_OP_I32CTZ: case WASM_OP_I32POPCNT: case WASM_OP_I32ADD: case WASM_OP_I32SUB: case WASM_OP_I32MUL: case WASM_OP_I32DIVS: case WASM_OP_I32DIVU: case WASM_OP_I32REMS: case WASM_OP_I32REMU: case WASM_OP_I32AND: case WASM_OP_I32OR: case WASM_OP_I32XOR: case WASM_OP_I32SHL: case WASM_OP_I32SHRS: case WASM_OP_I32SHRU: case WASM_OP_I32ROTL: case WASM_OP_I32ROTR: case WASM_OP_I64CLZ: case WASM_OP_I64CTZ: case WASM_OP_I64POPCNT: case WASM_OP_I64ADD: case WASM_OP_I64SUB: case WASM_OP_I64MUL: case WASM_OP_I64DIVS: case WASM_OP_I64DIVU: case WASM_OP_I64REMS: case WASM_OP_I64REMU: case WASM_OP_I64AND: case WASM_OP_I64OR: case WASM_OP_I64XOR: case WASM_OP_I64SHL: case WASM_OP_I64SHRS: case WASM_OP_I64SHRU: case WASM_OP_I64ROTL: case WASM_OP_I64ROTR: case WASM_OP_F32ABS: case WASM_OP_F32NEG: case WASM_OP_F32CEIL: case WASM_OP_F32FLOOR: case WASM_OP_F32TRUNC: case WASM_OP_F32NEAREST: case WASM_OP_F32SQRT: case WASM_OP_F32ADD: case WASM_OP_F32SUB: case WASM_OP_F32MUL: case WASM_OP_F32DIV: case WASM_OP_F32MIN: case WASM_OP_F32MAX: case WASM_OP_F32COPYSIGN: case WASM_OP_F64ABS: case WASM_OP_F64NEG: case WASM_OP_F64CEIL: case WASM_OP_F64FLOOR: case WASM_OP_F64TRUNC: case WASM_OP_F64NEAREST: case WASM_OP_F64SQRT: case WASM_OP_F64ADD: case WASM_OP_F64SUB: case WASM_OP_F64MUL: case WASM_OP_F64DIV: case WASM_OP_F64MIN: case WASM_OP_F64MAX: case WASM_OP_F64COPYSIGN: case WASM_OP_I32WRAPI64: case WASM_OP_I32TRUNCSF32: case WASM_OP_I32TRUNCUF32: case WASM_OP_I32TRUNCSF64: case WASM_OP_I32TRUNCUF64: case WASM_OP_I64EXTENDSI32: case WASM_OP_I64EXTENDUI32: case WASM_OP_I64TRUNCSF32: case WASM_OP_I64TRUNCUF32: case WASM_OP_I64TRUNCSF64: case WASM_OP_I64TRUNCUF64: case WASM_OP_F32CONVERTSI32: case WASM_OP_F32CONVERTUI32: case WASM_OP_F32CONVERTSI64: case WASM_OP_F32CONVERTUI64: case WASM_OP_F32DEMOTEF64: case WASM_OP_F64CONVERTSI32: case WASM_OP_F64CONVERTUI32: case WASM_OP_F64CONVERTSI64: case WASM_OP_F64CONVERTUI64: case WASM_OP_F64PROMOTEF32: case WASM_OP_I32REINTERPRETF32: case WASM_OP_I64REINTERPRETF64: case WASM_OP_F32REINTERPRETI32: case WASM_OP_F64REINTERPRETI64: case WASM_OP_END: { snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt); } break; case WASM_OP_BLOCK: case WASM_OP_LOOP: case WASM_OP_IF: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; switch (0x80 - val) { case R_BIN_WASM_VALUETYPE_EMPTY: snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i32: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i64: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f32: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f64: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt); break; default: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt); break; } op->len += n; } break; case WASM_OP_BR: case WASM_OP_BRIF: case WASM_OP_CALL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val); op->len += n; } break; case WASM_OP_BRTABLE: { ut32 count = 0, *table = NULL, def = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count); if (!(n > 0 && n < buf_len)) goto err; if (!(table = calloc (count, sizeof (ut32)))) goto err; int i = 0; op->len += n; for (i = 0; i < count; i++) { n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]); if (!(op->len + n <= buf_len)) goto beach; op->len += n; } n = read_u32_leb128 (buf + op->len, buf + buf_len, &def); if (!(n > 0 && n + op->len < buf_len)) goto beach; op->len += n; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count); for (i = 0; i < count && strlen (op->txt) < R_ASM_BUFSIZE; i++) { snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d ", table[i]); } snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def); free (table); break; beach: free (table); goto err; } break; case WASM_OP_CALLINDIRECT: { ut32 val = 0, reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved); if (!(n == 1 && op->len + n <= buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved); op->len += n; } break; case WASM_OP_GETLOCAL: case WASM_OP_SETLOCAL: case WASM_OP_TEELOCAL: case WASM_OP_GETGLOBAL: case WASM_OP_SETGLOBAL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val); op->len += n; } break; case WASM_OP_I32LOAD: case WASM_OP_I64LOAD: case WASM_OP_F32LOAD: case WASM_OP_F64LOAD: case WASM_OP_I32LOAD8S: case WASM_OP_I32LOAD8U: case WASM_OP_I32LOAD16S: case WASM_OP_I32LOAD16U: case WASM_OP_I64LOAD8S: case WASM_OP_I64LOAD8U: case WASM_OP_I64LOAD16S: case WASM_OP_I64LOAD16U: case WASM_OP_I64LOAD32S: case WASM_OP_I64LOAD32U: case WASM_OP_I32STORE: case WASM_OP_I64STORE: case WASM_OP_F32STORE: case WASM_OP_F64STORE: case WASM_OP_I32STORE8: case WASM_OP_I32STORE16: case WASM_OP_I64STORE8: case WASM_OP_I64STORE16: case WASM_OP_I64STORE32: { ut32 flag = 0, offset = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset); if (!(n > 0 && op->len + n <= buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset); op->len += n; } break; case WASM_OP_CURRENTMEMORY: case WASM_OP_GROWMEMORY: { ut32 reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved); if (!(n == 1 && n < buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved); op->len += n; } break; case WASM_OP_I32CONST: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val); op->len += n; } break; case WASM_OP_I64CONST: { st64 val = 0; size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val); op->len += n; } break; case WASM_OP_F32CONST: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d); op->len += n; } break; case WASM_OP_F64CONST: { ut64 val = 0; size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d); op->len += n; } break; default: goto err; } return op->len; err: op->len = 1; snprintf (op->txt, R_ASM_BUFSIZE, "invalid"); return op->len; }
CWE-125
1
0
void CairoOutputDev::beginTransparencyGroup(GfxState * /*state*/, double * /*bbox*/, GfxColorSpace * blendingColorSpace, GBool /*isolated*/, GBool knockout, GBool forSoftMask) { /* push color space */ ColorSpaceStack* css = new ColorSpaceStack; css->cs = blendingColorSpace; css->knockout = knockout; css->next = groupColorSpaceStack; groupColorSpaceStack = css; if (knockout) { knockoutCount++; if (!cairo_shape) { /* create a surface for tracking the shape */ cairo_surface_t *cairo_shape_surface = cairo_surface_create_similar_clip (cairo, CAIRO_CONTENT_ALPHA); cairo_shape = cairo_create (cairo_shape_surface); cairo_surface_destroy (cairo_shape_surface); /* the color doesn't matter as long as it is opaque */ cairo_set_source_rgb (cairo_shape, 0, 0, 0); cairo_matrix_t matrix; cairo_get_matrix (cairo, &matrix); cairo_set_matrix (cairo_shape, &matrix); } else { cairo_reference (cairo_shape); } } if (groupColorSpaceStack->next && groupColorSpaceStack->next->knockout) { /* we need to track the shape */ cairo_push_group (cairo_shape); } if (0 && forSoftMask) cairo_push_group_with_content (cairo, CAIRO_CONTENT_ALPHA); else cairo_push_group (cairo); /* push_group has an implicit cairo_save() */ if (knockout) { /*XXX: let's hope this matches the semantics needed */ cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE); } else { cairo_set_operator(cairo, CAIRO_OPERATOR_OVER); } }
none
24
1
bool GetURLRowForAutocompleteMatch(Profile* profile, const AutocompleteMatch& match, history::URLRow* url_row) { DCHECK(url_row); HistoryService* history_service = profile->GetHistoryService(Profile::EXPLICIT_ACCESS); if (!history_service) return false; history::URLDatabase* url_db = history_service->InMemoryDatabase(); return url_db && (url_db->GetRowForURL(match.destination_url, url_row) != 0); }
CWE-20
3
1
static void cli_session_setup_gensec_remote_done(struct tevent_req *subreq) { struct tevent_req *req = tevent_req_callback_data(subreq, struct tevent_req); struct cli_session_setup_gensec_state *state = tevent_req_data(req, struct cli_session_setup_gensec_state); NTSTATUS status; TALLOC_FREE(state->inbuf); TALLOC_FREE(state->recv_iov); status = cli_sesssetup_blob_recv(subreq, state, &state->blob_in, &state->inbuf, &state->recv_iov); TALLOC_FREE(subreq); data_blob_free(&state->blob_out); if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { tevent_req_nterror(req, status); return; } if (NT_STATUS_IS_OK(status)) { struct smbXcli_session *session = NULL; bool is_guest = false; if (smbXcli_conn_protocol(state->cli->conn) >= PROTOCOL_SMB2_02) { session = state->cli->smb2.session; } else { session = state->cli->smb1.session; } is_guest = smbXcli_session_is_guest(session); if (is_guest) { /* * We can't finish the gensec handshake, we don't * have a negotiated session key. * * So just pretend we are completely done. */ state->blob_in = data_blob_null; state->local_ready = true; } state->remote_ready = true; } if (state->local_ready && state->remote_ready) { cli_session_setup_gensec_ready(req); return; } cli_session_setup_gensec_local_next(req); }
CWE-94
23
1
tc_dump_action(struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; struct tc_action_ops *a_o; struct tc_action a; int ret = 0; struct tcamsg *t = (struct tcamsg *) NLMSG_DATA(cb->nlh); char *kind = find_dump_kind(cb->nlh); if (kind == NULL) { printk("tc_dump_action: action bad kind\n"); return 0; } a_o = tc_lookup_action_n(kind); if (a_o == NULL) { printk("failed to find %s\n", kind); return 0; } memset(&a, 0, sizeof(struct tc_action)); a.ops = a_o; if (a_o->walk == NULL) { printk("tc_dump_action: %s !capable of dumping table\n", kind); goto rtattr_failure; } nlh = NLMSG_PUT(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, cb->nlh->nlmsg_type, sizeof(*t)); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr *) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); ret = a_o->walk(skb, cb, RTM_GETACTION, &a); if (ret < 0) goto rtattr_failure; if (ret > 0) { x->rta_len = skb->tail - (u8 *) x; ret = skb->len; } else skb_trim(skb, (u8*)x - skb->data); nlh->nlmsg_len = skb->tail - b; if (NETLINK_CB(cb->skb).pid && ret) nlh->nlmsg_flags |= NLM_F_MULTI; module_put(a_o->owner); return skb->len; rtattr_failure: nlmsg_failure: module_put(a_o->owner); skb_trim(skb, b - skb->data); return skb->len; }
CWE-200
4
1
void JPXStream::init() { Object oLen, cspace, smaskInData; if (getDict()) { oLen = getDict()->lookup("Length"); cspace = getDict()->lookup("ColorSpace"); smaskInData = getDict()->lookup("SMaskInData"); } int bufSize = BUFFER_INITIAL_SIZE; if (oLen.isInt()) bufSize = oLen.getInt(); bool indexed = false; if (cspace.isArray() && cspace.arrayGetLength() > 0) { const Object cstype = cspace.arrayGet(0); if (cstype.isName("Indexed")) indexed = true; } priv->smaskInData = 0; if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt(); int length = 0; unsigned char *buf = str->toUnsignedChars(&length, bufSize); priv->init2(OPJ_CODEC_JP2, buf, length, indexed); gfree(buf); if (priv->image) { int numComps = (priv->image) ? priv->image->numcomps : 1; int alpha = 0; if (priv->image) { if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; } else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; } else if (numComps == 2) { numComps = 1; alpha = 1; } else if (numComps > 4) { numComps = 4; alpha = 1; } else { alpha = 0; } } priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h; priv->ncomps = priv->image->numcomps; if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--; for (int component = 0; component < priv->ncomps; component++) { if (priv->image->comps[component].data == nullptr) { close(); break; } const int componentPixels = priv->image->comps[component].w * priv->image->comps[component].h; if (componentPixels != priv->npixels) { error(errSyntaxWarning, -1, "Component {0:d} has different WxH than component 0", component); close(); break; } unsigned char *cdata = (unsigned char *)priv->image->comps[component].data; int adjust = 0; int depth = priv->image->comps[component].prec; if (priv->image->comps[component].prec > 8) adjust = priv->image->comps[component].prec - 8; int sgndcorr = 0; if (priv->image->comps[component].sgnd) sgndcorr = 1 << (priv->image->comps[0].prec - 1); for (int i = 0; i < priv->npixels; i++) { int r = priv->image->comps[component].data[i]; *(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed); } } } else { priv->npixels = 0; } priv->counter = 0; priv->ccounter = 0; priv->inited = true; }
CWE-190
2
1
static int build_audio_procunit(struct mixer_build *state, int unitid, void *raw_desc, struct procunit_info *list, char *name) { struct uac_processing_unit_descriptor *desc = raw_desc; int num_ins = desc->bNrInPins; struct usb_mixer_elem_info *cval; struct snd_kcontrol *kctl; int i, err, nameid, type, len; struct procunit_info *info; struct procunit_value_info *valinfo; const struct usbmix_name_map *map; static struct procunit_value_info default_value_info[] = { { 0x01, "Switch", USB_MIXER_BOOLEAN }, { 0 } }; static struct procunit_info default_info = { 0, NULL, default_value_info }; if (desc->bLength < 13 || desc->bLength < 13 + num_ins || desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) { usb_audio_err(state->chip, "invalid %s descriptor (id %d)\n", name, unitid); return -EINVAL; } for (i = 0; i < num_ins; i++) { err = parse_audio_unit(state, desc->baSourceID[i]); if (err < 0) return err; } type = le16_to_cpu(desc->wProcessType); for (info = list; info && info->type; info++) if (info->type == type) break; if (!info || !info->type) info = &default_info; for (valinfo = info->values; valinfo->control; valinfo++) { __u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol); if (state->mixer->protocol == UAC_VERSION_1) { if (!(controls[valinfo->control / 8] & (1 << ((valinfo->control % 8) - 1)))) continue; } else { /* UAC_VERSION_2/3 */ if (!uac_v2v3_control_is_readable(controls[valinfo->control / 8], valinfo->control)) continue; } map = find_map(state->map, unitid, valinfo->control); if (check_ignored_ctl(map)) continue; cval = kzalloc(sizeof(*cval), GFP_KERNEL); if (!cval) return -ENOMEM; snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid); cval->control = valinfo->control; cval->val_type = valinfo->val_type; cval->channels = 1; if (state->mixer->protocol > UAC_VERSION_1 && !uac_v2v3_control_is_writeable(controls[valinfo->control / 8], valinfo->control)) cval->master_readonly = 1; /* get min/max values */ switch (type) { case UAC_PROCESS_UP_DOWNMIX: { bool mode_sel = false; switch (state->mixer->protocol) { case UAC_VERSION_1: case UAC_VERSION_2: default: if (cval->control == UAC_UD_MODE_SELECT) mode_sel = true; break; case UAC_VERSION_3: if (cval->control == UAC3_UD_MODE_SELECT) mode_sel = true; break; } if (mode_sel) { __u8 *control_spec = uac_processing_unit_specific(desc, state->mixer->protocol); cval->min = 1; cval->max = control_spec[0]; cval->res = 1; cval->initialized = 1; break; } get_min_max(cval, valinfo->min_value); break; } case USB_XU_CLOCK_RATE: /* * E-Mu USB 0404/0202/TrackerPre/0204 * samplerate control quirk */ cval->min = 0; cval->max = 5; cval->res = 1; cval->initialized = 1; break; default: get_min_max(cval, valinfo->min_value); break; } kctl = snd_ctl_new1(&mixer_procunit_ctl, cval); if (!kctl) { kfree(cval); return -ENOMEM; } kctl->private_free = snd_usb_mixer_elem_free; if (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name))) { /* nothing */ ; } else if (info->name) { strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name)); } else { nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol); len = 0; if (nameid) len = snd_usb_copy_string_desc(state->chip, nameid, kctl->id.name, sizeof(kctl->id.name)); if (!len) strlcpy(kctl->id.name, name, sizeof(kctl->id.name)); } append_ctl_name(kctl, " "); append_ctl_name(kctl, valinfo->suffix); usb_audio_dbg(state->chip, "[%d] PU [%s] ch = %d, val = %d/%d\n", cval->head.id, kctl->id.name, cval->channels, cval->min, cval->max); err = snd_usb_mixer_add_control(&cval->head, kctl); if (err < 0) return err; } return 0; }
CWE-125
1
1
static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MaxTextExtent], text[MaxTextExtent]; Image *image; IndexPacket *indexes; long x_offset, y_offset; MagickBooleanType status; MagickPixelPacket pixel; QuantumAny range; register ssize_t i, x; register PixelPacket *q; ssize_t count, type, y; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) if (depth >= 64) break; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->matte=MagickFalse; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->matte=MagickTrue; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->colorspace=(ColorspaceType) type; (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); (void) SetImageBackgroundColor(image); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, index, opacity, red; red=0.0; green=0.0; blue=0.0; index=0.0; opacity=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->matte != MagickFalse) { (void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&opacity); green=red; blue=red; break; } (void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->matte != MagickFalse) { (void) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&index,&opacity); break; } (void) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&index); break; } default: { if (image->matte != MagickFalse) { (void) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&opacity); break; } (void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; index*=0.01*range; opacity*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5), range); pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5), range); pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5), range); pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5), range); pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+ 0.5),range); q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1, exception); if (q == (PixelPacket *) NULL) continue; SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->colorspace == CMYKColorspace) { indexes=GetAuthenticIndexQueue(image); SetPixelIndex(indexes,pixel.index); } if (image->matte != MagickFalse) SetPixelAlpha(q,pixel.opacity); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
CWE-190
2
1
void smp_proc_master_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; tBTM_LE_PENC_KEYS le_key; SMP_TRACE_DEBUG("%s", __func__); smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true); STREAM_TO_UINT16(le_key.ediv, p); STREAM_TO_ARRAY(le_key.rand, p, BT_OCTET8_LEN); /* store the encryption keys from peer device */ memcpy(le_key.ltk, p_cb->ltk, BT_OCTET16_LEN); le_key.sec_level = p_cb->sec_level; le_key.key_size = p_cb->loc_enc_size; if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, (tBTM_LE_KEY_VALUE*)&le_key, true); smp_key_distribution(p_cb, NULL); }
CWE-200
4
1
static void vmxnet3_activate_device(VMXNET3State *s) { int i; static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1; hwaddr qdescr_table_pa; uint64_t pa; uint32_t size; /* Verify configuration consistency */ if (!vmxnet3_verify_driver_magic(s->drv_shmem)) { VMW_ERPRN("Device configuration received from driver is invalid"); return; } vmxnet3_adjust_by_guest_type(s); vmxnet3_update_features(s); vmxnet3_update_pm_state(s); vmxnet3_setup_rx_filtering(s); /* Cache fields from shared memory */ s->mtu = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.misc.mtu); VMW_CFPRN("MTU is %u", s->mtu); s->max_rx_frags = VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); if (s->max_rx_frags == 0) { s->max_rx_frags = 1; } VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags); s->event_int_idx = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); assert(vmxnet3_verify_intx(s, s->event_int_idx)); VMW_CFPRN("Events interrupt line is %u", s->event_int_idx); s->auto_int_masking = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking); s->txq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); s->rxq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa); /* * Worst-case scenario is a packet that holds all TX rings space so * we calculate total size of all TX rings for max TX fragments number */ s->max_tx_frags = 0; /* TX queues */ for (i = 0; i < s->txq_num; i++) { hwaddr qdescr_pa = qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc); /* Read interrupt number for this TX queue */ s->txq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qdescr_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx)); VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx); /* Read rings memory locations for TX queues */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, sizeof(struct Vmxnet3_TxDesc), false); VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring); s->max_tx_frags += size; /* TXC ring */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_TxCompDesc), true); VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring); s->txq_descr[i].tx_stats_pa = qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); memset(&s->txq_descr[i].txq_stats, 0, sizeof(s->txq_descr[i].txq_stats)); /* Fill device-managed parameters for queues */ VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, ctrl.txThreshold, VMXNET3_DEF_TX_THRESHOLD); } /* Preallocate TX packet wrapper */ VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); /* Read rings memory locations for RX queues */ for (i = 0; i < s->rxq_num; i++) { int j; hwaddr qd_pa = qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + i * sizeof(struct Vmxnet3_RxQueueDesc); /* Read interrupt number for this RX queue */ s->rxq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx); /* Read rings memory locations */ for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { /* RX rings */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, sizeof(struct Vmxnet3_RxDesc), false); VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d", i, j, pa, size); } /* RXC ring */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_RxCompDesc), true); VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size); s->rxq_descr[i].rx_stats_pa = qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); memset(&s->rxq_descr[i].rxq_stats, 0, sizeof(s->rxq_descr[i].rxq_stats)); } vmxnet3_validate_interrupts(s); /* Make sure everything is in place before device activation */ smp_wmb(); vmxnet3_reset_mac(s); s->device_active = true; }
CWE-20
3
1
static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; }
CWE-125
1
0
SPICE_GNUC_VISIBLE void spice_server_vm_stop(SpiceServer *s) { RingItem *item; spice_assert(s == reds); reds->vm_running = FALSE; RING_FOREACH(item, &reds->char_devs_states) { SpiceCharDeviceStateItem *st_item; st_item = SPICE_CONTAINEROF(item, SpiceCharDeviceStateItem, link); spice_char_device_stop(st_item->st); } red_dispatcher_on_vm_stop(); }
none
24
1
export_desktop_file (const char *app, const char *branch, const char *arch, GKeyFile *metadata, const char * const *previous_ids, int parent_fd, const char *name, struct stat *stat_buf, char **target, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; glnx_autofd int desktop_fd = -1; g_autofree char *tmpfile_name = g_strdup_printf ("export-desktop-XXXXXX"); g_autoptr(GOutputStream) out_stream = NULL; g_autofree gchar *data = NULL; gsize data_len; g_autofree gchar *new_data = NULL; gsize new_data_len; g_autoptr(GKeyFile) keyfile = NULL; g_autofree gchar *old_exec = NULL; gint old_argc; g_auto(GStrv) old_argv = NULL; g_auto(GStrv) groups = NULL; GString *new_exec = NULL; g_autofree char *escaped_app = maybe_quote (app); g_autofree char *escaped_branch = maybe_quote (branch); g_autofree char *escaped_arch = maybe_quote (arch); int i; if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error)) goto out; if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error)) goto out; keyfile = g_key_file_new (); if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error)) goto out; if (g_str_has_suffix (name, ".service")) { g_autofree gchar *dbus_name = NULL; g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (".service")); dbus_name = g_key_file_get_string (keyfile, "D-BUS Service", "Name", NULL); if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0) { return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED, _("D-Bus service file '%s' has wrong name"), name); } } if (g_str_has_suffix (name, ".desktop")) { gsize length; g_auto(GStrv) tags = g_key_file_get_string_list (metadata, "Application", "tags", &length, NULL); if (tags != NULL) { g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, "X-Flatpak-Tags", (const char * const *) tags, length); } /* Add a marker so consumers can easily find out that this launches a sandbox */ g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, "X-Flatpak", app); /* If the app has been renamed, add its old .desktop filename to * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to * introduce duplicates. */ if (previous_ids != NULL) { const char *X_FLATPAK_RENAMED_FROM = "X-Flatpak-RenamedFrom"; g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, NULL, NULL); g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free); g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal); const char *new_suffix; for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++) { if (!g_hash_table_contains (seen, renamed_from[i])) { gchar *copy = g_strdup (renamed_from[i]); g_hash_table_insert (seen, copy, copy); g_ptr_array_add (merged, g_steal_pointer (&copy)); } } /* If an app was renamed from com.example.Foo to net.example.Bar, and * the new version exports net.example.Bar-suffix.desktop, we assume the * old version exported com.example.Foo-suffix.desktop. * * This assertion is true because * flatpak_name_matches_one_wildcard_prefix() is called on all * exported files before we get here. */ g_assert (g_str_has_prefix (name, app)); /* ".desktop" for the "main" desktop file; something like * "-suffix.desktop" for extra ones. */ new_suffix = name + strlen (app); for (i = 0; previous_ids[i] != NULL; i++) { g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL); if (!g_hash_table_contains (seen, previous_desktop)) { g_hash_table_insert (seen, previous_desktop, previous_desktop); g_ptr_array_add (merged, g_steal_pointer (&previous_desktop)); } } if (merged->len > 0) { g_ptr_array_add (merged, NULL); g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, (const char * const *) merged->pdata, merged->len - 1); } } } groups = g_key_file_get_groups (keyfile, NULL); for (i = 0; groups[i] != NULL; i++) { g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], "X-Flatpak-RunOptions", NULL, NULL); g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts); g_key_file_remove_key (keyfile, groups[i], "X-Flatpak-RunOptions", NULL); g_key_file_remove_key (keyfile, groups[i], "TryExec", NULL); /* Remove this to make sure nothing tries to execute it outside the sandbox*/ g_key_file_remove_key (keyfile, groups[i], "X-GNOME-Bugzilla-ExtraInfoScript", NULL); new_exec = g_string_new (""); g_string_append_printf (new_exec, FLATPAK_BINDIR "/flatpak run --branch=%s --arch=%s", escaped_branch, escaped_arch); if (flatpak_run_args != NULL) g_string_append_printf (new_exec, "%s", flatpak_run_args); old_exec = g_key_file_get_string (keyfile, groups[i], "Exec", NULL); if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1) { int j; g_autofree char *command = maybe_quote (old_argv[0]); g_string_append_printf (new_exec, " --command=%s", command); for (j = 1; j < old_argc; j++) { if (strcasecmp (old_argv[j], "%f") == 0 || strcasecmp (old_argv[j], "%u") == 0) { g_string_append (new_exec, " --file-forwarding"); break; } } g_string_append (new_exec, " "); g_string_append (new_exec, escaped_app); for (j = 1; j < old_argc; j++) { g_autofree char *arg = maybe_quote (old_argv[j]); if (strcasecmp (arg, "%f") == 0) g_string_append_printf (new_exec, " @@ %s @@", arg); else if (strcasecmp (arg, "%u") == 0) g_string_append_printf (new_exec, " @@u %s @@", arg); else g_string_append_printf (new_exec, " %s", arg); } } else { g_string_append (new_exec, " "); g_string_append (new_exec, escaped_app); } g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str); } new_data = g_key_file_to_data (keyfile, &new_data_len, error); if (new_data == NULL) goto out; if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error)) goto out; if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error)) goto out; if (!g_output_stream_close (out_stream, cancellable, error)) goto out; if (target) *target = g_steal_pointer (&tmpfile_name); ret = TRUE; out: if (new_exec != NULL) g_string_free (new_exec, TRUE); return ret; }
CWE-94
23
1
static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; }
CWE-200
4
1
static int logi_dj_ll_raw_request(struct hid_device *hid, unsigned char reportnum, __u8 *buf, size_t count, unsigned char report_type, int reqtype) { struct dj_device *djdev = hid->driver_data; struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev; u8 *out_buf; int ret; if (buf[0] != REPORT_TYPE_LEDS) return -EINVAL; out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC); if (!out_buf) return -ENOMEM; if (count < DJREPORT_SHORT_LENGTH - 2) count = DJREPORT_SHORT_LENGTH - 2; out_buf[0] = REPORT_ID_DJ_SHORT; out_buf[1] = djdev->device_index; memcpy(out_buf + 2, buf, count); ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf, DJREPORT_SHORT_LENGTH, report_type, reqtype); kfree(out_buf); return ret; }
CWE-119
0
1
static bool is_legal_file(const std::string &filename) { DBG_FS << "Looking for '" << filename << "'.\n"; if (filename.empty()) { LOG_FS << " invalid filename\n"; return false; } if (filename.find("..") != std::string::npos) { ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n"; return false; } return true; }
CWE-200
4
0
static int do_spice_init(SpiceCoreInterface *core_interface) { spice_info("starting %s", version_string); if (core_interface->base.major_version != SPICE_INTERFACE_CORE_MAJOR) { spice_warning("bad core interface version"); goto err; } core = core_interface; reds->listen_socket = -1; reds->secure_listen_socket = -1; init_vd_agent_resources(); ring_init(&reds->clients); reds->num_clients = 0; main_dispatcher_init(core); ring_init(&reds->channels); ring_init(&reds->mig_target_clients); ring_init(&reds->char_devs_states); ring_init(&reds->mig_wait_disconnect_clients); reds->vm_running = TRUE; /* for backward compatibility */ if (!(reds->mig_timer = core->timer_add(migrate_timeout, NULL))) { spice_error("migration timer create failed"); } #ifdef RED_STATISTICS int shm_name_len; int fd; shm_name_len = strlen(SPICE_STAT_SHM_NAME) + 20; reds->stat_shm_name = (char *)spice_malloc(shm_name_len); snprintf(reds->stat_shm_name, shm_name_len, SPICE_STAT_SHM_NAME, getpid()); if ((fd = shm_open(reds->stat_shm_name, O_CREAT | O_RDWR, 0444)) == -1) { spice_error("statistics shm_open failed, %s", strerror(errno)); } if (ftruncate(fd, REDS_STAT_SHM_SIZE) == -1) { spice_error("statistics ftruncate failed, %s", strerror(errno)); } reds->stat = (SpiceStat *)mmap(NULL, REDS_STAT_SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (reds->stat == (SpiceStat *)MAP_FAILED) { spice_error("statistics mmap failed, %s", strerror(errno)); } memset(reds->stat, 0, REDS_STAT_SHM_SIZE); reds->stat->magic = SPICE_STAT_MAGIC; reds->stat->version = SPICE_STAT_VERSION; reds->stat->root_index = INVALID_STAT_REF; if (pthread_mutex_init(&reds->stat_lock, NULL)) { spice_error("mutex init failed"); } #endif if (!(reds->mm_timer = core->timer_add(mm_timer_proc, NULL))) { spice_error("mm timer create failed"); } reds_enable_mm_timer(); if (reds_init_net() < 0) { goto err; } if (reds->secure_listen_socket != -1) { if (reds_init_ssl() < 0) { goto err; } } #if HAVE_SASL int saslerr; if ((saslerr = sasl_server_init(NULL, sasl_appname ? sasl_appname : "spice")) != SASL_OK) { spice_error("Failed to initialize SASL auth %s", sasl_errstring(saslerr, NULL, NULL)); goto err; } #endif reds->main_channel = main_channel_init(); inputs_init(); reds->mouse_mode = SPICE_MOUSE_MODE_SERVER; reds_client_monitors_config_cleanup(); reds->allow_multiple_clients = getenv(SPICE_DEBUG_ALLOW_MC_ENV) != NULL; if (reds->allow_multiple_clients) { spice_warning("spice: allowing multiple client connections (crashy)"); } atexit(reds_exit); return 0; err: return -1; }
none
24
0
void GfxState::getUserClipBBox(double *xMin, double *yMin, double *xMax, double *yMax) { double ictm[6]; double xMin1, yMin1, xMax1, yMax1, det, tx, ty; det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]); ictm[0] = ctm[3] * det; ictm[1] = -ctm[1] * det; ictm[2] = -ctm[2] * det; ictm[3] = ctm[0] * det; ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det; ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det; xMin1 = xMax1 = clipXMin * ictm[0] + clipYMin * ictm[2] + ictm[4]; yMin1 = yMax1 = clipXMin * ictm[1] + clipYMin * ictm[3] + ictm[5]; tx = clipXMin * ictm[0] + clipYMax * ictm[2] + ictm[4]; ty = clipXMin * ictm[1] + clipYMax * ictm[3] + ictm[5]; if (tx < xMin1) { xMin1 = tx; } else if (tx > xMax1) { xMax1 = tx; } if (ty < yMin1) { yMin1 = ty; } else if (ty > yMax1) { yMax1 = ty; } tx = clipXMax * ictm[0] + clipYMin * ictm[2] + ictm[4]; ty = clipXMax * ictm[1] + clipYMin * ictm[3] + ictm[5]; if (tx < xMin1) { xMin1 = tx; } else if (tx > xMax1) { xMax1 = tx; } if (ty < yMin1) { yMin1 = ty; } else if (ty > yMax1) { yMax1 = ty; } tx = clipXMax * ictm[0] + clipYMax * ictm[2] + ictm[4]; ty = clipXMax * ictm[1] + clipYMax * ictm[3] + ictm[5]; if (tx < xMin1) { xMin1 = tx; } else if (tx > xMax1) { xMax1 = tx; } if (ty < yMin1) { yMin1 = ty; } else if (ty > yMax1) { yMax1 = ty; } *xMin = xMin1; *yMin = yMin1; *xMax = xMax1; *yMax = yMax1; }
none
24
0
gs_gstate_putdeviceparams(gs_gstate *pgs, gx_device *dev, gs_param_list *plist) { int code; gx_device *dev2; if (dev) dev2 = dev; else dev2 = pgs->device; code = gs_putdeviceparams(dev2, plist); if (code >= 0) gs_gstate_update_device(pgs, dev2); return code; }
none
24
1
fetch_interval_quantifier(UChar** src, UChar* end, PToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = scan_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = scan_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = INFINITE_REPEAT; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_INFINITE_REPEAT(up) && low > up) { /* {n,m}+ supported case */ if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL)) return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; tok->u.repeat.possessive = 1; { int tmp; tmp = low; low = up; up = tmp; } } else tok->u.repeat.possessive = 0; tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; }
CWE-125
1
1
int Equalizer_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; int32_t param2; char *name; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (*pValueSize < sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (*pValueSize < 2 * sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (*pValueSize < 2 * sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (*pValueSize < sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t); break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param); return -EINVAL; } switch (param) { case EQ_PARAM_NUM_BANDS: *(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS; break; case EQ_PARAM_LEVEL_RANGE: *(int16_t *)pValue = -1500; *((int16_t *)pValue + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: param2 = *pParamTemp; if (param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; break; } *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2); break; case EQ_PARAM_CENTER_FREQ: param2 = *pParamTemp; if (param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; break; } *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: param2 = *pParamTemp; if (param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; break; } EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1)); break; case EQ_PARAM_GET_BAND: param2 = *pParamTemp; *(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2); break; case EQ_PARAM_CUR_PRESET: *(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext); break; case EQ_PARAM_GET_NUM_OF_PRESETS: *(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets(); break; case EQ_PARAM_GET_PRESET_NAME: param2 = *pParamTemp; if (param2 >= EqualizerGetNumPresets()) { status = -EINVAL; break; } name = (char *)pValue; strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1); name[*pValueSize - 1] = 0; *pValueSize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES"); p[0] = (int16_t)EqualizerGetPreset(pContext); p[1] = (int16_t)FIVEBAND_NUMBANDS; for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i); } } break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_getParameter */ int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int32_t preset; int32_t band; int32_t level; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param) { case EQ_PARAM_CUR_PRESET: preset = (int32_t)(*(uint16_t *)pValue); if ((preset >= EqualizerGetNumPresets())||(preset < 0)) { status = -EINVAL; break; } EqualizerSetPreset(pContext, preset); break; case EQ_PARAM_BAND_LEVEL: band = *pParamTemp; level = (int32_t)(*(int16_t *)pValue); if (band >= FIVEBAND_NUMBANDS) { status = -EINVAL; break; } EqualizerSetBandLevel(pContext, band, level); break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; if ((int)p[0] >= EqualizerGetNumPresets()) { status = -EINVAL; break; } if (p[0] >= 0) { EqualizerSetPreset(pContext, (int)p[0]); } else { if ((int)p[1] != FIVEBAND_NUMBANDS) { status = -EINVAL; break; } for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { EqualizerSetBandLevel(pContext, i, (int)p[2 + i]); } } } break; default: ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_setParameter */ int Volume_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++;; char *name; switch (param){ case VOLUME_PARAM_LEVEL: case VOLUME_PARAM_MAXLEVEL: case VOLUME_PARAM_STEREOPOSITION: if (*pValueSize != sizeof(int16_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case VOLUME_PARAM_MUTE: case VOLUME_PARAM_ENABLESTEREOPOSITION: if (*pValueSize < sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; default: ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param); return -EINVAL; } switch (param){ case VOLUME_PARAM_LEVEL: status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue)); break; case VOLUME_PARAM_MAXLEVEL: *(int16_t *)pValue = 0; break; case VOLUME_PARAM_STEREOPOSITION: VolumeGetStereoPosition(pContext, (int16_t *)pValue); break; case VOLUME_PARAM_MUTE: status = VolumeGetMute(pContext, (uint32_t *)pValue); ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d", *(uint32_t *)pValue); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: *(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled; break; default: ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Volume_getParameter */ int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t position; uint32_t mute; uint32_t positionEnabled; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param){ case VOLUME_PARAM_LEVEL: level = *(int16_t *)pValue; status = VolumeSetVolumeLevel(pContext, (int16_t)level); break; case VOLUME_PARAM_MUTE: mute = *(uint32_t *)pValue; status = VolumeSetMute(pContext, mute); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: positionEnabled = *(uint32_t *)pValue; status = VolumeEnableStereoPosition(pContext, positionEnabled); status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved); break; case VOLUME_PARAM_STEREOPOSITION: position = *(int16_t *)pValue; status = VolumeSetStereoPosition(pContext, (int16_t)position); break; default: ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param); break; } return status; } /* end Volume_setParameter */ /**************************************************************************************** * Name : LVC_ToDB_s32Tos16() * Input : Signed 32-bit integer * Output : Signed 16-bit integer * MSB (16) = sign bit * (15->05) = integer part * (04->01) = decimal part * Returns : Db value with respect to full scale * Description : * Remarks : ****************************************************************************************/ LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix) { LVM_INT16 db_fix; LVM_INT16 Shift; LVM_INT16 SmallRemainder; LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix; /* Count leading bits, 1 cycle in assembly*/ for (Shift = 0; Shift<32; Shift++) { if ((Remainder & 0x80000000U)!=0) { break; } Remainder = Remainder << 1; } /* * Based on the approximation equation (for Q11.4 format): * * dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2) */ db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/ SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24); db_fix = (LVM_INT16)(db_fix + SmallRemainder ); SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder); db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9)); /* Correct for small offset */ db_fix = (LVM_INT16)(db_fix - 5); return db_fix; } int Effect_setEnabled(EffectContext *pContext, bool enabled) { ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled); if (enabled) { bool tempDisabled = false; switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountBb <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountBb = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bBassEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bBassTempDisabled; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountEq <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountEq = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountVirt = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled"); return -EINVAL; } pContext->pBundledContext->NumberEffectsEnabled++; pContext->pBundledContext->bVolumeEnabled = LVM_TRUE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } if (!tempDisabled) { LvmEffect_enable(pContext); } } else { switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled"); return -EINVAL; } pContext->pBundledContext->bBassEnabled = LVM_FALSE; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled"); return -EINVAL; } pContext->pBundledContext->bVolumeEnabled = LVM_FALSE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } LvmEffect_disable(pContext); } return 0; } int16_t LVC_Convert_VolToDb(uint32_t vol){ int16_t dB; dB = LVC_ToDB_s32Tos16(vol <<7); dB = (dB +8)>>4; dB = (dB <-96) ? -96 : dB ; return dB; } } // namespace
CWE-200
4
0
_poppler_page_new (PopplerDocument *document, Page *page, int index) { PopplerPage *poppler_page; g_return_val_if_fail (POPPLER_IS_DOCUMENT (document), NULL); poppler_page = (PopplerPage *) g_object_new (POPPLER_TYPE_PAGE, NULL, NULL); poppler_page->document = (PopplerDocument *) g_object_ref (document); poppler_page->page = page; poppler_page->index = index; return poppler_page; }
none
24
1
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MaxTextExtent], keyword[MaxTextExtent], tag[MaxTextExtent], value[MaxTextExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register Quantum *q; register ssize_t i, x; register unsigned char *p; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MaxTextExtent); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; (void) sscanf(value,"%g %g %g %g %g %g %g %g", &chromaticity[0],&chromaticity[1],&chromaticity[2], &chromaticity[3],&chromaticity[4],&chromaticity[5], &white_point[0],&white_point[1]); image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'Y': case 'y': { char target[] = "Y"; if (strcmp(keyword,target) == 0) { int height, width; (void) sscanf(value,"%d +X %d",&height,&width); image->columns=(size_t) width; image->rows=(size_t) height; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } default: { (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace,exception); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace,exception); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(image,0,q); SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
CWE-20
3
1
MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) if (p->scene >= GetNextImageInList(p)->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); }
CWE-476
12