project
stringclasses
633 values
commit_id
stringlengths
7
81
target
int64
0
1
func
stringlengths
5
484k
cwe
stringclasses
131 values
big_vul_idx
float64
0
189k
idx
int64
0
522k
hash
stringlengths
34
39
size
float64
1
24k
message
stringlengths
0
11.5k
dataset
stringclasses
1 value
qemu
e3737b820b45e54b059656dc3f914f895ac7a88b
1
static int bochs_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVBochsState *s = bs->opaque; uint32_t i; struct bochs_header bochs; int ret; bs->read_only = 1; // no write support yet ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs)); if (ret < 0) { return ret; } if (strcmp(bochs.magic, HEADER_MAGIC) || strcmp(bochs.type, REDOLOG_TYPE) || strcmp(bochs.subtype, GROWING_TYPE) || ((le32_to_cpu(bochs.version) != HEADER_VERSION) && (le32_to_cpu(bochs.version) != HEADER_V1))) { error_setg(errp, "Image not in Bochs format"); return -EINVAL; } if (le32_to_cpu(bochs.version) == HEADER_V1) { bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512; } else { bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512; } s->catalog_size = le32_to_cpu(bochs.catalog); s->catalog_bitmap = g_malloc(s->catalog_size * 4); ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap, s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4); s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512; s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512; s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; fail: s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; extent_index = offset / s->extent_size; extent_offset = (offset % s->extent_size) / 512; if (s->catalog_bitmap[extent_index] == 0xffffffff) { return -1; /* not allocated */ } bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] * (s->extent_blocks + s->bitmap_blocks)); /* read in bitmap for current extent */ if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8), &bitmap_entry, 1) != 1) { return -1; } if (!((bitmap_entry >> (extent_offset % 8)) & 1)) { return -1; /* not allocated */ } return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset)); }
CWE-190
178,576
10,472
228447863724695353773983474484739084182
null
null
null
qemu
db8a31d11d6a60f48d6817530640d75aa72a9a2f
1
static int get_refcount(BlockDriverState *bs, int64_t cluster_index) { BDRVQcowState *s = bs->opaque; int refcount_table_index, block_index; int64_t refcount_block_offset; int ret; uint16_t *refcount_block; uint16_t refcount; refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT); if (refcount_table_index >= s->refcount_table_size) return 0; refcount_block_offset = s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK; if (!refcount_block_offset) return 0; ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset, (void**) &refcount_block); if (ret < 0) { return ret; } block_index = cluster_index & ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1); refcount = be16_to_cpu(refcount_block[block_index]); ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) &refcount_block); if (ret < 0) { return ret; } return refcount; }
CWE-190
178,577
10,473
40167723741227406833096476704543576337
null
null
null
qemu
6a83f8b5bec6f59e56cc49bd49e4c3f8f805d56f
1
int qcow2_snapshot_load_tmp(BlockDriverState *bs, const char *snapshot_id, const char *name, Error **errp) { int i, snapshot_index; BDRVQcowState *s = bs->opaque; QCowSnapshot *sn; uint64_t *new_l1_table; int new_l1_bytes; int ret; assert(bs->read_only); /* Search the snapshot */ snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name); if (snapshot_index < 0) { error_setg(errp, "Can't find snapshot"); return -ENOENT; } sn = &s->snapshots[snapshot_index]; /* Allocate and read in the snapshot's L1 table */ new_l1_bytes = sn->l1_size * sizeof(uint64_t); new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512)); return ret; }
CWE-190
178,578
10,474
73607432206298624875850649345190309833
null
null
null
qemu
8f4754ede56e3f9ea3fd7207f4a7c4453e59285b
1
static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num, int nb_sectors) { return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE, nb_sectors * BDRV_SECTOR_SIZE); }
CWE-190
178,580
10,476
334793103852536476332824314087366851637
null
null
null
qemu
cab60de930684c33f67d4e32c7509b567f8c445b
1
int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size, bool exact_size) { BDRVQcowState *s = bs->opaque; int new_l1_size2, ret, i; uint64_t *new_l1_table; int64_t old_l1_table_offset, old_l1_size; int64_t new_l1_table_offset, new_l1_size; uint8_t data[12]; if (min_size <= s->l1_size) return 0; if (exact_size) { new_l1_size = min_size; } else { /* Bump size up to reduce the number of times we have to grow */ new_l1_size = s->l1_size; if (new_l1_size == 0) { new_l1_size = 1; } while (min_size > new_l1_size) { new_l1_size = (new_l1_size * 3 + 1) / 2; } } if (new_l1_size > INT_MAX) { return -EFBIG; } #ifdef DEBUG_ALLOC2 fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n", s->l1_size, new_l1_size); #endif new_l1_size2 = sizeof(uint64_t) * new_l1_size; new_l1_table = g_malloc0(align_offset(new_l1_size2, 512)); memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t)); /* write new table (align to cluster) */ BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE); new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2); if (new_l1_table_offset < 0) { g_free(new_l1_table); return new_l1_table_offset; } ret = qcow2_cache_flush(bs, s->refcount_block_cache); if (ret < 0) { goto fail; } /* the L1 position has not yet been updated, so these clusters must * indeed be completely free */ ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset, new_l1_size2); if (ret < 0) { goto fail; } BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE); for(i = 0; i < s->l1_size; i++) new_l1_table[i] = cpu_to_be64(new_l1_table[i]); ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2); if (ret < 0) goto fail; for(i = 0; i < s->l1_size; i++) new_l1_table[i] = be64_to_cpu(new_l1_table[i]); /* set new table */ BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE); cpu_to_be32w((uint32_t*)data, new_l1_size); stq_be_p(data + 4, new_l1_table_offset); ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data)); if (ret < 0) { goto fail; } g_free(s->l1_table); old_l1_table_offset = s->l1_table_offset; s->l1_table_offset = new_l1_table_offset; s->l1_table = new_l1_table; old_l1_size = s->l1_size; s->l1_size = new_l1_size; qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t), QCOW2_DISCARD_OTHER); return 0; fail: g_free(new_l1_table); qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2, QCOW2_DISCARD_OTHER); return ret; }
CWE-190
178,581
10,477
250508172956291071194784303958969029867
null
null
null
qemu
9c6b899f7a46893ab3b671e341a2234e9c0c060e
1
static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); } else { v9fs_path_sprintf(target, "%s", name); } return 0; }
CWE-732
178,629
10,485
131046614036663157609097431513398193968
null
null
null
qemu
bea60dd7679364493a0d7f5b54316c767cf894ef
1
static void check_pointer_type_change(Notifier *notifier, void *data) { VncState *vs = container_of(notifier, VncState, mouse_mode_notifier); int absolute = qemu_input_is_absolute(); if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) { vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); vnc_framebuffer_update(vs, absolute, 0, surface_width(vs->vd->ds), surface_height(vs->vd->ds), VNC_ENCODING_POINTER_TYPE_CHANGE); vnc_unlock_output(vs); vnc_flush(vs); vnc_unlock_output(vs); vnc_flush(vs); } vs->absolute = absolute; }
CWE-125
178,630
10,486
294365666750487825835952464147911129318
null
null
null
xcursor
897213f36baf6926daf6d192c709cf627aa5fd05
1
_XcursorThemeInherits (const char *full) { char line[8192]; char *result = NULL; FILE *f; if (!full) return NULL; f = fopen (full, "r"); if (f) { while (fgets (line, sizeof (line), f)) { if (!strncmp (line, "Inherits", 8)) { char *l = line + 8; char *r; while (*l == ' ') l++; if (*l != '=') continue; l++; while (*l == ' ') l++; result = malloc (strlen (l)); if (result) { r = result; while (*l) { while (XcursorSep(*l) || XcursorWhite (*l)) l++; if (!*l) break; if (r != result) *r++ = ':'; while (*l && !XcursorWhite(*l) && !XcursorSep(*l)) *r++ = *l++; } *r++ = '\0'; } break; } } fclose (f); } return result; }
CWE-119
178,679
10,508
11633313935301853408507433195275635075
null
null
null
bdwgc
e10c1eb9908c2774c16b3148b30d2f3823d66a9a
1
void * calloc(size_t n, size_t lb) { # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); }
CWE-189
178,764
10,516
336851372175251465871619831251583666253
null
null
null
webserver
fbda667221c51f0aa476a02366e0cf66cb012f88
1
cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap, cherokee_connection_t *conn) { int re; ret_t ret; size_t size; char *dn; LDAPMessage *message; LDAPMessage *first; char *attrs[] = { LDAP_NO_ATTRS, NULL }; cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap); /* Sanity checks */ if ((conn->validator == NULL) || cherokee_buffer_is_empty (&conn->validator->user)) return ret_error; size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()"); if (size != conn->validator->user.len) return ret_error; /* Build filter */ ret = init_filter (ldap, props, conn); if (ret != ret_ok) return ret; /* Search */ re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message); if (re != LDAP_SUCCESS) { LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH, props->filter.buf ? props->filter.buf : ""); return ret_error; } TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : ""); /* Check that there a single entry */ re = ldap_count_entries (ldap->conn, message); if (re != 1) { ldap_msgfree (message); return ret_not_found; } /* Pick up the first one */ first = ldap_first_entry (ldap->conn, message); if (first == NULL) { ldap_msgfree (message); return ret_not_found; } /* Get DN */ dn = ldap_get_dn (ldap->conn, first); if (dn == NULL) { ldap_msgfree (message); return ret_error; } ldap_msgfree (message); /* Check that it's right */ ret = validate_dn (props, dn, conn->validator->passwd.buf); if (ret != ret_ok) return ret; /* Disconnect from the LDAP server */ re = ldap_unbind_s (ldap->conn); if (re != LDAP_SUCCESS) return ret_error; /* Validated! */ TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf); return ret_ok; }
CWE-287
179,460
10,519
314951664888072708386523323446709687526
null
null
null
postgres
31400a673325147e1205326008e32135a78b4d8a
1
hstore_from_array(PG_FUNCTION_ARGS) { ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0); int ndims = ARR_NDIM(in_array); int count; int32 buflen; HStore *out; Pairs *pairs; Datum *in_datums; bool *in_nulls; int in_count; int i; Assert(ARR_ELEMTYPE(in_array) == TEXTOID); switch (ndims) { case 0: out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); case 1: if ((ARR_DIMS(in_array)[0]) % 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have even number of elements"))); break; case 2: if ((ARR_DIMS(in_array)[1]) != 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have two columns"))); break; default: ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("wrong number of array subscripts"))); } deconstruct_array(in_array, TEXTOID, -1, false, 'i', &in_datums, &in_nulls, &in_count); count = in_count / 2; pairs = palloc(count * sizeof(Pairs)); for (i = 0; i < count; ++i) { if (in_nulls[i * 2]) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); if (in_nulls[i * 2 + 1]) { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = NULL; pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = 4; pairs[i].isnull = true; pairs[i].needfree = false; } else { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]); pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1])); pairs[i].isnull = false; pairs[i].needfree = false; } } count = hstoreUniquePairs(pairs, count, &buflen); out = hstorePairs(pairs, count, buflen); PG_RETURN_POINTER(out); }
CWE-189
179,568
10,520
35573989238073479818837185216786718926
null
null
null
postgres
31400a673325147e1205326008e32135a78b4d8a
1
hstore_from_arrays(PG_FUNCTION_ARGS) { int32 buflen; HStore *out; Pairs *pairs; Datum *key_datums; bool *key_nulls; int key_count; Datum *value_datums; bool *value_nulls; int value_count; ArrayType *key_array; ArrayType *value_array; int i; if (PG_ARGISNULL(0)) PG_RETURN_NULL(); key_array = PG_GETARG_ARRAYTYPE_P(0); Assert(ARR_ELEMTYPE(key_array) == TEXTOID); /* * must check >1 rather than != 1 because empty arrays have 0 dimensions, * not 1 */ if (ARR_NDIM(key_array) > 1) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("wrong number of array subscripts"))); deconstruct_array(key_array, TEXTOID, -1, false, 'i', &key_datums, &key_nulls, &key_count); /* value_array might be NULL */ if (PG_ARGISNULL(1)) { value_array = NULL; value_count = key_count; value_datums = NULL; value_nulls = NULL; } else { value_array = PG_GETARG_ARRAYTYPE_P(1); Assert(ARR_ELEMTYPE(value_array) == TEXTOID); if (ARR_NDIM(value_array) > 1) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("wrong number of array subscripts"))); if ((ARR_NDIM(key_array) > 0 || ARR_NDIM(value_array) > 0) && (ARR_NDIM(key_array) != ARR_NDIM(value_array) || ARR_DIMS(key_array)[0] != ARR_DIMS(value_array)[0] || ARR_LBOUND(key_array)[0] != ARR_LBOUND(value_array)[0])) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("arrays must have same bounds"))); deconstruct_array(value_array, TEXTOID, -1, false, 'i', &value_datums, &value_nulls, &value_count); Assert(key_count == value_count); } pairs = palloc(key_count * sizeof(Pairs)); for (i = 0; i < key_count; ++i) { if (key_nulls[i]) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); if (!value_nulls || value_nulls[i]) { pairs[i].key = VARDATA_ANY(key_datums[i]); pairs[i].val = NULL; pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i])); pairs[i].vallen = 4; pairs[i].isnull = true; pairs[i].needfree = false; } else { pairs[i].key = VARDATA_ANY(key_datums[i]); pairs[i].val = VARDATA_ANY(value_datums[i]); pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i])); pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(value_datums[i])); pairs[i].isnull = false; pairs[i].needfree = false; } } key_count = hstoreUniquePairs(pairs, key_count, &buflen); out = hstorePairs(pairs, key_count, buflen); PG_RETURN_POINTER(out); }
CWE-189
179,569
10,521
39825315315274816115858795994640705454
null
null
null
postgres
31400a673325147e1205326008e32135a78b4d8a
1
hstore_recv(PG_FUNCTION_ARGS) { int32 buflen; HStore *out; Pairs *pairs; int32 i; int32 pcount; StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); pcount = pq_getmsgint(buf, 4); if (pcount == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } pairs = palloc(pcount * sizeof(Pairs)); for (i = 0; i < pcount; ++i) { int rawlen = pq_getmsgint(buf, 4); int len; if (rawlen < 0) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); pairs[i].key = pq_getmsgtext(buf, rawlen, &len); pairs[i].keylen = hstoreCheckKeyLen(len); pairs[i].needfree = true; rawlen = pq_getmsgint(buf, 4); if (rawlen < 0) { pairs[i].val = NULL; pairs[i].vallen = 0; pairs[i].isnull = true; } else { pairs[i].val = pq_getmsgtext(buf, rawlen, &len); pairs[i].vallen = hstoreCheckValLen(len); pairs[i].isnull = false; } } pcount = hstoreUniquePairs(pairs, pcount, &buflen); out = hstorePairs(pairs, pcount, buflen); PG_RETURN_POINTER(out); }
CWE-189
179,571
10,523
173364060110722756484616438545635738721
null
null
null
postgres
31400a673325147e1205326008e32135a78b4d8a
1
hstoreArrayToPairs(ArrayType *a, int *npairs) { Datum *key_datums; bool *key_nulls; int key_count; Pairs *key_pairs; int bufsiz; int i, j; deconstruct_array(a, TEXTOID, -1, false, 'i', &key_datums, &key_nulls, &key_count); if (key_count == 0) { *npairs = 0; return NULL; } key_pairs = palloc(sizeof(Pairs) * key_count); for (i = 0, j = 0; i < key_count; i++) { if (!key_nulls[i]) { key_pairs[j].key = VARDATA(key_datums[i]); key_pairs[j].keylen = VARSIZE(key_datums[i]) - VARHDRSZ; key_pairs[j].val = NULL; key_pairs[j].vallen = 0; key_pairs[j].needfree = 0; key_pairs[j].isnull = 1; j++; } } *npairs = hstoreUniquePairs(key_pairs, j, &bufsiz); return key_pairs; }
CWE-189
179,572
10,524
9891750996379654953772632249610457461
null
null
null
postgres
31400a673325147e1205326008e32135a78b4d8a
1
path_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); PATH *path; int isopen; char *s; int npts; int size; int depth = 0; if ((npts = pair_count(str, ',')) <= 0) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type path: \"%s\"", str))); s = str; while (isspace((unsigned char) *s)) s++; /* skip single leading paren */ if ((*s == LDELIM) && (strrchr(s, LDELIM) == s)) { s++; depth++; } size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * npts; path = (PATH *) palloc(size); SET_VARSIZE(path, size); path->npts = npts; if ((!path_decode(TRUE, npts, s, &isopen, &s, &(path->p[0]))) && (!((depth == 0) && (*s == '\0'))) && !((depth >= 1) && (*s == RDELIM))) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type path: \"%s\"", str))); path->closed = (!isopen); /* prevent instability in unused pad bytes */ path->dummy = 0; PG_RETURN_PATH_P(path); }
CWE-189
179,581
10,533
185822385736836366672794190569870181445
null
null
null
libreswan
2899351224fe2940aec37d7656e1e392c0fe07f0
1
stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but no connection has been authorized%s%s", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? " with policy=" : "", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : ""); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but \"%s\" forbids connection", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( "local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( "local endpoint has narrowing=yes - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log("found connection: %s\n", c ? c->name : "<none>"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log("received a DOS cookie in I1 verify it")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk("dcookie received in I1 Packet", blob); DBG_dump("dcookie computed", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( "mismatch in DOS v2N_COOKIE,send a new one"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log("dcookie received match with computed one")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( "busy mode on. receieved I1 without a valid dcookie"); DBG_log("send a dcookie and forget this state")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log("will not send/process a dcookie")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); libreswan_log( "rejecting I1 from %s:%u, invalid DH group=%u", fromname, md->sender_port, ke->isak_group); return v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, "ikev2_inI1outR1 KE"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } }
CWE-20
179,646
10,551
38971431341179709655812321506677170808
null
null
null
redis
fdf9d455098f54f7666c702ae464e6ea21e25411
1
static void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); }
CWE-17
179,785
10,559
299852641650757270201178719755093825687
null
null
null
httpd
cd2b7a26c776b0754fb98426a67804fd48118708
1
AP_DECLARE(int) ap_process_request_internal(request_rec *r) { int file_req = (r->main && r->filename); int access_status; core_dir_config *d; /* Ignore embedded %2F's in path for proxy requests */ if (!r->proxyreq && r->parsed_uri.path) { d = ap_get_core_module_config(r->per_dir_config); if (d->allow_encoded_slashes) { access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes); } else { access_status = ap_unescape_url(r->parsed_uri.path); } if (access_status) { if (access_status == HTTP_NOT_FOUND) { if (! d->allow_encoded_slashes) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026) "found %%2f (encoded '/') in URI " "(decoded='%s'), returning 404", r->parsed_uri.path); } } return access_status; } } ap_getparents(r->uri); /* OK --- shrinking transformations... */ /* All file subrequests are a huge pain... they cannot bubble through the * next several steps. Only file subrequests are allowed an empty uri, * otherwise let translate_name kill the request. */ if (!file_req) { if ((access_status = ap_location_walk(r))) { return access_status; } if ((access_status = ap_if_walk(r))) { return access_status; } /* Don't set per-dir loglevel if LogLevelOverride is set */ if (!r->connection->log) { d = ap_get_core_module_config(r->per_dir_config); if (d->log) r->log = d->log; } if ((access_status = ap_run_translate_name(r))) { return decl_die(access_status, "translate", r); } } /* Reset to the server default config prior to running map_to_storage */ r->per_dir_config = r->server->lookup_defaults; if ((access_status = ap_run_map_to_storage(r))) { /* This request wasn't in storage (e.g. TRACE) */ return access_status; } /* Rerun the location walk, which overrides any map_to_storage config. */ if ((access_status = ap_location_walk(r))) { return access_status; } if ((access_status = ap_if_walk(r))) { return access_status; } /* Don't set per-dir loglevel if LogLevelOverride is set */ if (!r->connection->log) { d = ap_get_core_module_config(r->per_dir_config); if (d->log) r->log = d->log; } if ((access_status = ap_run_post_perdir_config(r))) { return access_status; } /* Only on the main request! */ if (r->main == NULL) { if ((access_status = ap_run_header_parser(r))) { return access_status; } } /* Skip authn/authz if the parent or prior request passed the authn/authz, * and that configuration didn't change (this requires optimized _walk() * functions in map_to_storage that use the same merge results given * identical input.) If the config changes, we must re-auth. */ if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) { r->user = r->prev->user; r->ap_auth_type = r->prev->ap_auth_type; } else if (r->main && (r->main->per_dir_config == r->per_dir_config)) { r->user = r->main->user; r->ap_auth_type = r->main->ap_auth_type; } else { switch (ap_satisfies(r)) { case SATISFY_ALL: case SATISFY_NOSPEC: if ((access_status = ap_run_access_checker(r)) != OK) { return decl_die(access_status, "check access (with Satisfy All)", r); } access_status = ap_run_access_checker_ex(r); if (access_status == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker_ex hook: %s", r->uri); } else if (access_status != DECLINED) { return decl_die(access_status, "check access", r); } else { if ((access_status = ap_run_check_user_id(r)) != OK) { return decl_die(access_status, "check user", r); } if (r->user == NULL) { /* don't let buggy authn module crash us in authz */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027) "No authentication done but request not " "allowed without authentication for %s. " "Authentication not configured?", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; return decl_die(access_status, "check user", r); } if ((access_status = ap_run_auth_checker(r)) != OK) { return decl_die(access_status, "check authorization", r); } } break; case SATISFY_ANY: if ((access_status = ap_run_access_checker(r)) == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker hook and 'Satisfy any': %s", r->uri); break; } access_status = ap_run_access_checker_ex(r); if (access_status == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker_ex hook: %s", r->uri); } else if (access_status != DECLINED) { return decl_die(access_status, "check access", r); } else { if ((access_status = ap_run_check_user_id(r)) != OK) { return decl_die(access_status, "check user", r); } if (r->user == NULL) { /* don't let buggy authn module crash us in authz */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028) "No authentication done but request not " "allowed without authentication for %s. " "Authentication not configured?", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; return decl_die(access_status, "check user", r); } if ((access_status = ap_run_auth_checker(r)) != OK) { return decl_die(access_status, "check authorization", r); } } break; } } /* XXX Must make certain the ap_run_type_checker short circuits mime * in mod-proxy for r->proxyreq && r->parsed_uri.scheme * && !strcmp(r->parsed_uri.scheme, "http") */ if ((access_status = ap_run_type_checker(r)) != OK) { return decl_die(access_status, "find types", r); } if ((access_status = ap_run_fixups(r)) != OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s", access_status, r->uri); return access_status; } return OK; }
CWE-264
179,804
10,560
39276683520320650740114699647946646838
null
null
null
httpd
6a974059190b8a0c7e499f4ab12fe108127099cb
1
static int read_request_line(request_rec *r, apr_bucket_brigade *bb) { const char *ll; const char *uri; const char *pro; unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */ char http[5]; apr_size_t len; int num_blank_lines = 0; int max_blank_lines = r->server->limit_req_fields; core_server_config *conf = ap_get_core_module_config(r->server->module_config); int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT; int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY); if (max_blank_lines <= 0) { max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS; } /* Read past empty lines until we get a real request line, * a read error, the connection closes (EOF), or we timeout. * * We skip empty lines because browsers have to tack a CRLF on to the end * of POSTs to support old CERN webservers. But note that we may not * have flushed any previous response completely to the client yet. * We delay the flush as long as possible so that we can improve * performance for clients that are pipelining requests. If a request * is pipelined then we won't block during the (implicit) read() below. * If the requests aren't pipelined, then the client is still waiting * for the final buffer flush from us, and we will block in the implicit * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will * have to block during a read. */ do { apr_status_t rv; /* ensure ap_rgetline allocates memory each time thru the loop * if there are empty lines */ r->the_request = NULL; rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2), &len, r, 0, bb); if (rv != APR_SUCCESS) { r->request_time = apr_time_now(); /* ap_rgetline returns APR_ENOSPC if it fills up the * buffer before finding the end-of-line. This is only going to * happen if it exceeds the configured limit for a request-line. */ if (APR_STATUS_IS_ENOSPC(rv)) { r->status = HTTP_REQUEST_URI_TOO_LARGE; r->proto_num = HTTP_VERSION(1,0); r->protocol = apr_pstrdup(r->pool, "HTTP/1.0"); } else if (APR_STATUS_IS_TIMEUP(rv)) { r->status = HTTP_REQUEST_TIME_OUT; } else if (APR_STATUS_IS_EINVAL(rv)) { r->status = HTTP_BAD_REQUEST; } return 0; } } while ((len <= 0) && (++num_blank_lines < max_blank_lines)); if (APLOGrtrace5(r)) { ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r, "Request received from client: %s", ap_escape_logitem(r->pool, r->the_request)); } r->request_time = apr_time_now(); ll = r->the_request; r->method = ap_getword_white(r->pool, &ll); uri = ap_getword_white(r->pool, &ll); /* Provide quick information about the request method as soon as known */ r->method_number = ap_method_number_of(r->method); if (r->method_number == M_GET && r->method[0] == 'H') { r->header_only = 1; } ap_parse_uri(r, uri); if (ll[0]) { r->assbackwards = 0; pro = ll; len = strlen(ll); } else { r->assbackwards = 1; pro = "HTTP/0.9"; len = 8; if (conf->http09_enable == AP_HTTP09_DISABLE) { r->status = HTTP_VERSION_NOT_SUPPORTED; r->protocol = apr_pstrmemdup(r->pool, pro, len); /* If we deny 0.9, send error message with 1.x */ r->assbackwards = 0; r->proto_num = HTTP_VERSION(0, 9); r->connection->keepalive = AP_CONN_CLOSE; ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401) "HTTP/0.9 denied by server configuration"); return 0; } } r->protocol = apr_pstrmemdup(r->pool, pro, len); /* Avoid sscanf in the common case */ if (len == 8 && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' && apr_isdigit(pro[7])) { r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0'); } else { if (strict) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418) "Invalid protocol '%s'", r->protocol); if (enforce_strict) { r->status = HTTP_BAD_REQUEST; return 0; } } if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor) && (strcasecmp("http", http) == 0) && (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */ r->proto_num = HTTP_VERSION(major, minor); } else { r->proto_num = HTTP_VERSION(1, 0); } } if (strict) { int err = 0; if (ap_has_cntrl(r->the_request)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420) "Request line must not contain control characters"); err = HTTP_BAD_REQUEST; } if (r->parsed_uri.fragment) { /* RFC3986 3.5: no fragment */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421) "URI must not contain a fragment"); err = HTTP_BAD_REQUEST; } else if (r->parsed_uri.user || r->parsed_uri.password) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422) "URI must not contain a username/password"); err = HTTP_BAD_REQUEST; } else if (r->method_number == M_INVALID) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423) "Invalid HTTP method string: %s", r->method); err = HTTP_NOT_IMPLEMENTED; } else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424) "HTTP/0.x does not take a protocol"); err = HTTP_BAD_REQUEST; } if (err && enforce_strict) { r->status = err; return 0; } } return 1; }
179,913
10,563
136620208579068354905594865138646822287
null
null
null
httpd
643f0fcf3b8ab09a68f0ecd2aa37aafeda3e63ef
1
static int lua_websocket_read(lua_State *L) { apr_socket_t *sock; apr_status_t rv; int n = 0; apr_size_t len = 1; apr_size_t plen = 0; unsigned short payload_short = 0; apr_uint64_t payload_long = 0; unsigned char *mask_bytes; char byte; int plaintext; request_rec *r = ap_lua_check_request_rec(L, 1); plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1; mask_bytes = apr_pcalloc(r->pool, 4); sock = ap_get_conn_socket(r->connection); /* Get opcode and FIN bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { unsigned char ubyte, fin, opcode, mask, payload; ubyte = (unsigned char)byte; /* fin bit is the first bit */ fin = ubyte >> (CHAR_BIT - 1); /* opcode is the last four bits (there's 3 reserved bits we don't care about) */ opcode = ubyte & 0xf; /* Get the payload length and mask bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { ubyte = (unsigned char)byte; /* Mask is the first bit */ mask = ubyte >> (CHAR_BIT - 1); /* Payload is the last 7 bits */ payload = ubyte & 0x7f; plen = payload; /* Extended payload? */ if (payload == 126) { len = 2; if (plaintext) { /* XXX: apr_socket_recv does not receive len bits, only up to len bits! */ rv = apr_socket_recv(sock, (char*) &payload_short, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_short, 2); } payload_short = ntohs(payload_short); if (rv == APR_SUCCESS) { plen = payload_short; } else { return 0; } } /* Super duper extended payload? */ if (payload == 127) { len = 8; if (plaintext) { rv = apr_socket_recv(sock, (char*) &payload_long, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_long, 8); } if (rv == APR_SUCCESS) { plen = ap_ntoh64(&payload_long); } else { return 0; } } ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s", plen, (payload >= 126) ? "extra payload" : "no extra payload", mask ? "on" : "off", fin ? "This is a final frame" : "more to follow"); if (mask) { len = 4; if (plaintext) { rv = apr_socket_recv(sock, (char*) mask_bytes, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) mask_bytes, 4); } if (rv != APR_SUCCESS) { return 0; } } if (plen < (HUGE_STRING_LEN*1024) && plen > 0) { apr_size_t remaining = plen; apr_size_t received; apr_off_t at = 0; char *buffer = apr_palloc(r->pool, plen+1); buffer[plen] = 0; if (plaintext) { while (remaining > 0) { received = remaining; rv = apr_socket_recv(sock, buffer+at, &received); if (received > 0 ) { remaining -= received; at += received; } } ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack", at); } else { rv = lua_websocket_readbytes(r->connection, buffer, remaining); ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\ "pushed to Lua stack", remaining); } if (mask) { for (n = 0; n < plen; n++) { buffer[n] ^= mask_bytes[n%4]; } } lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */ lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */ return 2; } /* Decide if we need to react to the opcode or not */ if (opcode == 0x09) { /* ping */ char frame[2]; plen = 2; frame[0] = 0x8A; frame[1] = 0; apr_socket_send(sock, frame, &plen); /* Pong! */ lua_websocket_read(L); /* read the next frame instead */ } } } return 0; }
CWE-20
179,916
10,564
94610840135161177600996480330152639241
null
null
null
libzip
9b46957ec98d85a572e9ef98301247f39338a3b5
1
_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error) { zip_cdir_t *cd; zip_uint64_t offset; zip_uint8_t eocd[EOCD64LEN]; zip_uint64_t eocd_offset; zip_uint64_t size, nentry, i, eocdloc_offset; bool free_buffer; zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64; eocdloc_offset = _zip_buffer_offset(buffer); _zip_buffer_get(buffer, 4); /* magic already verified */ num_disks = _zip_buffer_get_16(buffer); eocd_disk = _zip_buffer_get_16(buffer); eocd_offset = _zip_buffer_get_64(buffer); if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return NULL; } if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) { zip_error_set(error, ZIP_ER_INCONS, 0); return NULL; } if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) { _zip_buffer_set_offset(buffer, eocd_offset - buf_offset); free_buffer = false; } else { if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) { _zip_error_set_from_source(error, src); return NULL; } if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) { return NULL; } free_buffer = true; } if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) { zip_error_set(error, ZIP_ER_INCONS, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } size = _zip_buffer_get_64(buffer); if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) { zip_error_set(error, ZIP_ER_INCONS, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } _zip_buffer_get(buffer, 4); /* skip version made by/needed */ num_disks64 = _zip_buffer_get_32(buffer); eocd_disk64 = _zip_buffer_get_32(buffer); /* if eocd values are 0xffff, we have to use eocd64 values. otherwise, if the values are not the same, it's inconsistent; in any case, if the value is not 0, we don't support it */ if (num_disks == 0xffff) { num_disks = num_disks64; } if (eocd_disk == 0xffff) { eocd_disk = eocd_disk64; } if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) { zip_error_set(error, ZIP_ER_INCONS, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } if (num_disks != 0 || eocd_disk != 0) { zip_error_set(error, ZIP_ER_MULTIDISK, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } nentry = _zip_buffer_get_64(buffer); i = _zip_buffer_get_64(buffer); if (nentry != i) { zip_error_set(error, ZIP_ER_MULTIDISK, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } size = _zip_buffer_get_64(buffer); offset = _zip_buffer_get_64(buffer); if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (free_buffer) { _zip_buffer_free(buffer); } return NULL; } if (free_buffer) { _zip_buffer_free(buffer); } if (offset > ZIP_INT64_MAX || offset+size < offset) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return NULL; } if ((flags & ZIP_CHECKCONS) && offset+size != eocd_offset) { zip_error_set(error, ZIP_ER_INCONS, 0); return NULL; } if ((cd=_zip_cdir_new(nentry, error)) == NULL) return NULL; cd->is_zip64 = true; cd->size = size; cd->offset = offset; return cd; }
CWE-119
180,943
10,569
57474523618150936938684165193953028939
null
null
null
libzip
2217022b7d1142738656d891e00b3d2d9179b796
1
_zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error) { zip_uint8_t buf[CDENTRYSIZE]; zip_uint16_t dostime, dosdate; zip_uint32_t size, variable_size; zip_uint16_t filename_len, comment_len, ef_len; bool from_buffer = (buffer != NULL); size = local ? LENTRYSIZE : CDENTRYSIZE; if (buffer) { if (_zip_buffer_left(buffer) < size) { zip_error_set(error, ZIP_ER_NOZIP, 0); return -1; } } else { if ((buffer = _zip_buffer_new_from_source(src, size, buf, error)) == NULL) { return -1; } } if (memcmp(_zip_buffer_get(buffer, 4), (local ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) { zip_error_set(error, ZIP_ER_NOZIP, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } /* convert buffercontents to zip_dirent */ _zip_dirent_init(zde); if (!local) zde->version_madeby = _zip_buffer_get_16(buffer); else zde->version_madeby = 0; zde->version_needed = _zip_buffer_get_16(buffer); zde->bitflags = _zip_buffer_get_16(buffer); zde->comp_method = _zip_buffer_get_16(buffer); /* convert to time_t */ dostime = _zip_buffer_get_16(buffer); dosdate = _zip_buffer_get_16(buffer); zde->last_mod = _zip_d2u_time(dostime, dosdate); zde->crc = _zip_buffer_get_32(buffer); zde->comp_size = _zip_buffer_get_32(buffer); zde->uncomp_size = _zip_buffer_get_32(buffer); filename_len = _zip_buffer_get_16(buffer); ef_len = _zip_buffer_get_16(buffer); if (local) { comment_len = 0; zde->disk_number = 0; zde->int_attrib = 0; zde->ext_attrib = 0; zde->offset = 0; } else { comment_len = _zip_buffer_get_16(buffer); zde->disk_number = _zip_buffer_get_16(buffer); zde->int_attrib = _zip_buffer_get_16(buffer); zde->ext_attrib = _zip_buffer_get_32(buffer); zde->offset = _zip_buffer_get_32(buffer); } if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCRYPTED) { if (zde->bitflags & ZIP_GPBF_STRONG_ENCRYPTION) { /* TODO */ zde->encryption_method = ZIP_EM_UNKNOWN; } else { zde->encryption_method = ZIP_EM_TRAD_PKWARE; } } else { zde->encryption_method = ZIP_EM_NONE; } zde->filename = NULL; zde->extra_fields = NULL; zde->comment = NULL; variable_size = (zip_uint32_t)filename_len+(zip_uint32_t)ef_len+(zip_uint32_t)comment_len; if (from_buffer) { if (_zip_buffer_left(buffer) < variable_size) { zip_error_set(error, ZIP_ER_INCONS, 0); return -1; } } else { _zip_buffer_free(buffer); if ((buffer = _zip_buffer_new_from_source(src, variable_size, NULL, error)) == NULL) { return -1; } } if (filename_len) { zde->filename = _zip_read_string(buffer, src, filename_len, 1, error); if (!zde->filename) { if (zip_error_code_zip(error) == ZIP_ER_EOF) { zip_error_set(error, ZIP_ER_INCONS, 0); } if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { if (_zip_guess_encoding(zde->filename, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { zip_error_set(error, ZIP_ER_INCONS, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } } } if (ef_len) { zip_uint8_t *ef = _zip_read_data(buffer, src, ef_len, 0, error); if (ef == NULL) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (!_zip_ef_parse(ef, ef_len, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, &zde->extra_fields, error)) { free(ef); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } free(ef); if (local) zde->local_extra_fields_read = 1; } if (comment_len) { zde->comment = _zip_read_string(buffer, src, comment_len, 0, error); if (!zde->comment) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { if (_zip_guess_encoding(zde->comment, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { zip_error_set(error, ZIP_ER_INCONS, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } } } zde->filename = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_NAME, zde->filename); zde->comment = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_COMMENT, zde->comment); /* Zip64 */ if (zde->uncomp_size == ZIP_UINT32_MAX || zde->comp_size == ZIP_UINT32_MAX || zde->offset == ZIP_UINT32_MAX) { zip_uint16_t got_len; zip_buffer_t *ef_buffer; const zip_uint8_t *ef = _zip_ef_get_by_id(zde->extra_fields, &got_len, ZIP_EF_ZIP64, 0, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, error); /* TODO: if got_len == 0 && !ZIP64_EOCD: no error, 0xffffffff is valid value */ if (ef == NULL) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if ((ef_buffer = _zip_buffer_new((zip_uint8_t *)ef, got_len)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->uncomp_size == ZIP_UINT32_MAX) zde->uncomp_size = _zip_buffer_get_64(ef_buffer); else if (local) { /* From appnote.txt: This entry in the Local header MUST include BOTH original and compressed file size fields. */ (void)_zip_buffer_skip(ef_buffer, 8); /* error is caught by _zip_buffer_eof() call */ } if (zde->comp_size == ZIP_UINT32_MAX) zde->comp_size = _zip_buffer_get_64(ef_buffer); if (!local) { if (zde->offset == ZIP_UINT32_MAX) zde->offset = _zip_buffer_get_64(ef_buffer); if (zde->disk_number == ZIP_UINT16_MAX) zde->disk_number = _zip_buffer_get_32(buffer); } if (!_zip_buffer_eof(ef_buffer)) { zip_error_set(error, ZIP_ER_INCONS, 0); _zip_buffer_free(ef_buffer); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } _zip_buffer_free(ef_buffer); } if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (!from_buffer) { _zip_buffer_free(buffer); } /* zip_source_seek / zip_source_tell don't support values > ZIP_INT64_MAX */ if (zde->offset > ZIP_INT64_MAX) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return -1; } if (!_zip_dirent_process_winzip_aes(zde, error)) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } zde->extra_fields = _zip_ef_remove_internal(zde->extra_fields); return (zip_int64_t)(size + variable_size); }
CWE-415
181,137
10,573
126446829664279180383138499483071964636
null
null
null
nagioscore
1b197346d490df2e2d3b1dcce5ac6134ad0c8752
1
int main(int argc, char **argv) { int result; int error = FALSE; int display_license = FALSE; int display_help = FALSE; int c = 0; struct tm *tm, tm_s; time_t now; char datestring[256]; nagios_macros *mac; const char *worker_socket = NULL; int i; #ifdef HAVE_SIGACTION struct sigaction sig_action; #endif #ifdef HAVE_GETOPT_H int option_index = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"license", no_argument, 0, 'V'}, {"verify-config", no_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"test-scheduling", no_argument, 0, 's'}, {"precache-objects", no_argument, 0, 'p'}, {"use-precached-objects", no_argument, 0, 'u'}, {"enable-timing-point", no_argument, 0, 'T'}, {"worker", required_argument, 0, 'W'}, {0, 0, 0, 0} }; #define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index) #endif memset(&loadctl, 0, sizeof(loadctl)); mac = get_global_macros(); /* make sure we have the correct number of command line arguments */ if(argc < 2) error = TRUE; /* get all command line arguments */ while(1) { c = getopt(argc, argv, "+hVvdspuxTW"); if(c == -1 || c == EOF) break; switch(c) { case '?': /* usage */ case 'h': display_help = TRUE; break; case 'V': /* version */ display_license = TRUE; break; case 'v': /* verify */ verify_config++; break; case 's': /* scheduling check */ test_scheduling = TRUE; break; case 'd': /* daemon mode */ daemon_mode = TRUE; break; case 'p': /* precache object config */ precache_objects = TRUE; break; case 'u': /* use precached object config */ use_precached_objects = TRUE; break; case 'T': enable_timing_point = TRUE; break; case 'W': worker_socket = optarg; break; case 'x': printf("Warning: -x is deprecated and will be removed\n"); break; default: break; } } #ifdef DEBUG_MEMORY mtrace(); #endif /* if we're a worker we can skip everything below */ if(worker_socket) { exit(nagios_core_worker(worker_socket)); } /* Initialize configuration variables */ init_main_cfg_vars(1); init_shared_cfg_vars(1); if(daemon_mode == FALSE) { printf("\nNagios Core %s\n", PROGRAM_VERSION); printf("Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\n"); printf("Copyright (c) 1999-2009 Ethan Galstad\n"); printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE); printf("License: GPL\n\n"); printf("Website: https://www.nagios.org\n"); } /* just display the license */ if(display_license == TRUE) { printf("This program is free software; you can redistribute it and/or modify\n"); printf("it under the terms of the GNU General Public License version 2 as\n"); printf("published by the Free Software Foundation.\n\n"); printf("This program is distributed in the hope that it will be useful,\n"); printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf("GNU General Public License for more details.\n\n"); printf("You should have received a copy of the GNU General Public License\n"); printf("along with this program; if not, write to the Free Software\n"); printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n"); exit(OK); } /* make sure we got the main config file on the command line... */ if(optind >= argc) error = TRUE; /* if there are no command line options (or if we encountered an error), print usage */ if(error == TRUE || display_help == TRUE) { printf("Usage: %s [options] <main_config_file>\n", argv[0]); printf("\n"); printf("Options:\n"); printf("\n"); printf(" -v, --verify-config Verify all configuration data (-v -v for more info)\n"); printf(" -s, --test-scheduling Shows projected/recommended check scheduling and other\n"); printf(" diagnostic info based on the current configuration files.\n"); printf(" -T, --enable-timing-point Enable timed commentary on initialization\n"); printf(" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\n"); printf(" -p, --precache-objects Precache object configuration\n"); printf(" -u, --use-precached-objects Use precached object config file\n"); printf(" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\n"); printf(" -W, --worker /path/to/socket Act as a worker for an already running daemon\n"); printf("\n"); printf("Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\n"); printf("releases, online documentation, FAQs, information on subscribing to\n"); printf("the mailing lists, and commercial support options for Nagios.\n"); printf("\n"); exit(ERROR); } /* * config file is last argument specified. * Make sure it uses an absolute path */ config_file = nspath_absolute(argv[optind], NULL); if(config_file == NULL) { printf("Error allocating memory.\n"); exit(ERROR); } config_file_dir = nspath_absolute_dirname(config_file, NULL); /* * Set the signal handler for the SIGXFSZ signal here because * we may encounter this signal before the other signal handlers * are set. */ #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = handle_sigxfsz; sigfillset(&sig_action.sa_mask); sig_action.sa_flags = SA_NODEFER|SA_RESTART; sigaction(SIGXFSZ, &sig_action, NULL); #else signal(SIGXFSZ, handle_sigxfsz); #endif /* * let's go to town. We'll be noisy if we're verifying config * or running scheduling tests. */ if(verify_config || test_scheduling || precache_objects) { reset_variables(); /* * if we don't beef up our resource limits as much as * we can, it's quite possible we'll run headlong into * EAGAIN due to too many processes when we try to * drop privileges later. */ set_loadctl_defaults(); if(verify_config) printf("Reading configuration data...\n"); /* read our config file */ result = read_main_config_file(config_file); if(result != OK) { printf(" Error processing main config file!\n\n"); exit(EXIT_FAILURE); } if(verify_config) printf(" Read main config file okay...\n"); /* drop privileges */ if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) { printf(" Failed to drop privileges. Aborting."); exit(EXIT_FAILURE); } /* * this must come after dropping privileges, so we make * sure to test access permissions as the right user. */ if (!verify_config && test_configured_paths() == ERROR) { printf(" One or more path problems detected. Aborting.\n"); exit(EXIT_FAILURE); } /* read object config files */ result = read_all_object_data(config_file); if(result != OK) { printf(" Error processing object config files!\n\n"); /* if the config filename looks fishy, warn the user */ if(!strstr(config_file, "nagios.cfg")) { printf("\n***> The name of the main configuration file looks suspicious...\n"); printf("\n"); printf(" Make sure you are specifying the name of the MAIN configuration file on\n"); printf(" the command line and not the name of another configuration file. The\n"); printf(" main configuration file is typically '%s'\n", DEFAULT_CONFIG_FILE); } printf("\n***> One or more problems was encountered while processing the config files...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf(" Read object config files okay...\n\n"); printf("Running pre-flight check on configuration data...\n\n"); } /* run the pre-flight check to make sure things look okay... */ result = pre_flight_check(); if(result != OK) { printf("\n***> One or more problems was encountered while running the pre-flight check...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf("\nThings look okay - No serious problems were detected during the pre-flight check\n"); } /* scheduling tests need a bit more than config verifications */ if(test_scheduling == TRUE) { /* we'll need the event queue here so we can time insertions */ init_event_queue(); timing_point("Done initializing event queue\n"); /* read initial service and host state information */ initialize_retention_data(config_file); read_initial_state_information(); timing_point("Retention data and initial state parsed\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Timing loop initialized\n"); /* display scheduling information */ display_scheduling_info(); } if(precache_objects) { result = fcache_objects(object_precache_file); timing_point("Done precaching objects\n"); if(result == OK) { printf("Object precache file created:\n%s\n", object_precache_file); } else { printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno)); } } /* clean up after ourselves */ cleanup(); /* exit */ timing_point("Exiting\n"); /* make valgrind shut up about still reachable memory */ neb_free_module_list(); free(config_file_dir); free(config_file); exit(result); } /* else start to monitor things... */ else { /* * if we're called with a relative path we must make * it absolute so we can launch our workers. * If not, we needn't bother, as we're using execvp() */ if (strchr(argv[0], '/')) nagios_binary_path = nspath_absolute(argv[0], NULL); else nagios_binary_path = strdup(argv[0]); if (!nagios_binary_path) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to allocate memory for nagios_binary_path\n"); exit(EXIT_FAILURE); } if (!(nagios_iobs = iobroker_create())) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to create IO broker set: %s\n", strerror(errno)); exit(EXIT_FAILURE); } /* keep monitoring things until we get a shutdown command */ do { /* reset internal book-keeping (in case we're restarting) */ wproc_num_workers_spawned = wproc_num_workers_online = 0; caught_signal = sigshutdown = FALSE; sig_id = 0; /* reset program variables */ reset_variables(); timing_point("Variables reset\n"); /* get PID */ nagios_pid = (int)getpid(); /* read in the configuration files (main and resource config files) */ result = read_main_config_file(config_file); if (result != OK) { logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to process config file '%s'. Aborting\n", config_file); exit(EXIT_FAILURE); } timing_point("Main config file read\n"); /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */ /* get program (re)start time and save as macro */ program_start = time(NULL); my_free(mac->x[MACRO_PROCESSSTARTTIME]); asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%llu", (unsigned long long)program_start); /* drop privileges */ if(drop_privileges(nagios_user, nagios_group) == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges. Aborting."); cleanup(); exit(ERROR); } if (test_path_access(nagios_binary_path, X_OK)) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: failed to access() %s: %s\n", nagios_binary_path, strerror(errno)); logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Spawning workers will be impossible. Aborting.\n"); exit(EXIT_FAILURE); } if (test_configured_paths() == ERROR) { /* error has already been logged */ exit(EXIT_FAILURE); } /* enter daemon mode (unless we're restarting...) */ if(daemon_mode == TRUE && sigrestart == FALSE) { result = daemon_init(); /* we had an error daemonizing, so bail... */ if(result == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid()); cleanup(); exit(EXIT_FAILURE); } /* get new PID */ nagios_pid = (int)getpid(); } /* this must be logged after we read config data, as user may have changed location of main log file */ logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid()); /* log the local time - may be different than clock time due to timezone offset */ now = time(NULL); tm = localtime_r(&now, &tm_s); strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm); logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring); /* write log version/info */ write_log_file_info(NULL); /* open debug log now that we're the right user */ open_debug_log(); #ifdef USE_EVENT_BROKER /* initialize modules */ neb_init_modules(); neb_init_callback_list(); #endif timing_point("NEB module API initialized\n"); /* handle signals (interrupts) before we do any socket I/O */ setup_sighandler(); /* * Initialize query handler and event subscription service. * This must be done before modules are initialized, so * the modules can use our in-core stuff properly */ if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to initialize query handler. Aborting\n"); exit(EXIT_FAILURE); } timing_point("Query handler initialized\n"); nerd_init(); timing_point("NERD initialized\n"); /* initialize check workers */ if(init_workers(num_check_workers) < 0) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to spawn workers. Aborting\n"); exit(EXIT_FAILURE); } timing_point("%u workers spawned\n", wproc_num_workers_spawned); i = 0; while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) { iobroker_poll(nagios_iobs, 50); i++; } timing_point("%u workers connected\n", wproc_num_workers_online); /* now that workers have arrived we can set the defaults */ set_loadctl_defaults(); #ifdef USE_EVENT_BROKER /* load modules */ if (neb_load_all_modules() != OK) { logit(NSLOG_CONFIG_ERROR, ERROR, "Error: Module loading failed. Aborting.\n"); /* if we're dumping core, we must remove all dl-files */ if (daemon_dumps_core) neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN); exit(EXIT_FAILURE); } timing_point("Modules loaded\n"); /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL); timing_point("First callback made\n"); #endif /* read in all object config data */ if(result == OK) result = read_all_object_data(config_file); /* there was a problem reading the config files */ if(result != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid()); else { /* run the pre-flight check to make sure everything looks okay*/ if((result = pre_flight_check()) != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid()); } /* an error occurred that prevented us from (re)starting */ if(result != OK) { /* if we were restarting, we need to cleanup from the previous run */ if(sigrestart == TRUE) { /* clean up the status data */ cleanup_status_data(TRUE); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL); #endif cleanup(); exit(ERROR); } timing_point("Object configuration parsed and understood\n"); /* write the objects.cache file */ fcache_objects(object_cache_file); timing_point("Objects cached\n"); init_event_queue(); timing_point("Event queue initialized\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* initialize status data unless we're starting */ if(sigrestart == FALSE) { initialize_status_data(config_file); timing_point("Status data initialized\n"); } /* initialize scheduled downtime data */ initialize_downtime_data(); timing_point("Downtime data initialized\n"); /* read initial service and host state information */ initialize_retention_data(config_file); timing_point("Retention data initialized\n"); read_initial_state_information(); timing_point("Initial state information read\n"); /* initialize comment data */ initialize_comment_data(); timing_point("Comment data initialized\n"); /* initialize performance data */ initialize_performance_data(config_file); timing_point("Performance data initialized\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Event timing loop initialized\n"); /* initialize check statistics */ init_check_stats(); timing_point("check stats initialized\n"); /* check for updates */ check_for_nagios_updates(FALSE, TRUE); timing_point("Update check concluded\n"); /* update all status data (with retained information) */ update_all_status_data(); timing_point("Status data updated\n"); /* log initial host and service state */ log_host_states(INITIAL_STATES, NULL); log_service_states(INITIAL_STATES, NULL); timing_point("Initial states logged\n"); /* reset the restart flag */ sigrestart = FALSE; /* fire up command file worker */ launch_command_file_worker(); timing_point("Command file worker launched\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* get event start time and save as macro */ event_start = time(NULL); my_free(mac->x[MACRO_EVENTSTARTTIME]); asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%llu", (unsigned long long)event_start); timing_point("Entering event execution loop\n"); /***** start monitoring all services *****/ /* (doesn't return until a restart or shutdown signal is encountered) */ event_execution_loop(); /* * immediately deinitialize the query handler so it * can remove modules that have stashed data with it */ qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET); /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */ /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */ /* did we catch a signal? */ if(caught_signal == TRUE) { if(sig_id == SIGHUP) logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n"); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL); if(sigshutdown == TRUE) broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL); else if(sigrestart == TRUE) broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL); #endif /* save service and host state information */ save_state_information(FALSE); cleanup_retention_data(); /* clean up performance data */ cleanup_performance_data(); /* clean up the scheduled downtime data */ cleanup_downtime_data(); /* clean up the status data unless we're restarting */ if(sigrestart == FALSE) { cleanup_status_data(TRUE); } free_worker_memory(WPROC_FORCE); /* shutdown stuff... */ if(sigshutdown == TRUE) { iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS); nagios_iobs = NULL; /* log a shutdown message */ logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid()); } /* clean up after ourselves */ cleanup(); /* close debug log */ close_debug_log(); } while(sigrestart == TRUE && sigshutdown == FALSE); if(daemon_mode == TRUE) unlink(lock_file); /* free misc memory */ my_free(lock_file); my_free(config_file); my_free(config_file_dir); my_free(nagios_binary_path); } return OK; }
CWE-665
181,138
10,574
182984082189353008524205380329353449888
null
null
null
httpd
29afdd2550b3d30a8defece2b95ae81edcf66ac9
1
AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return "TRACE cannot be controlled by <Limit>, see TraceEnable"; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) <Limit>, else <LimitExcept> */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive excludes all methods", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive specifies methods already excluded", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; }
CWE-416
181,257
10,577
137119598395414459729239732675215829248
null
null
null
qemu
30663fd26c0307e414622c7a8607fbc04f92ec14
1
static target_ulong disas_insn(CPUX86State *env, DisasContext *s, target_ulong pc_start) { int b, prefixes; int shift; TCGMemOp ot, aflag, dflag; int modrm, reg, rm, mod, op, opreg, val; target_ulong next_eip, tval; int rex_w, rex_r; s->pc_start = s->pc = pc_start; prefixes = 0; s->override = -1; rex_w = -1; rex_r = 0; #ifdef TARGET_X86_64 s->rex_x = 0; s->rex_b = 0; x86_64_hregs = 0; #endif s->rip_offset = 0; /* for relative ip address */ s->vex_l = 0; s->vex_v = 0; next_byte: b = cpu_ldub_code(env, s->pc); s->pc++; /* Collect prefixes. */ switch (b) { case 0xf3: prefixes |= PREFIX_REPZ; goto next_byte; case 0xf2: prefixes |= PREFIX_REPNZ; goto next_byte; case 0xf0: prefixes |= PREFIX_LOCK; goto next_byte; case 0x2e: s->override = R_CS; goto next_byte; case 0x36: s->override = R_SS; goto next_byte; case 0x3e: s->override = R_DS; goto next_byte; case 0x26: s->override = R_ES; goto next_byte; case 0x64: s->override = R_FS; goto next_byte; case 0x65: s->override = R_GS; goto next_byte; case 0x66: prefixes |= PREFIX_DATA; goto next_byte; case 0x67: prefixes |= PREFIX_ADR; goto next_byte; #ifdef TARGET_X86_64 case 0x40 ... 0x4f: if (CODE64(s)) { /* REX prefix */ rex_w = (b >> 3) & 1; rex_r = (b & 0x4) << 1; s->rex_x = (b & 0x2) << 2; REX_B(s) = (b & 0x1) << 3; x86_64_hregs = 1; /* select uniform byte register addressing */ goto next_byte; } break; #endif case 0xc5: /* 2-byte VEX */ case 0xc4: /* 3-byte VEX */ /* VEX prefixes cannot be used except in 32-bit mode. Otherwise the instruction is LES or LDS. */ if (s->code32 && !s->vm86) { static const int pp_prefix[4] = { 0, PREFIX_DATA, PREFIX_REPZ, PREFIX_REPNZ }; int vex3, vex2 = cpu_ldub_code(env, s->pc); if (!CODE64(s) && (vex2 & 0xc0) != 0xc0) { /* 4.1.4.6: In 32-bit mode, bits [7:6] must be 11b, otherwise the instruction is LES or LDS. */ break; } s->pc++; /* 4.1.1-4.1.3: No preceding lock, 66, f2, f3, or rex prefixes. */ if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ | PREFIX_LOCK | PREFIX_DATA)) { goto illegal_op; } #ifdef TARGET_X86_64 if (x86_64_hregs) { goto illegal_op; } #endif rex_r = (~vex2 >> 4) & 8; if (b == 0xc5) { vex3 = vex2; b = cpu_ldub_code(env, s->pc++); } else { #ifdef TARGET_X86_64 s->rex_x = (~vex2 >> 3) & 8; s->rex_b = (~vex2 >> 2) & 8; #endif vex3 = cpu_ldub_code(env, s->pc++); rex_w = (vex3 >> 7) & 1; switch (vex2 & 0x1f) { case 0x01: /* Implied 0f leading opcode bytes. */ b = cpu_ldub_code(env, s->pc++) | 0x100; break; case 0x02: /* Implied 0f 38 leading opcode bytes. */ b = 0x138; break; case 0x03: /* Implied 0f 3a leading opcode bytes. */ b = 0x13a; break; default: /* Reserved for future use. */ goto unknown_op; } } s->vex_v = (~vex3 >> 3) & 0xf; s->vex_l = (vex3 >> 2) & 1; prefixes |= pp_prefix[vex3 & 3] | PREFIX_VEX; } break; } /* Post-process prefixes. */ if (CODE64(s)) { /* In 64-bit mode, the default data size is 32-bit. Select 64-bit data with rex_w, and 16-bit data with 0x66; rex_w takes precedence over 0x66 if both are present. */ dflag = (rex_w > 0 ? MO_64 : prefixes & PREFIX_DATA ? MO_16 : MO_32); /* In 64-bit mode, 0x67 selects 32-bit addressing. */ aflag = (prefixes & PREFIX_ADR ? MO_32 : MO_64); } else { /* In 16/32-bit mode, 0x66 selects the opposite data size. */ if (s->code32 ^ ((prefixes & PREFIX_DATA) != 0)) { dflag = MO_32; } else { dflag = MO_16; } /* In 16/32-bit mode, 0x67 selects the opposite addressing. */ if (s->code32 ^ ((prefixes & PREFIX_ADR) != 0)) { aflag = MO_32; } else { aflag = MO_16; } } s->prefix = prefixes; s->aflag = aflag; s->dflag = dflag; /* now check op code */ reswitch: switch(b) { case 0x0f: /**************************/ /* extended op code */ b = cpu_ldub_code(env, s->pc++) | 0x100; goto reswitch; /**************************/ /* arith & logic */ case 0x00 ... 0x05: case 0x08 ... 0x0d: case 0x10 ... 0x15: case 0x18 ... 0x1d: case 0x20 ... 0x25: case 0x28 ... 0x2d: case 0x30 ... 0x35: case 0x38 ... 0x3d: { int op, f, val; op = (b >> 3) & 7; f = (b >> 1) & 3; ot = mo_b_d(b, dflag); switch(f) { case 0: /* OP Ev, Gv */ modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); if (mod != 3) { gen_lea_modrm(env, s, modrm); opreg = OR_TMP0; } else if (op == OP_XORL && rm == reg) { xor_zero: /* xor reg, reg optimisation */ set_cc_op(s, CC_OP_CLR); tcg_gen_movi_tl(cpu_T0, 0); gen_op_mov_reg_v(ot, reg, cpu_T0); break; } else { opreg = rm; } gen_op_mov_v_reg(ot, cpu_T1, reg); gen_op(s, op, ot, opreg); break; case 1: /* OP Gv, Ev */ modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; reg = ((modrm >> 3) & 7) | rex_r; rm = (modrm & 7) | REX_B(s); if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, ot, cpu_T1, cpu_A0); } else if (op == OP_XORL && rm == reg) { goto xor_zero; } else { gen_op_mov_v_reg(ot, cpu_T1, rm); } gen_op(s, op, ot, reg); break; case 2: /* OP A, Iv */ val = insn_get(env, s, ot); tcg_gen_movi_tl(cpu_T1, val); gen_op(s, op, ot, OR_EAX); break; } } break; case 0x82: if (CODE64(s)) goto illegal_op; case 0x80: /* GRP1 */ case 0x81: case 0x83: { int val; ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); op = (modrm >> 3) & 7; if (mod != 3) { if (b == 0x83) s->rip_offset = 1; else s->rip_offset = insn_const_size(ot); gen_lea_modrm(env, s, modrm); opreg = OR_TMP0; } else { opreg = rm; } switch(b) { default: case 0x80: case 0x81: case 0x82: val = insn_get(env, s, ot); break; case 0x83: val = (int8_t)insn_get(env, s, MO_8); break; } tcg_gen_movi_tl(cpu_T1, val); gen_op(s, op, ot, opreg); } break; /**************************/ /* inc, dec, and other misc arith */ case 0x40 ... 0x47: /* inc Gv */ ot = dflag; gen_inc(s, ot, OR_EAX + (b & 7), 1); break; case 0x48 ... 0x4f: /* dec Gv */ ot = dflag; gen_inc(s, ot, OR_EAX + (b & 7), -1); break; case 0xf6: /* GRP3 */ case 0xf7: ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); op = (modrm >> 3) & 7; if (mod != 3) { if (op == 0) { s->rip_offset = insn_const_size(ot); } gen_lea_modrm(env, s, modrm); /* For those below that handle locked memory, don't load here. */ if (!(s->prefix & PREFIX_LOCK) || op != 2) { gen_op_ld_v(s, ot, cpu_T0, cpu_A0); } } else { gen_op_mov_v_reg(ot, cpu_T0, rm); } switch(op) { case 0: /* test */ val = insn_get(env, s, ot); tcg_gen_movi_tl(cpu_T1, val); gen_op_testl_T0_T1_cc(); set_cc_op(s, CC_OP_LOGICB + ot); break; case 2: /* not */ if (s->prefix & PREFIX_LOCK) { if (mod == 3) { goto illegal_op; } tcg_gen_movi_tl(cpu_T0, ~0); tcg_gen_atomic_xor_fetch_tl(cpu_T0, cpu_A0, cpu_T0, s->mem_index, ot | MO_LE); } else { tcg_gen_not_tl(cpu_T0, cpu_T0); if (mod != 3) { gen_op_st_v(s, ot, cpu_T0, cpu_A0); } else { gen_op_mov_reg_v(ot, rm, cpu_T0); } } break; case 3: /* neg */ if (s->prefix & PREFIX_LOCK) { TCGLabel *label1; TCGv a0, t0, t1, t2; if (mod == 3) { goto illegal_op; } a0 = tcg_temp_local_new(); t0 = tcg_temp_local_new(); label1 = gen_new_label(); tcg_gen_mov_tl(a0, cpu_A0); tcg_gen_mov_tl(t0, cpu_T0); gen_set_label(label1); t1 = tcg_temp_new(); t2 = tcg_temp_new(); tcg_gen_mov_tl(t2, t0); tcg_gen_neg_tl(t1, t0); tcg_gen_atomic_cmpxchg_tl(t0, a0, t0, t1, s->mem_index, ot | MO_LE); tcg_temp_free(t1); tcg_gen_brcond_tl(TCG_COND_NE, t0, t2, label1); tcg_temp_free(t2); tcg_temp_free(a0); tcg_gen_mov_tl(cpu_T0, t0); tcg_temp_free(t0); } else { tcg_gen_neg_tl(cpu_T0, cpu_T0); if (mod != 3) { gen_op_st_v(s, ot, cpu_T0, cpu_A0); } else { gen_op_mov_reg_v(ot, rm, cpu_T0); } } gen_op_update_neg_cc(); set_cc_op(s, CC_OP_SUBB + ot); break; case 4: /* mul */ switch(ot) { case MO_8: gen_op_mov_v_reg(MO_8, cpu_T1, R_EAX); tcg_gen_ext8u_tl(cpu_T0, cpu_T0); tcg_gen_ext8u_tl(cpu_T1, cpu_T1); /* XXX: use 32 bit mul which could be faster */ tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); tcg_gen_andi_tl(cpu_cc_src, cpu_T0, 0xff00); set_cc_op(s, CC_OP_MULB); break; case MO_16: gen_op_mov_v_reg(MO_16, cpu_T1, R_EAX); tcg_gen_ext16u_tl(cpu_T0, cpu_T0); tcg_gen_ext16u_tl(cpu_T1, cpu_T1); /* XXX: use 32 bit mul which could be faster */ tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); tcg_gen_shri_tl(cpu_T0, cpu_T0, 16); gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0); tcg_gen_mov_tl(cpu_cc_src, cpu_T0); set_cc_op(s, CC_OP_MULW); break; default: case MO_32: tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EAX]); tcg_gen_mulu2_i32(cpu_tmp2_i32, cpu_tmp3_i32, cpu_tmp2_i32, cpu_tmp3_i32); tcg_gen_extu_i32_tl(cpu_regs[R_EAX], cpu_tmp2_i32); tcg_gen_extu_i32_tl(cpu_regs[R_EDX], cpu_tmp3_i32); tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]); tcg_gen_mov_tl(cpu_cc_src, cpu_regs[R_EDX]); set_cc_op(s, CC_OP_MULL); break; #ifdef TARGET_X86_64 case MO_64: tcg_gen_mulu2_i64(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_T0, cpu_regs[R_EAX]); tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]); tcg_gen_mov_tl(cpu_cc_src, cpu_regs[R_EDX]); set_cc_op(s, CC_OP_MULQ); break; #endif } break; case 5: /* imul */ switch(ot) { case MO_8: gen_op_mov_v_reg(MO_8, cpu_T1, R_EAX); tcg_gen_ext8s_tl(cpu_T0, cpu_T0); tcg_gen_ext8s_tl(cpu_T1, cpu_T1); /* XXX: use 32 bit mul which could be faster */ tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); tcg_gen_ext8s_tl(cpu_tmp0, cpu_T0); tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0); set_cc_op(s, CC_OP_MULB); break; case MO_16: gen_op_mov_v_reg(MO_16, cpu_T1, R_EAX); tcg_gen_ext16s_tl(cpu_T0, cpu_T0); tcg_gen_ext16s_tl(cpu_T1, cpu_T1); /* XXX: use 32 bit mul which could be faster */ tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); tcg_gen_ext16s_tl(cpu_tmp0, cpu_T0); tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0); tcg_gen_shri_tl(cpu_T0, cpu_T0, 16); gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0); set_cc_op(s, CC_OP_MULW); break; default: case MO_32: tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EAX]); tcg_gen_muls2_i32(cpu_tmp2_i32, cpu_tmp3_i32, cpu_tmp2_i32, cpu_tmp3_i32); tcg_gen_extu_i32_tl(cpu_regs[R_EAX], cpu_tmp2_i32); tcg_gen_extu_i32_tl(cpu_regs[R_EDX], cpu_tmp3_i32); tcg_gen_sari_i32(cpu_tmp2_i32, cpu_tmp2_i32, 31); tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]); tcg_gen_sub_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32); tcg_gen_extu_i32_tl(cpu_cc_src, cpu_tmp2_i32); set_cc_op(s, CC_OP_MULL); break; #ifdef TARGET_X86_64 case MO_64: tcg_gen_muls2_i64(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_T0, cpu_regs[R_EAX]); tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]); tcg_gen_sari_tl(cpu_cc_src, cpu_regs[R_EAX], 63); tcg_gen_sub_tl(cpu_cc_src, cpu_cc_src, cpu_regs[R_EDX]); set_cc_op(s, CC_OP_MULQ); break; #endif } break; case 6: /* div */ switch(ot) { case MO_8: gen_helper_divb_AL(cpu_env, cpu_T0); break; case MO_16: gen_helper_divw_AX(cpu_env, cpu_T0); break; default: case MO_32: gen_helper_divl_EAX(cpu_env, cpu_T0); break; #ifdef TARGET_X86_64 case MO_64: gen_helper_divq_EAX(cpu_env, cpu_T0); break; #endif } break; case 7: /* idiv */ switch(ot) { case MO_8: gen_helper_idivb_AL(cpu_env, cpu_T0); break; case MO_16: gen_helper_idivw_AX(cpu_env, cpu_T0); break; default: case MO_32: gen_helper_idivl_EAX(cpu_env, cpu_T0); break; #ifdef TARGET_X86_64 case MO_64: gen_helper_idivq_EAX(cpu_env, cpu_T0); break; #endif } break; default: goto unknown_op; } break; case 0xfe: /* GRP4 */ case 0xff: /* GRP5 */ ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); op = (modrm >> 3) & 7; if (op >= 2 && b == 0xfe) { goto unknown_op; } if (CODE64(s)) { if (op == 2 || op == 4) { /* operand size for jumps is 64 bit */ ot = MO_64; } else if (op == 3 || op == 5) { ot = dflag != MO_16 ? MO_32 + (rex_w == 1) : MO_16; } else if (op == 6) { /* default push size is 64 bit */ ot = mo_pushpop(s, dflag); } } if (mod != 3) { gen_lea_modrm(env, s, modrm); if (op >= 2 && op != 3 && op != 5) gen_op_ld_v(s, ot, cpu_T0, cpu_A0); } else { gen_op_mov_v_reg(ot, cpu_T0, rm); } switch(op) { case 0: /* inc Ev */ if (mod != 3) opreg = OR_TMP0; else opreg = rm; gen_inc(s, ot, opreg, 1); break; case 1: /* dec Ev */ if (mod != 3) opreg = OR_TMP0; else opreg = rm; gen_inc(s, ot, opreg, -1); break; case 2: /* call Ev */ /* XXX: optimize if memory (no 'and' is necessary) */ if (dflag == MO_16) { tcg_gen_ext16u_tl(cpu_T0, cpu_T0); } next_eip = s->pc - s->cs_base; tcg_gen_movi_tl(cpu_T1, next_eip); gen_push_v(s, cpu_T1); gen_op_jmp_v(cpu_T0); gen_bnd_jmp(s); gen_eob(s); break; case 3: /* lcall Ev */ gen_op_ld_v(s, ot, cpu_T1, cpu_A0); gen_add_A0_im(s, 1 << ot); gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0); do_lcall: if (s->pe && !s->vm86) { tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_lcall_protected(cpu_env, cpu_tmp2_i32, cpu_T1, tcg_const_i32(dflag - 1), tcg_const_tl(s->pc - s->cs_base)); } else { tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_lcall_real(cpu_env, cpu_tmp2_i32, cpu_T1, tcg_const_i32(dflag - 1), tcg_const_i32(s->pc - s->cs_base)); } gen_eob(s); break; case 4: /* jmp Ev */ if (dflag == MO_16) { tcg_gen_ext16u_tl(cpu_T0, cpu_T0); } gen_op_jmp_v(cpu_T0); gen_bnd_jmp(s); gen_eob(s); break; case 5: /* ljmp Ev */ gen_op_ld_v(s, ot, cpu_T1, cpu_A0); gen_add_A0_im(s, 1 << ot); gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0); do_ljmp: if (s->pe && !s->vm86) { tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_ljmp_protected(cpu_env, cpu_tmp2_i32, cpu_T1, tcg_const_tl(s->pc - s->cs_base)); } else { gen_op_movl_seg_T0_vm(R_CS); gen_op_jmp_v(cpu_T1); } gen_eob(s); break; case 6: /* push Ev */ gen_push_v(s, cpu_T0); break; default: goto unknown_op; } break; case 0x84: /* test Ev, Gv */ case 0x85: ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); gen_op_mov_v_reg(ot, cpu_T1, reg); gen_op_testl_T0_T1_cc(); set_cc_op(s, CC_OP_LOGICB + ot); break; case 0xa8: /* test eAX, Iv */ case 0xa9: ot = mo_b_d(b, dflag); val = insn_get(env, s, ot); gen_op_mov_v_reg(ot, cpu_T0, OR_EAX); tcg_gen_movi_tl(cpu_T1, val); gen_op_testl_T0_T1_cc(); set_cc_op(s, CC_OP_LOGICB + ot); break; case 0x98: /* CWDE/CBW */ switch (dflag) { #ifdef TARGET_X86_64 case MO_64: gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX); tcg_gen_ext32s_tl(cpu_T0, cpu_T0); gen_op_mov_reg_v(MO_64, R_EAX, cpu_T0); break; #endif case MO_32: gen_op_mov_v_reg(MO_16, cpu_T0, R_EAX); tcg_gen_ext16s_tl(cpu_T0, cpu_T0); gen_op_mov_reg_v(MO_32, R_EAX, cpu_T0); break; case MO_16: gen_op_mov_v_reg(MO_8, cpu_T0, R_EAX); tcg_gen_ext8s_tl(cpu_T0, cpu_T0); gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0); break; default: tcg_abort(); } break; case 0x99: /* CDQ/CWD */ switch (dflag) { #ifdef TARGET_X86_64 case MO_64: gen_op_mov_v_reg(MO_64, cpu_T0, R_EAX); tcg_gen_sari_tl(cpu_T0, cpu_T0, 63); gen_op_mov_reg_v(MO_64, R_EDX, cpu_T0); break; #endif case MO_32: gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX); tcg_gen_ext32s_tl(cpu_T0, cpu_T0); tcg_gen_sari_tl(cpu_T0, cpu_T0, 31); gen_op_mov_reg_v(MO_32, R_EDX, cpu_T0); break; case MO_16: gen_op_mov_v_reg(MO_16, cpu_T0, R_EAX); tcg_gen_ext16s_tl(cpu_T0, cpu_T0); tcg_gen_sari_tl(cpu_T0, cpu_T0, 15); gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0); break; default: tcg_abort(); } break; case 0x1af: /* imul Gv, Ev */ case 0x69: /* imul Gv, Ev, I */ case 0x6b: ot = dflag; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; if (b == 0x69) s->rip_offset = insn_const_size(ot); else if (b == 0x6b) s->rip_offset = 1; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); if (b == 0x69) { val = insn_get(env, s, ot); tcg_gen_movi_tl(cpu_T1, val); } else if (b == 0x6b) { val = (int8_t)insn_get(env, s, MO_8); tcg_gen_movi_tl(cpu_T1, val); } else { gen_op_mov_v_reg(ot, cpu_T1, reg); } switch (ot) { #ifdef TARGET_X86_64 case MO_64: tcg_gen_muls2_i64(cpu_regs[reg], cpu_T1, cpu_T0, cpu_T1); tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[reg]); tcg_gen_sari_tl(cpu_cc_src, cpu_cc_dst, 63); tcg_gen_sub_tl(cpu_cc_src, cpu_cc_src, cpu_T1); break; #endif case MO_32: tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1); tcg_gen_muls2_i32(cpu_tmp2_i32, cpu_tmp3_i32, cpu_tmp2_i32, cpu_tmp3_i32); tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32); tcg_gen_sari_i32(cpu_tmp2_i32, cpu_tmp2_i32, 31); tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[reg]); tcg_gen_sub_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32); tcg_gen_extu_i32_tl(cpu_cc_src, cpu_tmp2_i32); break; default: tcg_gen_ext16s_tl(cpu_T0, cpu_T0); tcg_gen_ext16s_tl(cpu_T1, cpu_T1); /* XXX: use 32 bit mul which could be faster */ tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); tcg_gen_ext16s_tl(cpu_tmp0, cpu_T0); tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0); gen_op_mov_reg_v(ot, reg, cpu_T0); break; } set_cc_op(s, CC_OP_MULB + ot); break; case 0x1c0: case 0x1c1: /* xadd Ev, Gv */ ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; gen_op_mov_v_reg(ot, cpu_T0, reg); if (mod == 3) { rm = (modrm & 7) | REX_B(s); gen_op_mov_v_reg(ot, cpu_T1, rm); tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(ot, reg, cpu_T1); gen_op_mov_reg_v(ot, rm, cpu_T0); } else { gen_lea_modrm(env, s, modrm); if (s->prefix & PREFIX_LOCK) { tcg_gen_atomic_fetch_add_tl(cpu_T1, cpu_A0, cpu_T0, s->mem_index, ot | MO_LE); tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1); } else { gen_op_ld_v(s, ot, cpu_T1, cpu_A0); tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_st_v(s, ot, cpu_T0, cpu_A0); } gen_op_mov_reg_v(ot, reg, cpu_T1); } gen_op_update2_cc(); set_cc_op(s, CC_OP_ADDB + ot); break; case 0x1b0: case 0x1b1: /* cmpxchg Ev, Gv */ { TCGv oldv, newv, cmpv; ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; oldv = tcg_temp_new(); newv = tcg_temp_new(); cmpv = tcg_temp_new(); gen_op_mov_v_reg(ot, newv, reg); tcg_gen_mov_tl(cmpv, cpu_regs[R_EAX]); if (s->prefix & PREFIX_LOCK) { if (mod == 3) { goto illegal_op; } gen_lea_modrm(env, s, modrm); tcg_gen_atomic_cmpxchg_tl(oldv, cpu_A0, cmpv, newv, s->mem_index, ot | MO_LE); gen_op_mov_reg_v(ot, R_EAX, oldv); } else { if (mod == 3) { rm = (modrm & 7) | REX_B(s); gen_op_mov_v_reg(ot, oldv, rm); } else { gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, ot, oldv, cpu_A0); rm = 0; /* avoid warning */ } gen_extu(ot, oldv); gen_extu(ot, cmpv); /* store value = (old == cmp ? new : old); */ tcg_gen_movcond_tl(TCG_COND_EQ, newv, oldv, cmpv, newv, oldv); if (mod == 3) { gen_op_mov_reg_v(ot, R_EAX, oldv); gen_op_mov_reg_v(ot, rm, newv); } else { /* Perform an unconditional store cycle like physical cpu; must be before changing accumulator to ensure idempotency if the store faults and the instruction is restarted */ gen_op_st_v(s, ot, newv, cpu_A0); gen_op_mov_reg_v(ot, R_EAX, oldv); } } tcg_gen_mov_tl(cpu_cc_src, oldv); tcg_gen_mov_tl(cpu_cc_srcT, cmpv); tcg_gen_sub_tl(cpu_cc_dst, cmpv, oldv); set_cc_op(s, CC_OP_SUBB + ot); tcg_temp_free(oldv); tcg_temp_free(newv); tcg_temp_free(cmpv); } break; case 0x1c7: /* cmpxchg8b */ modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; if ((mod == 3) || ((modrm & 0x38) != 0x8)) goto illegal_op; #ifdef TARGET_X86_64 if (dflag == MO_64) { if (!(s->cpuid_ext_features & CPUID_EXT_CX16)) goto illegal_op; gen_lea_modrm(env, s, modrm); if ((s->prefix & PREFIX_LOCK) && parallel_cpus) { gen_helper_cmpxchg16b(cpu_env, cpu_A0); } else { gen_helper_cmpxchg16b_unlocked(cpu_env, cpu_A0); } } else #endif { if (!(s->cpuid_features & CPUID_CX8)) goto illegal_op; gen_lea_modrm(env, s, modrm); if ((s->prefix & PREFIX_LOCK) && parallel_cpus) { gen_helper_cmpxchg8b(cpu_env, cpu_A0); } else { gen_helper_cmpxchg8b_unlocked(cpu_env, cpu_A0); } } set_cc_op(s, CC_OP_EFLAGS); break; /**************************/ /* push/pop */ case 0x50 ... 0x57: /* push */ gen_op_mov_v_reg(MO_32, cpu_T0, (b & 7) | REX_B(s)); gen_push_v(s, cpu_T0); break; case 0x58 ... 0x5f: /* pop */ ot = gen_pop_T0(s); /* NOTE: order is important for pop %sp */ gen_pop_update(s, ot); gen_op_mov_reg_v(ot, (b & 7) | REX_B(s), cpu_T0); break; case 0x60: /* pusha */ if (CODE64(s)) goto illegal_op; gen_pusha(s); break; case 0x61: /* popa */ if (CODE64(s)) goto illegal_op; gen_popa(s); break; case 0x68: /* push Iv */ case 0x6a: ot = mo_pushpop(s, dflag); if (b == 0x68) val = insn_get(env, s, ot); else val = (int8_t)insn_get(env, s, MO_8); tcg_gen_movi_tl(cpu_T0, val); gen_push_v(s, cpu_T0); break; case 0x8f: /* pop Ev */ modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; ot = gen_pop_T0(s); if (mod == 3) { /* NOTE: order is important for pop %sp */ gen_pop_update(s, ot); rm = (modrm & 7) | REX_B(s); gen_op_mov_reg_v(ot, rm, cpu_T0); } else { /* NOTE: order is important too for MMU exceptions */ s->popl_esp_hack = 1 << ot; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1); s->popl_esp_hack = 0; gen_pop_update(s, ot); } break; case 0xc8: /* enter */ { int level; val = cpu_lduw_code(env, s->pc); s->pc += 2; level = cpu_ldub_code(env, s->pc++); gen_enter(s, val, level); } break; case 0xc9: /* leave */ gen_leave(s); break; case 0x06: /* push es */ case 0x0e: /* push cs */ case 0x16: /* push ss */ case 0x1e: /* push ds */ if (CODE64(s)) goto illegal_op; gen_op_movl_T0_seg(b >> 3); gen_push_v(s, cpu_T0); break; case 0x1a0: /* push fs */ case 0x1a8: /* push gs */ gen_op_movl_T0_seg((b >> 3) & 7); gen_push_v(s, cpu_T0); break; case 0x07: /* pop es */ case 0x17: /* pop ss */ case 0x1f: /* pop ds */ if (CODE64(s)) goto illegal_op; reg = b >> 3; ot = gen_pop_T0(s); gen_movl_seg_T0(s, reg); gen_pop_update(s, ot); /* Note that reg == R_SS in gen_movl_seg_T0 always sets is_jmp. */ if (s->is_jmp) { gen_jmp_im(s->pc - s->cs_base); if (reg == R_SS) { s->tf = 0; gen_eob_inhibit_irq(s, true); } else { gen_eob(s); } } break; case 0x1a1: /* pop fs */ case 0x1a9: /* pop gs */ ot = gen_pop_T0(s); gen_movl_seg_T0(s, (b >> 3) & 7); gen_pop_update(s, ot); if (s->is_jmp) { gen_jmp_im(s->pc - s->cs_base); gen_eob(s); } break; /**************************/ /* mov */ case 0x88: case 0x89: /* mov Gv, Ev */ ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; /* generate a generic store */ gen_ldst_modrm(env, s, modrm, ot, reg, 1); break; case 0xc6: case 0xc7: /* mov Ev, Iv */ ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; if (mod != 3) { s->rip_offset = insn_const_size(ot); gen_lea_modrm(env, s, modrm); } val = insn_get(env, s, ot); tcg_gen_movi_tl(cpu_T0, val); if (mod != 3) { gen_op_st_v(s, ot, cpu_T0, cpu_A0); } else { gen_op_mov_reg_v(ot, (modrm & 7) | REX_B(s), cpu_T0); } break; case 0x8a: case 0x8b: /* mov Ev, Gv */ ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); gen_op_mov_reg_v(ot, reg, cpu_T0); break; case 0x8e: /* mov seg, Gv */ modrm = cpu_ldub_code(env, s->pc++); reg = (modrm >> 3) & 7; if (reg >= 6 || reg == R_CS) goto illegal_op; gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); gen_movl_seg_T0(s, reg); /* Note that reg == R_SS in gen_movl_seg_T0 always sets is_jmp. */ if (s->is_jmp) { gen_jmp_im(s->pc - s->cs_base); if (reg == R_SS) { s->tf = 0; gen_eob_inhibit_irq(s, true); } else { gen_eob(s); } } break; case 0x8c: /* mov Gv, seg */ modrm = cpu_ldub_code(env, s->pc++); reg = (modrm >> 3) & 7; mod = (modrm >> 6) & 3; if (reg >= 6) goto illegal_op; gen_op_movl_T0_seg(reg); ot = mod == 3 ? dflag : MO_16; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1); break; case 0x1b6: /* movzbS Gv, Eb */ case 0x1b7: /* movzwS Gv, Eb */ case 0x1be: /* movsbS Gv, Eb */ case 0x1bf: /* movswS Gv, Eb */ { TCGMemOp d_ot; TCGMemOp s_ot; /* d_ot is the size of destination */ d_ot = dflag; /* ot is the size of source */ ot = (b & 1) + MO_8; /* s_ot is the sign+size of source */ s_ot = b & 8 ? MO_SIGN | ot : ot; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); if (mod == 3) { if (s_ot == MO_SB && byte_reg_is_xH(rm)) { tcg_gen_sextract_tl(cpu_T0, cpu_regs[rm - 4], 8, 8); } else { gen_op_mov_v_reg(ot, cpu_T0, rm); switch (s_ot) { case MO_UB: tcg_gen_ext8u_tl(cpu_T0, cpu_T0); break; case MO_SB: tcg_gen_ext8s_tl(cpu_T0, cpu_T0); break; case MO_UW: tcg_gen_ext16u_tl(cpu_T0, cpu_T0); break; default: case MO_SW: tcg_gen_ext16s_tl(cpu_T0, cpu_T0); break; } } gen_op_mov_reg_v(d_ot, reg, cpu_T0); } else { gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, s_ot, cpu_T0, cpu_A0); gen_op_mov_reg_v(d_ot, reg, cpu_T0); } } break; case 0x8d: /* lea */ modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; if (mod == 3) goto illegal_op; reg = ((modrm >> 3) & 7) | rex_r; { AddressParts a = gen_lea_modrm_0(env, s, modrm); TCGv ea = gen_lea_modrm_1(a); gen_lea_v_seg(s, s->aflag, ea, -1, -1); gen_op_mov_reg_v(dflag, reg, cpu_A0); } break; case 0xa0: /* mov EAX, Ov */ case 0xa1: case 0xa2: /* mov Ov, EAX */ case 0xa3: { target_ulong offset_addr; ot = mo_b_d(b, dflag); switch (s->aflag) { #ifdef TARGET_X86_64 case MO_64: offset_addr = cpu_ldq_code(env, s->pc); s->pc += 8; break; #endif default: offset_addr = insn_get(env, s, s->aflag); break; } tcg_gen_movi_tl(cpu_A0, offset_addr); gen_add_A0_ds_seg(s); if ((b & 2) == 0) { gen_op_ld_v(s, ot, cpu_T0, cpu_A0); gen_op_mov_reg_v(ot, R_EAX, cpu_T0); } else { gen_op_mov_v_reg(ot, cpu_T0, R_EAX); gen_op_st_v(s, ot, cpu_T0, cpu_A0); } } break; case 0xd7: /* xlat */ tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EBX]); tcg_gen_ext8u_tl(cpu_T0, cpu_regs[R_EAX]); tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_T0); gen_extu(s->aflag, cpu_A0); gen_add_A0_ds_seg(s); gen_op_ld_v(s, MO_8, cpu_T0, cpu_A0); gen_op_mov_reg_v(MO_8, R_EAX, cpu_T0); break; case 0xb0 ... 0xb7: /* mov R, Ib */ val = insn_get(env, s, MO_8); tcg_gen_movi_tl(cpu_T0, val); gen_op_mov_reg_v(MO_8, (b & 7) | REX_B(s), cpu_T0); break; case 0xb8 ... 0xbf: /* mov R, Iv */ #ifdef TARGET_X86_64 if (dflag == MO_64) { uint64_t tmp; /* 64 bit case */ tmp = cpu_ldq_code(env, s->pc); s->pc += 8; reg = (b & 7) | REX_B(s); tcg_gen_movi_tl(cpu_T0, tmp); gen_op_mov_reg_v(MO_64, reg, cpu_T0); } else #endif { ot = dflag; val = insn_get(env, s, ot); reg = (b & 7) | REX_B(s); tcg_gen_movi_tl(cpu_T0, val); gen_op_mov_reg_v(ot, reg, cpu_T0); } break; case 0x91 ... 0x97: /* xchg R, EAX */ do_xchg_reg_eax: ot = dflag; reg = (b & 7) | REX_B(s); rm = R_EAX; goto do_xchg_reg; case 0x86: case 0x87: /* xchg Ev, Gv */ ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; if (mod == 3) { rm = (modrm & 7) | REX_B(s); do_xchg_reg: gen_op_mov_v_reg(ot, cpu_T0, reg); gen_op_mov_v_reg(ot, cpu_T1, rm); gen_op_mov_reg_v(ot, rm, cpu_T0); gen_op_mov_reg_v(ot, reg, cpu_T1); } else { gen_lea_modrm(env, s, modrm); gen_op_mov_v_reg(ot, cpu_T0, reg); /* for xchg, lock is implicit */ tcg_gen_atomic_xchg_tl(cpu_T1, cpu_A0, cpu_T0, s->mem_index, ot | MO_LE); gen_op_mov_reg_v(ot, reg, cpu_T1); } break; case 0xc4: /* les Gv */ /* In CODE64 this is VEX3; see above. */ op = R_ES; goto do_lxx; case 0xc5: /* lds Gv */ /* In CODE64 this is VEX2; see above. */ op = R_DS; goto do_lxx; case 0x1b2: /* lss Gv */ op = R_SS; goto do_lxx; case 0x1b4: /* lfs Gv */ op = R_FS; goto do_lxx; case 0x1b5: /* lgs Gv */ op = R_GS; do_lxx: ot = dflag != MO_16 ? MO_32 : MO_16; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; if (mod == 3) goto illegal_op; gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, ot, cpu_T1, cpu_A0); gen_add_A0_im(s, 1 << ot); /* load the segment first to handle exceptions properly */ gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0); gen_movl_seg_T0(s, op); /* then put the data */ gen_op_mov_reg_v(ot, reg, cpu_T1); if (s->is_jmp) { gen_jmp_im(s->pc - s->cs_base); gen_eob(s); } break; /************************/ /* shifts */ case 0xc0: case 0xc1: /* shift Ev,Ib */ shift = 2; grp2: { ot = mo_b_d(b, dflag); modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; op = (modrm >> 3) & 7; if (mod != 3) { if (shift == 2) { s->rip_offset = 1; } gen_lea_modrm(env, s, modrm); opreg = OR_TMP0; } else { opreg = (modrm & 7) | REX_B(s); } /* simpler op */ if (shift == 0) { gen_shift(s, op, ot, opreg, OR_ECX); } else { if (shift == 2) { shift = cpu_ldub_code(env, s->pc++); } gen_shifti(s, op, ot, opreg, shift); } } break; case 0xd0: case 0xd1: /* shift Ev,1 */ shift = 1; goto grp2; case 0xd2: case 0xd3: /* shift Ev,cl */ shift = 0; goto grp2; case 0x1a4: /* shld imm */ op = 0; shift = 1; goto do_shiftd; case 0x1a5: /* shld cl */ op = 0; shift = 0; goto do_shiftd; case 0x1ac: /* shrd imm */ op = 1; shift = 1; goto do_shiftd; case 0x1ad: /* shrd cl */ op = 1; shift = 0; do_shiftd: ot = dflag; modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); reg = ((modrm >> 3) & 7) | rex_r; if (mod != 3) { gen_lea_modrm(env, s, modrm); opreg = OR_TMP0; } else { opreg = rm; } gen_op_mov_v_reg(ot, cpu_T1, reg); if (shift) { TCGv imm = tcg_const_tl(cpu_ldub_code(env, s->pc++)); gen_shiftd_rm_T1(s, ot, opreg, op, imm); tcg_temp_free(imm); } else { gen_shiftd_rm_T1(s, ot, opreg, op, cpu_regs[R_ECX]); } break; /************************/ /* floats */ case 0xd8 ... 0xdf: if (s->flags & (HF_EM_MASK | HF_TS_MASK)) { /* if CR0.EM or CR0.TS are set, generate an FPU exception */ /* XXX: what to do if illegal op ? */ gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); break; } modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; rm = modrm & 7; op = ((b & 7) << 3) | ((modrm >> 3) & 7); if (mod != 3) { /* memory op */ gen_lea_modrm(env, s, modrm); switch(op) { case 0x00 ... 0x07: /* fxxxs */ case 0x10 ... 0x17: /* fixxxl */ case 0x20 ... 0x27: /* fxxxl */ case 0x30 ... 0x37: /* fixxx */ { int op1; op1 = op & 7; switch(op >> 4) { case 0: tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); gen_helper_flds_FT0(cpu_env, cpu_tmp2_i32); break; case 1: tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32); break; case 2: tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); gen_helper_fldl_FT0(cpu_env, cpu_tmp1_i64); break; case 3: default: tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LESW); gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32); break; } gen_helper_fp_arith_ST0_FT0(op1); if (op1 == 3) { /* fcomp needs pop */ gen_helper_fpop(cpu_env); } } break; case 0x08: /* flds */ case 0x0a: /* fsts */ case 0x0b: /* fstps */ case 0x18 ... 0x1b: /* fildl, fisttpl, fistl, fistpl */ case 0x28 ... 0x2b: /* fldl, fisttpll, fstl, fstpl */ case 0x38 ... 0x3b: /* filds, fisttps, fists, fistps */ switch(op & 7) { case 0: switch(op >> 4) { case 0: tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); gen_helper_flds_ST0(cpu_env, cpu_tmp2_i32); break; case 1: tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32); break; case 2: tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); gen_helper_fldl_ST0(cpu_env, cpu_tmp1_i64); break; case 3: default: tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LESW); gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32); break; } break; case 1: /* XXX: the corresponding CPUID bit must be tested ! */ switch(op >> 4) { case 1: gen_helper_fisttl_ST0(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); break; case 2: gen_helper_fisttll_ST0(cpu_tmp1_i64, cpu_env); tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); break; case 3: default: gen_helper_fistt_ST0(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUW); break; } gen_helper_fpop(cpu_env); break; default: switch(op >> 4) { case 0: gen_helper_fsts_ST0(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); break; case 1: gen_helper_fistl_ST0(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); break; case 2: gen_helper_fstl_ST0(cpu_tmp1_i64, cpu_env); tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); break; case 3: default: gen_helper_fist_ST0(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUW); break; } if ((op & 7) == 3) gen_helper_fpop(cpu_env); break; } break; case 0x0c: /* fldenv mem */ gen_helper_fldenv(cpu_env, cpu_A0, tcg_const_i32(dflag - 1)); break; case 0x0d: /* fldcw mem */ tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUW); gen_helper_fldcw(cpu_env, cpu_tmp2_i32); break; case 0x0e: /* fnstenv mem */ gen_helper_fstenv(cpu_env, cpu_A0, tcg_const_i32(dflag - 1)); break; case 0x0f: /* fnstcw mem */ gen_helper_fnstcw(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUW); break; case 0x1d: /* fldt mem */ gen_helper_fldt_ST0(cpu_env, cpu_A0); break; case 0x1f: /* fstpt mem */ gen_helper_fstt_ST0(cpu_env, cpu_A0); gen_helper_fpop(cpu_env); break; case 0x2c: /* frstor mem */ gen_helper_frstor(cpu_env, cpu_A0, tcg_const_i32(dflag - 1)); break; case 0x2e: /* fnsave mem */ gen_helper_fsave(cpu_env, cpu_A0, tcg_const_i32(dflag - 1)); break; case 0x2f: /* fnstsw mem */ gen_helper_fnstsw(cpu_tmp2_i32, cpu_env); tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUW); break; case 0x3c: /* fbld */ gen_helper_fbld_ST0(cpu_env, cpu_A0); break; case 0x3e: /* fbstp */ gen_helper_fbst_ST0(cpu_env, cpu_A0); gen_helper_fpop(cpu_env); break; case 0x3d: /* fildll */ tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); gen_helper_fildll_ST0(cpu_env, cpu_tmp1_i64); break; case 0x3f: /* fistpll */ gen_helper_fistll_ST0(cpu_tmp1_i64, cpu_env); tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); gen_helper_fpop(cpu_env); break; default: goto unknown_op; } } else { /* register float ops */ opreg = rm; switch(op) { case 0x08: /* fld sti */ gen_helper_fpush(cpu_env); gen_helper_fmov_ST0_STN(cpu_env, tcg_const_i32((opreg + 1) & 7)); break; case 0x09: /* fxchg sti */ case 0x29: /* fxchg4 sti, undocumented op */ case 0x39: /* fxchg7 sti, undocumented op */ gen_helper_fxchg_ST0_STN(cpu_env, tcg_const_i32(opreg)); break; case 0x0a: /* grp d9/2 */ switch(rm) { case 0: /* fnop */ /* check exceptions (FreeBSD FPU probe) */ gen_helper_fwait(cpu_env); break; default: goto unknown_op; } break; case 0x0c: /* grp d9/4 */ switch(rm) { case 0: /* fchs */ gen_helper_fchs_ST0(cpu_env); break; case 1: /* fabs */ gen_helper_fabs_ST0(cpu_env); break; case 4: /* ftst */ gen_helper_fldz_FT0(cpu_env); gen_helper_fcom_ST0_FT0(cpu_env); break; case 5: /* fxam */ gen_helper_fxam_ST0(cpu_env); break; default: goto unknown_op; } break; case 0x0d: /* grp d9/5 */ { switch(rm) { case 0: gen_helper_fpush(cpu_env); gen_helper_fld1_ST0(cpu_env); break; case 1: gen_helper_fpush(cpu_env); gen_helper_fldl2t_ST0(cpu_env); break; case 2: gen_helper_fpush(cpu_env); gen_helper_fldl2e_ST0(cpu_env); break; case 3: gen_helper_fpush(cpu_env); gen_helper_fldpi_ST0(cpu_env); break; case 4: gen_helper_fpush(cpu_env); gen_helper_fldlg2_ST0(cpu_env); break; case 5: gen_helper_fpush(cpu_env); gen_helper_fldln2_ST0(cpu_env); break; case 6: gen_helper_fpush(cpu_env); gen_helper_fldz_ST0(cpu_env); break; default: goto unknown_op; } } break; case 0x0e: /* grp d9/6 */ switch(rm) { case 0: /* f2xm1 */ gen_helper_f2xm1(cpu_env); break; case 1: /* fyl2x */ gen_helper_fyl2x(cpu_env); break; case 2: /* fptan */ gen_helper_fptan(cpu_env); break; case 3: /* fpatan */ gen_helper_fpatan(cpu_env); break; case 4: /* fxtract */ gen_helper_fxtract(cpu_env); break; case 5: /* fprem1 */ gen_helper_fprem1(cpu_env); break; case 6: /* fdecstp */ gen_helper_fdecstp(cpu_env); break; default: case 7: /* fincstp */ gen_helper_fincstp(cpu_env); break; } break; case 0x0f: /* grp d9/7 */ switch(rm) { case 0: /* fprem */ gen_helper_fprem(cpu_env); break; case 1: /* fyl2xp1 */ gen_helper_fyl2xp1(cpu_env); break; case 2: /* fsqrt */ gen_helper_fsqrt(cpu_env); break; case 3: /* fsincos */ gen_helper_fsincos(cpu_env); break; case 5: /* fscale */ gen_helper_fscale(cpu_env); break; case 4: /* frndint */ gen_helper_frndint(cpu_env); break; case 6: /* fsin */ gen_helper_fsin(cpu_env); break; default: case 7: /* fcos */ gen_helper_fcos(cpu_env); break; } break; case 0x00: case 0x01: case 0x04 ... 0x07: /* fxxx st, sti */ case 0x20: case 0x21: case 0x24 ... 0x27: /* fxxx sti, st */ case 0x30: case 0x31: case 0x34 ... 0x37: /* fxxxp sti, st */ { int op1; op1 = op & 7; if (op >= 0x20) { gen_helper_fp_arith_STN_ST0(op1, opreg); if (op >= 0x30) gen_helper_fpop(cpu_env); } else { gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fp_arith_ST0_FT0(op1); } } break; case 0x02: /* fcom */ case 0x22: /* fcom2, undocumented op */ gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fcom_ST0_FT0(cpu_env); break; case 0x03: /* fcomp */ case 0x23: /* fcomp3, undocumented op */ case 0x32: /* fcomp5, undocumented op */ gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fcom_ST0_FT0(cpu_env); gen_helper_fpop(cpu_env); break; case 0x15: /* da/5 */ switch(rm) { case 1: /* fucompp */ gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1)); gen_helper_fucom_ST0_FT0(cpu_env); gen_helper_fpop(cpu_env); gen_helper_fpop(cpu_env); break; default: goto unknown_op; } break; case 0x1c: switch(rm) { case 0: /* feni (287 only, just do nop here) */ break; case 1: /* fdisi (287 only, just do nop here) */ break; case 2: /* fclex */ gen_helper_fclex(cpu_env); break; case 3: /* fninit */ gen_helper_fninit(cpu_env); break; case 4: /* fsetpm (287 only, just do nop here) */ break; default: goto unknown_op; } break; case 0x1d: /* fucomi */ if (!(s->cpuid_features & CPUID_CMOV)) { goto illegal_op; } gen_update_cc_op(s); gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fucomi_ST0_FT0(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x1e: /* fcomi */ if (!(s->cpuid_features & CPUID_CMOV)) { goto illegal_op; } gen_update_cc_op(s); gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fcomi_ST0_FT0(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x28: /* ffree sti */ gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg)); break; case 0x2a: /* fst sti */ gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg)); break; case 0x2b: /* fstp sti */ case 0x0b: /* fstp1 sti, undocumented op */ case 0x3a: /* fstp8 sti, undocumented op */ case 0x3b: /* fstp9 sti, undocumented op */ gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg)); gen_helper_fpop(cpu_env); break; case 0x2c: /* fucom st(i) */ gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fucom_ST0_FT0(cpu_env); break; case 0x2d: /* fucomp st(i) */ gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fucom_ST0_FT0(cpu_env); gen_helper_fpop(cpu_env); break; case 0x33: /* de/3 */ switch(rm) { case 1: /* fcompp */ gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1)); gen_helper_fcom_ST0_FT0(cpu_env); gen_helper_fpop(cpu_env); gen_helper_fpop(cpu_env); break; default: goto unknown_op; } break; case 0x38: /* ffreep sti, undocumented op */ gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fpop(cpu_env); break; case 0x3c: /* df/4 */ switch(rm) { case 0: gen_helper_fnstsw(cpu_tmp2_i32, cpu_env); tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32); gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0); break; default: goto unknown_op; } break; case 0x3d: /* fucomip */ if (!(s->cpuid_features & CPUID_CMOV)) { goto illegal_op; } gen_update_cc_op(s); gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fucomi_ST0_FT0(cpu_env); gen_helper_fpop(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x3e: /* fcomip */ if (!(s->cpuid_features & CPUID_CMOV)) { goto illegal_op; } gen_update_cc_op(s); gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg)); gen_helper_fcomi_ST0_FT0(cpu_env); gen_helper_fpop(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x10 ... 0x13: /* fcmovxx */ case 0x18 ... 0x1b: { int op1; TCGLabel *l1; static const uint8_t fcmov_cc[8] = { (JCC_B << 1), (JCC_Z << 1), (JCC_BE << 1), (JCC_P << 1), }; if (!(s->cpuid_features & CPUID_CMOV)) { goto illegal_op; } op1 = fcmov_cc[op & 3] | (((op >> 3) & 1) ^ 1); l1 = gen_new_label(); gen_jcc1_noeob(s, op1, l1); gen_helper_fmov_ST0_STN(cpu_env, tcg_const_i32(opreg)); gen_set_label(l1); } break; default: goto unknown_op; } } break; /************************/ /* string ops */ case 0xa4: /* movsS */ case 0xa5: ot = mo_b_d(b, dflag); if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) { gen_repz_movs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base); } else { gen_movs(s, ot); } break; case 0xaa: /* stosS */ case 0xab: ot = mo_b_d(b, dflag); if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) { gen_repz_stos(s, ot, pc_start - s->cs_base, s->pc - s->cs_base); } else { gen_stos(s, ot); } break; case 0xac: /* lodsS */ case 0xad: ot = mo_b_d(b, dflag); if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) { gen_repz_lods(s, ot, pc_start - s->cs_base, s->pc - s->cs_base); } else { gen_lods(s, ot); } break; case 0xae: /* scasS */ case 0xaf: ot = mo_b_d(b, dflag); if (prefixes & PREFIX_REPNZ) { gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1); } else if (prefixes & PREFIX_REPZ) { gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0); } else { gen_scas(s, ot); } break; case 0xa6: /* cmpsS */ case 0xa7: ot = mo_b_d(b, dflag); if (prefixes & PREFIX_REPNZ) { gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1); } else if (prefixes & PREFIX_REPZ) { gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0); } else { gen_cmps(s, ot); } break; case 0x6c: /* insS */ case 0x6d: ot = mo_b_d32(b, dflag); tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]); gen_check_io(s, ot, pc_start - s->cs_base, SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes) | 4); if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) { gen_repz_ins(s, ot, pc_start - s->cs_base, s->pc - s->cs_base); } else { gen_ins(s, ot); if (s->tb->cflags & CF_USE_ICOUNT) { gen_jmp(s, s->pc - s->cs_base); } } break; case 0x6e: /* outsS */ case 0x6f: ot = mo_b_d32(b, dflag); tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]); gen_check_io(s, ot, pc_start - s->cs_base, svm_is_rep(prefixes) | 4); if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) { gen_repz_outs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base); } else { gen_outs(s, ot); if (s->tb->cflags & CF_USE_ICOUNT) { gen_jmp(s, s->pc - s->cs_base); } } break; /************************/ /* port I/O */ case 0xe4: case 0xe5: ot = mo_b_d32(b, dflag); val = cpu_ldub_code(env, s->pc++); tcg_gen_movi_tl(cpu_T0, val); gen_check_io(s, ot, pc_start - s->cs_base, SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes)); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } tcg_gen_movi_i32(cpu_tmp2_i32, val); gen_helper_in_func(ot, cpu_T1, cpu_tmp2_i32); gen_op_mov_reg_v(ot, R_EAX, cpu_T1); gen_bpt_io(s, cpu_tmp2_i32, ot); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); gen_jmp(s, s->pc - s->cs_base); } break; case 0xe6: case 0xe7: ot = mo_b_d32(b, dflag); val = cpu_ldub_code(env, s->pc++); tcg_gen_movi_tl(cpu_T0, val); gen_check_io(s, ot, pc_start - s->cs_base, svm_is_rep(prefixes)); gen_op_mov_v_reg(ot, cpu_T1, R_EAX); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } tcg_gen_movi_i32(cpu_tmp2_i32, val); tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1); gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32); gen_bpt_io(s, cpu_tmp2_i32, ot); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); gen_jmp(s, s->pc - s->cs_base); } break; case 0xec: case 0xed: ot = mo_b_d32(b, dflag); tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]); gen_check_io(s, ot, pc_start - s->cs_base, SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes)); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_in_func(ot, cpu_T1, cpu_tmp2_i32); gen_op_mov_reg_v(ot, R_EAX, cpu_T1); gen_bpt_io(s, cpu_tmp2_i32, ot); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); gen_jmp(s, s->pc - s->cs_base); } break; case 0xee: case 0xef: ot = mo_b_d32(b, dflag); tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]); gen_check_io(s, ot, pc_start - s->cs_base, svm_is_rep(prefixes)); gen_op_mov_v_reg(ot, cpu_T1, R_EAX); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1); gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32); gen_bpt_io(s, cpu_tmp2_i32, ot); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); gen_jmp(s, s->pc - s->cs_base); } break; /************************/ /* control */ case 0xc2: /* ret im */ val = cpu_ldsw_code(env, s->pc); s->pc += 2; ot = gen_pop_T0(s); gen_stack_update(s, val + (1 << ot)); /* Note that gen_pop_T0 uses a zero-extending load. */ gen_op_jmp_v(cpu_T0); gen_bnd_jmp(s); gen_eob(s); break; case 0xc3: /* ret */ ot = gen_pop_T0(s); gen_pop_update(s, ot); /* Note that gen_pop_T0 uses a zero-extending load. */ gen_op_jmp_v(cpu_T0); gen_bnd_jmp(s); gen_eob(s); break; case 0xca: /* lret im */ val = cpu_ldsw_code(env, s->pc); s->pc += 2; do_lret: if (s->pe && !s->vm86) { gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_lret_protected(cpu_env, tcg_const_i32(dflag - 1), tcg_const_i32(val)); } else { gen_stack_A0(s); /* pop offset */ gen_op_ld_v(s, dflag, cpu_T0, cpu_A0); /* NOTE: keeping EIP updated is not a problem in case of exception */ gen_op_jmp_v(cpu_T0); /* pop selector */ gen_add_A0_im(s, 1 << dflag); gen_op_ld_v(s, dflag, cpu_T0, cpu_A0); gen_op_movl_seg_T0_vm(R_CS); /* add stack offset */ gen_stack_update(s, val + (2 << dflag)); } gen_eob(s); break; case 0xcb: /* lret */ val = 0; goto do_lret; case 0xcf: /* iret */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_IRET); if (!s->pe) { /* real mode */ gen_helper_iret_real(cpu_env, tcg_const_i32(dflag - 1)); set_cc_op(s, CC_OP_EFLAGS); } else if (s->vm86) { if (s->iopl != 3) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_helper_iret_real(cpu_env, tcg_const_i32(dflag - 1)); set_cc_op(s, CC_OP_EFLAGS); } } else { gen_helper_iret_protected(cpu_env, tcg_const_i32(dflag - 1), tcg_const_i32(s->pc - s->cs_base)); set_cc_op(s, CC_OP_EFLAGS); } gen_eob(s); break; case 0xe8: /* call im */ { if (dflag != MO_16) { tval = (int32_t)insn_get(env, s, MO_32); } else { tval = (int16_t)insn_get(env, s, MO_16); } next_eip = s->pc - s->cs_base; tval += next_eip; if (dflag == MO_16) { tval &= 0xffff; } else if (!CODE64(s)) { tval &= 0xffffffff; } tcg_gen_movi_tl(cpu_T0, next_eip); gen_push_v(s, cpu_T0); gen_bnd_jmp(s); gen_jmp(s, tval); } break; case 0x9a: /* lcall im */ { unsigned int selector, offset; if (CODE64(s)) goto illegal_op; ot = dflag; offset = insn_get(env, s, ot); selector = insn_get(env, s, MO_16); tcg_gen_movi_tl(cpu_T0, selector); tcg_gen_movi_tl(cpu_T1, offset); } goto do_lcall; case 0xe9: /* jmp im */ if (dflag != MO_16) { tval = (int32_t)insn_get(env, s, MO_32); } else { tval = (int16_t)insn_get(env, s, MO_16); } tval += s->pc - s->cs_base; if (dflag == MO_16) { tval &= 0xffff; } else if (!CODE64(s)) { tval &= 0xffffffff; } gen_bnd_jmp(s); gen_jmp(s, tval); break; case 0xea: /* ljmp im */ { unsigned int selector, offset; if (CODE64(s)) goto illegal_op; ot = dflag; offset = insn_get(env, s, ot); selector = insn_get(env, s, MO_16); tcg_gen_movi_tl(cpu_T0, selector); tcg_gen_movi_tl(cpu_T1, offset); } goto do_ljmp; case 0xeb: /* jmp Jb */ tval = (int8_t)insn_get(env, s, MO_8); tval += s->pc - s->cs_base; if (dflag == MO_16) { tval &= 0xffff; } gen_jmp(s, tval); break; case 0x70 ... 0x7f: /* jcc Jb */ tval = (int8_t)insn_get(env, s, MO_8); goto do_jcc; case 0x180 ... 0x18f: /* jcc Jv */ if (dflag != MO_16) { tval = (int32_t)insn_get(env, s, MO_32); } else { tval = (int16_t)insn_get(env, s, MO_16); } do_jcc: next_eip = s->pc - s->cs_base; tval += next_eip; if (dflag == MO_16) { tval &= 0xffff; } gen_bnd_jmp(s); gen_jcc(s, b, tval, next_eip); break; case 0x190 ... 0x19f: /* setcc Gv */ modrm = cpu_ldub_code(env, s->pc++); gen_setcc1(s, b, cpu_T0); gen_ldst_modrm(env, s, modrm, MO_8, OR_TMP0, 1); break; case 0x140 ... 0x14f: /* cmov Gv, Ev */ if (!(s->cpuid_features & CPUID_CMOV)) { goto illegal_op; } ot = dflag; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; gen_cmovcc1(env, s, ot, b, modrm, reg); break; /************************/ /* flags */ case 0x9c: /* pushf */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_PUSHF); if (s->vm86 && s->iopl != 3) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_update_cc_op(s); gen_helper_read_eflags(cpu_T0, cpu_env); gen_push_v(s, cpu_T0); } break; case 0x9d: /* popf */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_POPF); if (s->vm86 && s->iopl != 3) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { ot = gen_pop_T0(s); if (s->cpl == 0) { if (dflag != MO_16) { gen_helper_write_eflags(cpu_env, cpu_T0, tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK | IOPL_MASK))); } else { gen_helper_write_eflags(cpu_env, cpu_T0, tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK | IOPL_MASK) & 0xffff)); } } else { if (s->cpl <= s->iopl) { if (dflag != MO_16) { gen_helper_write_eflags(cpu_env, cpu_T0, tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK))); } else { gen_helper_write_eflags(cpu_env, cpu_T0, tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK) & 0xffff)); } } else { if (dflag != MO_16) { gen_helper_write_eflags(cpu_env, cpu_T0, tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK))); } else { gen_helper_write_eflags(cpu_env, cpu_T0, tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK) & 0xffff)); } } } gen_pop_update(s, ot); set_cc_op(s, CC_OP_EFLAGS); /* abort translation because TF/AC flag may change */ gen_jmp_im(s->pc - s->cs_base); gen_eob(s); } break; case 0x9e: /* sahf */ if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM)) goto illegal_op; gen_op_mov_v_reg(MO_8, cpu_T0, R_AH); gen_compute_eflags(s); tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, CC_O); tcg_gen_andi_tl(cpu_T0, cpu_T0, CC_S | CC_Z | CC_A | CC_P | CC_C); tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_T0); break; case 0x9f: /* lahf */ if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM)) goto illegal_op; gen_compute_eflags(s); /* Note: gen_compute_eflags() only gives the condition codes */ tcg_gen_ori_tl(cpu_T0, cpu_cc_src, 0x02); gen_op_mov_reg_v(MO_8, R_AH, cpu_T0); break; case 0xf5: /* cmc */ gen_compute_eflags(s); tcg_gen_xori_tl(cpu_cc_src, cpu_cc_src, CC_C); break; case 0xf8: /* clc */ gen_compute_eflags(s); tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_C); break; case 0xf9: /* stc */ gen_compute_eflags(s); tcg_gen_ori_tl(cpu_cc_src, cpu_cc_src, CC_C); break; case 0xfc: /* cld */ tcg_gen_movi_i32(cpu_tmp2_i32, 1); tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, df)); break; case 0xfd: /* std */ tcg_gen_movi_i32(cpu_tmp2_i32, -1); tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, df)); break; /************************/ /* bit operations */ case 0x1ba: /* bt/bts/btr/btc Gv, im */ ot = dflag; modrm = cpu_ldub_code(env, s->pc++); op = (modrm >> 3) & 7; mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); if (mod != 3) { s->rip_offset = 1; gen_lea_modrm(env, s, modrm); if (!(s->prefix & PREFIX_LOCK)) { gen_op_ld_v(s, ot, cpu_T0, cpu_A0); } } else { gen_op_mov_v_reg(ot, cpu_T0, rm); } /* load shift */ val = cpu_ldub_code(env, s->pc++); tcg_gen_movi_tl(cpu_T1, val); if (op < 4) goto unknown_op; op -= 4; goto bt_op; case 0x1a3: /* bt Gv, Ev */ op = 0; goto do_btx; case 0x1ab: /* bts */ op = 1; goto do_btx; case 0x1b3: /* btr */ op = 2; goto do_btx; case 0x1bb: /* btc */ op = 3; do_btx: ot = dflag; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); gen_op_mov_v_reg(MO_32, cpu_T1, reg); if (mod != 3) { AddressParts a = gen_lea_modrm_0(env, s, modrm); /* specific case: we need to add a displacement */ gen_exts(ot, cpu_T1); tcg_gen_sari_tl(cpu_tmp0, cpu_T1, 3 + ot); tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, ot); tcg_gen_add_tl(cpu_A0, gen_lea_modrm_1(a), cpu_tmp0); gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override); if (!(s->prefix & PREFIX_LOCK)) { gen_op_ld_v(s, ot, cpu_T0, cpu_A0); } } else { gen_op_mov_v_reg(ot, cpu_T0, rm); } bt_op: tcg_gen_andi_tl(cpu_T1, cpu_T1, (1 << (3 + ot)) - 1); tcg_gen_movi_tl(cpu_tmp0, 1); tcg_gen_shl_tl(cpu_tmp0, cpu_tmp0, cpu_T1); if (s->prefix & PREFIX_LOCK) { switch (op) { case 0: /* bt */ /* Needs no atomic ops; we surpressed the normal memory load for LOCK above so do it now. */ gen_op_ld_v(s, ot, cpu_T0, cpu_A0); break; case 1: /* bts */ tcg_gen_atomic_fetch_or_tl(cpu_T0, cpu_A0, cpu_tmp0, s->mem_index, ot | MO_LE); break; case 2: /* btr */ tcg_gen_not_tl(cpu_tmp0, cpu_tmp0); tcg_gen_atomic_fetch_and_tl(cpu_T0, cpu_A0, cpu_tmp0, s->mem_index, ot | MO_LE); break; default: case 3: /* btc */ tcg_gen_atomic_fetch_xor_tl(cpu_T0, cpu_A0, cpu_tmp0, s->mem_index, ot | MO_LE); break; } tcg_gen_shr_tl(cpu_tmp4, cpu_T0, cpu_T1); } else { tcg_gen_shr_tl(cpu_tmp4, cpu_T0, cpu_T1); switch (op) { case 0: /* bt */ /* Data already loaded; nothing to do. */ break; case 1: /* bts */ tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_tmp0); break; case 2: /* btr */ tcg_gen_andc_tl(cpu_T0, cpu_T0, cpu_tmp0); break; default: case 3: /* btc */ tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_tmp0); break; } if (op != 0) { if (mod != 3) { gen_op_st_v(s, ot, cpu_T0, cpu_A0); } else { gen_op_mov_reg_v(ot, rm, cpu_T0); } } } /* Delay all CC updates until after the store above. Note that C is the result of the test, Z is unchanged, and the others are all undefined. */ switch (s->cc_op) { case CC_OP_MULB ... CC_OP_MULQ: case CC_OP_ADDB ... CC_OP_ADDQ: case CC_OP_ADCB ... CC_OP_ADCQ: case CC_OP_SUBB ... CC_OP_SUBQ: case CC_OP_SBBB ... CC_OP_SBBQ: case CC_OP_LOGICB ... CC_OP_LOGICQ: case CC_OP_INCB ... CC_OP_INCQ: case CC_OP_DECB ... CC_OP_DECQ: case CC_OP_SHLB ... CC_OP_SHLQ: case CC_OP_SARB ... CC_OP_SARQ: case CC_OP_BMILGB ... CC_OP_BMILGQ: /* Z was going to be computed from the non-zero status of CC_DST. We can get that same Z value (and the new C value) by leaving CC_DST alone, setting CC_SRC, and using a CC_OP_SAR of the same width. */ tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4); set_cc_op(s, ((s->cc_op - CC_OP_MULB) & 3) + CC_OP_SARB); break; default: /* Otherwise, generate EFLAGS and replace the C bit. */ gen_compute_eflags(s); tcg_gen_deposit_tl(cpu_cc_src, cpu_cc_src, cpu_tmp4, ctz32(CC_C), 1); break; } break; case 0x1bc: /* bsf / tzcnt */ case 0x1bd: /* bsr / lzcnt */ ot = dflag; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); gen_extu(ot, cpu_T0); /* Note that lzcnt and tzcnt are in different extensions. */ if ((prefixes & PREFIX_REPZ) && (b & 1 ? s->cpuid_ext3_features & CPUID_EXT3_ABM : s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)) { int size = 8 << ot; /* For lzcnt/tzcnt, C bit is defined related to the input. */ tcg_gen_mov_tl(cpu_cc_src, cpu_T0); if (b & 1) { /* For lzcnt, reduce the target_ulong result by the number of zeros that we expect to find at the top. */ tcg_gen_clzi_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS); tcg_gen_subi_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS - size); } else { /* For tzcnt, a zero input must return the operand size. */ tcg_gen_ctzi_tl(cpu_T0, cpu_T0, size); } /* For lzcnt/tzcnt, Z bit is defined related to the result. */ gen_op_update1_cc(); set_cc_op(s, CC_OP_BMILGB + ot); } else { /* For bsr/bsf, only the Z bit is defined and it is related to the input and not the result. */ tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); set_cc_op(s, CC_OP_LOGICB + ot); /* ??? The manual says that the output is undefined when the input is zero, but real hardware leaves it unchanged, and real programs appear to depend on that. Accomplish this by passing the output as the value to return upon zero. */ if (b & 1) { /* For bsr, return the bit index of the first 1 bit, not the count of leading zeros. */ tcg_gen_xori_tl(cpu_T1, cpu_regs[reg], TARGET_LONG_BITS - 1); tcg_gen_clz_tl(cpu_T0, cpu_T0, cpu_T1); tcg_gen_xori_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS - 1); } else { tcg_gen_ctz_tl(cpu_T0, cpu_T0, cpu_regs[reg]); } } gen_op_mov_reg_v(ot, reg, cpu_T0); break; /************************/ /* bcd */ case 0x27: /* daa */ if (CODE64(s)) goto illegal_op; gen_update_cc_op(s); gen_helper_daa(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x2f: /* das */ if (CODE64(s)) goto illegal_op; gen_update_cc_op(s); gen_helper_das(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x37: /* aaa */ if (CODE64(s)) goto illegal_op; gen_update_cc_op(s); gen_helper_aaa(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0x3f: /* aas */ if (CODE64(s)) goto illegal_op; gen_update_cc_op(s); gen_helper_aas(cpu_env); set_cc_op(s, CC_OP_EFLAGS); break; case 0xd4: /* aam */ if (CODE64(s)) goto illegal_op; val = cpu_ldub_code(env, s->pc++); if (val == 0) { gen_exception(s, EXCP00_DIVZ, pc_start - s->cs_base); } else { gen_helper_aam(cpu_env, tcg_const_i32(val)); set_cc_op(s, CC_OP_LOGICB); } break; case 0xd5: /* aad */ if (CODE64(s)) goto illegal_op; val = cpu_ldub_code(env, s->pc++); gen_helper_aad(cpu_env, tcg_const_i32(val)); set_cc_op(s, CC_OP_LOGICB); break; /************************/ /* misc */ case 0x90: /* nop */ /* XXX: correct lock test for all insn */ if (prefixes & PREFIX_LOCK) { goto illegal_op; } /* If REX_B is set, then this is xchg eax, r8d, not a nop. */ if (REX_B(s)) { goto do_xchg_reg_eax; } if (prefixes & PREFIX_REPZ) { gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_pause(cpu_env, tcg_const_i32(s->pc - pc_start)); s->is_jmp = DISAS_TB_JUMP; } break; case 0x9b: /* fwait */ if ((s->flags & (HF_MP_MASK | HF_TS_MASK)) == (HF_MP_MASK | HF_TS_MASK)) { gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); } else { gen_helper_fwait(cpu_env); } break; case 0xcc: /* int3 */ gen_interrupt(s, EXCP03_INT3, pc_start - s->cs_base, s->pc - s->cs_base); break; case 0xcd: /* int N */ val = cpu_ldub_code(env, s->pc++); if (s->vm86 && s->iopl != 3) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_interrupt(s, val, pc_start - s->cs_base, s->pc - s->cs_base); } break; case 0xce: /* into */ if (CODE64(s)) goto illegal_op; gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_into(cpu_env, tcg_const_i32(s->pc - pc_start)); break; #ifdef WANT_ICEBP case 0xf1: /* icebp (undocumented, exits to external debugger) */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_ICEBP); #if 1 gen_debug(s, pc_start - s->cs_base); #else /* start debug */ tb_flush(CPU(x86_env_get_cpu(env))); qemu_set_log(CPU_LOG_INT | CPU_LOG_TB_IN_ASM); #endif break; #endif case 0xfa: /* cli */ if (!s->vm86) { if (s->cpl <= s->iopl) { gen_helper_cli(cpu_env); } else { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } } else { if (s->iopl == 3) { gen_helper_cli(cpu_env); } else { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } } break; case 0xfb: /* sti */ if (s->vm86 ? s->iopl == 3 : s->cpl <= s->iopl) { gen_helper_sti(cpu_env); /* interruptions are enabled only the first insn after sti */ gen_jmp_im(s->pc - s->cs_base); gen_eob_inhibit_irq(s, true); } else { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } break; case 0x62: /* bound */ if (CODE64(s)) goto illegal_op; ot = dflag; modrm = cpu_ldub_code(env, s->pc++); reg = (modrm >> 3) & 7; mod = (modrm >> 6) & 3; if (mod == 3) goto illegal_op; gen_op_mov_v_reg(ot, cpu_T0, reg); gen_lea_modrm(env, s, modrm); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); if (ot == MO_16) { gen_helper_boundw(cpu_env, cpu_A0, cpu_tmp2_i32); } else { gen_helper_boundl(cpu_env, cpu_A0, cpu_tmp2_i32); } break; case 0x1c8 ... 0x1cf: /* bswap reg */ reg = (b & 7) | REX_B(s); #ifdef TARGET_X86_64 if (dflag == MO_64) { gen_op_mov_v_reg(MO_64, cpu_T0, reg); tcg_gen_bswap64_i64(cpu_T0, cpu_T0); gen_op_mov_reg_v(MO_64, reg, cpu_T0); } else #endif { gen_op_mov_v_reg(MO_32, cpu_T0, reg); tcg_gen_ext32u_tl(cpu_T0, cpu_T0); tcg_gen_bswap32_tl(cpu_T0, cpu_T0); gen_op_mov_reg_v(MO_32, reg, cpu_T0); } break; case 0xd6: /* salc */ if (CODE64(s)) goto illegal_op; gen_compute_eflags_c(s, cpu_T0); tcg_gen_neg_tl(cpu_T0, cpu_T0); gen_op_mov_reg_v(MO_8, R_EAX, cpu_T0); break; case 0xe0: /* loopnz */ case 0xe1: /* loopz */ case 0xe2: /* loop */ case 0xe3: /* jecxz */ { TCGLabel *l1, *l2, *l3; tval = (int8_t)insn_get(env, s, MO_8); next_eip = s->pc - s->cs_base; tval += next_eip; if (dflag == MO_16) { tval &= 0xffff; } l1 = gen_new_label(); l2 = gen_new_label(); l3 = gen_new_label(); b &= 3; switch(b) { case 0: /* loopnz */ case 1: /* loopz */ gen_op_add_reg_im(s->aflag, R_ECX, -1); gen_op_jz_ecx(s->aflag, l3); gen_jcc1(s, (JCC_Z << 1) | (b ^ 1), l1); break; case 2: /* loop */ gen_op_add_reg_im(s->aflag, R_ECX, -1); gen_op_jnz_ecx(s->aflag, l1); break; default: case 3: /* jcxz */ gen_op_jz_ecx(s->aflag, l1); break; } gen_set_label(l3); gen_jmp_im(next_eip); tcg_gen_br(l2); gen_set_label(l1); gen_jmp_im(tval); gen_set_label(l2); gen_eob(s); } break; case 0x130: /* wrmsr */ case 0x132: /* rdmsr */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); if (b & 2) { gen_helper_rdmsr(cpu_env); } else { gen_helper_wrmsr(cpu_env); } } break; case 0x131: /* rdtsc */ gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } gen_helper_rdtsc(cpu_env); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); gen_jmp(s, s->pc - s->cs_base); } break; case 0x133: /* rdpmc */ gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_rdpmc(cpu_env); break; case 0x134: /* sysenter */ /* For Intel SYSENTER is valid on 64-bit */ if (CODE64(s) && env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1) goto illegal_op; if (!s->pe) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_helper_sysenter(cpu_env); gen_eob(s); } break; case 0x135: /* sysexit */ /* For Intel SYSEXIT is valid on 64-bit */ if (CODE64(s) && env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1) goto illegal_op; if (!s->pe) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_helper_sysexit(cpu_env, tcg_const_i32(dflag - 1)); gen_eob(s); } break; #ifdef TARGET_X86_64 case 0x105: /* syscall */ /* XXX: is it usable in real mode ? */ gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_syscall(cpu_env, tcg_const_i32(s->pc - pc_start)); /* TF handling for the syscall insn is different. The TF bit is checked after the syscall insn completes. This allows #DB to not be generated after one has entered CPL0 if TF is set in FMASK. */ gen_eob_worker(s, false, true); break; case 0x107: /* sysret */ if (!s->pe) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_helper_sysret(cpu_env, tcg_const_i32(dflag - 1)); /* condition codes are modified only in long mode */ if (s->lma) { set_cc_op(s, CC_OP_EFLAGS); } /* TF handling for the sysret insn is different. The TF bit is checked after the sysret insn completes. This allows #DB to be generated "as if" the syscall insn in userspace has just completed. */ gen_eob_worker(s, false, true); } break; #endif case 0x1a2: /* cpuid */ gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_cpuid(cpu_env); break; case 0xf4: /* hlt */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_hlt(cpu_env, tcg_const_i32(s->pc - pc_start)); s->is_jmp = DISAS_TB_JUMP; } break; case 0x100: modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; op = (modrm >> 3) & 7; switch(op) { case 0: /* sldt */ if (!s->pe || s->vm86) goto illegal_op; gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_READ); tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, ldt.selector)); ot = mod == 3 ? dflag : MO_16; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1); break; case 2: /* lldt */ if (!s->pe || s->vm86) goto illegal_op; if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_WRITE); gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_lldt(cpu_env, cpu_tmp2_i32); } break; case 1: /* str */ if (!s->pe || s->vm86) goto illegal_op; gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_READ); tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, tr.selector)); ot = mod == 3 ? dflag : MO_16; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1); break; case 3: /* ltr */ if (!s->pe || s->vm86) goto illegal_op; if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_WRITE); gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_ltr(cpu_env, cpu_tmp2_i32); } break; case 4: /* verr */ case 5: /* verw */ if (!s->pe || s->vm86) goto illegal_op; gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); gen_update_cc_op(s); if (op == 4) { gen_helper_verr(cpu_env, cpu_T0); } else { gen_helper_verw(cpu_env, cpu_T0); } set_cc_op(s, CC_OP_EFLAGS); break; default: goto unknown_op; } break; case 0x101: modrm = cpu_ldub_code(env, s->pc++); switch (modrm) { CASE_MODRM_MEM_OP(0): /* sgdt */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_READ); gen_lea_modrm(env, s, modrm); tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.limit)); gen_op_st_v(s, MO_16, cpu_T0, cpu_A0); gen_add_A0_im(s, 2); tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.base)); if (dflag == MO_16) { tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff); } gen_op_st_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0); break; case 0xc8: /* monitor */ if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) || s->cpl != 0) { goto illegal_op; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EAX]); gen_extu(s->aflag, cpu_A0); gen_add_A0_ds_seg(s); gen_helper_monitor(cpu_env, cpu_A0); break; case 0xc9: /* mwait */ if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) || s->cpl != 0) { goto illegal_op; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_mwait(cpu_env, tcg_const_i32(s->pc - pc_start)); gen_eob(s); break; case 0xca: /* clac */ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_SMAP) || s->cpl != 0) { goto illegal_op; } gen_helper_clac(cpu_env); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); break; case 0xcb: /* stac */ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_SMAP) || s->cpl != 0) { goto illegal_op; } gen_helper_stac(cpu_env); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); break; CASE_MODRM_MEM_OP(1): /* sidt */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_READ); gen_lea_modrm(env, s, modrm); tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.limit)); gen_op_st_v(s, MO_16, cpu_T0, cpu_A0); gen_add_A0_im(s, 2); tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.base)); if (dflag == MO_16) { tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff); } gen_op_st_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0); break; case 0xd0: /* xgetbv */ if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0 || (s->prefix & (PREFIX_LOCK | PREFIX_DATA | PREFIX_REPZ | PREFIX_REPNZ))) { goto illegal_op; } tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]); gen_helper_xgetbv(cpu_tmp1_i64, cpu_env, cpu_tmp2_i32); tcg_gen_extr_i64_tl(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_tmp1_i64); break; case 0xd1: /* xsetbv */ if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0 || (s->prefix & (PREFIX_LOCK | PREFIX_DATA | PREFIX_REPZ | PREFIX_REPNZ))) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX], cpu_regs[R_EDX]); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]); gen_helper_xsetbv(cpu_env, cpu_tmp2_i32, cpu_tmp1_i64); /* End TB because translation flags may change. */ gen_jmp_im(s->pc - s->cs_base); gen_eob(s); break; case 0xd8: /* VMRUN */ if (!(s->flags & HF_SVME_MASK) || !s->pe) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_vmrun(cpu_env, tcg_const_i32(s->aflag - 1), tcg_const_i32(s->pc - pc_start)); tcg_gen_exit_tb(0); s->is_jmp = DISAS_TB_JUMP; break; case 0xd9: /* VMMCALL */ if (!(s->flags & HF_SVME_MASK)) { goto illegal_op; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_vmmcall(cpu_env); break; case 0xda: /* VMLOAD */ if (!(s->flags & HF_SVME_MASK) || !s->pe) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_vmload(cpu_env, tcg_const_i32(s->aflag - 1)); break; case 0xdb: /* VMSAVE */ if (!(s->flags & HF_SVME_MASK) || !s->pe) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_vmsave(cpu_env, tcg_const_i32(s->aflag - 1)); break; case 0xdc: /* STGI */ if ((!(s->flags & HF_SVME_MASK) && !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT)) || !s->pe) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_stgi(cpu_env); break; case 0xdd: /* CLGI */ if (!(s->flags & HF_SVME_MASK) || !s->pe) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_clgi(cpu_env); break; case 0xde: /* SKINIT */ if ((!(s->flags & HF_SVME_MASK) && !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT)) || !s->pe) { goto illegal_op; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_skinit(cpu_env); break; case 0xdf: /* INVLPGA */ if (!(s->flags & HF_SVME_MASK) || !s->pe) { goto illegal_op; } if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_helper_invlpga(cpu_env, tcg_const_i32(s->aflag - 1)); break; CASE_MODRM_MEM_OP(2): /* lgdt */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_WRITE); gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, MO_16, cpu_T1, cpu_A0); gen_add_A0_im(s, 2); gen_op_ld_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0); if (dflag == MO_16) { tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff); } tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.base)); tcg_gen_st32_tl(cpu_T1, cpu_env, offsetof(CPUX86State, gdt.limit)); break; CASE_MODRM_MEM_OP(3): /* lidt */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_WRITE); gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, MO_16, cpu_T1, cpu_A0); gen_add_A0_im(s, 2); gen_op_ld_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0); if (dflag == MO_16) { tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff); } tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.base)); tcg_gen_st32_tl(cpu_T1, cpu_env, offsetof(CPUX86State, idt.limit)); break; CASE_MODRM_OP(4): /* smsw */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_CR0); tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, cr[0])); if (CODE64(s)) { mod = (modrm >> 6) & 3; ot = (mod != 3 ? MO_16 : s->dflag); } else { ot = MO_16; } gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1); break; case 0xee: /* rdpkru */ if (prefixes & PREFIX_LOCK) { goto illegal_op; } tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]); gen_helper_rdpkru(cpu_tmp1_i64, cpu_env, cpu_tmp2_i32); tcg_gen_extr_i64_tl(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_tmp1_i64); break; case 0xef: /* wrpkru */ if (prefixes & PREFIX_LOCK) { goto illegal_op; } tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX], cpu_regs[R_EDX]); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]); gen_helper_wrpkru(cpu_env, cpu_tmp2_i32, cpu_tmp1_i64); break; CASE_MODRM_OP(6): /* lmsw */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0); gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); gen_helper_lmsw(cpu_env, cpu_T0); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); break; CASE_MODRM_MEM_OP(7): /* invlpg */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); break; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); gen_lea_modrm(env, s, modrm); gen_helper_invlpg(cpu_env, cpu_A0); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); break; case 0xf8: /* swapgs */ #ifdef TARGET_X86_64 if (CODE64(s)) { if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { tcg_gen_mov_tl(cpu_T0, cpu_seg_base[R_GS]); tcg_gen_ld_tl(cpu_seg_base[R_GS], cpu_env, offsetof(CPUX86State, kernelgsbase)); tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, kernelgsbase)); } break; } #endif goto illegal_op; case 0xf9: /* rdtscp */ if (!(s->cpuid_ext2_features & CPUID_EXT2_RDTSCP)) { goto illegal_op; } gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } gen_helper_rdtscp(cpu_env); if (s->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); gen_jmp(s, s->pc - s->cs_base); } break; default: goto unknown_op; } break; case 0x108: /* invd */ case 0x109: /* wbinvd */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_svm_check_intercept(s, pc_start, (b & 2) ? SVM_EXIT_INVD : SVM_EXIT_WBINVD); /* nothing to do */ } break; case 0x63: /* arpl or movslS (x86_64) */ #ifdef TARGET_X86_64 if (CODE64(s)) { int d_ot; /* d_ot is the size of destination */ d_ot = dflag; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; rm = (modrm & 7) | REX_B(s); if (mod == 3) { gen_op_mov_v_reg(MO_32, cpu_T0, rm); /* sign extend */ if (d_ot == MO_64) { tcg_gen_ext32s_tl(cpu_T0, cpu_T0); } gen_op_mov_reg_v(d_ot, reg, cpu_T0); } else { gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, MO_32 | MO_SIGN, cpu_T0, cpu_A0); gen_op_mov_reg_v(d_ot, reg, cpu_T0); } } else #endif { TCGLabel *label1; TCGv t0, t1, t2, a0; if (!s->pe || s->vm86) goto illegal_op; t0 = tcg_temp_local_new(); t1 = tcg_temp_local_new(); t2 = tcg_temp_local_new(); ot = MO_16; modrm = cpu_ldub_code(env, s->pc++); reg = (modrm >> 3) & 7; mod = (modrm >> 6) & 3; rm = modrm & 7; if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, ot, t0, cpu_A0); a0 = tcg_temp_local_new(); tcg_gen_mov_tl(a0, cpu_A0); } else { gen_op_mov_v_reg(ot, t0, rm); TCGV_UNUSED(a0); } gen_op_mov_v_reg(ot, t1, reg); tcg_gen_andi_tl(cpu_tmp0, t0, 3); tcg_gen_andi_tl(t1, t1, 3); tcg_gen_movi_tl(t2, 0); label1 = gen_new_label(); tcg_gen_brcond_tl(TCG_COND_GE, cpu_tmp0, t1, label1); tcg_gen_andi_tl(t0, t0, ~3); tcg_gen_or_tl(t0, t0, t1); tcg_gen_movi_tl(t2, CC_Z); gen_set_label(label1); if (mod != 3) { gen_op_st_v(s, ot, t0, a0); tcg_temp_free(a0); } else { gen_op_mov_reg_v(ot, rm, t0); } gen_compute_eflags(s); tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_Z); tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, t2); tcg_temp_free(t0); tcg_temp_free(t1); tcg_temp_free(t2); } break; case 0x102: /* lar */ case 0x103: /* lsl */ { TCGLabel *label1; TCGv t0; if (!s->pe || s->vm86) goto illegal_op; ot = dflag != MO_16 ? MO_32 : MO_16; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); t0 = tcg_temp_local_new(); gen_update_cc_op(s); if (b == 0x102) { gen_helper_lar(t0, cpu_env, cpu_T0); } else { gen_helper_lsl(t0, cpu_env, cpu_T0); } tcg_gen_andi_tl(cpu_tmp0, cpu_cc_src, CC_Z); label1 = gen_new_label(); tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1); gen_op_mov_reg_v(ot, reg, t0); gen_set_label(label1); set_cc_op(s, CC_OP_EFLAGS); tcg_temp_free(t0); } break; case 0x118: modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; op = (modrm >> 3) & 7; switch(op) { case 0: /* prefetchnta */ case 1: /* prefetchnt0 */ case 2: /* prefetchnt0 */ case 3: /* prefetchnt0 */ if (mod == 3) goto illegal_op; gen_nop_modrm(env, s, modrm); /* nothing more to do */ break; default: /* nop (multi byte) */ gen_nop_modrm(env, s, modrm); break; } break; case 0x11a: modrm = cpu_ldub_code(env, s->pc++); if (s->flags & HF_MPX_EN_MASK) { mod = (modrm >> 6) & 3; reg = ((modrm >> 3) & 7) | rex_r; if (prefixes & PREFIX_REPZ) { /* bndcl */ if (reg >= 4 || (prefixes & PREFIX_LOCK) || s->aflag == MO_16) { goto illegal_op; } gen_bndck(env, s, modrm, TCG_COND_LTU, cpu_bndl[reg]); } else if (prefixes & PREFIX_REPNZ) { /* bndcu */ if (reg >= 4 || (prefixes & PREFIX_LOCK) || s->aflag == MO_16) { goto illegal_op; } TCGv_i64 notu = tcg_temp_new_i64(); tcg_gen_not_i64(notu, cpu_bndu[reg]); gen_bndck(env, s, modrm, TCG_COND_GTU, notu); tcg_temp_free_i64(notu); } else if (prefixes & PREFIX_DATA) { /* bndmov -- from reg/mem */ if (reg >= 4 || s->aflag == MO_16) { goto illegal_op; } if (mod == 3) { int reg2 = (modrm & 7) | REX_B(s); if (reg2 >= 4 || (prefixes & PREFIX_LOCK)) { goto illegal_op; } if (s->flags & HF_MPX_IU_MASK) { tcg_gen_mov_i64(cpu_bndl[reg], cpu_bndl[reg2]); tcg_gen_mov_i64(cpu_bndu[reg], cpu_bndu[reg2]); } } else { gen_lea_modrm(env, s, modrm); if (CODE64(s)) { tcg_gen_qemu_ld_i64(cpu_bndl[reg], cpu_A0, s->mem_index, MO_LEQ); tcg_gen_addi_tl(cpu_A0, cpu_A0, 8); tcg_gen_qemu_ld_i64(cpu_bndu[reg], cpu_A0, s->mem_index, MO_LEQ); } else { tcg_gen_qemu_ld_i64(cpu_bndl[reg], cpu_A0, s->mem_index, MO_LEUL); tcg_gen_addi_tl(cpu_A0, cpu_A0, 4); tcg_gen_qemu_ld_i64(cpu_bndu[reg], cpu_A0, s->mem_index, MO_LEUL); } /* bnd registers are now in-use */ gen_set_hflag(s, HF_MPX_IU_MASK); } } else if (mod != 3) { /* bndldx */ AddressParts a = gen_lea_modrm_0(env, s, modrm); if (reg >= 4 || (prefixes & PREFIX_LOCK) || s->aflag == MO_16 || a.base < -1) { goto illegal_op; } if (a.base >= 0) { tcg_gen_addi_tl(cpu_A0, cpu_regs[a.base], a.disp); } else { tcg_gen_movi_tl(cpu_A0, 0); } gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override); if (a.index >= 0) { tcg_gen_mov_tl(cpu_T0, cpu_regs[a.index]); } else { tcg_gen_movi_tl(cpu_T0, 0); } if (CODE64(s)) { gen_helper_bndldx64(cpu_bndl[reg], cpu_env, cpu_A0, cpu_T0); tcg_gen_ld_i64(cpu_bndu[reg], cpu_env, offsetof(CPUX86State, mmx_t0.MMX_Q(0))); } else { gen_helper_bndldx32(cpu_bndu[reg], cpu_env, cpu_A0, cpu_T0); tcg_gen_ext32u_i64(cpu_bndl[reg], cpu_bndu[reg]); tcg_gen_shri_i64(cpu_bndu[reg], cpu_bndu[reg], 32); } gen_set_hflag(s, HF_MPX_IU_MASK); } } gen_nop_modrm(env, s, modrm); break; case 0x11b: modrm = cpu_ldub_code(env, s->pc++); if (s->flags & HF_MPX_EN_MASK) { mod = (modrm >> 6) & 3; reg = ((modrm >> 3) & 7) | rex_r; if (mod != 3 && (prefixes & PREFIX_REPZ)) { /* bndmk */ if (reg >= 4 || (prefixes & PREFIX_LOCK) || s->aflag == MO_16) { goto illegal_op; } AddressParts a = gen_lea_modrm_0(env, s, modrm); if (a.base >= 0) { tcg_gen_extu_tl_i64(cpu_bndl[reg], cpu_regs[a.base]); if (!CODE64(s)) { tcg_gen_ext32u_i64(cpu_bndl[reg], cpu_bndl[reg]); } } else if (a.base == -1) { /* no base register has lower bound of 0 */ tcg_gen_movi_i64(cpu_bndl[reg], 0); } else { /* rip-relative generates #ud */ goto illegal_op; } tcg_gen_not_tl(cpu_A0, gen_lea_modrm_1(a)); if (!CODE64(s)) { tcg_gen_ext32u_tl(cpu_A0, cpu_A0); } tcg_gen_extu_tl_i64(cpu_bndu[reg], cpu_A0); /* bnd registers are now in-use */ gen_set_hflag(s, HF_MPX_IU_MASK); break; } else if (prefixes & PREFIX_REPNZ) { /* bndcn */ if (reg >= 4 || (prefixes & PREFIX_LOCK) || s->aflag == MO_16) { goto illegal_op; } gen_bndck(env, s, modrm, TCG_COND_GTU, cpu_bndu[reg]); } else if (prefixes & PREFIX_DATA) { /* bndmov -- to reg/mem */ if (reg >= 4 || s->aflag == MO_16) { goto illegal_op; } if (mod == 3) { int reg2 = (modrm & 7) | REX_B(s); if (reg2 >= 4 || (prefixes & PREFIX_LOCK)) { goto illegal_op; } if (s->flags & HF_MPX_IU_MASK) { tcg_gen_mov_i64(cpu_bndl[reg2], cpu_bndl[reg]); tcg_gen_mov_i64(cpu_bndu[reg2], cpu_bndu[reg]); } } else { gen_lea_modrm(env, s, modrm); if (CODE64(s)) { tcg_gen_qemu_st_i64(cpu_bndl[reg], cpu_A0, s->mem_index, MO_LEQ); tcg_gen_addi_tl(cpu_A0, cpu_A0, 8); tcg_gen_qemu_st_i64(cpu_bndu[reg], cpu_A0, s->mem_index, MO_LEQ); } else { tcg_gen_qemu_st_i64(cpu_bndl[reg], cpu_A0, s->mem_index, MO_LEUL); tcg_gen_addi_tl(cpu_A0, cpu_A0, 4); tcg_gen_qemu_st_i64(cpu_bndu[reg], cpu_A0, s->mem_index, MO_LEUL); } } } else if (mod != 3) { /* bndstx */ AddressParts a = gen_lea_modrm_0(env, s, modrm); if (reg >= 4 || (prefixes & PREFIX_LOCK) || s->aflag == MO_16 || a.base < -1) { goto illegal_op; } if (a.base >= 0) { tcg_gen_addi_tl(cpu_A0, cpu_regs[a.base], a.disp); } else { tcg_gen_movi_tl(cpu_A0, 0); } gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override); if (a.index >= 0) { tcg_gen_mov_tl(cpu_T0, cpu_regs[a.index]); } else { tcg_gen_movi_tl(cpu_T0, 0); } if (CODE64(s)) { gen_helper_bndstx64(cpu_env, cpu_A0, cpu_T0, cpu_bndl[reg], cpu_bndu[reg]); } else { gen_helper_bndstx32(cpu_env, cpu_A0, cpu_T0, cpu_bndl[reg], cpu_bndu[reg]); } } } gen_nop_modrm(env, s, modrm); break; case 0x119: case 0x11c ... 0x11f: /* nop (multi byte) */ modrm = cpu_ldub_code(env, s->pc++); gen_nop_modrm(env, s, modrm); break; case 0x120: /* mov reg, crN */ case 0x122: /* mov crN, reg */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { modrm = cpu_ldub_code(env, s->pc++); /* Ignore the mod bits (assume (modrm&0xc0)==0xc0). * AMD documentation (24594.pdf) and testing of * intel 386 and 486 processors all show that the mod bits * are assumed to be 1's, regardless of actual values. */ rm = (modrm & 7) | REX_B(s); reg = ((modrm >> 3) & 7) | rex_r; if (CODE64(s)) ot = MO_64; else ot = MO_32; if ((prefixes & PREFIX_LOCK) && (reg == 0) && (s->cpuid_ext3_features & CPUID_EXT3_CR8LEG)) { reg = 8; } switch(reg) { case 0: case 2: case 3: case 4: case 8: gen_update_cc_op(s); gen_jmp_im(pc_start - s->cs_base); if (b & 2) { gen_op_mov_v_reg(ot, cpu_T0, rm); gen_helper_write_crN(cpu_env, tcg_const_i32(reg), cpu_T0); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); } else { gen_helper_read_crN(cpu_T0, cpu_env, tcg_const_i32(reg)); gen_op_mov_reg_v(ot, rm, cpu_T0); } break; default: goto unknown_op; } } break; case 0x121: /* mov reg, drN */ case 0x123: /* mov drN, reg */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { modrm = cpu_ldub_code(env, s->pc++); /* Ignore the mod bits (assume (modrm&0xc0)==0xc0). * AMD documentation (24594.pdf) and testing of * intel 386 and 486 processors all show that the mod bits * are assumed to be 1's, regardless of actual values. */ rm = (modrm & 7) | REX_B(s); reg = ((modrm >> 3) & 7) | rex_r; if (CODE64(s)) ot = MO_64; else ot = MO_32; if (reg >= 8) { goto illegal_op; } if (b & 2) { gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_DR0 + reg); gen_op_mov_v_reg(ot, cpu_T0, rm); tcg_gen_movi_i32(cpu_tmp2_i32, reg); gen_helper_set_dr(cpu_env, cpu_tmp2_i32, cpu_T0); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); } else { gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_DR0 + reg); tcg_gen_movi_i32(cpu_tmp2_i32, reg); gen_helper_get_dr(cpu_T0, cpu_env, cpu_tmp2_i32); gen_op_mov_reg_v(ot, rm, cpu_T0); } } break; case 0x106: /* clts */ if (s->cpl != 0) { gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base); } else { gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0); gen_helper_clts(cpu_env); /* abort block because static cpu state changed */ gen_jmp_im(s->pc - s->cs_base); gen_eob(s); } break; /* MMX/3DNow!/SSE/SSE2/SSE3/SSSE3/SSE4 support */ case 0x1c3: /* MOVNTI reg, mem */ if (!(s->cpuid_features & CPUID_SSE2)) goto illegal_op; ot = mo_64_32(dflag); modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; if (mod == 3) goto illegal_op; reg = ((modrm >> 3) & 7) | rex_r; /* generate a generic store */ gen_ldst_modrm(env, s, modrm, ot, reg, 1); break; case 0x1ae: modrm = cpu_ldub_code(env, s->pc++); switch (modrm) { CASE_MODRM_MEM_OP(0): /* fxsave */ if (!(s->cpuid_features & CPUID_FXSR) || (prefixes & PREFIX_LOCK)) { goto illegal_op; } if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) { gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); break; } gen_lea_modrm(env, s, modrm); gen_helper_fxsave(cpu_env, cpu_A0); break; CASE_MODRM_MEM_OP(1): /* fxrstor */ if (!(s->cpuid_features & CPUID_FXSR) || (prefixes & PREFIX_LOCK)) { goto illegal_op; } if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) { gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); break; } gen_lea_modrm(env, s, modrm); gen_helper_fxrstor(cpu_env, cpu_A0); break; CASE_MODRM_MEM_OP(2): /* ldmxcsr */ if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK)) { goto illegal_op; } if (s->flags & HF_TS_MASK) { gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); break; } gen_lea_modrm(env, s, modrm); tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); gen_helper_ldmxcsr(cpu_env, cpu_tmp2_i32); break; CASE_MODRM_MEM_OP(3): /* stmxcsr */ if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK)) { goto illegal_op; } if (s->flags & HF_TS_MASK) { gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); break; } gen_lea_modrm(env, s, modrm); tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, mxcsr)); gen_op_st_v(s, MO_32, cpu_T0, cpu_A0); break; CASE_MODRM_MEM_OP(4): /* xsave */ if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0 || (prefixes & (PREFIX_LOCK | PREFIX_DATA | PREFIX_REPZ | PREFIX_REPNZ))) { goto illegal_op; } gen_lea_modrm(env, s, modrm); tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX], cpu_regs[R_EDX]); gen_helper_xsave(cpu_env, cpu_A0, cpu_tmp1_i64); break; CASE_MODRM_MEM_OP(5): /* xrstor */ if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0 || (prefixes & (PREFIX_LOCK | PREFIX_DATA | PREFIX_REPZ | PREFIX_REPNZ))) { goto illegal_op; } gen_lea_modrm(env, s, modrm); tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX], cpu_regs[R_EDX]); gen_helper_xrstor(cpu_env, cpu_A0, cpu_tmp1_i64); /* XRSTOR is how MPX is enabled, which changes how we translate. Thus we need to end the TB. */ gen_update_cc_op(s); gen_jmp_im(s->pc - s->cs_base); gen_eob(s); break; CASE_MODRM_MEM_OP(6): /* xsaveopt / clwb */ if (prefixes & PREFIX_LOCK) { goto illegal_op; } if (prefixes & PREFIX_DATA) { /* clwb */ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_CLWB)) { goto illegal_op; } gen_nop_modrm(env, s, modrm); } else { /* xsaveopt */ if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0 || (s->cpuid_xsave_features & CPUID_XSAVE_XSAVEOPT) == 0 || (prefixes & (PREFIX_REPZ | PREFIX_REPNZ))) { goto illegal_op; } gen_lea_modrm(env, s, modrm); tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX], cpu_regs[R_EDX]); gen_helper_xsaveopt(cpu_env, cpu_A0, cpu_tmp1_i64); } break; CASE_MODRM_MEM_OP(7): /* clflush / clflushopt */ if (prefixes & PREFIX_LOCK) { goto illegal_op; } if (prefixes & PREFIX_DATA) { /* clflushopt */ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_CLFLUSHOPT)) { goto illegal_op; } } else { /* clflush */ if ((s->prefix & (PREFIX_REPZ | PREFIX_REPNZ)) || !(s->cpuid_features & CPUID_CLFLUSH)) { goto illegal_op; } } gen_nop_modrm(env, s, modrm); break; case 0xc0 ... 0xc7: /* rdfsbase (f3 0f ae /0) */ case 0xc8 ... 0xc8: /* rdgsbase (f3 0f ae /1) */ case 0xd0 ... 0xd7: /* wrfsbase (f3 0f ae /2) */ case 0xd8 ... 0xd8: /* wrgsbase (f3 0f ae /3) */ if (CODE64(s) && (prefixes & PREFIX_REPZ) && !(prefixes & PREFIX_LOCK) && (s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_FSGSBASE)) { TCGv base, treg, src, dst; /* Preserve hflags bits by testing CR4 at runtime. */ tcg_gen_movi_i32(cpu_tmp2_i32, CR4_FSGSBASE_MASK); gen_helper_cr4_testbit(cpu_env, cpu_tmp2_i32); base = cpu_seg_base[modrm & 8 ? R_GS : R_FS]; treg = cpu_regs[(modrm & 7) | REX_B(s)]; if (modrm & 0x10) { /* wr*base */ dst = base, src = treg; } else { /* rd*base */ dst = treg, src = base; } if (s->dflag == MO_32) { tcg_gen_ext32u_tl(dst, src); } else { tcg_gen_mov_tl(dst, src); } break; } goto unknown_op; case 0xf8: /* sfence / pcommit */ if (prefixes & PREFIX_DATA) { /* pcommit */ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_PCOMMIT) || (prefixes & PREFIX_LOCK)) { goto illegal_op; } break; } /* fallthru */ case 0xf9 ... 0xff: /* sfence */ if (!(s->cpuid_features & CPUID_SSE) || (prefixes & PREFIX_LOCK)) { goto illegal_op; } tcg_gen_mb(TCG_MO_ST_ST | TCG_BAR_SC); break; case 0xe8 ... 0xef: /* lfence */ if (!(s->cpuid_features & CPUID_SSE) || (prefixes & PREFIX_LOCK)) { goto illegal_op; } tcg_gen_mb(TCG_MO_LD_LD | TCG_BAR_SC); break; case 0xf0 ... 0xf7: /* mfence */ if (!(s->cpuid_features & CPUID_SSE2) || (prefixes & PREFIX_LOCK)) { goto illegal_op; } tcg_gen_mb(TCG_MO_ALL | TCG_BAR_SC); break; default: goto unknown_op; } break; case 0x10d: /* 3DNow! prefetch(w) */ modrm = cpu_ldub_code(env, s->pc++); mod = (modrm >> 6) & 3; if (mod == 3) goto illegal_op; gen_nop_modrm(env, s, modrm); break; case 0x1aa: /* rsm */ gen_svm_check_intercept(s, pc_start, SVM_EXIT_RSM); if (!(s->flags & HF_SMM_MASK)) goto illegal_op; gen_update_cc_op(s); gen_jmp_im(s->pc - s->cs_base); gen_helper_rsm(cpu_env); gen_eob(s); break; case 0x1b8: /* SSE4.2 popcnt */ if ((prefixes & (PREFIX_REPZ | PREFIX_LOCK | PREFIX_REPNZ)) != PREFIX_REPZ) goto illegal_op; if (!(s->cpuid_ext_features & CPUID_EXT_POPCNT)) goto illegal_op; modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; if (s->prefix & PREFIX_DATA) { ot = MO_16; } else { ot = mo_64_32(dflag); } gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); gen_extu(ot, cpu_T0); tcg_gen_mov_tl(cpu_cc_src, cpu_T0); tcg_gen_ctpop_tl(cpu_T0, cpu_T0); gen_op_mov_reg_v(ot, reg, cpu_T0); set_cc_op(s, CC_OP_POPCNT); break; case 0x10e ... 0x10f: /* 3DNow! instructions, ignore prefixes */ s->prefix &= ~(PREFIX_REPZ | PREFIX_REPNZ | PREFIX_DATA); case 0x110 ... 0x117: case 0x128 ... 0x12f: case 0x138 ... 0x13a: case 0x150 ... 0x179: case 0x17c ... 0x17f: case 0x1c2: case 0x1c4 ... 0x1c6: case 0x1d0 ... 0x1fe: gen_sse(env, s, b, pc_start, rex_r); break; default: goto unknown_op; } return s->pc; illegal_op: gen_illegal_opcode(s); return s->pc; unknown_op: gen_unknown_opcode(env, s); return s->pc; }
CWE-94
181,377
10,578
221784271832947287450039586155595286180
null
null
null
redis
874804da0c014a7d704b3d285aa500098a931f50
1
void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; }
CWE-254
181,625
10,586
23874964081148539594061330300699288829
null
null
null
quagga
cfb1fae25f8c092e0d17073eaf7bd428ce1cd546
1
rtadv_read (struct thread *thread) { int sock; int len; u_char buf[RTADV_MSG_SIZE]; struct sockaddr_in6 from; ifindex_t ifindex = 0; int hoplimit = -1; struct zebra_vrf *zvrf = THREAD_ARG (thread); sock = THREAD_FD (thread); zvrf->rtadv.ra_read = NULL; /* Register myself. */ rtadv_event (zvrf, RTADV_READ, sock); len = rtadv_recv_packet (sock, buf, BUFSIZ, &from, &ifindex, &hoplimit); if (len < 0) { zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno)); return len; } rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id); return 0; }
CWE-119
182,020
10,589
147071443723396086519744310507543357888
null
null
null
ntp
553f2fa65865c31c5e3c48812cfd46176cffdd27
1
yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: /* Line 1455 of yacc.c */ #line 320 "ntp_parser.y" { /* I will need to incorporate much more fine grained * error messages. The following should suffice for * the time being. */ msyslog(LOG_ERR, "syntax error in %s line %d, column %d", ip_file->fname, ip_file->err_line_no, ip_file->err_col_no); } break; case 19: /* Line 1455 of yacc.c */ #line 354 "ntp_parser.y" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (3)].Integer), (yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue)); if (my_node) enqueue(cfgt.peers, my_node); } break; case 20: /* Line 1455 of yacc.c */ #line 360 "ntp_parser.y" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node), NULL); if (my_node) enqueue(cfgt.peers, my_node); } break; case 27: /* Line 1455 of yacc.c */ #line 377 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET); } break; case 28: /* Line 1455 of yacc.c */ #line 378 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET6); } break; case 29: /* Line 1455 of yacc.c */ #line 382 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(1) - (1)].String), 0); } break; case 30: /* Line 1455 of yacc.c */ #line 386 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 31: /* Line 1455 of yacc.c */ #line 387 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 32: /* Line 1455 of yacc.c */ #line 391 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 33: /* Line 1455 of yacc.c */ #line 392 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 34: /* Line 1455 of yacc.c */ #line 393 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 35: /* Line 1455 of yacc.c */ #line 394 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 36: /* Line 1455 of yacc.c */ #line 395 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 37: /* Line 1455 of yacc.c */ #line 396 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 38: /* Line 1455 of yacc.c */ #line 397 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 39: /* Line 1455 of yacc.c */ #line 398 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 40: /* Line 1455 of yacc.c */ #line 399 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 41: /* Line 1455 of yacc.c */ #line 400 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 42: /* Line 1455 of yacc.c */ #line 401 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 43: /* Line 1455 of yacc.c */ #line 402 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 44: /* Line 1455 of yacc.c */ #line 403 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 45: /* Line 1455 of yacc.c */ #line 404 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 46: /* Line 1455 of yacc.c */ #line 405 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 47: /* Line 1455 of yacc.c */ #line 415 "ntp_parser.y" { struct unpeer_node *my_node = create_unpeer_node((yyvsp[(2) - (2)].Address_node)); if (my_node) enqueue(cfgt.unpeers, my_node); } break; case 50: /* Line 1455 of yacc.c */ #line 434 "ntp_parser.y" { cfgt.broadcastclient = 1; } break; case 51: /* Line 1455 of yacc.c */ #line 436 "ntp_parser.y" { append_queue(cfgt.manycastserver, (yyvsp[(2) - (2)].Queue)); } break; case 52: /* Line 1455 of yacc.c */ #line 438 "ntp_parser.y" { append_queue(cfgt.multicastclient, (yyvsp[(2) - (2)].Queue)); } break; case 53: /* Line 1455 of yacc.c */ #line 449 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 54: /* Line 1455 of yacc.c */ #line 451 "ntp_parser.y" { cfgt.auth.control_key = (yyvsp[(2) - (2)].Integer); } break; case 55: /* Line 1455 of yacc.c */ #line 453 "ntp_parser.y" { cfgt.auth.cryptosw++; append_queue(cfgt.auth.crypto_cmd_list, (yyvsp[(2) - (2)].Queue)); } break; case 56: /* Line 1455 of yacc.c */ #line 458 "ntp_parser.y" { cfgt.auth.keys = (yyvsp[(2) - (2)].String); } break; case 57: /* Line 1455 of yacc.c */ #line 460 "ntp_parser.y" { cfgt.auth.keysdir = (yyvsp[(2) - (2)].String); } break; case 58: /* Line 1455 of yacc.c */ #line 462 "ntp_parser.y" { cfgt.auth.request_key = (yyvsp[(2) - (2)].Integer); } break; case 59: /* Line 1455 of yacc.c */ #line 464 "ntp_parser.y" { cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); } break; case 60: /* Line 1455 of yacc.c */ #line 466 "ntp_parser.y" { cfgt.auth.trusted_key_list = (yyvsp[(2) - (2)].Queue); } break; case 61: /* Line 1455 of yacc.c */ #line 468 "ntp_parser.y" { cfgt.auth.ntp_signd_socket = (yyvsp[(2) - (2)].String); } break; case 63: /* Line 1455 of yacc.c */ #line 474 "ntp_parser.y" { (yyval.Queue) = create_queue(); } break; case 64: /* Line 1455 of yacc.c */ #line 479 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 65: /* Line 1455 of yacc.c */ #line 486 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 66: /* Line 1455 of yacc.c */ #line 496 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 67: /* Line 1455 of yacc.c */ #line 498 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 68: /* Line 1455 of yacc.c */ #line 500 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 69: /* Line 1455 of yacc.c */ #line 502 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 70: /* Line 1455 of yacc.c */ #line 504 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 71: /* Line 1455 of yacc.c */ #line 506 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 72: /* Line 1455 of yacc.c */ #line 508 "ntp_parser.y" { (yyval.Attr_val) = NULL; cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); msyslog(LOG_WARNING, "'crypto revoke %d' is deprecated, " "please use 'revoke %d' instead.", cfgt.auth.revoke, cfgt.auth.revoke); } break; case 73: /* Line 1455 of yacc.c */ #line 525 "ntp_parser.y" { append_queue(cfgt.orphan_cmds,(yyvsp[(2) - (2)].Queue)); } break; case 74: /* Line 1455 of yacc.c */ #line 529 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 75: /* Line 1455 of yacc.c */ #line 530 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 76: /* Line 1455 of yacc.c */ #line 535 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 77: /* Line 1455 of yacc.c */ #line 537 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 78: /* Line 1455 of yacc.c */ #line 539 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 79: /* Line 1455 of yacc.c */ #line 541 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 80: /* Line 1455 of yacc.c */ #line 543 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 81: /* Line 1455 of yacc.c */ #line 545 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 82: /* Line 1455 of yacc.c */ #line 547 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 83: /* Line 1455 of yacc.c */ #line 549 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 84: /* Line 1455 of yacc.c */ #line 551 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 85: /* Line 1455 of yacc.c */ #line 553 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 86: /* Line 1455 of yacc.c */ #line 555 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 87: /* Line 1455 of yacc.c */ #line 565 "ntp_parser.y" { append_queue(cfgt.stats_list, (yyvsp[(2) - (2)].Queue)); } break; case 88: /* Line 1455 of yacc.c */ #line 567 "ntp_parser.y" { if (input_from_file) cfgt.stats_dir = (yyvsp[(2) - (2)].String); else { free((yyvsp[(2) - (2)].String)); yyerror("statsdir remote configuration ignored"); } } break; case 89: /* Line 1455 of yacc.c */ #line 576 "ntp_parser.y" { enqueue(cfgt.filegen_opts, create_filegen_node((yyvsp[(2) - (3)].Integer), (yyvsp[(3) - (3)].Queue))); } break; case 90: /* Line 1455 of yacc.c */ #line 583 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 91: /* Line 1455 of yacc.c */ #line 584 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 100: /* Line 1455 of yacc.c */ #line 600 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 101: /* Line 1455 of yacc.c */ #line 607 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 102: /* Line 1455 of yacc.c */ #line 617 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); else { (yyval.Attr_val) = NULL; free((yyvsp[(2) - (2)].String)); yyerror("filegen file remote configuration ignored"); } } break; case 103: /* Line 1455 of yacc.c */ #line 627 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen type remote configuration ignored"); } } break; case 104: /* Line 1455 of yacc.c */ #line 636 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen link remote configuration ignored"); } } break; case 105: /* Line 1455 of yacc.c */ #line 645 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen nolink remote configuration ignored"); } } break; case 106: /* Line 1455 of yacc.c */ #line 653 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 107: /* Line 1455 of yacc.c */ #line 654 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 115: /* Line 1455 of yacc.c */ #line 674 "ntp_parser.y" { append_queue(cfgt.discard_opts, (yyvsp[(2) - (2)].Queue)); } break; case 116: /* Line 1455 of yacc.c */ #line 678 "ntp_parser.y" { append_queue(cfgt.mru_opts, (yyvsp[(2) - (2)].Queue)); } break; case 117: /* Line 1455 of yacc.c */ #line 682 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (3)].Address_node), NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 118: /* Line 1455 of yacc.c */ #line 687 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (5)].Address_node), (yyvsp[(4) - (5)].Address_node), (yyvsp[(5) - (5)].Queue), ip_file->line_no)); } break; case 119: /* Line 1455 of yacc.c */ #line 692 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node(NULL, NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 120: /* Line 1455 of yacc.c */ #line 697 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup("0.0.0.0"), AF_INET), create_address_node( estrdup("0.0.0.0"), AF_INET), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 121: /* Line 1455 of yacc.c */ #line 710 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup("::"), AF_INET6), create_address_node( estrdup("::"), AF_INET6), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 122: /* Line 1455 of yacc.c */ #line 723 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( NULL, NULL, enqueue((yyvsp[(3) - (3)].Queue), create_ival((yyvsp[(2) - (3)].Integer))), ip_file->line_no)); } break; case 123: /* Line 1455 of yacc.c */ #line 734 "ntp_parser.y" { (yyval.Queue) = create_queue(); } break; case 124: /* Line 1455 of yacc.c */ #line 736 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 139: /* Line 1455 of yacc.c */ #line 758 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 140: /* Line 1455 of yacc.c */ #line 760 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 141: /* Line 1455 of yacc.c */ #line 764 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 142: /* Line 1455 of yacc.c */ #line 765 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 143: /* Line 1455 of yacc.c */ #line 766 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 144: /* Line 1455 of yacc.c */ #line 771 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 145: /* Line 1455 of yacc.c */ #line 773 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 146: /* Line 1455 of yacc.c */ #line 777 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 147: /* Line 1455 of yacc.c */ #line 778 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 148: /* Line 1455 of yacc.c */ #line 779 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 149: /* Line 1455 of yacc.c */ #line 780 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 150: /* Line 1455 of yacc.c */ #line 781 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 151: /* Line 1455 of yacc.c */ #line 782 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 152: /* Line 1455 of yacc.c */ #line 783 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 153: /* Line 1455 of yacc.c */ #line 784 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 154: /* Line 1455 of yacc.c */ #line 793 "ntp_parser.y" { enqueue(cfgt.fudge, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 155: /* Line 1455 of yacc.c */ #line 798 "ntp_parser.y" { enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 156: /* Line 1455 of yacc.c */ #line 800 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 157: /* Line 1455 of yacc.c */ #line 804 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 158: /* Line 1455 of yacc.c */ #line 805 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 159: /* Line 1455 of yacc.c */ #line 806 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 160: /* Line 1455 of yacc.c */ #line 807 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 161: /* Line 1455 of yacc.c */ #line 808 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 162: /* Line 1455 of yacc.c */ #line 809 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 163: /* Line 1455 of yacc.c */ #line 810 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 164: /* Line 1455 of yacc.c */ #line 811 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 165: /* Line 1455 of yacc.c */ #line 820 "ntp_parser.y" { append_queue(cfgt.enable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 166: /* Line 1455 of yacc.c */ #line 822 "ntp_parser.y" { append_queue(cfgt.disable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 167: /* Line 1455 of yacc.c */ #line 827 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 168: /* Line 1455 of yacc.c */ #line 834 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 169: /* Line 1455 of yacc.c */ #line 843 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 170: /* Line 1455 of yacc.c */ #line 844 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 171: /* Line 1455 of yacc.c */ #line 845 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 172: /* Line 1455 of yacc.c */ #line 846 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 173: /* Line 1455 of yacc.c */ #line 847 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 174: /* Line 1455 of yacc.c */ #line 848 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 175: /* Line 1455 of yacc.c */ #line 850 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("enable/disable stats remote configuration ignored"); } } break; case 176: /* Line 1455 of yacc.c */ #line 865 "ntp_parser.y" { append_queue(cfgt.tinker, (yyvsp[(2) - (2)].Queue)); } break; case 177: /* Line 1455 of yacc.c */ #line 869 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 178: /* Line 1455 of yacc.c */ #line 870 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 179: /* Line 1455 of yacc.c */ #line 874 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 180: /* Line 1455 of yacc.c */ #line 875 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 181: /* Line 1455 of yacc.c */ #line 876 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 182: /* Line 1455 of yacc.c */ #line 877 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 183: /* Line 1455 of yacc.c */ #line 878 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 184: /* Line 1455 of yacc.c */ #line 879 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 185: /* Line 1455 of yacc.c */ #line 880 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 187: /* Line 1455 of yacc.c */ #line 891 "ntp_parser.y" { if (curr_include_level >= MAXINCLUDELEVEL) { fprintf(stderr, "getconfig: Maximum include file level exceeded.\n"); msyslog(LOG_ERR, "getconfig: Maximum include file level exceeded."); } else { fp[curr_include_level + 1] = F_OPEN(FindConfig((yyvsp[(2) - (3)].String)), "r"); if (fp[curr_include_level + 1] == NULL) { fprintf(stderr, "getconfig: Couldn't open <%s>\n", FindConfig((yyvsp[(2) - (3)].String))); msyslog(LOG_ERR, "getconfig: Couldn't open <%s>", FindConfig((yyvsp[(2) - (3)].String))); } else ip_file = fp[++curr_include_level]; } } break; case 188: /* Line 1455 of yacc.c */ #line 907 "ntp_parser.y" { while (curr_include_level != -1) FCLOSE(fp[curr_include_level--]); } break; case 189: /* Line 1455 of yacc.c */ #line 913 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 190: /* Line 1455 of yacc.c */ #line 915 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 191: /* Line 1455 of yacc.c */ #line 917 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 192: /* Line 1455 of yacc.c */ #line 919 "ntp_parser.y" { /* Null action, possibly all null parms */ } break; case 193: /* Line 1455 of yacc.c */ #line 921 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 194: /* Line 1455 of yacc.c */ #line 924 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 195: /* Line 1455 of yacc.c */ #line 926 "ntp_parser.y" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror("logfile remote configuration ignored"); } } break; case 196: /* Line 1455 of yacc.c */ #line 937 "ntp_parser.y" { append_queue(cfgt.logconfig, (yyvsp[(2) - (2)].Queue)); } break; case 197: /* Line 1455 of yacc.c */ #line 939 "ntp_parser.y" { append_queue(cfgt.phone, (yyvsp[(2) - (2)].Queue)); } break; case 198: /* Line 1455 of yacc.c */ #line 941 "ntp_parser.y" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror("saveconfigdir remote configuration ignored"); } } break; case 199: /* Line 1455 of yacc.c */ #line 951 "ntp_parser.y" { enqueue(cfgt.setvar, (yyvsp[(2) - (2)].Set_var)); } break; case 200: /* Line 1455 of yacc.c */ #line 953 "ntp_parser.y" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (2)].Address_node), NULL)); } break; case 201: /* Line 1455 of yacc.c */ #line 955 "ntp_parser.y" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 202: /* Line 1455 of yacc.c */ #line 957 "ntp_parser.y" { append_queue(cfgt.ttl, (yyvsp[(2) - (2)].Queue)); } break; case 203: /* Line 1455 of yacc.c */ #line 959 "ntp_parser.y" { enqueue(cfgt.qos, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 204: /* Line 1455 of yacc.c */ #line 964 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (1)].String))); } break; case 205: /* Line 1455 of yacc.c */ #line 966 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval(T_WanderThreshold, (yyvsp[(2) - (2)].Double))); enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (2)].String))); } break; case 206: /* Line 1455 of yacc.c */ #line 969 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, "\0")); } break; case 207: /* Line 1455 of yacc.c */ #line 974 "ntp_parser.y" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (4)].String), (yyvsp[(3) - (4)].String), (yyvsp[(4) - (4)].Integer)); } break; case 208: /* Line 1455 of yacc.c */ #line 976 "ntp_parser.y" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (3)].String), (yyvsp[(3) - (3)].String), 0); } break; case 209: /* Line 1455 of yacc.c */ #line 981 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 210: /* Line 1455 of yacc.c */ #line 982 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 211: /* Line 1455 of yacc.c */ #line 986 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 212: /* Line 1455 of yacc.c */ #line 987 "ntp_parser.y" { (yyval.Attr_val) = create_attr_pval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node)); } break; case 213: /* Line 1455 of yacc.c */ #line 991 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 214: /* Line 1455 of yacc.c */ #line 992 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 215: /* Line 1455 of yacc.c */ #line 997 "ntp_parser.y" { char prefix = (yyvsp[(1) - (1)].String)[0]; char *type = (yyvsp[(1) - (1)].String) + 1; if (prefix != '+' && prefix != '-' && prefix != '=') { yyerror("Logconfig prefix is not '+', '-' or '='\n"); } else (yyval.Attr_val) = create_attr_sval(prefix, estrdup(type)); YYFREE((yyvsp[(1) - (1)].String)); } break; case 216: /* Line 1455 of yacc.c */ #line 1012 "ntp_parser.y" { enqueue(cfgt.nic_rules, create_nic_rule_node((yyvsp[(3) - (3)].Integer), NULL, (yyvsp[(2) - (3)].Integer))); } break; case 217: /* Line 1455 of yacc.c */ #line 1017 "ntp_parser.y" { enqueue(cfgt.nic_rules, create_nic_rule_node(0, (yyvsp[(3) - (3)].String), (yyvsp[(2) - (3)].Integer))); } break; case 227: /* Line 1455 of yacc.c */ #line 1048 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 228: /* Line 1455 of yacc.c */ #line 1049 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 229: /* Line 1455 of yacc.c */ #line 1054 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 230: /* Line 1455 of yacc.c */ #line 1056 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 231: /* Line 1455 of yacc.c */ #line 1061 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival('i', (yyvsp[(1) - (1)].Integer)); } break; case 233: /* Line 1455 of yacc.c */ #line 1067 "ntp_parser.y" { (yyval.Attr_val) = create_attr_shorts('-', (yyvsp[(2) - (5)].Integer), (yyvsp[(4) - (5)].Integer)); } break; case 234: /* Line 1455 of yacc.c */ #line 1071 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_pval((yyvsp[(2) - (2)].String))); } break; case 235: /* Line 1455 of yacc.c */ #line 1072 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_pval((yyvsp[(1) - (1)].String))); } break; case 236: /* Line 1455 of yacc.c */ #line 1076 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Address_node)); } break; case 237: /* Line 1455 of yacc.c */ #line 1077 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Address_node)); } break; case 238: /* Line 1455 of yacc.c */ #line 1082 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Integer) != 0 && (yyvsp[(1) - (1)].Integer) != 1) { yyerror("Integer value is not boolean (0 or 1). Assuming 1"); (yyval.Integer) = 1; } else (yyval.Integer) = (yyvsp[(1) - (1)].Integer); } break; case 239: /* Line 1455 of yacc.c */ #line 1090 "ntp_parser.y" { (yyval.Integer) = 1; } break; case 240: /* Line 1455 of yacc.c */ #line 1091 "ntp_parser.y" { (yyval.Integer) = 0; } break; case 241: /* Line 1455 of yacc.c */ #line 1095 "ntp_parser.y" { (yyval.Double) = (double)(yyvsp[(1) - (1)].Integer); } break; case 243: /* Line 1455 of yacc.c */ #line 1106 "ntp_parser.y" { cfgt.sim_details = create_sim_node((yyvsp[(3) - (5)].Queue), (yyvsp[(4) - (5)].Queue)); /* Reset the old_config_style variable */ old_config_style = 1; } break; case 244: /* Line 1455 of yacc.c */ #line 1120 "ntp_parser.y" { old_config_style = 0; } break; case 245: /* Line 1455 of yacc.c */ #line 1124 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 246: /* Line 1455 of yacc.c */ #line 1125 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 247: /* Line 1455 of yacc.c */ #line 1129 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 248: /* Line 1455 of yacc.c */ #line 1130 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 249: /* Line 1455 of yacc.c */ #line 1134 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_server)); } break; case 250: /* Line 1455 of yacc.c */ #line 1135 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_server)); } break; case 251: /* Line 1455 of yacc.c */ #line 1140 "ntp_parser.y" { (yyval.Sim_server) = create_sim_server((yyvsp[(1) - (5)].Address_node), (yyvsp[(3) - (5)].Double), (yyvsp[(4) - (5)].Queue)); } break; case 252: /* Line 1455 of yacc.c */ #line 1144 "ntp_parser.y" { (yyval.Double) = (yyvsp[(3) - (4)].Double); } break; case 253: /* Line 1455 of yacc.c */ #line 1148 "ntp_parser.y" { (yyval.Address_node) = (yyvsp[(3) - (3)].Address_node); } break; case 254: /* Line 1455 of yacc.c */ #line 1152 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_script)); } break; case 255: /* Line 1455 of yacc.c */ #line 1153 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_script)); } break; case 256: /* Line 1455 of yacc.c */ #line 1158 "ntp_parser.y" { (yyval.Sim_script) = create_sim_script_info((yyvsp[(3) - (6)].Double), (yyvsp[(5) - (6)].Queue)); } break; case 257: /* Line 1455 of yacc.c */ #line 1162 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 258: /* Line 1455 of yacc.c */ #line 1163 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 259: /* Line 1455 of yacc.c */ #line 1168 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 260: /* Line 1455 of yacc.c */ #line 1170 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 261: /* Line 1455 of yacc.c */ #line 1172 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 262: /* Line 1455 of yacc.c */ #line 1174 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 263: /* Line 1455 of yacc.c */ #line 1176 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; /* Line 1455 of yacc.c */ #line 3826 "ntp_parser.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); }
CWE-20
182,049
10,592
257701482880795128416825559925329074524
null
null
null
libinfinity
c97f870f5ae13112988d9f8ad464b4f679903706
1
inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection, gnutls_session_t session, InfCertificateChain* chain, gpointer user_data) { InfGtkCertificateManager* manager; InfGtkCertificateManagerPrivate* priv; InfGtkCertificateDialogFlags flags; gnutls_x509_crt_t presented_cert; gnutls_x509_crt_t known_cert; gchar* hostname; gboolean match_hostname; gboolean issuer_known; gnutls_x509_crt_t root_cert; int ret; unsigned int verify; GHashTable* table; gboolean cert_equal; time_t expiration_time; InfGtkCertificateManagerQuery* query; gchar* text; GtkWidget* vbox; GtkWidget* label; GError* error; manager = INF_GTK_CERTIFICATE_MANAGER(user_data); priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager); g_object_get(G_OBJECT(connection), "remote-hostname", &hostname, NULL); presented_cert = inf_certificate_chain_get_own_certificate(chain); match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname); /* First, validate the certificate */ ret = gnutls_certificate_verify_peers2(session, &verify); error = NULL; if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); /* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification * result, and if the certificate is still invalid, then set an error. */ if(error == NULL) { issuer_known = TRUE; if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND) { issuer_known = FALSE; /* Re-validate the certificate for other failure reasons -- * unfortunately the gnutls_certificate_verify_peers2() call * does not tell us whether the certificate is otherwise invalid * if a signer is not found already. */ /* TODO: Here it would be good to use the verify flags from the * certificate credentials, but GnuTLS does not have API to * retrieve them. */ root_cert = inf_certificate_chain_get_root_certificate(chain); ret = gnutls_x509_crt_list_verify( inf_certificate_chain_get_raw(chain), inf_certificate_chain_get_n_certificates(chain), &root_cert, 1, NULL, 0, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT, &verify ); if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); else if(verify & GNUTLS_CERT_INVALID) inf_gnutls_certificate_verification_set_error(&error, verify); } } /* Look up the host in our database of pinned certificates if we could not * fully verify the certificate, i.e. if either the issuer is not known or * the hostname of the connection does not match the certificate. */ table = NULL; if(error == NULL) { known_cert = NULL; if(!match_hostname || !issuer_known) { /* If we cannot load the known host file, then cancel the connection. * Otherwise it might happen that someone shows us a certificate that we * tell the user we don't know, if though actually for that host we expect * a different certificate. */ table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error); if(table != NULL) known_cert = g_hash_table_lookup(table, hostname); } } /* Next, configure the flags for the dialog to be shown based on the * verification result, and on whether the pinned certificate matches * the one presented by the host or not. */ flags = 0; if(error == NULL) { if(known_cert != NULL) { cert_equal = inf_gtk_certificate_manager_compare_fingerprint( known_cert, presented_cert, &error ); if(error == NULL && cert_equal == FALSE) { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED; expiration_time = gnutls_x509_crt_get_expiration_time(known_cert); if(expiration_time != (time_t)(-1)) { expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE; if(time(NULL) > expiration_time) { flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED; } } } } else { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; } } /* Now proceed either by accepting the connection, rejecting it, or * bothering the user with an annoying dialog. */ if(error == NULL) { if(flags == 0) { if(match_hostname && issuer_known) { /* Remove the pinned entry if we now have a valid certificate for * this host. */ if(table != NULL && g_hash_table_remove(table, hostname) == TRUE) { inf_gtk_certificate_manager_write_known_hosts_with_warning( manager, table ); } } inf_xmpp_connection_certificate_verify_continue(connection); } else { query = g_slice_new(InfGtkCertificateManagerQuery); query->manager = manager; query->known_hosts = table; query->connection = connection; query->dialog = inf_gtk_certificate_dialog_new( priv->parent_window, 0, flags, hostname, chain ); query->certificate_chain = chain; table = NULL; g_object_ref(query->connection); inf_certificate_chain_ref(chain); g_signal_connect( G_OBJECT(connection), "notify::status", G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb), query ); g_signal_connect( G_OBJECT(query->dialog), "response", G_CALLBACK(inf_gtk_certificate_manager_response_cb), query ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _("_Cancel connection"), GTK_RESPONSE_REJECT ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _("C_ontinue connection"), GTK_RESPONSE_ACCEPT ); text = g_strdup_printf( _("Do you want to continue the connection to host \"%s\"? If you " "choose to continue, this certificate will be trusted in the " "future when connecting to this host."), hostname ); label = gtk_label_new(text); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); gtk_label_set_max_width_chars(GTK_LABEL(label), 60); gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0); gtk_widget_show(label); g_free(text); vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog)); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); priv->queries = g_slist_prepend(priv->queries, query); gtk_window_present(GTK_WINDOW(query->dialog)); } } else { inf_xmpp_connection_certificate_verify_cancel(connection, error); g_error_free(error); } if(table != NULL) g_hash_table_unref(table); g_free(hostname); }
CWE-295
182,057
10,593
235055126631798935911565164799775266026
null
null
null
aircrack-ng
88702a3ce4c28a973bf69023cd0312f412f6193e
1
int net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; }
CWE-20
182,084
10,594
279652316899343591611148131048521991444
null
null
null
aircrack-ng
da087238963c1239fdabd47dc1b65279605aca70
1
int handle(int s, unsigned char* data, int len, struct sockaddr_in *s_in) { char buf[2048]; unsigned short *cmd = (unsigned short *)buf; int plen; struct in_addr *addr = &s_in->sin_addr; unsigned short *pid = (unsigned short*) data; /* inet check */ if (len == S_HELLO_LEN && memcmp(data, "sorbo", 5) == 0) { unsigned short *id = (unsigned short*) (data+5); int x = 2+4+2; *cmd = htons(S_CMD_INET_CHECK); memcpy(cmd+1, addr, 4); memcpy(cmd+1+2, id, 2); printf("Inet check by %s %d\n", inet_ntoa(*addr), ntohs(*id)); if (send(s, buf, x, 0) != x) return 1; return 0; } *cmd++ = htons(S_CMD_PACKET); *cmd++ = *pid; plen = len - 2; last_id = ntohs(*pid); if (last_id > 20000) wrap = 1; if (wrap && last_id < 100) { wrap = 0; memset(ids, 0, sizeof(ids)); } printf("Got packet %d %d", last_id, plen); if (is_dup(last_id)) { printf(" (DUP)\n"); return 0; } printf("\n"); *cmd++ = htons(plen); memcpy(cmd, data+2, plen); plen += 2 + 2 + 2; assert(plen <= (int) sizeof(buf)); if (send(s, buf, plen, 0) != plen) return 1; return 0; }
CWE-20
182,085
10,595
25249288086872366820177062772247791085
null
null
null
liblouis
5e4089659bb49b3095fa541fa6387b4c40d7396e
1
matchCurrentInput( const InString *input, int pos, const widechar *passInstructions, int passIC) { int k; int kk = pos; for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++) if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++]) return 0; return 1; }
CWE-125
182,194
10,596
186673007973266342184945021931615627315
null
null
null
gimp
c21eff4b031acb04fb4dfce8bd5fdfecc2b6524f
1
gimp_write_and_read_file (Gimp *gimp, gboolean with_unusual_stuff, gboolean compat_paths, gboolean use_gimp_2_8_features) { GimpImage *image; GimpImage *loaded_image; GimpPlugInProcedure *proc; gchar *filename; GFile *file; /* Create the image */ image = gimp_create_mainimage (gimp, with_unusual_stuff, compat_paths, use_gimp_2_8_features); /* Assert valid state */ gimp_assert_mainimage (image, with_unusual_stuff, compat_paths, use_gimp_2_8_features); /* Write to file */ filename = g_build_filename (g_get_tmp_dir (), "gimp-test.xcf", NULL); file = g_file_new_for_path (filename); g_free (filename); proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager, GIMP_FILE_PROCEDURE_GROUP_SAVE, file, NULL /*error*/); file_save (gimp, image, NULL /*progress*/, file, proc, GIMP_RUN_NONINTERACTIVE, FALSE /*change_saved_state*/, FALSE /*export_backward*/, FALSE /*export_forward*/, NULL /*error*/); /* Load from file */ loaded_image = gimp_test_load_image (image->gimp, file); /* Assert on the loaded file. If success, it means that there is no * significant information loss when we wrote the image to a file * and loaded it again */ gimp_assert_mainimage (loaded_image, with_unusual_stuff, compat_paths, use_gimp_2_8_features); g_file_delete (file, NULL, NULL); g_object_unref (file); }
CWE-20
182,359
10,597
123602888792994783014141880578339311930
null
null
null
redis
c04082cf138f1f51cedf05ee9ad36fb6763cafc6
1
void xgroupCommand(client *c) { const char *help[] = { "CREATE <key> <groupname> <id or $> -- Create a new consumer group.", "SETID <key> <groupname> <id or $> -- Set the current group ID.", "DELGROUP <key> <groupname> -- Remove the specified group.", "DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.", "HELP -- Prints this help.", NULL }; stream *s = NULL; sds grpname = NULL; streamCG *cg = NULL; char *opt = c->argv[1]->ptr; /* Subcommand name. */ /* Lookup the key now, this is common for all the subcommands but HELP. */ if (c->argc >= 4) { robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr); if (o == NULL) return; s = o->ptr; grpname = c->argv[3]->ptr; /* Certain subcommands require the group to exist. */ if ((cg = streamLookupCG(s,grpname)) == NULL && (!strcasecmp(opt,"SETID") || !strcasecmp(opt,"DELCONSUMER"))) { addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' " "for key name '%s'", (char*)grpname, (char*)c->argv[2]->ptr); return; } } /* Dispatch the different subcommands. */ if (!strcasecmp(opt,"CREATE") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,"$")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id); if (cg) { addReply(c,shared.ok); server.dirty++; } else { addReplySds(c, sdsnew("-BUSYGROUP Consumer Group name already exists\r\n")); } } else if (!strcasecmp(opt,"SETID") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,"$")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } cg->last_id = id; addReply(c,shared.ok); } else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) { if (cg) { raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL); streamFreeCG(cg); addReply(c,shared.cone); } else { addReply(c,shared.czero); } } else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) { /* Delete the consumer and returns the number of pending messages * that were yet associated with such a consumer. */ long long pending = streamDelConsumer(cg,c->argv[4]->ptr); addReplyLongLong(c,pending); server.dirty++; } else if (!strcasecmp(opt,"HELP")) { addReplyHelp(c, help); } else { addReply(c,shared.syntaxerr); } }
CWE-704
182,365
10,598
81308784981755860722994284208362336847
null
null
null
redis
9fdcc15962f9ff4baebe6fdd947816f43f730d50
1
static void cliRefreshPrompt(void) { int len; if (config.eval_ldb) return; if (config.hostsocket != NULL) len = snprintf(config.prompt,sizeof(config.prompt),"redis %s", config.hostsocket); else len = anetFormatAddr(config.prompt, sizeof(config.prompt), config.hostip, config.hostport); /* Add [dbnum] if needed */ if (config.dbnum != 0) len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]", config.dbnum); snprintf(config.prompt+len,sizeof(config.prompt)-len,"> "); }
CWE-119
182,368
10,599
178423737865105367007882243456807161156
null
null
null
PDFGen
ee58aff6918b8bbc3be29b9e3089485ea46ff956
1
static int jpeg_size(unsigned char* data, unsigned int data_size, int *width, int *height) { int i = 0; if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 && data[i+2] == 0xFF && data[i+3] == 0xE0) { i += 4; if(i + 6 < data_size && data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' && data[i+5] == 'F' && data[i+6] == 0x00) { unsigned short block_length = data[i] * 256 + data[i+1]; while(i<data_size) { i+=block_length; if((i + 1) >= data_size) return -1; if(data[i] != 0xFF) return -1; if(data[i+1] == 0xC0) { *height = data[i+5]*256 + data[i+6]; *width = data[i+7]*256 + data[i+8]; return 0; } i+=2; block_length = data[i] * 256 + data[i+1]; } } } return -1; }
CWE-125
182,407
10,600
283638409723498753336753828056220225436
null
null
null
redis
e89086e09a38cc6713bcd4b9c29abf92cf393936
1
static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; }
CWE-190
182,409
10,601
173966888912004301187439638689567797148
null
null
null
openmpt
492022c7297ede682161d9c0ec2de15526424e76
1
std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector<GetLengthType> results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; std::bitset<MAX_EFFECTS> forbiddenCommands; std::bitset<MAX_VOLCMDS> forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } uint32 oldTickDuration = 0; for (;;) { if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { break; } else { retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { break; } if(!Patterns.IsValidPat(playState.m_nPattern)) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { break; } else { retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { break; } else { retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; playState.m_nNextRow = playState.m_nRow + 1; if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } if (!(adjustMode & eAdjust)) continue; switch(command) { case CMD_PORTAMENTOUP: if(param) { if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast<uint8>(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast<uint8>(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { pChn->nPanbrelloPos += static_cast<uint8>(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map<double, int> startTimes; pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS std::bitset<MAX_MIXPLUGINS> plugSetProgram; for(const auto &param : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; }
CWE-125
182,436
10,607
139424168971208381954102639997829251436
null
null
null
libevt
444ca3ce7853538c577e0ec3f6146d2d65780734
1
int libevt_record_values_read_event( libevt_record_values_t *record_values, uint8_t *record_data, size_t record_data_size, uint8_t strict_mode, libcerror_error_t **error ) { static char *function = "libevt_record_values_read_event"; size_t record_data_offset = 0; size_t strings_data_offset = 0; ssize_t value_data_size = 0; uint32_t data_offset = 0; uint32_t data_size = 0; uint32_t members_data_size = 0; uint32_t size = 0; uint32_t size_copy = 0; uint32_t strings_offset = 0; uint32_t strings_size = 0; uint32_t user_sid_offset = 0; uint32_t user_sid_size = 0; #if defined( HAVE_DEBUG_OUTPUT ) uint32_t value_32bit = 0; uint16_t value_16bit = 0; #endif if( record_values == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid record values.", function ); return( -1 ); } if( record_data == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid record data.", function ); return( -1 ); } if( record_data_size > (size_t) SSIZE_MAX ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid record data size value exceeds maximum.", function ); return( -1 ); } if( record_data_size < ( sizeof( evt_record_event_header_t ) + 4 ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: record data size value out of bounds.", function ); return( -1 ); } byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->size, size ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->record_number, record_values->number ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->creation_time, record_values->creation_time ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->written_time, record_values->written_time ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->event_identifier, record_values->event_identifier ); byte_stream_copy_to_uint16_little_endian( ( (evt_record_event_header_t *) record_data )->event_type, record_values->event_type ); byte_stream_copy_to_uint16_little_endian( ( (evt_record_event_header_t *) record_data )->event_category, record_values->event_category ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->strings_offset, strings_offset ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->user_sid_size, user_sid_size ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->user_sid_offset, user_sid_offset ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->data_size, data_size ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->data_offset, data_offset ); byte_stream_copy_to_uint32_little_endian( &( record_data[ record_data_size - 4 ] ), size_copy ); #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: size\t\t\t\t\t: %" PRIu32 "\n", function, size ); libcnotify_printf( "%s: signature\t\t\t\t: %c%c%c%c\n", function, ( (evt_record_event_header_t *) record_data )->signature[ 0 ], ( (evt_record_event_header_t *) record_data )->signature[ 1 ], ( (evt_record_event_header_t *) record_data )->signature[ 2 ], ( (evt_record_event_header_t *) record_data )->signature[ 3 ] ); libcnotify_printf( "%s: record number\t\t\t\t: %" PRIu32 "\n", function, record_values->number ); if( libevt_debug_print_posix_time_value( function, "creation time\t\t\t\t", ( (evt_record_event_header_t *) record_data )->creation_time, 4, LIBFDATETIME_ENDIAN_LITTLE, LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED, LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_PRINT_FAILED, "%s: unable to print POSIX time value.", function ); goto on_error; } if( libevt_debug_print_posix_time_value( function, "written time\t\t\t\t", ( (evt_record_event_header_t *) record_data )->written_time, 4, LIBFDATETIME_ENDIAN_LITTLE, LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED, LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_PRINT_FAILED, "%s: unable to print POSIX time value.", function ); goto on_error; } libcnotify_printf( "%s: event identifier\t\t\t: 0x%08" PRIx32 "\n", function, record_values->event_identifier ); libcnotify_printf( "%s: event identifier: code\t\t\t: %" PRIu32 "\n", function, record_values->event_identifier & 0x0000ffffUL ); libcnotify_printf( "%s: event identifier: facility\t\t: %" PRIu32 "\n", function, ( record_values->event_identifier & 0x0fff0000UL ) >> 16 ); libcnotify_printf( "%s: event identifier: reserved\t\t: %" PRIu32 "\n", function, ( record_values->event_identifier & 0x10000000UL ) >> 28 ); libcnotify_printf( "%s: event identifier: customer flags\t: %" PRIu32 "\n", function, ( record_values->event_identifier & 0x20000000UL ) >> 29 ); libcnotify_printf( "%s: event identifier: severity\t\t: %" PRIu32 " (", function, ( record_values->event_identifier & 0xc0000000UL ) >> 30 ); libevt_debug_print_event_identifier_severity( record_values->event_identifier ); libcnotify_printf( ")\n" ); libcnotify_printf( "%s: event type\t\t\t\t: %" PRIu16 " (", function, record_values->event_type ); libevt_debug_print_event_type( record_values->event_type ); libcnotify_printf( ")\n" ); byte_stream_copy_to_uint16_little_endian( ( (evt_record_event_header_t *) record_data )->number_of_strings, value_16bit ); libcnotify_printf( "%s: number of strings\t\t\t: %" PRIu16 "\n", function, value_16bit ); libcnotify_printf( "%s: event category\t\t\t\t: %" PRIu16 "\n", function, record_values->event_category ); byte_stream_copy_to_uint16_little_endian( ( (evt_record_event_header_t *) record_data )->event_flags, value_16bit ); libcnotify_printf( "%s: event flags\t\t\t\t: 0x%04" PRIx16 "\n", function, value_16bit ); byte_stream_copy_to_uint32_little_endian( ( (evt_record_event_header_t *) record_data )->closing_record_number, value_32bit ); libcnotify_printf( "%s: closing record values number\t\t: %" PRIu32 "\n", function, value_32bit ); libcnotify_printf( "%s: strings offset\t\t\t\t: %" PRIu32 "\n", function, strings_offset ); libcnotify_printf( "%s: user security identifier (SID) size\t: %" PRIu32 "\n", function, user_sid_size ); libcnotify_printf( "%s: user security identifier (SID) offset\t: %" PRIu32 "\n", function, user_sid_offset ); libcnotify_printf( "%s: data size\t\t\t\t: %" PRIu32 "\n", function, data_size ); libcnotify_printf( "%s: data offset\t\t\t\t: %" PRIu32 "\n", function, data_offset ); } #endif record_data_offset = sizeof( evt_record_event_header_t ); if( ( user_sid_offset == 0 ) && ( user_sid_size != 0 ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: user SID offset or size value out of bounds.", function ); goto on_error; } if( user_sid_offset != 0 ) { if( ( (size_t) user_sid_offset < record_data_offset ) || ( (size_t) user_sid_offset >= ( record_data_size - 4 ) ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: user SID offset value out of bounds.", function ); goto on_error; } if( user_sid_size != 0 ) { if( (size_t) ( user_sid_offset + user_sid_size ) > ( record_data_size - 4 ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: user SID size value out of bounds.", function ); goto on_error; } } } /* If the strings offset is points at the offset at record data size - 4 * the strings are empty. For this to be sane the data offset should * be the same as the strings offset or the data size 0. */ if( ( (size_t) strings_offset < user_sid_offset ) || ( (size_t) strings_offset >= ( record_data_size - 4 ) ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: strings offset value out of bounds.", function ); goto on_error; } if( ( (size_t) data_offset < strings_offset ) || ( (size_t) data_offset >= ( record_data_size - 4 ) ) ) { if( data_size != 0 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: data offset value out of bounds.", function ); goto on_error; } data_offset = (uint32_t) record_data_size - 4; } if( ( (size_t) strings_offset >= ( record_data_size - 4 ) ) && ( strings_offset != data_offset ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: strings offset value out of bounds.", function ); goto on_error; } if( strings_offset != 0 ) { if( strings_offset < record_data_offset ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: strings offset value out of bounds.", function ); goto on_error; } } if( user_sid_offset != 0 ) { members_data_size = user_sid_offset - (uint32_t) record_data_offset; } else if( strings_offset != 0 ) { members_data_size = strings_offset - (uint32_t) record_data_offset; } if( strings_offset != 0 ) { strings_size = data_offset - strings_offset; } if( data_size != 0 ) { if( (size_t) ( data_offset + data_size ) > ( record_data_size - 4 ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: data size value out of bounds.", function ); goto on_error; } } if( members_data_size != 0 ) { #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: members data:\n", function ); libcnotify_print_data( &( record_data[ record_data_offset ] ), members_data_size, LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA ); } #endif if( libfvalue_value_type_initialize( &( record_values->source_name ), LIBFVALUE_VALUE_TYPE_STRING_UTF16, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED, "%s: unable to create source name value.", function ); goto on_error; } value_data_size = libfvalue_value_type_set_data_string( record_values->source_name, &( record_data[ record_data_offset ] ), members_data_size, LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN, LIBFVALUE_VALUE_DATA_FLAG_MANAGED, error ); if( value_data_size == -1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set data of source name value.", function ); goto on_error; } #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: source name\t\t\t\t: ", function ); if( libfvalue_value_print( record_values->source_name, 0, 0, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_PRINT_FAILED, "%s: unable to print source name value.", function ); goto on_error; } libcnotify_printf( "\n" ); } #endif record_data_offset += value_data_size; members_data_size -= (uint32_t) value_data_size; if( libfvalue_value_type_initialize( &( record_values->computer_name ), LIBFVALUE_VALUE_TYPE_STRING_UTF16, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED, "%s: unable to create computer name value.", function ); goto on_error; } value_data_size = libfvalue_value_type_set_data_string( record_values->computer_name, &( record_data[ record_data_offset ] ), members_data_size, LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN, LIBFVALUE_VALUE_DATA_FLAG_MANAGED, error ); if( value_data_size == -1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set data of computer name value.", function ); goto on_error; } #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: computer name\t\t\t\t: ", function ); if( libfvalue_value_print( record_values->computer_name, 0, 0, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_PRINT_FAILED, "%s: unable to print computer name value.", function ); goto on_error; } libcnotify_printf( "\n" ); } #endif record_data_offset += value_data_size; members_data_size -= (uint32_t) value_data_size; if( members_data_size > 0 ) { #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: members trailing data:\n", function ); libcnotify_print_data( &( record_data[ record_data_offset ] ), members_data_size, LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA ); } #endif record_data_offset += members_data_size; } } if( user_sid_size != 0 ) { if( libfvalue_value_type_initialize( &( record_values->user_security_identifier ), LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED, "%s: unable to create user security identifier (SID) value.", function ); goto on_error; } if( libfvalue_value_set_data( record_values->user_security_identifier, &( record_data[ user_sid_offset ] ), (size_t) user_sid_size, LIBFVALUE_ENDIAN_LITTLE, LIBFVALUE_VALUE_DATA_FLAG_MANAGED, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set data of user security identifier (SID) value.", function ); goto on_error; } #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: user security identifier (SID)\t\t: ", function ); if( libfvalue_value_print( record_values->user_security_identifier, 0, 0, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_PRINT_FAILED, "%s: unable to print user security identifier (SID) value.", function ); goto on_error; } libcnotify_printf( "\n" ); } #endif record_data_offset += user_sid_size; } if( strings_size != 0 ) { #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: strings data:\n", function ); libcnotify_print_data( &( record_data[ strings_offset ] ), strings_size, LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA ); } #endif if( size_copy == 0 ) { /* If the strings data is truncated */ strings_data_offset = strings_offset + strings_size - 2; while( strings_data_offset > strings_offset ) { if( ( record_data[ strings_data_offset ] != 0 ) || ( record_data[ strings_data_offset + 1 ] != 0 ) ) { strings_size += 2; break; } strings_data_offset -= 2; strings_size -= 2; } } if( libfvalue_value_type_initialize( &( record_values->strings ), LIBFVALUE_VALUE_TYPE_STRING_UTF16, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED, "%s: unable to create strings value.", function ); goto on_error; } value_data_size = libfvalue_value_type_set_data_strings_array( record_values->strings, &( record_data[ strings_offset ] ), strings_size, LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN, error ); if( value_data_size == -1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set data of strings value.", function ); goto on_error; } record_data_offset += strings_size; } if( data_size != 0 ) { #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { libcnotify_printf( "%s: data:\n", function ); libcnotify_print_data( &( record_data[ data_offset ] ), (size_t) data_size, LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA ); } #endif if( libfvalue_value_type_initialize( &( record_values->data ), LIBFVALUE_VALUE_TYPE_BINARY_DATA, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED, "%s: unable to create data value.", function ); goto on_error; } if( libfvalue_value_set_data( record_values->data, &( record_data[ record_data_offset ] ), (size_t) data_size, LIBFVALUE_ENDIAN_LITTLE, LIBFVALUE_VALUE_DATA_FLAG_MANAGED, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set data of data value.", function ); goto on_error; } #if defined( HAVE_DEBUG_OUTPUT ) record_data_offset += data_size; #endif } #if defined( HAVE_DEBUG_OUTPUT ) if( libcnotify_verbose != 0 ) { if( record_data_offset < ( record_data_size - 4 ) ) { libcnotify_printf( "%s: padding:\n", function ); libcnotify_print_data( &( record_data[ record_data_offset ] ), (size_t) record_data_size - record_data_offset - 4, LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA ); } libcnotify_printf( "%s: size copy\t\t\t\t: %" PRIu32 "\n", function, size_copy ); libcnotify_printf( "\n" ); } #endif if( ( strict_mode == 0 ) && ( size_copy == 0 ) ) { size_copy = size; } if( size != size_copy ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_INPUT, LIBCERROR_INPUT_ERROR_VALUE_MISMATCH, "%s: value mismatch for size and size copy.", function ); goto on_error; } if( record_data_size != (size_t) size ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_INPUT, LIBCERROR_INPUT_ERROR_VALUE_MISMATCH, "%s: value mismatch for record_values data size and size.", function ); goto on_error; } return( 1 ); on_error: if( record_values->data != NULL ) { libfvalue_value_free( &( record_values->data ), NULL ); } if( record_values->strings != NULL ) { libfvalue_value_free( &( record_values->strings ), NULL ); } if( record_values->user_security_identifier != NULL ) { libfvalue_value_free( &( record_values->user_security_identifier ), NULL ); } if( record_values->computer_name != NULL ) { libfvalue_value_free( &( record_values->computer_name ), NULL ); } if( record_values->source_name != NULL ) { libfvalue_value_free( &( record_values->source_name ), NULL ); } return( -1 ); }
CWE-125
182,470
10,608
288479666967874894760846617494006477245
null
null
null
gifsicle
118a46090c50829dc543179019e6140e1235f909
1
read_gif(Gif_Reader *grr, int read_flags, const char* landmark, Gif_ReadErrorHandler handler) { Gif_Stream *gfs; Gif_Image *gfi; Gif_Context gfc; int unknown_block_type = 0; if (gifgetc(grr) != 'G' || gifgetc(grr) != 'I' || gifgetc(grr) != 'F') return 0; (void)gifgetc(grr); (void)gifgetc(grr); (void)gifgetc(grr); gfs = Gif_NewStream(); gfi = Gif_NewImage(); gfc.stream = gfs; gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE); gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE); gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE); gfc.handler = handler; gfc.gfi = gfi; gfc.errors[0] = gfc.errors[1] = 0; if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length) goto done; gfs->landmark = landmark; GIF_DEBUG(("\nGIF ")); if (!read_logical_screen_descriptor(gfs, grr)) goto done; GIF_DEBUG(("logscrdesc ")); while (!gifeof(grr)) { uint8_t block = gifgetbyte(grr); switch (block) { case ',': /* image block */ GIF_DEBUG(("imageread %d ", gfs->nimages)); gfi->identifier = last_name; last_name = 0; if (!Gif_AddImage(gfs, gfi)) goto done; else if (!read_image(grr, &gfc, gfi, read_flags)) { Gif_RemoveImage(gfs, gfs->nimages - 1); gfi = 0; goto done; } gfc.gfi = gfi = Gif_NewImage(); if (!gfi) goto done; break; case ';': /* terminator */ GIF_DEBUG(("term\n")); goto done; case '!': /* extension */ block = gifgetbyte(grr); GIF_DEBUG(("ext(0x%02X) ", block)); switch (block) { case 0xF9: read_graphic_control_extension(&gfc, gfi, grr); break; case 0xCE: last_name = suck_data(last_name, 0, grr); break; case 0xFE: if (!read_comment_extension(gfi, grr)) goto done; break; case 0xFF: read_application_extension(&gfc, grr); break; default: read_unknown_extension(&gfc, grr, block, 0, 0); break; } break; default: if (!unknown_block_type) { char buf[256]; sprintf(buf, "unknown block type %d at file offset %u", block, grr->pos - 1); gif_read_error(&gfc, 1, buf); unknown_block_type = 1; } break; } } done: /* Move comments and extensions after last image into stream. */ if (gfs && gfi) { Gif_Extension* gfex; gfs->end_comment = gfi->comment; gfi->comment = 0; gfs->end_extension_list = gfi->extension_list; gfi->extension_list = 0; for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next) gfex->image = NULL; } Gif_DeleteImage(gfi); Gif_DeleteArray(last_name); Gif_DeleteArray(gfc.prefix); Gif_DeleteArray(gfc.suffix); Gif_DeleteArray(gfc.length); gfc.gfi = 0; if (gfs) gfs->errors = gfc.errors[1]; if (gfs && gfc.errors[1] == 0 && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK) && !grr->eofer(grr)) gif_read_error(&gfc, 0, "trailing garbage after GIF ignored"); /* finally, export last message */ gif_read_error(&gfc, -1, 0); return gfs; }
CWE-415
182,592
10,616
145328850450328547417088906038602241492
null
null
null
rpm
c815822c8bdb138066ff58c624ae83e3a12ebfa9
1
rpmVerifyAttrs rpmfilesVerify(rpmfiles fi, int ix, rpmVerifyAttrs omitMask) { rpm_mode_t fmode = rpmfilesFMode(fi, ix); rpmfileAttrs fileAttrs = rpmfilesFFlags(fi, ix); rpmVerifyAttrs flags = rpmfilesVFlags(fi, ix); const char * fn = rpmfilesFN(fi, ix); struct stat sb; rpmVerifyAttrs vfy = RPMVERIFY_NONE; /* * Check to see if the file was installed - if not pretend all is OK. */ switch (rpmfilesFState(fi, ix)) { case RPMFILE_STATE_NETSHARED: case RPMFILE_STATE_NOTINSTALLED: goto exit; break; case RPMFILE_STATE_REPLACED: /* For replaced files we can only verify if it exists at all */ flags = RPMVERIFY_LSTATFAIL; break; case RPMFILE_STATE_WRONGCOLOR: /* * Files with wrong color are supposed to share some attributes * with the actually installed file - verify what we can. */ flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_RDEV); break; case RPMFILE_STATE_NORMAL: /* File from a non-installed package, try to verify nevertheless */ case RPMFILE_STATE_MISSING: break; } if (fn == NULL || lstat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* If we expected a directory but got a symlink to one, follow the link */ if (S_ISDIR(fmode) && S_ISLNK(sb.st_mode) && stat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* Links have no mode, other types have no linkto */ if (S_ISLNK(sb.st_mode)) flags &= ~(RPMVERIFY_MODE); else flags &= ~(RPMVERIFY_LINKTO); /* Not all attributes of non-regular files can be verified */ if (!S_ISREG(sb.st_mode)) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_CAPS); /* Content checks of %ghost files are meaningless. */ if (fileAttrs & RPMFILE_GHOST) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_LINKTO); /* Don't verify any features in omitMask. */ flags &= ~(omitMask | RPMVERIFY_FAILURES); if (flags & RPMVERIFY_FILEDIGEST) { const unsigned char *digest; int algo; size_t diglen; /* XXX If --nomd5, then prelinked library sizes are not corrected. */ if ((digest = rpmfilesFDigest(fi, ix, &algo, &diglen))) { unsigned char fdigest[diglen]; rpm_loff_t fsize; if (rpmDoDigest(algo, fn, 0, fdigest, &fsize)) { vfy |= (RPMVERIFY_READFAIL|RPMVERIFY_FILEDIGEST); } else { sb.st_size = fsize; if (memcmp(fdigest, digest, diglen)) vfy |= RPMVERIFY_FILEDIGEST; } } else { vfy |= RPMVERIFY_FILEDIGEST; } } if (flags & RPMVERIFY_LINKTO) { char linkto[1024+1]; int size = 0; if ((size = readlink(fn, linkto, sizeof(linkto)-1)) == -1) vfy |= (RPMVERIFY_READLINKFAIL|RPMVERIFY_LINKTO); else { const char * flink = rpmfilesFLink(fi, ix); linkto[size] = '\0'; if (flink == NULL || !rstreq(linkto, flink)) vfy |= RPMVERIFY_LINKTO; } } if (flags & RPMVERIFY_FILESIZE) { if (sb.st_size != rpmfilesFSize(fi, ix)) vfy |= RPMVERIFY_FILESIZE; } if (flags & RPMVERIFY_MODE) { rpm_mode_t metamode = fmode; rpm_mode_t filemode; /* * Platforms (like AIX) where sizeof(rpm_mode_t) != sizeof(mode_t) * need the (rpm_mode_t) cast here. */ filemode = (rpm_mode_t)sb.st_mode; /* * Comparing the type of %ghost files is meaningless, but perms are OK. */ if (fileAttrs & RPMFILE_GHOST) { metamode &= ~0xf000; filemode &= ~0xf000; } if (metamode != filemode) vfy |= RPMVERIFY_MODE; #if WITH_ACL /* * For now, any non-default acl's on a file is a difference as rpm * cannot have set them. */ acl_t facl = acl_get_file(fn, ACL_TYPE_ACCESS); if (facl) { if (acl_equiv_mode(facl, NULL) == 1) { vfy |= RPMVERIFY_MODE; } acl_free(facl); } #endif } if (flags & RPMVERIFY_RDEV) { if (S_ISCHR(fmode) != S_ISCHR(sb.st_mode) || S_ISBLK(fmode) != S_ISBLK(sb.st_mode)) { vfy |= RPMVERIFY_RDEV; } else if (S_ISDEV(fmode) && S_ISDEV(sb.st_mode)) { rpm_rdev_t st_rdev = (sb.st_rdev & 0xffff); rpm_rdev_t frdev = (rpmfilesFRdev(fi, ix) & 0xffff); if (st_rdev != frdev) vfy |= RPMVERIFY_RDEV; } } #if WITH_CAP if (flags & RPMVERIFY_CAPS) { /* * Empty capability set ("=") is not exactly the same as no * capabilities at all but suffices for now... */ cap_t cap, fcap; cap = cap_from_text(rpmfilesFCaps(fi, ix)); if (!cap) { cap = cap_from_text("="); } fcap = cap_get_file(fn); if (!fcap) { fcap = cap_from_text("="); } if (cap_compare(cap, fcap) != 0) vfy |= RPMVERIFY_CAPS; cap_free(fcap); cap_free(cap); } #endif if ((flags & RPMVERIFY_MTIME) && (sb.st_mtime != rpmfilesFMtime(fi, ix))) { vfy |= RPMVERIFY_MTIME; } if (flags & RPMVERIFY_USER) { const char * name = rpmugUname(sb.st_uid); const char * fuser = rpmfilesFUser(fi, ix); uid_t uid; int namematch = 0; int idmatch = 0; if (name && fuser) namematch = rstreq(name, fuser); if (fuser && rpmugUid(fuser, &uid) == 0) idmatch = (uid == sb.st_uid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate username or UID for user %s\n"), fuser); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_USER; } if (flags & RPMVERIFY_GROUP) { const char * name = rpmugGname(sb.st_gid); const char * fgroup = rpmfilesFGroup(fi, ix); gid_t gid; int namematch = 0; int idmatch = 0; if (name && fgroup) namematch = rstreq(name, fgroup); if (fgroup && rpmugGid(fgroup, &gid) == 0) idmatch = (gid == sb.st_gid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate groupname or GID for group %s\n"), fgroup); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_GROUP; } exit: return vfy; }
CWE-59
182,606
10,617
253992275898542277166622642852757005506
null
null
null
optee_os
b60e1cee406a1ff521145ab9534370dfb85dd592
1
TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; attrs = malloc(sizeof(TEE_Attribute) * attr_count); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; }
CWE-119
182,641
10,622
230472388512462148717464534991479963363
null
null
null
optee_os
7e768f8a473409215fe3fff8f6e31f8a3a0103c6
1
static struct mobj *alloc_ta_mem(size_t size) { #ifdef CFG_PAGED_USER_TA return mobj_paged_alloc(size); #else struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr); if (mobj) memset(mobj_get_va(mobj, 0), 0, size); return mobj; #endif }
CWE-189
182,644
10,625
333142874986827667625591185721531467472
null
null
null
optee_os
95f36d661f2b75887772ea28baaad904bde96970
1
TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &a)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = uaddr; a < (uaddr + len); a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; }
CWE-20
182,645
10,626
309046461438464895940445245939118987341
null
null
null
optee_os
e3adcf566cb278444830e7badfdcc3983e334fd1
1
static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem, struct param_mem *mem) { uint64_t shm_ref = READ_ONCE(rmem->shm_ref); mem->mobj = mobj_reg_shm_get_by_cookie(shm_ref); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = READ_ONCE(rmem->offs); mem->size = READ_ONCE(rmem->size); return TEE_SUCCESS; }
CWE-119
182,646
10,627
15438417749328557825920116641375234946
null
null
null
openmpt
927688ddab43c2b203569de79407a899e734fabe
1
LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; }
CWE-120
182,672
10,628
12124114212897463104829635933058850664
null
null
null
openmpt
927688ddab43c2b203569de79407a899e734fabe
1
LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_sample_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; }
CWE-120
182,673
10,629
294694415044715360192257996161415532126
null
null
null
pam-u2f
7db3386fcdb454e33a3ea30dcfb8e8960d4c3aa3
1
int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) { struct passwd *pw = NULL, pw_s; const char *user = NULL; cfg_t cfg_st; cfg_t *cfg = &cfg_st; char buffer[BUFSIZE]; char *buf = NULL; char *authfile_dir; size_t authfile_dir_len; int pgu_ret, gpn_ret; int retval = PAM_IGNORE; device_t *devices = NULL; unsigned n_devices = 0; int openasuser; int should_free_origin = 0; int should_free_appid = 0; int should_free_auth_file = 0; int should_free_authpending_file = 0; parse_cfg(flags, argc, argv, cfg); if (!cfg->origin) { strcpy(buffer, DEFAULT_ORIGIN_PREFIX); if (gethostname(buffer + strlen(DEFAULT_ORIGIN_PREFIX), BUFSIZE - strlen(DEFAULT_ORIGIN_PREFIX)) == -1) { DBG("Unable to get host name"); goto done; } DBG("Origin not specified, using \"%s\"", buffer); cfg->origin = strdup(buffer); if (!cfg->origin) { DBG("Unable to allocate memory"); goto done; } else { should_free_origin = 1; } } if (!cfg->appid) { DBG("Appid not specified, using the same value of origin (%s)", cfg->origin); cfg->appid = strdup(cfg->origin); if (!cfg->appid) { DBG("Unable to allocate memory") goto done; } else { should_free_appid = 1; } } if (cfg->max_devs == 0) { DBG("Maximum devices number not set. Using default (%d)", MAX_DEVS); cfg->max_devs = MAX_DEVS; } devices = malloc(sizeof(device_t) * cfg->max_devs); if (!devices) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } pgu_ret = pam_get_user(pamh, &user, NULL); if (pgu_ret != PAM_SUCCESS || user == NULL) { DBG("Unable to access user %s", user); retval = PAM_CONV_ERR; goto done; } DBG("Requesting authentication for user %s", user); gpn_ret = getpwnam_r(user, &pw_s, buffer, sizeof(buffer), &pw); if (gpn_ret != 0 || pw == NULL || pw->pw_dir == NULL || pw->pw_dir[0] != '/') { DBG("Unable to retrieve credentials for user %s, (%s)", user, strerror(errno)); retval = PAM_USER_UNKNOWN; goto done; } DBG("Found user %s", user); DBG("Home directory for %s is %s", user, pw->pw_dir); if (!cfg->auth_file) { buf = NULL; authfile_dir = secure_getenv(DEFAULT_AUTHFILE_DIR_VAR); if (!authfile_dir) { DBG("Variable %s is not set. Using default value ($HOME/.config/)", DEFAULT_AUTHFILE_DIR_VAR); authfile_dir_len = strlen(pw->pw_dir) + strlen("/.config") + strlen(DEFAULT_AUTHFILE) + 1; buf = malloc(sizeof(char) * (authfile_dir_len)); if (!buf) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } snprintf(buf, authfile_dir_len, "%s/.config%s", pw->pw_dir, DEFAULT_AUTHFILE); } else { DBG("Variable %s set to %s", DEFAULT_AUTHFILE_DIR_VAR, authfile_dir); authfile_dir_len = strlen(authfile_dir) + strlen(DEFAULT_AUTHFILE) + 1; buf = malloc(sizeof(char) * (authfile_dir_len)); if (!buf) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } snprintf(buf, authfile_dir_len, "%s%s", authfile_dir, DEFAULT_AUTHFILE); } DBG("Using default authentication file %s", buf); cfg->auth_file = buf; /* cfg takes ownership */ should_free_auth_file = 1; buf = NULL; } else { DBG("Using authentication file %s", cfg->auth_file); } openasuser = geteuid() == 0 && cfg->openasuser; if (openasuser) { if (seteuid(pw_s.pw_uid)) { DBG("Unable to switch user to uid %i", pw_s.pw_uid); retval = PAM_IGNORE; goto done; } DBG("Switched to uid %i", pw_s.pw_uid); } retval = get_devices_from_authfile(cfg->auth_file, user, cfg->max_devs, cfg->debug, cfg->debug_file, devices, &n_devices); if (openasuser) { if (seteuid(0)) { DBG("Unable to switch back to uid 0"); retval = PAM_IGNORE; goto done; } DBG("Switched back to uid 0"); } if (retval != 1) { n_devices = 0; } if (n_devices == 0) { if (cfg->nouserok) { DBG("Found no devices but nouserok specified. Skipping authentication"); retval = PAM_SUCCESS; goto done; } else if (retval != 1) { DBG("Unable to get devices from file %s", cfg->auth_file); retval = PAM_AUTHINFO_UNAVAIL; goto done; } else { DBG("Found no devices. Aborting."); retval = PAM_AUTHINFO_UNAVAIL; goto done; } } if (!cfg->authpending_file) { int actual_size = snprintf(buffer, BUFSIZE, DEFAULT_AUTHPENDING_FILE_PATH, getuid()); if (actual_size >= 0 && actual_size < BUFSIZE) { cfg->authpending_file = strdup(buffer); } if (!cfg->authpending_file) { DBG("Unable to allocate memory for the authpending_file, touch request notifications will not be emitted"); } else { should_free_authpending_file = 1; } } else { if (strlen(cfg->authpending_file) == 0) { DBG("authpending_file is set to an empty value, touch request notifications will be disabled"); cfg->authpending_file = NULL; } } int authpending_file_descriptor = -1; if (cfg->authpending_file) { DBG("Using file '%s' for emitting touch request notifications", cfg->authpending_file); authpending_file_descriptor = open(cfg->authpending_file, O_RDONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NOCTTY, 0664); if (authpending_file_descriptor < 0) { DBG("Unable to emit 'authentication started' notification by opening the file '%s', (%s)", cfg->authpending_file, strerror(errno)); } } if (cfg->manual == 0) { if (cfg->interactive) { converse(pamh, PAM_PROMPT_ECHO_ON, cfg->prompt != NULL ? cfg->prompt : DEFAULT_PROMPT); } retval = do_authentication(cfg, devices, n_devices, pamh); } else { retval = do_manual_authentication(cfg, devices, n_devices, pamh); } if (authpending_file_descriptor >= 0) { if (close(authpending_file_descriptor) < 0) { DBG("Unable to emit 'authentication stopped' notification by closing the file '%s', (%s)", cfg->authpending_file, strerror(errno)); } } if (retval != 1) { DBG("do_authentication returned %d", retval); retval = PAM_AUTH_ERR; goto done; } retval = PAM_SUCCESS; done: free_devices(devices, n_devices); if (buf) { free(buf); buf = NULL; } if (should_free_origin) { free((char *) cfg->origin); cfg->origin = NULL; } if (should_free_appid) { free((char *) cfg->appid); cfg->appid = NULL; } if (should_free_auth_file) { free((char *) cfg->auth_file); cfg->auth_file = NULL; } if (should_free_authpending_file) { free((char *) cfg->authpending_file); cfg->authpending_file = NULL; } if (cfg->alwaysok && retval != PAM_SUCCESS) { DBG("alwaysok needed (otherwise return with %d)", retval); retval = PAM_SUCCESS; } DBG("done. [%s]", pam_strerror(pamh, retval)); if (cfg->is_custom_debug_file) { fclose(cfg->debug_file); } return retval; }
CWE-200
182,836
10,636
247266602847718435082966207404227201258
null
null
null
ext-http
17137d4ab1ce81a2cee0fae842340a344ef3da83
1
static void merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC) { zval **ptr, **zdata_ptr; php_http_array_hashkey_t hkey = php_http_array_hashkey_init(0); #if 0 { zval tmp; INIT_PZVAL_ARRAY(&tmp, params); fprintf(stderr, "params = "); zend_print_zval_r(&tmp, 1 TSRMLS_CC); fprintf(stderr, "\n"); } #endif hkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL); if ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len)) || (hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num)) ) { zval *tmp, *arg, **args; /* create the entry if it doesn't exist */ zend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr); Z_ADDREF_PP(ptr); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(tmp, ZEND_STRS("value"), *ptr); MAKE_STD_ZVAL(arg); array_init(arg); zend_hash_update(Z_ARRVAL_P(tmp), "arguments", sizeof("arguments"), (void *) &arg, sizeof(zval *), (void *) &args); *current_args = args; if (hkey.type == HASH_KEY_IS_STRING) { zend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr); } else { zend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr); } } else { /* merge */ if (hkey.type == HASH_KEY_IS_STRING) { zend_hash_find(params, hkey.str, hkey.len, (void *) &ptr); } else { zend_hash_index_find(params, hkey.num, (void *) &ptr); } zdata_ptr = &zdata; if (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), "value", sizeof("value"), (void *) &ptr) && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr) ) { /* * params = [arr => [value => [0 => 1]]] * ^- ptr * zdata = [arr => [0 => NULL]] * ^- zdata_ptr */ zval **test_ptr; while (Z_TYPE_PP(zdata_ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr) ) { if (Z_TYPE_PP(test_ptr) == IS_ARRAY) { /* now find key in ptr */ if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) { if (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) { zdata_ptr = test_ptr; } else { Z_ADDREF_PP(test_ptr); zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr); break; } } else { if (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) { zdata_ptr = test_ptr; } else if (hkey.num) { Z_ADDREF_PP(test_ptr); zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr); break; } else { Z_ADDREF_PP(test_ptr); zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr); break; } } } else { /* this is the leaf */ Z_ADDREF_PP(test_ptr); if (Z_TYPE_PP(ptr) != IS_ARRAY) { zval_dtor(*ptr); array_init(*ptr); } if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) { zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr); } else if (hkey.num) { zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr); } else { zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr); } break; } } } } /* bubble up */ while (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr)); *current_param = ptr; }
CWE-704
183,037
10,640
164440707986027166207133584858712006875
null
null
null
bdwgc
be9df82919960214ee4b9d3313523bff44fd99e1
1
GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner((word)lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } }
CWE-189
183,050
10,641
130048329424182725359327406564956238801
null
null
null
bdwgc
be9df82919960214ee4b9d3313523bff44fd99e1
1
GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k) { void *result; size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; DCL_LOCK_STATE; if (SMALL_OBJ(lb)) return(GC_generic_malloc((word)lb, k)); lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); LOCK(); result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; if (0 == result) { GC_oom_func oom_fn = GC_oom_fn; UNLOCK(); return((*oom_fn)(lb)); } else { UNLOCK(); if (init && !GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } return(result); } }
CWE-189
183,051
10,642
174440046177171580621011422434179791291
null
null
null
bdwgc
6a93f8e5bcad22137f41b6c60a1c7384baaec2b3
1
void * calloc(size_t n, size_t lb) { if (lb && n > SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); }
CWE-189
183,052
10,643
6900566949430079286336569974830416523
null
null
null
bdwgc
83231d0ab5ed60015797c3d1ad9056295ac3b2bb
1
void * calloc(size_t n, size_t lb) { if (lb && n > GC_SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); }
CWE-189
183,053
10,644
286136948008637883570400561604207145027
null
null
null
OpenJK
f61fe5f6a0419ef4a88d46a128052f2e8352e85d
1
qboolean S_AL_Init( soundInterface_t *si ) { #ifdef USE_OPENAL const char* device = NULL; const char* inputdevice = NULL; int i; if( !si ) { return qfalse; } for (i = 0; i < MAX_RAW_STREAMS; i++) { streamSourceHandles[i] = -1; streamPlaying[i] = qfalse; streamSources[i] = 0; streamNumBuffers[i] = 0; streamBufIndex[i] = 0; } s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE ); s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE ); s_alSources = Cvar_Get( "s_alSources", "96", CVAR_ARCHIVE ); s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE ); s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE ); s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT ); s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT); s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT); s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT); s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH ); s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH ); s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH); if( !QAL_Init( s_alDriver->string ) ) { Com_Printf( "Failed to load library: \"%s\".\n", s_alDriver->string ); if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) { return qfalse; } } device = s_alDevice->string; if(device && !*device) device = NULL; inputdevice = s_alInputDevice->string; if(inputdevice && !*inputdevice) inputdevice = NULL; enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT"); enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"); if(enumeration_ext || enumeration_all_ext) { char devicenames[16384] = ""; const char *devicelist; #ifdef _WIN32 const char *defaultdevice; #endif int curlen; if(enumeration_all_ext) { devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER); #ifdef _WIN32 defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER); #endif } else { devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER); #ifdef _WIN32 defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); #endif enumeration_ext = qtrue; } #ifdef _WIN32 if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware")) device = "Generic Software"; #endif if(devicelist) { while((curlen = strlen(devicelist))) { Q_strcat(devicenames, sizeof(devicenames), devicelist); Q_strcat(devicenames, sizeof(devicenames), "\n"); devicelist += curlen + 1; } } s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART); } alDevice = qalcOpenDevice(device); if( !alDevice && device ) { Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device ); alDevice = qalcOpenDevice(NULL); } if( !alDevice ) { QAL_Shutdown( ); Com_Printf( "Failed to open OpenAL device.\n" ); return qfalse; } alContext = qalcCreateContext( alDevice, NULL ); if( !alContext ) { QAL_Shutdown( ); qalcCloseDevice( alDevice ); Com_Printf( "Failed to create OpenAL context.\n" ); return qfalse; } qalcMakeContextCurrent( alContext ); S_AL_BufferInit( ); S_AL_SrcInit( ); qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); qalDopplerFactor( s_alDopplerFactor->value ); qalSpeedOfSound( s_alDopplerSpeed->value ); #ifdef USE_VOIP s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH ); if (!s_alCapture->integer) { Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n"); } #if USE_MUMBLE else if (cl_useMumble->integer) { Com_Printf("OpenAL capture support disabled for Mumble support\n"); } #endif else { #ifdef __APPLE__ if (qalcCaptureOpenDevice == NULL) #else if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture")) #endif { Com_Printf("No ALC_EXT_capture support, can't record audio.\n"); } else { char inputdevicenames[16384] = ""; const char *inputdevicelist; const char *defaultinputdevice; int curlen; capture_ext = qtrue; inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER); defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER); if (inputdevicelist) { while((curlen = strlen(inputdevicelist))) { Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist); Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n"); inputdevicelist += curlen + 1; } } s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART); Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none"); alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4); if( !alCaptureDevice && inputdevice ) { Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice ); alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4); } Com_Printf( "OpenAL capture device %s.\n", (alCaptureDevice == NULL) ? "failed to open" : "opened"); } } #endif si->Shutdown = S_AL_Shutdown; si->StartSound = S_AL_StartSound; si->StartLocalSound = S_AL_StartLocalSound; si->StartBackgroundTrack = S_AL_StartBackgroundTrack; si->StopBackgroundTrack = S_AL_StopBackgroundTrack; si->RawSamples = S_AL_RawSamples; si->StopAllSounds = S_AL_StopAllSounds; si->ClearLoopingSounds = S_AL_ClearLoopingSounds; si->AddLoopingSound = S_AL_AddLoopingSound; si->AddRealLoopingSound = S_AL_AddRealLoopingSound; si->StopLoopingSound = S_AL_StopLoopingSound; si->Respatialize = S_AL_Respatialize; si->UpdateEntityPosition = S_AL_UpdateEntityPosition; si->Update = S_AL_Update; si->DisableSounds = S_AL_DisableSounds; si->BeginRegistration = S_AL_BeginRegistration; si->RegisterSound = S_AL_RegisterSound; si->ClearSoundBuffer = S_AL_ClearSoundBuffer; si->SoundInfo = S_AL_SoundInfo; si->SoundList = S_AL_SoundList; #ifdef USE_VOIP si->StartCapture = S_AL_StartCapture; si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples; si->Capture = S_AL_Capture; si->StopCapture = S_AL_StopCapture; si->MasterGain = S_AL_MasterGain; #endif return qtrue; #else return qfalse; #endif }
CWE-269
183,250
10,651
150263890990416823420481826028533431773
null
null
null
redis
1eb08bcd4634ae42ec45e8284923ac048beaa4c3
1
static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } }
CWE-190
183,337
10,663
107382855017923038496801612055445938421
null
null
null
redis
52a00201fca331217c3b4b8b634f6a0f57d6b7d3
1
int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; }
CWE-119
183,339
10,665
31024745101585963470448361807114846408
null
null
null
FFmpeg
afc9c683ed9db01edb357bc8c19edad4282b3a97
1
static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: // if (avio_feof(s->pb)) { // ret = 0; // } avio_seek(s->pb, current_pos, SEEK_SET); return ret; }
nan
null
10,668
185787158206728816406767136333163823448
62
avformat/asfdec: Fix DoS in asf_build_simple_index() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
WavPack
6f8bb34c2993a48ab9afbe353e6d0cff7c8d821d
1
int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,669
51282300993233378503454277820073646043
262
issue #33, sanitize size of unknown chunks before malloc()
null
WavPack
6f8bb34c2993a48ab9afbe353e6d0cff7c8d821d
1
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,670
140429834578859407919474197908436574214
232
issue #33, sanitize size of unknown chunks before malloc()
null
WavPack
6f8bb34c2993a48ab9afbe353e6d0cff7c8d821d
1
int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,671
210565535641398624373028337173596658513
221
issue #33, sanitize size of unknown chunks before malloc()
null
file
d7cdad007c507e6c79f51f058dd77fab70ceb9f6
1
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int mach, int strtab) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ char name[50]; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) { file_badread(ms); return -1; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) { file_badread(ms); return -1; } name[sizeof(name) - 1] = '\0'; if (strcmp(name, ".debug_info") == 0) stripped = 0; if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } // gnu attributes #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "0x%" INT64_T_FORMAT "x = 0x%" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; }
nan
null
10,672
221056719166951268472690542990298523353
231
Stop reporting bad capabilities after the first few.
null
linux
820f9f147dcce2602eefd9b575bbbd9ea14f0953
1
void pin_remove(struct fs_pin *pin) { spin_lock(&pin_lock); hlist_del(&pin->m_list); hlist_del(&pin->s_list); spin_unlock(&pin_lock); spin_lock_irq(&pin->wait.lock); pin->done = 1; wake_up_locked(&pin->wait); spin_unlock_irq(&pin->wait.lock); }
nan
null
10,673
276769003975703437447793406610065481694
11
fs_pin: Allow for the possibility that m_list or s_list go unused. This is needed to support lazily umounting locked mounts. Because the entire unmounted subtree needs to stay together until there are no users with references to any part of the subtree. To support this guarantee that the fs_pin m_list and s_list nodes are initialized by initializing them in init_fs_pin allowing for the possibility that pin_insert_group does not touch them. Further use hlist_del_init in pin_remove so that there is a hlist_unhashed test before the list we attempt to update the previous list item. Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
null
linux
820f9f147dcce2602eefd9b575bbbd9ea14f0953
1
static inline void init_fs_pin(struct fs_pin *p, void (*kill)(struct fs_pin *)) { init_waitqueue_head(&p->wait); p->kill = kill; }
nan
null
10,674
755181173966157256946379814863583450
5
fs_pin: Allow for the possibility that m_list or s_list go unused. This is needed to support lazily umounting locked mounts. Because the entire unmounted subtree needs to stay together until there are no users with references to any part of the subtree. To support this guarantee that the fs_pin m_list and s_list nodes are initialized by initializing them in init_fs_pin allowing for the possibility that pin_insert_group does not touch them. Further use hlist_del_init in pin_remove so that there is a hlist_unhashed test before the list we attempt to update the previous list item. Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
null
qemu
5193be3be35f29a35bc465036cd64ad60d43385f
1
static int tsc210x_load(QEMUFile *f, void *opaque, int version_id) { TSC210xState *s = (TSC210xState *) opaque; int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); int i; s->x = qemu_get_be16(f); s->y = qemu_get_be16(f); s->pressure = qemu_get_byte(f); s->state = qemu_get_byte(f); s->page = qemu_get_byte(f); s->offset = qemu_get_byte(f); s->command = qemu_get_byte(f); s->irq = qemu_get_byte(f); qemu_get_be16s(f, &s->dav); timer_get(f, s->timer); s->enabled = qemu_get_byte(f); s->host_mode = qemu_get_byte(f); s->function = qemu_get_byte(f); s->nextfunction = qemu_get_byte(f); s->precision = qemu_get_byte(f); s->nextprecision = qemu_get_byte(f); s->filter = qemu_get_byte(f); s->pin_func = qemu_get_byte(f); s->ref = qemu_get_byte(f); s->timing = qemu_get_byte(f); s->noise = qemu_get_be32(f); qemu_get_be16s(f, &s->audio_ctrl1); qemu_get_be16s(f, &s->audio_ctrl2); qemu_get_be16s(f, &s->audio_ctrl3); qemu_get_be16s(f, &s->pll[0]); qemu_get_be16s(f, &s->pll[1]); qemu_get_be16s(f, &s->volume); s->volume_change = qemu_get_sbe64(f) + now; s->powerdown = qemu_get_sbe64(f) + now; s->softstep = qemu_get_byte(f); qemu_get_be16s(f, &s->dac_power); for (i = 0; i < 0x14; i ++) qemu_get_be16s(f, &s->filter_data[i]); s->busy = timer_pending(s->timer); qemu_set_irq(s->pint, !s->irq); qemu_set_irq(s->davint, !s->dav); return 0; }
nan
null
10,675
138472856828999154739469049501987117952
51
tsc210x: fix buffer overrun on invalid state load CVE-2013-4539 s->precision, nextprecision, function and nextfunction come from wire and are used as idx into resolution[] in TSC_CUT_RESOLUTION. Validate after load to avoid buffer overrun. Cc: Andreas Färber <afaerber@suse.de> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Juan Quintela <quintela@redhat.com>
null
FFmpeg
7d57ca4d9a75562fa32e40766211de150f8b3ee7
1
static int rtmp_packet_read_one_chunk(URLContext *h, RTMPPacket *p, int chunk_size, RTMPPacket **prev_pkt_ptr, int *nb_prev_pkt, uint8_t hdr) { uint8_t buf[16]; int channel_id, timestamp, size; uint32_t ts_field; // non-extended timestamp or delta field uint32_t extra = 0; enum RTMPPacketType type; int written = 0; int ret, toread; RTMPPacket *prev_pkt; written++; channel_id = hdr & 0x3F; if (channel_id < 2) { //special case for channel number >= 64 buf[1] = 0; if (ffurl_read_complete(h, buf, channel_id + 1) != channel_id + 1) return AVERROR(EIO); written += channel_id + 1; channel_id = AV_RL16(buf) + 64; } if ((ret = ff_rtmp_check_alloc_array(prev_pkt_ptr, nb_prev_pkt, channel_id)) < 0) return ret; prev_pkt = *prev_pkt_ptr; size = prev_pkt[channel_id].size; type = prev_pkt[channel_id].type; extra = prev_pkt[channel_id].extra; hdr >>= 6; // header size indicator if (hdr == RTMP_PS_ONEBYTE) { ts_field = prev_pkt[channel_id].ts_field; } else { if (ffurl_read_complete(h, buf, 3) != 3) return AVERROR(EIO); written += 3; ts_field = AV_RB24(buf); if (hdr != RTMP_PS_FOURBYTES) { if (ffurl_read_complete(h, buf, 3) != 3) return AVERROR(EIO); written += 3; size = AV_RB24(buf); if (ffurl_read_complete(h, buf, 1) != 1) return AVERROR(EIO); written++; type = buf[0]; if (hdr == RTMP_PS_TWELVEBYTES) { if (ffurl_read_complete(h, buf, 4) != 4) return AVERROR(EIO); written += 4; extra = AV_RL32(buf); } } } if (ts_field == 0xFFFFFF) { if (ffurl_read_complete(h, buf, 4) != 4) return AVERROR(EIO); timestamp = AV_RB32(buf); } else { timestamp = ts_field; } if (hdr != RTMP_PS_TWELVEBYTES) timestamp += prev_pkt[channel_id].timestamp; if (!prev_pkt[channel_id].read) { if ((ret = ff_rtmp_packet_create(p, channel_id, type, timestamp, size)) < 0) return ret; p->read = written; p->offset = 0; prev_pkt[channel_id].ts_field = ts_field; prev_pkt[channel_id].timestamp = timestamp; } else { // previous packet in this channel hasn't completed reading RTMPPacket *prev = &prev_pkt[channel_id]; p->data = prev->data; p->size = prev->size; p->channel_id = prev->channel_id; p->type = prev->type; p->ts_field = prev->ts_field; p->extra = prev->extra; p->offset = prev->offset; p->read = prev->read + written; p->timestamp = prev->timestamp; prev->data = NULL; } p->extra = extra; // save history prev_pkt[channel_id].channel_id = channel_id; prev_pkt[channel_id].type = type; prev_pkt[channel_id].size = size; prev_pkt[channel_id].extra = extra; size = size - p->offset; toread = FFMIN(size, chunk_size); if (ffurl_read_complete(h, p->data + p->offset, toread) != toread) { ff_rtmp_packet_destroy(p); return AVERROR(EIO); } size -= toread; p->read += toread; p->offset += toread; if (size > 0) { RTMPPacket *prev = &prev_pkt[channel_id]; prev->data = p->data; prev->read = p->read; prev->offset = p->offset; p->data = NULL; return AVERROR(EAGAIN); } prev_pkt[channel_id].read = 0; // read complete; reset if needed return p->read; }
nan
null
10,676
40257325432950084704999739528714595436
118
avformat/rtmppkt: Check for packet size mismatches Fixes out of array access Found-by: Paul Cher <paulcher@icloud.com> Reviewed-by: Paul Cher <paulcher@icloud.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
Espruino
a0d7f432abee692402c00e8b615ff5982dde9780
1
size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) // On linux, we set STACK_BASE from `main`. char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); return 1000000 - count; // give it 1 megabyte of stack #else // stack depth seems pretty platform-specific :( Default to a value that disables it return 1000000; // no stack depth check on this platform #endif }
nan
null
10,677
330734069179736975467710679001026316321
18
Fix stack size detection on Linux (fix #1427)
null
suricata
11f3659f64a4e42e90cb3c09fcef66894205aefe
1
int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { if (!g_teredo_enabled) return TM_ECODE_FAILED; uint8_t *start = pkt; /* Is this packet to short to contain an IPv6 packet ? */ if (len < IPV6_HEADER_LEN) return TM_ECODE_FAILED; /* Teredo encapsulate IPv6 in UDP and can add some custom message * part before the IPv6 packet. In our case, we just want to get * over an ORIGIN indication. So we just make one offset if needed. */ if (start[0] == 0x0) { switch (start[1]) { /* origin indication: compatible with tunnel */ case 0x0: /* offset is coherent with len and presence of an IPv6 header */ if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN) start += TEREDO_ORIG_INDICATION_LENGTH; else return TM_ECODE_FAILED; break; /* authentication: negotiation not real tunnel */ case 0x1: return TM_ECODE_FAILED; /* this case is not possible in Teredo: not that protocol */ default: return TM_ECODE_FAILED; } } /* There is no specific field that we can check to prove that the packet * is a Teredo packet. We've zapped here all the possible Teredo header * and we should have an IPv6 packet at the start pointer. * We then can only do two checks before sending the encapsulated packets * to decoding: * - The packet has a protocol version which is IPv6. * - The IPv6 length of the packet matches what remains in buffer. */ if (IP_GET_RAW_VER(start) == 6) { IPV6Hdr *thdr = (IPV6Hdr *)start; if (len == IPV6_HEADER_LEN + IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) { if (pq != NULL) { int blen = len - (start - pkt); /* spawn off tunnel packet */ Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen, DECODE_TUNNEL_IPV6, pq); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO); /* add the tp to the packet queue. */ PacketEnqueue(pq,tp); StatsIncr(tv, dtv->counter_teredo); return TM_ECODE_OK; } } } return TM_ECODE_FAILED; } return TM_ECODE_FAILED; }
nan
null
10,678
14393695795783695984453018272592080460
64
teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736.
null
suricata
11f3659f64a4e42e90cb3c09fcef66894205aefe
1
DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { SCEnter(); uint8_t *orig_pkt = pkt; uint8_t nh = 0; /* careful, 0 is actually a real type */ uint16_t hdrextlen = 0; uint16_t plen; char dstopts = 0; char exthdr_fh_done = 0; int hh = 0; int rh = 0; int eh = 0; int ah = 0; nh = IPV6_GET_NH(p); plen = len; while(1) { /* No upper layer, but we do have data. Suspicious. */ if (nh == IPPROTO_NONE && plen > 0) { ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER); SCReturn; } if (plen < 2) { /* minimal needed in a hdr */ SCReturn; } switch(nh) { case IPPROTO_TCP: IPV6_SET_L4PROTO(p,nh); DecodeTCP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_UDP: IPV6_SET_L4PROTO(p,nh); DecodeUDP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ICMPV6: IPV6_SET_L4PROTO(p,nh); DecodeICMPV6(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_SCTP: IPV6_SET_L4PROTO(p,nh); DecodeSCTP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ROUTING: IPV6_SET_L4PROTO(p,nh); hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (rh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } rh = 1; IPV6_EXTHDR_SET_RH(p); uint8_t ip6rh_type = *(pkt + 2); if (ip6rh_type == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0); } p->ip6eh.rh_type = ip6rh_type; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; case IPPROTO_HOPOPTS: case IPPROTO_DSTOPTS: { IPV6OptHAO hao_s, *hao = &hao_s; IPV6OptRA ra_s, *ra = &ra_s; IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s; uint16_t optslen = 0; IPV6_SET_L4PROTO(p,nh); hdrextlen = (*(pkt+1) + 1) << 3; if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */ /* point the pointers to right structures * in Packet. */ if (nh == IPPROTO_HOPOPTS) { if (hh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } hh = 1; optslen = ((*(pkt + 1) + 1 ) << 3) - 2; } else if (nh == IPPROTO_DSTOPTS) { if (dstopts == 0) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 1; } else if (dstopts == 1) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 2; } else { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } } if (optslen > plen) { /* since the packet is long enough (we checked * plen against hdrlen, the optlen must be malformed. */ ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /** \todo move into own function to loaded on demand */ uint16_t padn_cnt = 0; uint16_t other_cnt = 0; uint16_t offset = 0; while(offset < optslen) { if (*ptr == IPV6OPT_PAD1) { padn_cnt++; offset++; ptr++; continue; } if (offset + 1 >= optslen) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } /* length field for each opt */ uint8_t ip6_optlen = *(ptr + 1); /* see if the optlen from the packet fits the total optslen */ if ((offset + 1 + ip6_optlen) > optslen) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } if (*ptr == IPV6OPT_PADN) /* PadN */ { //printf("PadN option\n"); padn_cnt++; /* a zero padN len would be weird */ if (ip6_optlen == 0) ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN); } else if (*ptr == IPV6OPT_RA) /* RA */ { ra->ip6ra_type = *(ptr); ra->ip6ra_len = ip6_optlen; if (ip6_optlen < sizeof(ra->ip6ra_value)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value)); ra->ip6ra_value = SCNtohs(ra->ip6ra_value); //printf("RA option: type %" PRIu32 " len %" PRIu32 " value %" PRIu32 "\n", // ra->ip6ra_type, ra->ip6ra_len, ra->ip6ra_value); other_cnt++; } else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */ { jumbo->ip6j_type = *(ptr); jumbo->ip6j_len = ip6_optlen; if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len)); jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len); //printf("Jumbo option: type %" PRIu32 " len %" PRIu32 " payload len %" PRIu32 "\n", // jumbo->ip6j_type, jumbo->ip6j_len, jumbo->ip6j_payload_len); } else if (*ptr == IPV6OPT_HAO) /* HAO */ { hao->ip6hao_type = *(ptr); hao->ip6hao_len = ip6_optlen; if (ip6_optlen < sizeof(hao->ip6hao_hoa)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa)); //printf("HAO option: type %" PRIu32 " len %" PRIu32 " ", // hao->ip6hao_type, hao->ip6hao_len); //char addr_buf[46]; //PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa), // addr_buf,sizeof(addr_buf)); //printf("home addr %s\n", addr_buf); other_cnt++; } else { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT); other_cnt++; } uint16_t optlen = (*(ptr + 1) + 2); ptr += optlen; /* +2 for opt type and opt len fields */ offset += optlen; } /* flag packets that have only padding */ if (padn_cnt > 0 && other_cnt == 0) { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING); } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_FRAGMENT: { IPV6_SET_L4PROTO(p,nh); /* store the offset of this extension into the packet * past the ipv6 header. We use it in defrag for creating * a defragmented packet without the frag header */ if (exthdr_fh_done == 0) { p->ip6eh.fh_offset = pkt - orig_pkt; exthdr_fh_done = 1; } uint16_t prev_hdrextlen = hdrextlen; hdrextlen = sizeof(IPV6FragHdr); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } /* for the frag header, the length field is reserved */ if (*(pkt + 1) != 0) { ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD); /* non fatal, lets try to continue */ } if (IPV6_EXTHDR_ISSET_FH(p)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* set the header flag first */ IPV6_EXTHDR_SET_FH(p); /* parse the header and setup the vars */ DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen); /* if FH has offset 0 and no more fragments are coming, we * parse this packet further right away, no defrag will be * needed. It is a useless FH then though, so we do set an * decoder event. */ if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* the rest is parsed upon reassembly */ p->flags |= PKT_IS_FRAGMENT; SCReturn; } case IPPROTO_ESP: { IPV6_SET_L4PROTO(p,nh); hdrextlen = sizeof(IPV6EspHdr); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (eh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH); SCReturn; } eh = 1; nh = IPPROTO_NONE; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_AH: { IPV6_SET_L4PROTO(p,nh); /* we need the header as a minimum */ hdrextlen = sizeof(IPV6AuthHdr); /* the payload len field is the number of extra 4 byte fields, * IPV6AuthHdr already contains the first */ if (*(pkt+1) > 0) hdrextlen += ((*(pkt+1) - 1) * 4); SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt; if (ahhdr->ip6ah_reserved != 0x0000) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL); } if (ah) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } ah = 1; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_IPIP: IPV6_SET_L4PROTO(p,nh); DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq); SCReturn; /* none, last header */ case IPPROTO_NONE: IPV6_SET_L4PROTO(p,nh); SCReturn; case IPPROTO_ICMP: ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4); SCReturn; /* no parsing yet, just skip it */ case IPPROTO_MH: case IPPROTO_HIP: case IPPROTO_SHIM6: hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; default: ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER); IPV6_SET_L4PROTO(p,nh); SCReturn; } } SCReturn; }
nan
null
10,679
156698936785910112236845492611231810990
409
teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736.
null
qemu
afbcc40bee4ef51731102d7d4b499ee12fc182e1
1
static int parallels_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVParallelsState *s = bs->opaque; int i; struct parallels_header ph; int ret; bs->read_only = 1; // no write support yet ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph)); if (ret < 0) { goto fail; } if (memcmp(ph.magic, HEADER_MAGIC, 16) || (le32_to_cpu(ph.version) != HEADER_VERSION)) { error_setg(errp, "Image not in Parallels format"); ret = -EINVAL; goto fail; } bs->total_sectors = le32_to_cpu(ph.nb_sectors); s->tracks = le32_to_cpu(ph.tracks); s->catalog_size = le32_to_cpu(ph.catalog_entries); s->catalog_bitmap = g_malloc(s->catalog_size * 4); ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4); if (ret < 0) { goto fail; } for (i = 0; i < s->catalog_size; i++) le32_to_cpus(&s->catalog_bitmap[i]); qemu_co_mutex_init(&s->lock); return 0; fail: g_free(s->catalog_bitmap); return ret; }
nan
null
10,682
208362155379597659075378323736126828438
44
parallels: Fix catalog size integer overflow (CVE-2014-0143) The first test case would cause a huge memory allocation, leading to a qemu abort; the second one to a too small malloc() for the catalog (smaller than s->catalog_size), which causes a read-only out-of-bounds array access and on big endian hosts an endianess conversion for an undefined memory area. The sample image used here is not an original Parallels image. It was created using an hexeditor on the basis of the struct that qemu uses. Good enough for trying to crash the driver, but not for ensuring compatibility. Signed-off-by: Kevin Wolf <kwolf@redhat.com> Reviewed-by: Max Reitz <mreitz@redhat.com> Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
null
FFmpeg
bd27a9364ca274ca97f1df6d984e88a0700fb235
1
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { int profile, level; mpeg4_decode_profile_level(s, gb, &profile, &level); if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (level > 0 && level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } else if (s->studio_profile) { avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n"); return AVERROR_PATCHWELCOME; } s->avctx->profile = profile; s->avctx->level = level; } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO); if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); }
nan
null
10,684
81820958375911647065073113438778363533
154
avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile The profile field is changed by code inside and outside the decoder, its not a reliable indicator of the internal codec state. Maintaining it consistency with studio_profile is messy. Its easier to just avoid it and use only studio_profile Fixes: assertion failure Fixes: ffmpeg_crash_9.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
FFmpeg
bd27a9364ca274ca97f1df6d984e88a0700fb235
1
static int er_supported(ERContext *s) { if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice || !s->cur_pic.f || s->cur_pic.field_picture || s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO ) return 0; return 1; }
nan
null
10,685
141920714405357946260120320990848134262
10
avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile The profile field is changed by code inside and outside the decoder, its not a reliable indicator of the internal codec state. Maintaining it consistency with studio_profile is messy. Its easier to just avoid it and use only studio_profile Fixes: assertion failure Fixes: ffmpeg_crash_9.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
file
27a14bc7ba285a0a5ebfdb55e54001aa11932b08
1
*/ private int mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0;
nan
null
10,687
118264346288892306650219295986767732551
138
Correctly compute the truncated pascal string size (Francisco Alonso and Jan Kaluza at RedHat)
null
xserver
d2f813f7db157fc83abc4b3726821c36ee7e40b1
1
fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; CompositeFunc func = NULL; Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; Bool maskTransform = FALSE; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; int w, h, w_this, h_this; #ifdef USE_MMX static Bool mmx_setup = FALSE; if (!mmx_setup) { fbComposeSetupMMX(); mmx_setup = TRUE; } #endif xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) srcTransform = FALSE; if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) maskTransform = TRUE; maskAlphaMap = pMask->alphaMap != 0; if (maskRepeat && maskTransform && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) maskTransform = FALSE; } if (pSrc->pDrawable && (!pMask || pMask->pDrawable) && !srcTransform && !maskTransform && !maskAlphaMap && !srcAlphaMap && !dstAlphaMap && (pSrc->filter != PictFilterConvolution) && (!pMask || pMask->filter != PictFilterConvolution)) switch (op) { case PictOpOver: if (pMask) { if (fbCanGetSolid(pSrc) && !maskRepeat) { if (PICT_FORMAT_COLOR(pSrc->format)) { switch (pMask->format) { case PICT_a8: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x0565mmx; else #endif func = fbCompositeSolidMask_nx8x0565; break; case PICT_r8g8b8: case PICT_b8g8r8: func = fbCompositeSolidMask_nx8x0888; break; case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else #endif func = fbCompositeSolidMask_nx8x8888; break; default: break; } break; case PICT_a8r8g8b8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; } } if (func) srcRepeat = FALSE; } else if (!srcRepeat) /* has mask and non-repeating source */ { if (pSrc->pDrawable == pMask->pDrawable && xSrc == xMask && ySrc == yMask && !pMask->componentAlpha && !maskRepeat) { /* source == mask: non-premultiplied data */ switch (pSrc->format) { case PICT_x8b8g8r8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; default: break; } break; default: break; } break; case PICT_x8r8g8b8: switch (pMask->format) { case PICT_a8r8g8b8: case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx8888mmx; #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888RevNPx0565mmx; #endif break; default: break; } break; default: break; } break; default: break; } break; } else if (maskRepeat && pMask->pDrawable->width == 1 && pMask->pDrawable->height == 1) { switch (pSrc->format) { case PICT_r5g6b5: case PICT_b5g6r5: if (pDst->format == pSrc->format) func = fbCompositeTrans_0565xnx0565; break; case PICT_r8g8b8: case PICT_b8g8r8: if (pDst->format == pSrc->format) func = fbCompositeTrans_0888xnx0888; break; #ifdef USE_MMX case PICT_x8r8g8b8: if ((pDst->format == PICT_a8r8g8b8 || pDst->format == PICT_x8r8g8b8) && pMask->format == PICT_a8 && fbHaveMMX()) func = fbCompositeSrc_x888x8x8888mmx; break; case PICT_x8b8g8r8: if ((pDst->format == PICT_a8b8g8r8 || pDst->format == PICT_x8b8g8r8) && pMask->format == PICT_a8 && fbHaveMMX()) func = fbCompositeSrc_x888x8x8888mmx; break; case PICT_a8r8g8b8: if ((pDst->format == PICT_a8r8g8b8 || pDst->format == PICT_x8r8g8b8) && pMask->format == PICT_a8 && fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; break; case PICT_a8b8g8r8: if ((pDst->format == PICT_a8b8g8r8 || pDst->format == PICT_x8b8g8r8) && pMask->format == PICT_a8 && fbHaveMMX()) func = fbCompositeSrc_8888x8x8888mmx; break; #endif default: break; } if (func) maskRepeat = FALSE; } } } else /* no mask */ { if (fbCanGetSolid(pSrc)) { /* no mask and repeating source */ switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx8888mmx; } #endif break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolid_nx0565mmx; } #endif break; default: break; } break; default: break; } } else if (! srcRepeat) { /* * Formats without alpha bits are just Copy with Over */ if (pSrc->format == pDst->format && !PICT_FORMAT_A(pSrc->format)) { #ifdef USE_MMX if (fbHaveMMX() && (pSrc->format == PICT_x8r8g8b8 || pSrc->format == PICT_x8b8g8r8)) func = fbCompositeCopyAreammx; else #endif func = fbCompositeSrcSrc_nxn; } else switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_r8g8b8: func = fbCompositeSrc_8888x0888; break; case PICT_r5g6b5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x0565mmx; else #endif func = fbCompositeSrc_8888x0565; break; default: break; } break; case PICT_x8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; default: break; } case PICT_x8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeCopyAreammx; #endif break; default: break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x8888mmx; else #endif func = fbCompositeSrc_8888x8888; break; case PICT_b8g8r8: func = fbCompositeSrc_8888x0888; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrc_8888x0565mmx; else #endif func = fbCompositeSrc_8888x0565; break; default: break; } break; default: break; } } } break; case PictOpAdd: if (pMask == 0) { switch (pSrc->format) { case PICT_a8r8g8b8: switch (pDst->format) { case PICT_a8r8g8b8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; default: break; } break; case PICT_a8b8g8r8: switch (pDst->format) { case PICT_a8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8888mmx; else #endif func = fbCompositeSrcAdd_8888x8888; break; default: break; } break; case PICT_a8: switch (pDst->format) { case PICT_a8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8000x8000mmx; else #endif func = fbCompositeSrcAdd_8000x8000; break; default: break; } break; case PICT_a1: switch (pDst->format) { case PICT_a1: func = fbCompositeSrcAdd_1000x1000; break; default: break; } break; default: break; } } else { if ((pSrc->format == PICT_a8r8g8b8 || pSrc->format == PICT_a8b8g8r8) && fbCanGetSolid (pSrc) && pMask->format == PICT_a8 && pDst->format == PICT_a8) { srcRepeat = FALSE; #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSrcAdd_8888x8x8mmx; else #endif func = fbCompositeSrcAdd_8888x8x8; } } break; case PictOpSrc: if (pMask) { #ifdef USE_MMX if (fbCanGetSolid (pSrc)) { if (pMask->format == PICT_a8) { switch (pDst->format) { case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeSolidMaskSrc_nx8x8888mmx; } break; default: break; } } } #endif } else { if (pSrc->format == pDst->format) { #ifdef USE_MMX if (pSrc->pDrawable != pDst->pDrawable && fbHaveMMX() && (PICT_FORMAT_BPP (pSrc->format) == 16 || PICT_FORMAT_BPP (pSrc->format) == 32)) func = fbCompositeCopyAreammx; else #endif func = fbCompositeSrcSrc_nxn; } } break; case PictOpIn: #ifdef USE_MMX if (pSrc->format == PICT_a8 && pDst->format == PICT_a8 && !pMask) { if (fbHaveMMX()) func = fbCompositeIn_8x8mmx; } else if (srcRepeat && pMask && !pMask->componentAlpha && (pSrc->format == PICT_a8r8g8b8 || pSrc->format == PICT_a8b8g8r8) && (pMask->format == PICT_a8) && pDst->format == PICT_a8) { if (fbHaveMMX()) { srcRepeat = FALSE; func = fbCompositeIn_nx8x8mmx; } } #else func = NULL; #endif break; default: break; } if (!func) { func = fbCompositeRectWrapper; } /* if we are transforming, we handle repeats in fbFetchTransformed */ if (srcTransform) srcRepeat = FALSE; if (maskTransform) maskRepeat = FALSE; if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; y_msk += pMask->pDrawable->y; } if (srcRepeat) { y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; y_src += pSrc->pDrawable->y; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; x_msk += pMask->pDrawable->x; } if (srcRepeat) { x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; x_src += pSrc->pDrawable->x; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); }
nan
null
10,690
235510315218058737263813032488380398967
681
New fbWalkCompositeRegion() function This new function walks the composite region and calls a rectangle compositing function on each compositing rectangle. Previously there were buggy duplicates of this code in fbcompose.c and miext/rootles/safealpha/safeAlphaPicture.c.
null
sleuthkit
114cd3d0aac8bd1aeaf4b33840feb0163d342d5b
1
hfs_cat_traverse(HFS_INFO * hfs, TSK_HFS_BTREE_CB a_cb, void *ptr) { TSK_FS_INFO *fs = &(hfs->fs_info); uint32_t cur_node; /* node id of the current node */ char *node; uint16_t nodesize; uint8_t is_done = 0; tsk_error_reset(); nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) return 1; /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: " "empty extents btree\n"); free(node); return 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: starting at " "root node %" PRIu32 "; nodesize = %" PRIu16 "\n", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; // sanity check if (cur_node > tsk_getu32(fs->endian, hfs->catalog_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node %d too large for file", cur_node); free(node); return 1; } // read the current node cur_off = cur_node * nodesize; cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_traverse: Error reading node %d at offset %" PRIuOFF, cur_node, cur_off); free(node); return 1; } // process the header / descriptor if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node size %d is too small to be valid", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: zero records in node %" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; uint16_t keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 " ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ /* save the info from this record unless it is too big */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } // record the closest entry else if ((retval == HFS_BTREE_CB_IDX_LT) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->catalog_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (retval == HFS_BTREE_CB_IDX_EQGT) { // move down to the next node break; } } // check if we found a relevant node if (next_node == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: did not find any keys in index node %d", cur_node); is_done = 1; break; } // TODO: Handle multinode loops if (next_node == cur_node) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: node %d references itself as next node", cur_node); is_done = 1; break; } cur_node = next_node; } /* With a leaf, we look for the specific record. */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; uint16_t keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 "; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ // rec_cnid = tsk_getu32(fs->endian, key->file_id); retval = a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_LEAF_STOP) { is_done = 1; break; } else if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } } // move right to the next node if we got this far if (is_done == 0) { cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: moving forward to next leaf"); } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32 " (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; }
nan
null
10,691
5527278486832853535759333086577578884
285
hfs: fix keylen check in hfs_cat_traverse() If key->key_len is 65535, calculating "uint16_t keylen' would cause an overflow: uint16_t keylen; ... keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len) so the code bypasses the sanity check "if (keylen > nodesize)" which results in crash later: ./toolfs/fstools/fls -b 512 -f hfs <image> ================================================================= ==16==ERROR: AddressSanitizer: SEGV on unknown address 0x6210000256a4 (pc 0x00000054812b bp 0x7ffca548a8f0 sp 0x7ffca548a480 T0) ==16==The signal is caused by a READ memory access. #0 0x54812a in hfs_dir_open_meta_cb /fuzzing/sleuthkit/tsk/fs/hfs_dent.c:237:20 #1 0x51a96c in hfs_cat_traverse /fuzzing/sleuthkit/tsk/fs/hfs.c:1082:21 #2 0x547785 in hfs_dir_open_meta /fuzzing/sleuthkit/tsk/fs/hfs_dent.c:480:9 #3 0x50f57d in tsk_fs_dir_open_meta /fuzzing/sleuthkit/tsk/fs/fs_dir.c:290:14 #4 0x54af17 in tsk_fs_path2inum /fuzzing/sleuthkit/tsk/fs/ifind_lib.c:237:23 #5 0x522266 in hfs_open /fuzzing/sleuthkit/tsk/fs/hfs.c:6579:9 #6 0x508e89 in main /fuzzing/sleuthkit/tools/fstools/fls.cpp:267:19 #7 0x7f9daf67c2b0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202b0) #8 0x41d679 in _start (/fuzzing/sleuthkit/tools/fstools/fls+0x41d679) Make 'keylen' int type to prevent the overflow and fix that. Now, I get proper error message instead of crash: ./toolfs/fstools/fls -b 512 -f hfs <image> General file system error (hfs_cat_traverse: length of key 3 in leaf node 1 too large (65537 vs 4096))
null
systemd
505b6a61c22d5565e9308045c7b9bf79f7d0517e
1
void server_process_native_message( Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) { struct iovec *iovec = NULL; unsigned n = 0, m = 0, j, tn = (unsigned) -1; const char *p; size_t remaining; int priority = LOG_INFO; char *identifier = NULL, *message = NULL; assert(s); assert(buffer || buffer_size == 0); p = buffer; remaining = buffer_size; while (remaining > 0) { const char *e, *q; e = memchr(p, '\n', remaining); if (!e) { /* Trailing noise, let's ignore it, and flush what we collected */ log_debug("Received message with trailing noise, ignoring."); break; } if (e == p) { /* Entry separator */ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); n = 0; priority = LOG_INFO; p++; remaining--; continue; } if (*p == '.' || *p == '#') { /* Ignore control commands for now, and * comments too. */ remaining -= (e - p) + 1; p = e + 1; continue; } /* A property follows */ if (n+N_IOVEC_META_FIELDS >= m) { struct iovec *c; unsigned u; u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U); c = realloc(iovec, u * sizeof(struct iovec)); if (!c) { log_oom(); break; } iovec = c; m = u; } q = memchr(p, '=', e - p); if (q) { if (valid_user_field(p, q - p)) { size_t l; l = e - p; /* If the field name starts with an * underscore, skip the variable, * since that indidates a trusted * field */ iovec[n].iov_base = (char*) p; iovec[n].iov_len = l; n++; /* We need to determine the priority * of this entry for the rate limiting * logic */ if (l == 10 && memcmp(p, "PRIORITY=", 9) == 0 && p[9] >= '0' && p[9] <= '9') priority = (priority & LOG_FACMASK) | (p[9] - '0'); else if (l == 17 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9') priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3); else if (l == 18 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9' && p[17] >= '0' && p[17] <= '9') priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3); else if (l >= 19 && memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) { char *t; t = strndup(p + 18, l - 18); if (t) { free(identifier); identifier = t; } } else if (l >= 8 && memcmp(p, "MESSAGE=", 8) == 0) { char *t; t = strndup(p + 8, l - 8); if (t) { free(message); message = t; } } } remaining -= (e - p) + 1; p = e + 1; continue; } else { le64_t l_le; uint64_t l; char *k; if (remaining < e - p + 1 + sizeof(uint64_t) + 1) { log_debug("Failed to parse message, ignoring."); break; } memcpy(&l_le, e + 1, sizeof(uint64_t)); l = le64toh(l_le); if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 || e[1+sizeof(uint64_t)+l] != '\n') { log_debug("Failed to parse message, ignoring."); break; } k = malloc((e - p) + 1 + l); if (!k) { log_oom(); break; } memcpy(k, p, e - p); k[e - p] = '='; memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l); if (valid_user_field(p, e - p)) { iovec[n].iov_base = k; iovec[n].iov_len = (e - p) + 1 + l; n++; } else free(k); remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1; p = e + 1 + sizeof(uint64_t) + l + 1; } } if (n <= 0) goto finish; tn = n++; IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal"); if (message) { if (s->forward_to_syslog) server_forward_syslog(s, priority, identifier, message, ucred, tv); if (s->forward_to_kmsg) server_forward_kmsg(s, priority, identifier, message, ucred); if (s->forward_to_console) server_forward_console(s, priority, identifier, message, ucred); } server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); finish: for (j = 0; j < n; j++) { if (j == tn) continue; if (iovec[j].iov_base < buffer || (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size) free(iovec[j].iov_base); } free(iovec); free(identifier); free(message); }
nan
null
10,692
206165572902001341820075512674135605797
199
journald: don't accept arbitrarily sized journal data fields https://bugzilla.redhat.com/show_bug.cgi?id=858746
null
WavPack
8e3fe45a7bac31d9a3b558ae0079e2d92a04799e
1
int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { uint32_t chan_chunk = 0, channel_layout = 0, bcount; unsigned char *channel_identities = NULL; unsigned char *channel_reorder = NULL; int64_t total_samples = 0, infilesize; CAFFileHeader caf_file_header; CAFChunkHeader caf_chunk_header; CAFAudioFormat caf_audio_format; int i; infilesize = DoGetFileSize (infile); memcpy (&caf_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) || bcount != sizeof (CAFFileHeader) - 4)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat); if (caf_file_header.mFileVersion != 1) { error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) || bcount != sizeof (CAFChunkHeader)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat); // if it's the format chunk, we want to get some info out of there and // make sure it's a .caf file we can handle if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) { int supported = TRUE; if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) || !DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat); if (debug_logging_mode) { char formatstr [5]; memcpy (formatstr, caf_audio_format.mFormatID, 4); formatstr [4] = 0; error_line ("format = %s, flags = %x, sampling rate = %g", formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate); error_line ("packet = %d bytes and %d frames", caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket); error_line ("channels per frame = %d, bits per channel = %d", caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel); } if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3)) supported = FALSE; else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 || caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate)) supported = FALSE; else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256) supported = FALSE; else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 || ((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32)) supported = FALSE; else if (caf_audio_format.mFramesPerPacket != 1 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 || caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .CAF format!", infilename); return WAVPACK_SOFT_ERROR; } config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame; config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0; config->bits_per_sample = caf_audio_format.mBitsPerChannel; config->num_channels = caf_audio_format.mChannelsPerFrame; config->sample_rate = (int) caf_audio_format.mSampleRate; if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1) config->qmode |= QMODE_BIG_ENDIAN; if (config->bytes_per_sample == 1) config->qmode |= QMODE_SIGNED_BYTES; if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little"); else error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)", config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample); } } else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) { CAFChannelLayout *caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize); if (caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout) || !DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat); chan_chunk = 1; if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) { error_line ("this CAF file already has channel order information!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } switch (caf_channel_layout->mChannelLayoutTag) { case kCAFChannelLayoutTag_UseChannelDescriptions: { CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1); int num_descriptions = caf_channel_layout->mNumberChannelDescriptions; int label, cindex = 0, idents = 0; if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions || num_descriptions != config->num_channels) { error_line ("channel descriptions in 'chan' chunk are the wrong size!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } if (num_descriptions >= 256) { error_line ("%d channel descriptions is more than we can handle...ignoring!"); break; } // we allocate (and initialize to invalid values) a channel reorder array // (even though we might not end up doing any reordering) and a string for // any non-Microsoft channels we encounter channel_reorder = malloc (num_descriptions); memset (channel_reorder, -1, num_descriptions); channel_identities = malloc (num_descriptions+1); // convert the descriptions array to our native endian so it's easy to access for (i = 0; i < num_descriptions; ++i) { WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat); if (debug_logging_mode) error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel); } // first, we go though and find any MS channels present, and move those to the beginning for (label = 1; label <= 18; ++label) for (i = 0; i < num_descriptions; ++i) if (descriptions [i].mChannelLabel == label) { config->channel_mask |= 1 << (label - 1); channel_reorder [i] = cindex++; break; } // next, we go though the channels again assigning any we haven't done for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] == (unsigned char) -1) { uint32_t clabel = descriptions [i].mChannelLabel; if (clabel == 0 || clabel == 0xffffffff || clabel == 100) channel_identities [idents++] = 0xff; else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305)) channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel; else { error_line ("warning: unknown channel descriptions label: %d", clabel); channel_identities [idents++] = 0xff; } channel_reorder [i] = cindex++; } // then, go through the reordering array and see if we really have to reorder for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] != i) break; if (i == num_descriptions) { free (channel_reorder); // no reordering required, so don't channel_reorder = NULL; } else { config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout channel_layout = num_descriptions; } if (!idents) { // if no non-MS channels, free the identities string free (channel_identities); channel_identities = NULL; } else channel_identities [idents] = 0; // otherwise NULL terminate it if (debug_logging_mode) { error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS", caf_channel_layout->mChannelLayoutTag, config->channel_mask, caf_channel_layout->mNumberChannelDescriptions, idents); // if debugging, display the reordering as a string (but only little ones) if (channel_reorder && num_descriptions <= 8) { char reorder_string [] = "12345678"; for (i = 0; i < num_descriptions; ++i) reorder_string [i] = channel_reorder [i] + '1'; reorder_string [i] = 0; error_line ("reordering string = \"%s\"\n", reorder_string); } } } break; case kCAFChannelLayoutTag_UseChannelBitmap: config->channel_mask = caf_channel_layout->mChannelBitmap; if (debug_logging_mode) error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x", caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap); break; default: for (i = 0; i < NUM_LAYOUTS; ++i) if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) { config->channel_mask = layouts [i].mChannelBitmap; channel_layout = layouts [i].mChannelLayoutTag; if (layouts [i].mChannelReorder) { channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder); config->qmode |= QMODE_REORDERED_CHANS; } if (layouts [i].mChannelIdentities) channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities); if (debug_logging_mode) error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s", channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no"); break; } if (i == NUM_LAYOUTS && debug_logging_mode) error_line ("layout_tag 0x%08x not found in table...all channels unassigned", caf_channel_layout->mChannelLayoutTag); break; } free (caf_channel_layout); } else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop uint32_t mEditCount; if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) || bcount != sizeof (mEditCount)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket; else total_samples = -1; } else { if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) { error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) { error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket; if (!total_samples) { error_line ("this .CAF file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } break; } else { // just copy unknown chunks to output file int bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2], caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED)) config->channel_mask = 0x5 - config->num_channels; if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if (channel_identities) free (channel_identities); if (channel_layout || channel_reorder) { if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) { error_line ("problem with setting channel layout (should not happen)"); return WAVPACK_SOFT_ERROR; } if (channel_reorder) free (channel_reorder); } return WAVPACK_NO_ERROR; }
nan
null
10,693
248948390429775126389579670769420402057
389
issue #28, fix buffer overflows and bad allocs on corrupt CAF files
null
linux
f8bd2258e2d520dff28c855658bd24bdafb5102d
1
static inline long div_ll_X_l_rem(long long divs, long div, long *rem) { long dum2; asm("divl %2":"=a"(dum2), "=d"(*rem) : "rm"(div), "A"(divs)); return dum2; }
nan
null
10,697
96771922327756497470830411260636440935
9
remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <zippel@linux-m68k.org> Cc: Ralf Baechle <ralf@linux-mips.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: john stultz <johnstul@us.ibm.com> Cc: Christoph Lameter <clameter@sgi.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
null
qemu
b16c129daf0fed91febbb88de23dae8271c8898a
1
static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE || pg > 6) { return -1; } ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ if (pg == 6) { return -1; /* avoid page pg + 1 */ } ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK); uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; }
nan
null
10,708
33948406223871265377712183152949365150
102
usb: ehci: fix memory leak in ehci_process_itd While processing isochronous transfer descriptors(iTD), if the page select(PG) field value is out of bands it will return. In this situation the ehci's sg list is not freed thus leading to a memory leak issue. This patch avoid this. Signed-off-by: Li Qiang <liqiang6-s@360.cn> Reviewed-by: Thomas Huth <thuth@redhat.com> Signed-off-by: Michael Tokarev <mjt@tls.msk.ru>
null
radare2
ead645853a63bf83d8386702cad0cf23b31d7eeb
1
static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size - 1) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; }
nan
null
10,709
59972490419326856568360264397731246212
123
fix #6857
null
file
447558595a3650db2886cd2f416ad0beba965801
1
private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t count = m->str_range; int rv, oneed_separator, in_type; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, count) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, " "nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o, nbytes, count); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (in_type = cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (nbytes < offset || nbytes < (offset + 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (nbytes < offset || nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[0]<<8)| (p->hs[1])) & off; break; case FILE_OPOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[0]<<8)| (p->hs[1])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[0]<<8)| (p->hs[1])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[0]<<8)| (p->hs[1])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[0]<<8)| (p->hs[1])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[0]<<8)| (p->hs[1])) % off; break; } } else offset = (short)((p->hs[0]<<8)| (p->hs[1])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (nbytes < offset || nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[1]<<8)| (p->hs[0])) & off; break; case FILE_OPOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[1]<<8)| (p->hs[0])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[1]<<8)| (p->hs[0])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[1]<<8)| (p->hs[0])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[1]<<8)| (p->hs[0])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[1]<<8)| (p->hs[0])) % off; break; } } else offset = (short)((p->hs[1]<<8)| (p->hs[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (nbytes < offset || nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) % off; break; } } else offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) % off; break; } } else offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) % off; break; } } else offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; default: break; } switch (in_type) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (nbytes < (offset + 1)) /* should alway be true */ return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (nbytes < (offset + 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (nbytes < (offset + 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (nbytes < (offset + 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (nbytes < (offset + m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, F(m->desc, "%u"), offset) == -1) return -1; if (file_printf(ms, "%s", rbuf) == -1) return -1; free(rbuf); } return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ case FILE_CLEAR: default: break; } if (!mconvert(ms, m, flip)) return 0;
nan
null
10,710
271515507458392817577838848298354421846
645
PR/313: Aaron Reffett: Check properly for exceeding the offset.
null
libpcap
33834cb2a4d035b52aa2a26742f832a112e90a0a
1
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; // XXX - make sure it's *not* a URL; we don't support opening // remote devices here. // Open the selected device // This is a fake open, since we do that only to get the needed parameters, then we close the device again if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; // Now, I can send a RPCAP open reply message if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ // We're done with the pcap_t. pcap_close(fp); // Send the reply. if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; }
nan
null
10,711
213239153397732860065657195093437594591
84
In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs.
null
libplist
7391a506352c009fe044dead7baad9e22dd279ee
1
int main(int argc, char *argv[]) { FILE *iplist = NULL; plist_t root_node = NULL; char *plist_out = NULL; uint32_t size = 0; int read_size = 0; char *plist_entire = NULL; struct stat filestats; options_t *options = parse_arguments(argc, argv); if (!options) { print_usage(argc, argv); return 0; } // read input file iplist = fopen(options->in_file, "rb"); if (!iplist) { free(options); return 1; } stat(options->in_file, &filestats); plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); fclose(iplist); // convert from binary to xml or vice-versa if (memcmp(plist_entire, "bplist00", 8) == 0) { plist_from_bin(plist_entire, read_size, &root_node); plist_to_xml(root_node, &plist_out, &size); } else { plist_from_xml(plist_entire, read_size, &root_node); plist_to_bin(root_node, &plist_out, &size); } plist_free(root_node); free(plist_entire); if (plist_out) { if (options->out_file != NULL) { FILE *oplist = fopen(options->out_file, "wb"); if (!oplist) { free(options); return 1; } fwrite(plist_out, size, sizeof(char), oplist); fclose(oplist); } // if no output file specified, write to stdout else fwrite(plist_out, size, sizeof(char), stdout); free(plist_out); } else printf("ERROR: Failed to convert input file.\n"); free(options); return 0; }
nan
null
10,712
113011307546855478065257608108227691081
67
plistutil: Prevent OOB heap buffer read by checking input size As pointed out in #87 plistutil would do a memcmp with a heap buffer without checking the size. If the size is less than 8 it would read beyond the bounds of this heap buffer. This commit prevents that.
null
qemu
3592fe0c919cf27a81d8e9f9b4f269553418bb01
1
static void serial_update_parameters(SerialState *s) { int speed, parity, data_bits, stop_bits, frame_size; QEMUSerialSetParams ssp; if (s->divider == 0) return; /* Start bit. */ frame_size = 1; if (s->lcr & 0x08) { /* Parity bit. */ frame_size++; if (s->lcr & 0x10) parity = 'E'; else parity = 'O'; } else { parity = 'N'; } if (s->lcr & 0x04) stop_bits = 2; else stop_bits = 1; data_bits = (s->lcr & 0x03) + 5; frame_size += data_bits + stop_bits; speed = s->baudbase / s->divider; ssp.speed = speed; ssp.parity = parity; ssp.data_bits = data_bits; ssp.stop_bits = stop_bits; s->char_transmit_time = (NANOSECONDS_PER_SECOND / speed) * frame_size; qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp); DPRINTF("speed=%d parity=%c data=%d stop=%d\n", speed, parity, data_bits, stop_bits); }
nan
null
10,713
35876664800758521993467434976737176489
38
char: serial: check divider value against baud base 16550A UART device uses an oscillator to generate frequencies (baud base), which decide communication speed. This speed could be changed by dividing it by a divider. If the divider is greater than the baud base, speed is set to zero, leading to a divide by zero error. Add check to avoid it. Reported-by: Huawei PSIRT <psirt@huawei.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Message-Id: <1476251888-20238-1-git-send-email-ppandit@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
null
haproxy
efbbdf72992cd20458259962346044cafd9331c0
1
static int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend, struct dns_resolution *resolution, int max_answer_records) { unsigned char *reader; char *previous_dname, tmpname[DNS_MAX_NAME_SIZE]; int len, flags, offset; int dns_query_record_id; int nb_saved_records; struct dns_query_item *dns_query; struct dns_answer_item *dns_answer_record, *tmp_record; struct dns_response_packet *dns_p; int i, found = 0; reader = resp; len = 0; previous_dname = NULL; dns_query = NULL; /* Initialization of response buffer and structure */ dns_p = &resolution->response; /* query id */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_p->header.id = reader[0] * 256 + reader[1]; reader += 2; /* Flags and rcode are stored over 2 bytes * First byte contains: * - response flag (1 bit) * - opcode (4 bits) * - authoritative (1 bit) * - truncated (1 bit) * - recursion desired (1 bit) */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; flags = reader[0] * 256 + reader[1]; if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) { if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) return DNS_RESP_NX_DOMAIN; else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) return DNS_RESP_REFUSED; return DNS_RESP_ERROR; } /* Move forward 2 bytes for flags */ reader += 2; /* 2 bytes for question count */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_p->header.qdcount = reader[0] * 256 + reader[1]; /* (for now) we send one query only, so we expect only one in the * response too */ if (dns_p->header.qdcount != 1) return DNS_RESP_QUERY_COUNT_ERROR; if (dns_p->header.qdcount > DNS_MAX_QUERY_RECORDS) return DNS_RESP_INVALID; reader += 2; /* 2 bytes for answer count */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_p->header.ancount = reader[0] * 256 + reader[1]; if (dns_p->header.ancount == 0) return DNS_RESP_ANCOUNT_ZERO; /* Check if too many records are announced */ if (dns_p->header.ancount > max_answer_records) return DNS_RESP_INVALID; reader += 2; /* 2 bytes authority count */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_p->header.nscount = reader[0] * 256 + reader[1]; reader += 2; /* 2 bytes additional count */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_p->header.arcount = reader[0] * 256 + reader[1]; reader += 2; /* Parsing dns queries */ LIST_INIT(&dns_p->query_list); for (dns_query_record_id = 0; dns_query_record_id < dns_p->header.qdcount; dns_query_record_id++) { /* Use next pre-allocated dns_query_item after ensuring there is * still one available. * It's then added to our packet query list. */ if (dns_query_record_id > DNS_MAX_QUERY_RECORDS) return DNS_RESP_INVALID; dns_query = &resolution->response_query_records[dns_query_record_id]; LIST_ADDQ(&dns_p->query_list, &dns_query->list); /* Name is a NULL terminated string in our case, since we have * one query per response and the first one can't be compressed * (using the 0x0c format) */ offset = 0; len = dns_read_name(resp, bufend, reader, dns_query->name, DNS_MAX_NAME_SIZE, &offset, 0); if (len == 0) return DNS_RESP_INVALID; reader += offset; previous_dname = dns_query->name; /* move forward 2 bytes for question type */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_query->type = reader[0] * 256 + reader[1]; reader += 2; /* move forward 2 bytes for question class */ if (reader + 2 >= bufend) return DNS_RESP_INVALID; dns_query->class = reader[0] * 256 + reader[1]; reader += 2; } /* TRUNCATED flag must be checked after we could read the query type * because a TRUNCATED SRV query type response can still be exploited */ if (dns_query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) return DNS_RESP_TRUNCATED; /* now parsing response records */ nb_saved_records = 0; for (i = 0; i < dns_p->header.ancount; i++) { if (reader >= bufend) return DNS_RESP_INVALID; dns_answer_record = pool_alloc(dns_answer_item_pool); if (dns_answer_record == NULL) return (DNS_RESP_INVALID); offset = 0; len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0); if (len == 0) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } /* Check if the current record dname is valid. previous_dname * points either to queried dname or last CNAME target */ if (dns_query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) { pool_free(dns_answer_item_pool, dns_answer_record); if (i == 0) { /* First record, means a mismatch issue between * queried dname and dname found in the first * record */ return DNS_RESP_INVALID; } else { /* If not the first record, this means we have a * CNAME resolution error */ return DNS_RESP_CNAME_ERROR; } } memcpy(dns_answer_record->name, tmpname, len); dns_answer_record->name[len] = 0; reader += offset; if (reader >= bufend) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } /* 2 bytes for record type (A, AAAA, CNAME, etc...) */ if (reader + 2 > bufend) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->type = reader[0] * 256 + reader[1]; reader += 2; /* 2 bytes for class (2) */ if (reader + 2 > bufend) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->class = reader[0] * 256 + reader[1]; reader += 2; /* 4 bytes for ttl (4) */ if (reader + 4 > bufend) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536 + reader[2] * 256 + reader[3]; reader += 4; /* Now reading data len */ if (reader + 2 > bufend) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->data_len = reader[0] * 256 + reader[1]; /* Move forward 2 bytes for data len */ reader += 2; /* Analyzing record content */ switch (dns_answer_record->type) { case DNS_RTYPE_A: /* ipv4 is stored on 4 bytes */ if (dns_answer_record->data_len != 4) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->address.sa_family = AF_INET; memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr), reader, dns_answer_record->data_len); break; case DNS_RTYPE_CNAME: /* Check if this is the last record and update the caller about the status: * no IP could be found and last record was a CNAME. Could be triggered * by a wrong query type * * + 1 because dns_answer_record_id starts at 0 * while number of answers is an integer and * starts at 1. */ if (i + 1 == dns_p->header.ancount) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_CNAME_ERROR; } offset = 0; len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0); if (len == 0) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } memcpy(dns_answer_record->target, tmpname, len); dns_answer_record->target[len] = 0; previous_dname = dns_answer_record->target; break; case DNS_RTYPE_SRV: /* Answer must contain : * - 2 bytes for the priority * - 2 bytes for the weight * - 2 bytes for the port * - the target hostname */ if (dns_answer_record->data_len <= 6) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->priority = read_n16(reader); reader += sizeof(uint16_t); dns_answer_record->weight = read_n16(reader); reader += sizeof(uint16_t); dns_answer_record->port = read_n16(reader); reader += sizeof(uint16_t); offset = 0; len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0); if (len == 0) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->data_len = len; memcpy(dns_answer_record->target, tmpname, len); dns_answer_record->target[len] = 0; break; case DNS_RTYPE_AAAA: /* ipv6 is stored on 16 bytes */ if (dns_answer_record->data_len != 16) { pool_free(dns_answer_item_pool, dns_answer_record); return DNS_RESP_INVALID; } dns_answer_record->address.sa_family = AF_INET6; memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr), reader, dns_answer_record->data_len); break; } /* switch (record type) */ /* Increment the counter for number of records saved into our * local response */ nb_saved_records++; /* Move forward dns_answer_record->data_len for analyzing next * record in the response */ reader += ((dns_answer_record->type == DNS_RTYPE_SRV) ? offset : dns_answer_record->data_len); /* Lookup to see if we already had this entry */ found = 0; list_for_each_entry(tmp_record, &dns_p->answer_list, list) { if (tmp_record->type != dns_answer_record->type) continue; switch(tmp_record->type) { case DNS_RTYPE_A: if (!memcmp(&((struct sockaddr_in *)&dns_answer_record->address)->sin_addr, &((struct sockaddr_in *)&tmp_record->address)->sin_addr, sizeof(in_addr_t))) found = 1; break; case DNS_RTYPE_AAAA: if (!memcmp(&((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr, &((struct sockaddr_in6 *)&tmp_record->address)->sin6_addr, sizeof(struct in6_addr))) found = 1; break; case DNS_RTYPE_SRV: if (dns_answer_record->data_len == tmp_record->data_len && !memcmp(dns_answer_record->target, tmp_record->target, dns_answer_record->data_len) && dns_answer_record->port == tmp_record->port) { tmp_record->weight = dns_answer_record->weight; found = 1; } break; default: break; } if (found == 1) break; } if (found == 1) { tmp_record->last_seen = now.tv_sec; pool_free(dns_answer_item_pool, dns_answer_record); } else { dns_answer_record->last_seen = now.tv_sec; LIST_ADDQ(&dns_p->answer_list, &dns_answer_record->list); } } /* for i 0 to ancount */ /* Save the number of records we really own */ dns_p->header.ancount = nb_saved_records; dns_check_dns_response(resolution); return DNS_RESP_VALID; }
nan
null
10,714
318380429260227181665321972959150365631
351
BUG: dns: Prevent out-of-bounds read in dns_validate_dns_response() We need to make sure that the record length is not making us read past the end of the data we received. Before this patch we could for example read the 16 bytes corresponding to an AAAA record from the non-initialized part of the buffer, possibly accessing anything that was left on the stack, or even past the end of the 8193-byte buffer, depending on the value of accepted_payload_size. To be backported to 1.8, probably also 1.7.
null
libpcap
437b273761adedcbd880f714bfa44afeec186a31
1
daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } // This call should change the current thread to the selected user. // I didn't test it. if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif // This call is needed to get the uid if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } #ifdef HAVE_GETSPNAM // This call is needed to get the password; otherwise 'x' is returned if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif if (strcmp(user_password, (char *) crypt(password, user_password)) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); return -1; } */ return 0; #endif }
nan
null
10,715
63029283185700501091425531953439161347
122
Don't crash if crypt() fails. It can fail, so make sure it doesn't before comparing its result with the password. This addresses Include Security issue F12: [libpcap] Remote Packet Capture Daemon Null Pointer Dereference Denial of Service.
null
poppler
da63c35549e8852a410946ab016a3f25ac701bdf
1
void FoFiType1C::convertToType0(char *psName, int *codeMap, int nCodes, FoFiOutputFunc outputFunc, void *outputStream) { int *cidMap; Type1CIndex subrIdx; Type1CIndexVal val; int nCIDs; GooString *buf; Type1CEexecBuf eb; GBool ok; int fd, i, j, k; // compute the CID count and build the CID-to-GID mapping if (codeMap) { nCIDs = nCodes; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCodes; ++i) { if (codeMap[i] >= 0 && codeMap[i] < nGlyphs) { cidMap[i] = codeMap[i]; } else { cidMap[i] = -1; } } } else if (topDict.firstOp == 0x0c1e) { nCIDs = 0; for (i = 0; i < nGlyphs && i < charsetLength; ++i) { if (charset[i] >= nCIDs) { nCIDs = charset[i] + 1; } } cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = -1; } for (i = 0; i < nGlyphs && i < charsetLength; ++i) { cidMap[charset[i]] = i; } } else { nCIDs = nGlyphs; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = i; } } if (privateDicts) { // write the descendant Type 1 fonts for (i = 0; i < nCIDs; i += 256) { //~ this assumes that all CIDs in this block have the same FD -- //~ to handle multiple FDs correctly, need to somehow divide the //~ font up by FD; as a kludge we ignore CID 0, which is .notdef fd = 0; // if fdSelect is NULL, we have an 8-bit font, so just leave fd=0 if (fdSelect) { for (j = i==0 ? 1 : 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { fd = fdSelect[cidMap[i+j]]; break; } } } // font dictionary (unencrypted section) (*outputFunc)(outputStream, "16 dict begin\n", 14); (*outputFunc)(outputStream, "/FontName /", 11); (*outputFunc)(outputStream, psName, strlen(psName)); buf = GooString::format("_{0:02x} def\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; (*outputFunc)(outputStream, "/FontType 1 def\n", 16); if (privateDicts[fd].hasFontMatrix) { buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\n", privateDicts[fd].fontMatrix[0], privateDicts[fd].fontMatrix[1], privateDicts[fd].fontMatrix[2], privateDicts[fd].fontMatrix[3], privateDicts[fd].fontMatrix[4], privateDicts[fd].fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else if (topDict.hasFontMatrix) { (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30); } else { (*outputFunc)(outputStream, "/FontMatrix [0.001 0 0 0.001 0 0] def\n", 38); } buf = GooString::format("/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] def\n", topDict.fontBBox[0], topDict.fontBBox[1], topDict.fontBBox[2], topDict.fontBBox[3]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; buf = GooString::format("/PaintType {0:d} def\n", topDict.paintType); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; if (topDict.paintType != 0) { buf = GooString::format("/StrokeWidth {0:.4g} def\n", topDict.strokeWidth); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "/Encoding 256 array\n", 20); for (j = 0; j < 256 && i+j < nCIDs; ++j) { buf = GooString::format("dup {0:d} /c{1:02x} put\n", j, j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } if (j < 256) { buf = GooString::format("{0:d} 1 255 {{ 1 index exch /.notdef put }} for\n", j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "readonly def\n", 13); (*outputFunc)(outputStream, "currentdict end\n", 16); // start the binary section (*outputFunc)(outputStream, "currentfile eexec\n", 18); eb.outputFunc = outputFunc; eb.outputStream = outputStream; eb.ascii = gTrue; eb.r1 = 55665; eb.line = 0; // start the private dictionary eexecWrite(&eb, "\x83\xca\x73\xd5"); eexecWrite(&eb, "dup /Private 32 dict dup begin\n"); eexecWrite(&eb, "/RD {string currentfile exch readstring pop}" " executeonly def\n"); eexecWrite(&eb, "/ND {noaccess def} executeonly def\n"); eexecWrite(&eb, "/NP {noaccess put} executeonly def\n"); eexecWrite(&eb, "/MinFeature {16 16} def\n"); eexecWrite(&eb, "/password 5839 def\n"); if (privateDicts[fd].nBlueValues) { eexecWrite(&eb, "/BlueValues ["); for (k = 0; k < privateDicts[fd].nBlueValues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].blueValues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nOtherBlues) { eexecWrite(&eb, "/OtherBlues ["); for (k = 0; k < privateDicts[fd].nOtherBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].otherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nFamilyBlues) { eexecWrite(&eb, "/FamilyBlues ["); for (k = 0; k < privateDicts[fd].nFamilyBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].familyBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nFamilyOtherBlues) { eexecWrite(&eb, "/FamilyOtherBlues ["); for (k = 0; k < privateDicts[fd].nFamilyOtherBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].familyOtherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].blueScale != 0.039625) { buf = GooString::format("/BlueScale {0:.4g} def\n", privateDicts[fd].blueScale); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueShift != 7) { buf = GooString::format("/BlueShift {0:d} def\n", privateDicts[fd].blueShift); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueFuzz != 1) { buf = GooString::format("/BlueFuzz {0:d} def\n", privateDicts[fd].blueFuzz); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdHW) { buf = GooString::format("/StdHW [{0:.4g}] def\n", privateDicts[fd].stdHW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdVW) { buf = GooString::format("/StdVW [{0:.4g}] def\n", privateDicts[fd].stdVW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].nStemSnapH) { eexecWrite(&eb, "/StemSnapH ["); for (k = 0; k < privateDicts[fd].nStemSnapH; ++k) { buf = GooString::format("{0:s}{1:.4g}", k > 0 ? " " : "", privateDicts[fd].stemSnapH[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nStemSnapV) { eexecWrite(&eb, "/StemSnapV ["); for (k = 0; k < privateDicts[fd].nStemSnapV; ++k) { buf = GooString::format("{0:s}{1:.4g}", k > 0 ? " " : "", privateDicts[fd].stemSnapV[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].hasForceBold) { buf = GooString::format("/ForceBold {0:s} def\n", privateDicts[fd].forceBold ? "true" : "false"); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].forceBoldThreshold != 0) { buf = GooString::format("/ForceBoldThreshold {0:.4g} def\n", privateDicts[fd].forceBoldThreshold); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].languageGroup != 0) { buf = GooString::format("/LanguageGroup {0:d} def\n", privateDicts[fd].languageGroup); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].expansionFactor != 0.06) { buf = GooString::format("/ExpansionFactor {0:.4g} def\n", privateDicts[fd].expansionFactor); eexecWrite(&eb, buf->getCString()); delete buf; } // set up the subroutines ok = gTrue; getIndex(privateDicts[fd].subrsOffset, &subrIdx, &ok); if (!ok) { subrIdx.pos = -1; } // start the CharStrings eexecWrite(&eb, "2 index /CharStrings 256 dict dup begin\n"); // write the .notdef CharString ok = gTrue; getIndexVal(&charStringsIdx, 0, &val, &ok); if (ok) { eexecCvtGlyph(&eb, ".notdef", val.pos, val.len, &subrIdx, &privateDicts[fd]); } // write the CharStrings for (j = 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { ok = gTrue; getIndexVal(&charStringsIdx, cidMap[i+j], &val, &ok); if (ok) { buf = GooString::format("c{0:02x}", j); eexecCvtGlyph(&eb, buf->getCString(), val.pos, val.len, &subrIdx, &privateDicts[fd]); delete buf; } } } eexecWrite(&eb, "end\n"); eexecWrite(&eb, "end\n"); eexecWrite(&eb, "readonly put\n"); eexecWrite(&eb, "noaccess put\n"); eexecWrite(&eb, "dup /FontName get exch definefont pop\n"); eexecWrite(&eb, "mark currentfile closefile\n"); // trailer if (eb.line > 0) { (*outputFunc)(outputStream, "\n", 1); } for (j = 0; j < 8; ++j) { (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65); } (*outputFunc)(outputStream, "cleartomark\n", 12); } } else { error(errSyntaxError, -1, "FoFiType1C::convertToType0 without privateDicts"); } // write the Type 0 parent font (*outputFunc)(outputStream, "16 dict begin\n", 14); (*outputFunc)(outputStream, "/FontName /", 11); (*outputFunc)(outputStream, psName, strlen(psName)); (*outputFunc)(outputStream, " def\n", 5); (*outputFunc)(outputStream, "/FontType 0 def\n", 16); if (topDict.hasFontMatrix) { buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\n", topDict.fontMatrix[0], topDict.fontMatrix[1], topDict.fontMatrix[2], topDict.fontMatrix[3], topDict.fontMatrix[4], topDict.fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else { (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30); } (*outputFunc)(outputStream, "/FMapType 2 def\n", 16); (*outputFunc)(outputStream, "/Encoding [\n", 12); for (i = 0; i < nCIDs; i += 256) { buf = GooString::format("{0:d}\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "] def\n", 6); (*outputFunc)(outputStream, "/FDepVector [\n", 14); for (i = 0; i < nCIDs; i += 256) { (*outputFunc)(outputStream, "/", 1); (*outputFunc)(outputStream, psName, strlen(psName)); buf = GooString::format("_{0:02x} findfont\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "] def\n", 6); (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40); gfree(cidMap); }
nan
null
10,716
147790478051028064626601767859835006488
335
FoFiType1C::convertToType0: Fix crash in broken files Bug #102724
null
WavPack
36a24c7881427d2e1e4dc1cef58f19eee0d13aec
1
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,717
129741665744977360638249250180738228989
222
issue #28, do not overwrite heap on corrupt DSDIFF file
null
linux
0449641130f5652b344ef6fa39fa019d7e94660a
1
__acquires(kernel_lock) { char *orig_data = kstrdup(data, GFP_KERNEL); struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -ENOMEM; int blocksize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; ext4_group_t first_not_zeroed; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) goto out_free_orig; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); goto out_free_orig; } sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; if (sb->s_bdev->bd_part) sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; ret = -EINVAL; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, "unable to set blocksize"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, "unable to read superblock"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); set_opt(sb, INIT_INODE_TABLE); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sb, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) { ext4_msg(sb, KERN_WARNING, deprecated_msg, "bsdgroups", "2.6.38"); set_opt(sb, GRPID); } if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sb, NO_UID32); /* xattr user namespace & acls are now defaulted on */ #ifdef CONFIG_EXT4_FS_XATTR set_opt(sb, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL set_opt(sb, POSIX_ACL); #endif set_opt(sb, MBLK_IO_SUBMIT); if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sb, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sb, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sb, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sb, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sb, ERRORS_CONT); else set_opt(sb, ERRORS_RO); if (def_mount_opts & EXT4_DEFM_BLOCK_VALIDITY) set_opt(sb, BLOCK_VALIDITY); if (def_mount_opts & EXT4_DEFM_DISCARD) set_opt(sb, DISCARD); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0) set_opt(sb, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ if (!IS_EXT3_SB(sb) && ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0)) set_opt(sb, DELALLOC); if (!parse_options((char *) sbi->s_es->s_mount_opts, sb, &journal_devnum, &journal_ioprio, NULL, 0)) { ext4_msg(sb, KERN_WARNING, "failed to parse options in superblock: %s", sbi->s_es->s_mount_opts); } if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, "feature flags set on rev 0 fs, " "running e2fsck is recommended"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, "Unsupported filesystem blocksize %d", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, "bad block size %d", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, "Can't read superblock on 2nd try"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, "Magic mismatch, very weird!"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, "unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, "unsupported descriptor size %lu", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ err = generic_check_addressable(sb->s_blocksize_bits, ext4_blocks_count(es)); if (err) { ext4_msg(sb, KERN_ERR, "filesystem" " too large to mount safely on this system"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled"); ret = err; goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu " "exceeds size of device (%llu blocks)", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, "bad geometry: first data" "block %u is beyond end of filesystem (%llu)", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, "groups count too large: %u " "(block count %llu, first data block %u, " "blocks per group %lu)", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); #endif bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, "can't read group descriptor %d", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb, &first_not_zeroed)) { ext4_msg(sb, KERN_ERR, "group descriptors corrupted!"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, "unable to initialize " "flex_bg meta info!"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { ext4_msg(sb, KERN_ERR, "insufficient memory"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_max_writeback_mb_bump = 128; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid)); INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, "required journal recovery " "suppressed and not mounted read-only"); goto failed_mount_wq; } else { clear_opt(sb, DATA_FLAGS); set_opt(sb, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature"); goto failed_mount_wq; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sb, ORDERED_DATA); else set_opt(sb, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, "Journal does not support " "requested data journaling mode"); goto failed_mount_wq; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); /* * The journal may have updated the bg summary counts, so we * need to update the global counters. */ percpu_counter_set(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); percpu_counter_set(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); percpu_counter_set(&sbi->s_dirs_counter, ext4_count_dirs(sb)); percpu_counter_set(&sbi->s_dirtyblocks_counter, 0); no_journal: /* * The maximum number of concurrent works can be high and * concurrency isn't really necessary. Limit it to 1. */ EXT4_SB(sb)->dio_unwritten_wq = alloc_workqueue("ext4-dio-unwritten", WQ_MEM_RECLAIM | WQ_UNBOUND, 1); if (!EXT4_SB(sb)->dio_unwritten_wq) { printk(KERN_ERR "EXT4-fs: failed to create DIO workqueue\n"); goto failed_mount_wq; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, "get root inode failed"); ret = PTR_ERR(root); root = NULL; goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, "get root dentry failed"); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, "required extra inode space not" "available"); } if (test_opt(sb, DELALLOC) && (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) { ext4_msg(sb, KERN_WARNING, "Ignoring delalloc option - " "requested data journaling mode"); clear_opt(sb, DELALLOC); } if (test_opt(sb, DIOREAD_NOLOCK)) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) { ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock " "option - requested data journaling mode"); clear_opt(sb, DIOREAD_NOLOCK); } if (sb->s_blocksize < PAGE_SIZE) { ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock " "option - block size is too small"); clear_opt(sb, DIOREAD_NOLOCK); } } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize system " "zone (%d)", err); goto failed_mount4; } ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)", err); goto failed_mount4; } err = ext4_register_li_request(sb, first_not_zeroed); if (err) goto failed_mount4; sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, "%s", sb->s_id); if (err) { ext4_mb_release(sb); ext4_ext_release(sb); goto failed_mount4; }; EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, "recovery complete"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = " journalled data mode"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = " ordered data mode"; else descr = " writeback data mode"; } else descr = "out journal"; ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. " "Opts: %s%s%s", descr, sbi->s_es->s_mount_opts, *sbi->s_es->s_mount_opts ? "; " : "", orig_data); init_timer(&sbi->s_err_report); sbi->s_err_report.function = print_daily_error_info; sbi->s_err_report.data = (unsigned long) sb; if (es->s_error_count) mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */ kfree(orig_data); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem"); goto failed_mount; failed_mount4: iput(root); sb->s_root = NULL; ext4_msg(sb, KERN_ERR, "mount failed"); destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq); failed_mount_wq: ext4_release_system_zone(sb); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: if (sbi->s_flex_groups) { if (is_vmalloc_addr(sbi->s_flex_groups)) vfree(sbi->s_flex_groups); else kfree(sbi->s_flex_groups); } percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); out_free_orig: kfree(orig_data); return ret; }
nan
null
10,718
2883871233556823875946218609012452938
698
ext4: init timer earlier to avoid a kernel panic in __save_error_info During mount, when we fail to open journal inode or root inode, the __save_error_info will mod_timer. But actually s_err_report isn't initialized yet and the kernel oops. The detailed information can be found https://bugzilla.kernel.org/show_bug.cgi?id=32082. The best way is to check whether the timer s_err_report is initialized or not. But it seems that in include/linux/timer.h, we can't find a good function to check the status of this timer, so this patch just move the initializtion of s_err_report earlier so that we can avoid the kernel panic. The corresponding del_timer is also added in the error path. Reported-by: Sami Liedes <sliedes@cc.hut.fi> Signed-off-by: Tao Ma <boyu.mt@taobao.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
null
qemu
844864fbae66935951529408831c2f22367a57b6
1
static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; int num_pd_disks = 0; memset(&info, 0x0, dcmd_size); if (cmd->iov_size < dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } info.pci.vendor = cpu_to_le16(pci_class->vendor_id); info.pci.device = cpu_to_le16(pci_class->device_id); info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports * only up to 8 device ports. * Despite supporting a far larger number * of devices for the physical devices. * So just display the first 8 devices * in the device port list, independent * of how many logical devices are actually * present. */ info.host.type = MFI_INFO_HOST_PCIE; info.device.type = MFI_INFO_DEV_SAS3G; info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t pd_id; if (num_pd_disks < 8) { pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); info.device.port_addr[num_pd_disks] = cpu_to_le64(megasas_get_sata_addr(pd_id)); } num_pd_disks++; } memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version()); memcpy(info.image_component[0].name, "APP", 3); snprintf(info.image_component[0].version, 10, "%s-QEMU", base_class->product_version); memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; uint8_t *ptr; ptr = memory_region_get_ram_ptr(&pci_dev->rom); memcpy(biosver, ptr + 0x41, 31); memcpy(info.image_component[1].name, "BIOS", 4); memcpy(info.image_component[1].version, biosver, strlen((const char *)biosver)); info.image_component_count++; } info.current_fw_time = cpu_to_le32(megasas_fw_time()); info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); if (!megasas_is_jbod(s)) info.lds_present = cpu_to_le16(num_pd_disks); info.pd_present = cpu_to_le16(num_pd_disks); info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); info.memory_size = cpu_to_le16(512); info.nvram_size = cpu_to_le16(32); info.flash_size = cpu_to_le16(16); info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | MFI_INFO_AOPS_SELF_DIAGNOSTIC | MFI_INFO_AOPS_MIXED_ARRAY); info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | MFI_INFO_LDOPS_ACCESS_POLICY | MFI_INFO_LDOPS_IO_POLICY | MFI_INFO_LDOPS_WRITE_POLICY | MFI_INFO_LDOPS_READ_POLICY); info.max_strips_per_io = cpu_to_le16(s->fw_sge); info.stripe_sz_ops.min = 3; info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); info.properties.pred_fail_poll_interval = cpu_to_le16(300); info.properties.intr_throttle_cnt = cpu_to_le16(16); info.properties.intr_throttle_timeout = cpu_to_le16(50); info.properties.rebuild_rate = 30; info.properties.patrol_read_rate = 30; info.properties.bgi_rate = 30; info.properties.cc_rate = 30; info.properties.recon_rate = 30; info.properties.cache_flush_interval = 4; info.properties.spinup_drv_cnt = 2; info.properties.spinup_delay = 6; info.properties.ecc_bucket_size = 15; info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); info.properties.expose_encl_devices = 1; info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | MFI_INFO_PDOPS_FORCE_OFFLINE); info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | MFI_INFO_PDMIX_SATA | MFI_INFO_PDMIX_LD); cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); return MFI_STAT_OK; }
nan
null
10,719
340248343264835044637877256529834628735
121
scsi: megasas: null terminate bios version buffer While reading information via 'megasas_ctrl_get_info' routine, a local bios version buffer isn't null terminated. Add the terminating null byte to avoid any OOB access. Reported-by: Li Qiang <liqiang6-s@360.cn> Reviewed-by: Peter Maydell <peter.maydell@linaro.org> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
null
FFmpeg
c24bcb553650b91e9eff15ef6e54ca73de2453b7
1
static int nsv_parse_NSVf_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; file_size = (uint32_t)avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size); av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration); // XXX: store it in AVStreams strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz((size_t)strings_size + 1); if (!p) return AVERROR(ENOMEM); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_timestamps) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (avio_feof(pb)) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; }
nan
null
10,720
56714162752573533278678291213660112236
105
avformat/nsvdec: Fix DoS due to lack of eof check in nsvs_file_offset loop. Fixes: 20170829.nsv Co-Author: 张洪亮(望初)" <wangchu.zhl@alibaba-inc.com> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
php-src
8d2539fa0faf3f63e1d1e7635347c5b9e777d47b
1
*/ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry *pce; zval obj; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ object_init_ex(&obj, pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; }
nan
null
10,721
51441026749032163263461096977571663031
140
Fix bug #73831 - NULL Pointer Dereference while unserialize php object
null
qemu
a9c380db3b8c6af19546a68145c8d1438a09c92b
1
static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id) { SSISlave *ss = SSI_SLAVE(opaque); ssi_sd_state *s = (ssi_sd_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->mode = qemu_get_be32(f); s->cmd = qemu_get_be32(f); for (i = 0; i < 4; i++) s->cmdarg[i] = qemu_get_be32(f); for (i = 0; i < 5; i++) s->response[i] = qemu_get_be32(f); s->arglen = qemu_get_be32(f); s->response_pos = qemu_get_be32(f); s->stopping = qemu_get_be32(f); ss->cs = qemu_get_be32(f); return 0; }
nan
null
10,722
257645210657267781938458060581261083310
23
ssi-sd: fix buffer overrun on invalid state load CVE-2013-4537 s->arglen is taken from wire and used as idx in ssi_sd_transfer(). Validate it before access. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Juan Quintela <quintela@redhat.com>
null
libx11
b469da1430cdcee06e31c6251b83aede072a1ff0
1
char **XListExtensions( register Display *dpy, int *nextensions) /* RETURN */ { xListExtensionsReply rep; char **list = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetEmptyReq (ListExtensions, req); if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nExtensions) { list = Xmalloc (rep.nExtensions * sizeof (char *)); if (rep.length > 0 && rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc (rlen + 1); /* +1 to leave room for last null-terminator */ } if ((!list) || (!ch)) { Xfree(list); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *ch; for (i = 0; i < rep.nExtensions; i++) { if (ch + length < chend) { list[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ if (ch <= chend) { length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else { list[i] = NULL; } } else list[i] = NULL; } } *nextensions = count; UnlockDisplay(dpy); SyncHandle(); return (list); }
nan
null
10,723
163033534115641510884339691654335376485
67
Fixed off-by-one writes (CVE-2018-14599). The functions XGetFontPath, XListExtensions, and XListFonts are vulnerable to an off-by-one override on malicious server responses. The server replies consist of chunks consisting of a length byte followed by actual string, which is not NUL-terminated. While parsing the response, the length byte is overridden with '\0', thus the memory area can be used as storage of C strings later on. To be able to NUL-terminate the last string, the buffer is reserved with an additional byte of space. For a boundary check, the variable chend (end of ch) was introduced, pointing at the end of the buffer which ch initially points to. Unfortunately there is a difference in handling "the end of ch". While chend points at the first byte that must not be written to, the for-loop uses chend as the last byte that can be written to. Therefore, an off-by-one can occur. I have refactored the code so chend actually points to the last byte that can be written to without an out of boundary access. As it is not possible to achieve "ch + length < chend" and "ch + length + 1 > chend" with the corrected chend meaning, I removed the inner if-check. Signed-off-by: Tobias Stoeckmann <tobias@stoeckmann.org>
null
php-src
35ceea928b12373a3b1e3eecdc32ed323223a40d
1
int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */ { struct fpm_worker_pool_config_s *c = wp->config; /* uninitialized */ wp->socket_uid = -1; wp->socket_gid = -1; wp->socket_mode = 0666; if (!c) { return 0; } if (c->listen_owner && *c->listen_owner) { struct passwd *pwd; pwd = getpwnam(c->listen_owner); if (!pwd) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get uid for user '%s'", wp->config->name, c->listen_owner); return -1; } wp->socket_uid = pwd->pw_uid; wp->socket_gid = pwd->pw_gid; } if (c->listen_group && *c->listen_group) { struct group *grp; grp = getgrnam(c->listen_group); if (!grp) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get gid for group '%s'", wp->config->name, c->listen_group); return -1; } wp->socket_gid = grp->gr_gid; } if (c->listen_mode && *c->listen_mode) { wp->socket_mode = strtoul(c->listen_mode, 0, 8); } return 0; }
nan
null
10,726
91364791922883397508362036933771852145
42
Fix bug #67060: use default mode of 660
null
WavPack
33a0025d1d63ccd05d9dbaa6923d52b1446a62fe
1
int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; int format_chunk = 0; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; if (format_chunk++) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,727
277131272340638840836076003365853988981
234
issue #68: clear WaveHeader at start to prevent uninitialized read
null
radare2
bbb4af56003c1afdad67af0c4339267ca38b1017
1
static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { char addrbuf[64]; const int buffsize = sizeof (addrbuf) - 1; memset (op, '\0', sizeof (RAnalOp)); op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502 op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->id = data[0]; r_strbuf_init (&op->esil); switch (data[0]) { case 0x02: case 0x03: case 0x04: case 0x07: case 0x0b: case 0x0c: case 0x0f: case 0x12: case 0x13: case 0x14: case 0x17: case 0x1a: case 0x1b: case 0x1c: case 0x1f: case 0x22: case 0x23: case 0x27: case 0x2b: case 0x2f: case 0x32: case 0x33: case 0x34: case 0x37: case 0x3a: case 0x3b: case 0x3c: case 0x3f: case 0x42: case 0x43: case 0x44: case 0x47: case 0x4b: case 0x4f: case 0x52: case 0x53: case 0x54: case 0x57: case 0x5a: case 0x5b: case 0x5c: case 0x5f: case 0x62: case 0x63: case 0x64: case 0x67: case 0x6b: case 0x6f: case 0x72: case 0x73: case 0x74: case 0x77: case 0x7a: case 0x7b: case 0x7c: case 0x7f: case 0x80: case 0x82: case 0x83: case 0x87: case 0x89: case 0x8b: case 0x8f: case 0x92: case 0x93: case 0x97: case 0x9b: case 0x9c: case 0x9e: case 0x9f: case 0xa3: case 0xa7: case 0xab: case 0xaf: case 0xb2: case 0xb3: case 0xb7: case 0xbb: case 0xbf: case 0xc2: case 0xc3: case 0xc7: case 0xcb: case 0xcf: case 0xd2: case 0xd3: case 0xd4: case 0xd7: case 0xda: case 0xdb: case 0xdc: case 0xdf: case 0xe2: case 0xe3: case 0xe7: case 0xeb: case 0xef: case 0xf2: case 0xf3: case 0xf4: case 0xf7: case 0xfa: case 0xfb: case 0xfc: case 0xff: // undocumented or not-implemented opcodes for 6502. // some of them might be implemented in 65816 op->size = 1; op->type = R_ANAL_OP_TYPE_ILL; break; // BRK case 0x00: // brk op->cycles = 7; op->type = R_ANAL_OP_TYPE_SWI; // override 65816 code which seems to be wrong: size is 1, but pc = pc + 2 op->size = 1; // PC + 2 to Stack, P to Stack B=1 D=0 I=1. "B" is not a flag. Only its bit is pushed on the stack // PC was already incremented by one at this point. Needs to incremented once more // New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502) r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,="); break; // FLAGS case 0x78: // sei case 0x58: // cli case 0x38: // sec case 0x18: // clc case 0xf8: // sed case 0xd8: // cld case 0xb8: // clv op->cycles = 2; // FIXME: what opcode for this? op->type = R_ANAL_OP_TYPE_NOP; _6502_anal_esil_flags (op, data[0]); break; // BIT case 0x24: // bit $ff case 0x2c: // bit $ffff op->type = R_ANAL_OP_TYPE_MOV; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf); break; // ADC case 0x69: // adc #$ff case 0x65: // adc $ff case 0x75: // adc $ff,x case 0x6d: // adc $ffff case 0x7d: // adc $ffff,x case 0x79: // adc $ffff,y case 0x61: // adc ($ff,x) case 0x71: // adc ($ff,y) // FIXME: update V // FIXME: support BCD mode op->type = R_ANAL_OP_TYPE_ADD; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x69) // immediate mode r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); // fix Z r_strbuf_append (&op->esil, ",a,a,=,$z,Z,="); break; // SBC case 0xe9: // sbc #$ff case 0xe5: // sbc $ff case 0xf5: // sbc $ff,x case 0xed: // sbc $ffff case 0xfd: // sbc $ffff,x case 0xf9: // sbc $ffff,y case 0xe1: // sbc ($ff,x) case 0xf1: // sbc ($ff,y) // FIXME: update V // FIXME: support BCD mode op->type = R_ANAL_OP_TYPE_SUB; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xe9) // immediate mode r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf); else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // fix Z and revert C r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!="); break; // ORA case 0x09: // ora #$ff case 0x05: // ora $ff case 0x15: // ora $ff,x case 0x0d: // ora $ffff case 0x1d: // ora $ffff,x case 0x19: // ora $ffff,y case 0x01: // ora ($ff,x) case 0x11: // ora ($ff),y op->type = R_ANAL_OP_TYPE_OR; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x09) // immediate mode r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // AND case 0x29: // and #$ff case 0x25: // and $ff case 0x35: // and $ff,x case 0x2d: // and $ffff case 0x3d: // and $ffff,x case 0x39: // and $ffff,y case 0x21: // and ($ff,x) case 0x31: // and ($ff),y op->type = R_ANAL_OP_TYPE_AND; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x29) // immediate mode r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // EOR case 0x49: // eor #$ff case 0x45: // eor $ff case 0x55: // eor $ff,x case 0x4d: // eor $ffff case 0x5d: // eor $ffff,x case 0x59: // eor $ffff,y case 0x41: // eor ($ff,x) case 0x51: // eor ($ff),y op->type = R_ANAL_OP_TYPE_XOR; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x49) // immediate mode r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ASL case 0x0a: // asl a case 0x06: // asl $ff case 0x16: // asl $ff,x case 0x0e: // asl $ffff case 0x1e: // asl $ffff,x op->type = R_ANAL_OP_TYPE_SHL; if (data[0] == 0x0a) { r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,="); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LSR case 0x4a: // lsr a case 0x46: // lsr $ff case 0x56: // lsr $ff,x case 0x4e: // lsr $ffff case 0x5e: // lsr $ffff,x op->type = R_ANAL_OP_TYPE_SHR; if (data[0] == 0x4a) { r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>="); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ROL case 0x2a: // rol a case 0x26: // rol $ff case 0x36: // rol $ff,x case 0x2e: // rol $ffff case 0x3e: // rol $ffff,x op->type = R_ANAL_OP_TYPE_ROL; if (data[0] == 0x2a) { r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,="); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ROR case 0x6a: // ror a case 0x66: // ror $ff case 0x76: // ror $ff,x case 0x6e: // ror $ffff case 0x7e: // ror $ffff,x // uses N as temporary to hold C value. but in fact, // it is not temporary since in all ROR ops, N will have the value of C op->type = R_ANAL_OP_TYPE_ROR; if (data[0] == 0x6a) { r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,="); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // INC case 0xe6: // inc $ff case 0xf6: // inc $ff,x case 0xee: // inc $ffff case 0xfe: // inc $ffff,x op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // DEC case 0xc6: // dec $ff case 0xd6: // dec $ff,x case 0xce: // dec $ffff case 0xde: // dec $ffff,x op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // INX, INY case 0xe8: // inx case 0xc8: // iny op->cycles = 2; op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_inc_reg (op, data[0], "+"); break; // DEX, DEY case 0xca: // dex case 0x88: // dey op->cycles = 2; op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_inc_reg (op, data[0], "-"); break; // CMP case 0xc9: // cmp #$ff case 0xc5: // cmp $ff case 0xd5: // cmp $ff,x case 0xcd: // cmp $ffff case 0xdd: // cmp $ffff,x case 0xd9: // cmp $ffff,y case 0xc1: // cmp ($ff,x) case 0xd1: // cmp ($ff),y op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xc9) // immediate mode r_strbuf_setf (&op->esil, "%s,a,==", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, ",C,!,C,="); break; // CPX case 0xe0: // cpx #$ff case 0xe4: // cpx $ff case 0xec: // cpx $ffff op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); if (data[0] == 0xe0) // immediate mode r_strbuf_setf (&op->esil, "%s,x,==", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, ",C,!,C,="); break; // CPY case 0xc0: // cpy #$ff case 0xc4: // cpy $ff case 0xcc: // cpy $ffff op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); if (data[0] == 0xc0) // immediate mode r_strbuf_setf (&op->esil, "%s,y,==", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, ",C,!,C,="); break; // BRANCHES case 0x10: // bpl $ffff case 0x30: // bmi $ffff case 0x50: // bvc $ffff case 0x70: // bvs $ffff case 0x90: // bcc $ffff case 0xb0: // bcs $ffff case 0xd0: // bne $ffff case 0xf0: // beq $ffff // FIXME: Add 1 if branch occurs to same page. // FIXME: Add 2 if branch occurs to different page op->cycles = 2; op->failcycles = 3; op->type = R_ANAL_OP_TYPE_CJMP; if (data[1] <= 127) op->jump = addr + data[1] + op->size; else op->jump = addr - (256 - data[1]) + op->size; op->fail = addr + op->size; // FIXME: add a type of conditional // op->cond = R_ANAL_COND_LE; _6502_anal_esil_ccall (op, data[0]); break; // JSR case 0x20: // jsr $ffff op->cycles = 6; op->type = R_ANAL_OP_TYPE_CALL; op->jump = data[1] | data[2] << 8; op->stackop = R_ANAL_STACK_INC; op->stackptr = 2; // JSR pushes the address-1 of the next operation on to the stack before transferring program // control to the following address // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump); break; // JMP case 0x4c: // jmp $ffff op->cycles = 3; op->type = R_ANAL_OP_TYPE_JMP; op->jump = data[1] | data[2] << 8; r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump); break; case 0x6c: // jmp ($ffff) op->cycles = 5; op->type = R_ANAL_OP_TYPE_UJMP; // FIXME: how to read memory? // op->jump = data[1] | data[2] << 8; r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8); break; // RTS case 0x60: // rts op->eob = true; op->type = R_ANAL_OP_TYPE_RET; op->cycles = 6; op->stackop = R_ANAL_STACK_INC; op->stackptr = -2; // Operation: PC from Stack, PC + 1 -> PC // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+="); break; // RTI case 0x40: // rti op->eob = true; op->type = R_ANAL_OP_TYPE_RET; op->cycles = 6; op->stackop = R_ANAL_STACK_INC; op->stackptr = -3; // Operation: P from Stack, PC from Stack // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+="); break; // NOP case 0xea: // nop op->type = R_ANAL_OP_TYPE_NOP; op->cycles = 2; break; // LDA case 0xa9: // lda #$ff case 0xa5: // lda $ff case 0xb5: // lda $ff,x case 0xad: // lda $ffff case 0xbd: // lda $ffff,x case 0xb9: // lda $ffff,y case 0xa1: // lda ($ff,x) case 0xb1: // lda ($ff),y op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xa9) // immediate mode r_strbuf_setf (&op->esil, "%s,a,=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LDX case 0xa2: // ldx #$ff case 0xa6: // ldx $ff case 0xb6: // ldx $ff,y case 0xae: // ldx $ffff case 0xbe: // ldx $ffff,y op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); if (data[0] == 0xa2) // immediate mode r_strbuf_setf (&op->esil, "%s,x,=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LDY case 0xa0: // ldy #$ff case 0xa4: // ldy $ff case 0xb4: // ldy $ff,x case 0xac: // ldy $ffff case 0xbc: // ldy $ffff,x op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); if (data[0] == 0xa0) // immediate mode r_strbuf_setf (&op->esil, "%s,y,=", addrbuf); else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // STA case 0x85: // sta $ff case 0x95: // sta $ff,x case 0x8d: // sta $ffff case 0x9d: // sta $ffff,x case 0x99: // sta $ffff,y case 0x81: // sta ($ff,x) case 0x91: // sta ($ff),y op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf); break; // STX case 0x86: // stx $ff case 0x96: // stx $ff,y case 0x8e: // stx $ffff op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf); break; // STY case 0x84: // sty $ff case 0x94: // sty $ff,x case 0x8c: // sty $ffff op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf); break; // PHP/PHA case 0x08: // php case 0x48: // pha op->type = R_ANAL_OP_TYPE_PUSH; op->cycles = 3; op->stackop = R_ANAL_STACK_INC; op->stackptr = 1; _6502_anal_esil_push (op, data[0]); break; // PLP,PLA case 0x28: // plp case 0x68: // plp op->type = R_ANAL_OP_TYPE_POP; op->cycles = 4; op->stackop = R_ANAL_STACK_INC; op->stackptr = -1; _6502_anal_esil_pop (op, data[0]); break; // TAX,TYA,... case 0xaa: // tax case 0x8a: // txa case 0xa8: // tay case 0x98: // tya op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; _6502_anal_esil_mov (op, data[0]); break; case 0x9a: // txs op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; op->stackop = R_ANAL_STACK_SET; // FIXME: should I get register X a place it here? // op->stackptr = get_register_x(); _6502_anal_esil_mov (op, data[0]); break; case 0xba: // tsx op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; op->stackop = R_ANAL_STACK_GET; _6502_anal_esil_mov (op, data[0]); break; } return op->size; }
nan
null
10,728
55851122861549743711012319500974454230
571
Fix #10294 - crash in r2_hoobr__6502_op
null
yara
992480c30f75943e9cd6245bb2015c7737f9b661
1
int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? (int) input_backwards_size : (int) input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { FAIL_ON_ERROR(callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args)); break; } else { if (matches != NULL) *matches = bytes_matched; return ERROR_SUCCESS; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { next_input = input + i * input_incr; if (bytes_matched + i >= max_bytes_matched) break; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; ip = next_opcode; break; default: assert(FALSE); } } } if (matches != NULL) *matches = -1; return ERROR_SUCCESS; }
nan
null
10,729
21370740863343673121904571563568531162
164
Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
null
yara
992480c30f75943e9cd6245bb2015c7737f9b661
1
int _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; // total match length is the sum of backward and forward matches. match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; }
nan
null
10,730
24636487109590925760827310339220852102
99
Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
null
poppler
9cf2325fb22f812b31858e519411f57747d39bd8
1
poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmalloc (cairo_height * cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); }
nan
null
10,731
214787271645859102019934251717102571339
42
More gmalloc → gmallocn
null
poppler
9cf2325fb22f812b31858e519411f57747d39bd8
1
SplashBitmap::SplashBitmap(int widthA, int heightA, int rowPad, SplashColorMode modeA, GBool alphaA, GBool topDown) { width = widthA; height = heightA; mode = modeA; switch (mode) { case splashModeMono1: rowSize = (width + 7) >> 3; break; case splashModeMono8: rowSize = width; break; case splashModeRGB8: case splashModeBGR8: rowSize = width * 3; break; case splashModeXBGR8: rowSize = width * 4; break; #if SPLASH_CMYK case splashModeCMYK8: rowSize = width * 4; break; #endif } rowSize += rowPad - 1; rowSize -= rowSize % rowPad; data = (SplashColorPtr)gmalloc(rowSize * height); if (!topDown) { data += (height - 1) * rowSize; rowSize = -rowSize; } if (alphaA) { alpha = (Guchar *)gmalloc(width * height); } else { alpha = NULL; } }
nan
null
10,734
291686055334142585352002241454564713585
39
More gmalloc → gmallocn
null