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, ®s[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(®s[1], argv, argc-mlen); /* m1 + o */
}
if (argc < m1) {
stack_clear(®s[argc+1], m1-argc);
}
/* copy post mandatory arguments */
if (mlen) {
value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
}
if (mlen < m2) {
stack_clear(®s[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(®s[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(®s[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(®s[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, ®s[a]);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARRAY2, BBB) {
regs[a] = mrb_ary_new_from_values(mrb, c, ®s[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, ®s[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
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- -