code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
skb_dst_drop(skb);
} | CWE-476 | 46 |
SYSCALL_DEFINE5(add_key, const char __user *, _type,
const char __user *, _description,
const void __user *, _payload,
size_t, plen,
key_serial_t, ringid)
{
key_ref_t keyring_ref, key_ref;
char type[32], *description;
void *payload;
long ret;
ret = -EINVAL;
if (plen > 1024 * 1024 - 1)
goto error;
/* draw all the data into kernel space */
ret = key_get_type_from_user(type, _type, sizeof(type));
if (ret < 0)
goto error;
description = NULL;
if (_description) {
description = strndup_user(_description, KEY_MAX_DESC_SIZE);
if (IS_ERR(description)) {
ret = PTR_ERR(description);
goto error;
}
if (!*description) {
kfree(description);
description = NULL;
} else if ((description[0] == '.') &&
(strncmp(type, "keyring", 7) == 0)) {
ret = -EPERM;
goto error2;
}
}
/* pull the payload in if one was supplied */
payload = NULL;
if (_payload) {
ret = -ENOMEM;
payload = kvmalloc(plen, GFP_KERNEL);
if (!payload)
goto error2;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error3;
}
/* find the target keyring (which must be writable) */
keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
if (IS_ERR(keyring_ref)) {
ret = PTR_ERR(keyring_ref);
goto error3;
}
/* create or update the requested key and add it to the target
* keyring */
key_ref = key_create_or_update(keyring_ref, type, description,
payload, plen, KEY_PERM_UNDEF,
KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key_ref)) {
ret = key_ref_to_ptr(key_ref)->serial;
key_ref_put(key_ref);
}
else {
ret = PTR_ERR(key_ref);
}
key_ref_put(keyring_ref);
error3:
kvfree(payload);
error2:
kfree(description);
error:
return ret;
} | CWE-476 | 46 |
spnego_gss_verify_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t msg_buffer,
const gss_buffer_t token_buffer,
gss_qop_t *qop_state)
{
OM_uint32 ret;
ret = gss_verify_mic(minor_status,
context_handle,
msg_buffer,
token_buffer,
qop_state);
return (ret);
} | CWE-763 | 61 |
pci_lintr_route(struct pci_vdev *dev)
{
struct businfo *bi;
struct intxinfo *ii;
if (dev->lintr.pin == 0)
return;
bi = pci_businfo[dev->bus];
assert(bi != NULL);
ii = &bi->slotinfo[dev->slot].si_intpins[dev->lintr.pin - 1];
/*
* Attempt to allocate an I/O APIC pin for this intpin if one
* is not yet assigned.
*/
if (ii->ii_ioapic_irq == 0)
ii->ii_ioapic_irq = ioapic_pci_alloc_irq(dev);
assert(ii->ii_ioapic_irq > 0);
/*
* Attempt to allocate a PIRQ pin for this intpin if one is
* not yet assigned.
*/
if (ii->ii_pirq_pin == 0)
ii->ii_pirq_pin = pirq_alloc_pin(dev);
assert(ii->ii_pirq_pin > 0);
dev->lintr.ioapic_irq = ii->ii_ioapic_irq;
dev->lintr.pirq_pin = ii->ii_pirq_pin;
pci_set_cfgdata8(dev, PCIR_INTLINE, pirq_irq(ii->ii_pirq_pin));
} | CWE-617 | 51 |
process_bitmap_updates(STREAM s)
{
uint16 num_updates;
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, compress, bufsize, size;
uint8 *data, *bmpdata;
int i;
logger(Protocol, Debug, "%s()", __func__);
in_uint16_le(s, num_updates);
for (i = 0; i < num_updates; i++)
{
in_uint16_le(s, left);
in_uint16_le(s, top);
in_uint16_le(s, right);
in_uint16_le(s, bottom);
in_uint16_le(s, width);
in_uint16_le(s, height);
in_uint16_le(s, bpp);
Bpp = (bpp + 7) / 8;
in_uint16_le(s, compress);
in_uint16_le(s, bufsize);
cx = right - left + 1;
cy = bottom - top + 1;
logger(Graphics, Debug,
"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d",
left, top, right, bottom, width, height, Bpp, compress);
if (!compress)
{
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],
width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
continue;
}
if (compress & 0x400)
{
size = bufsize;
}
else
{
in_uint8s(s, 2); /* pad */
in_uint16_le(s, size);
in_uint8s(s, 4); /* line_size, final_size */
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Graphics, Warning,
"process_bitmap_updates(), failed to decompress bitmap");
}
xfree(bmpdata);
}
} | CWE-191 | 55 |
mrb_proc_s_new(mrb_state *mrb, mrb_value proc_class)
{
mrb_value blk;
mrb_value proc;
struct RProc *p;
/* Calling Proc.new without a block is not implemented yet */
mrb_get_args(mrb, "&!", &blk);
p = MRB_OBJ_ALLOC(mrb, MRB_TT_PROC, mrb_class_ptr(proc_class));
mrb_proc_copy(p, mrb_proc_ptr(blk));
proc = mrb_obj_value(p);
mrb_funcall_with_block(mrb, proc, MRB_SYM(initialize), 0, NULL, proc);
if (!MRB_PROC_STRICT_P(p) &&
mrb->c->ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb->c->ci[-1].u.env) {
p->flags |= MRB_PROC_ORPHAN;
}
return proc;
} | CWE-476 | 46 |
static int bson_string_is_db_ref( const unsigned char *string, const int length ) {
int result = 0;
if( length >= 4 ) {
if( string[1] == 'r' && string[2] == 'e' && string[3] == 'f' )
result = 1;
}
else if( length >= 3 ) {
if( string[1] == 'i' && string[2] == 'd' )
result = 1;
else if( string[1] == 'd' && string[2] == 'b' )
result = 1;
}
return result;
} | CWE-190 | 19 |
int main(int argc, char *argv[])
{
int ret;
struct lxc_lock *lock;
lock = lxc_newlock(NULL, NULL);
if (!lock) {
fprintf(stderr, "%d: failed to get unnamed lock\n", __LINE__);
exit(1);
}
ret = lxclock(lock, 0);
if (ret) {
fprintf(stderr, "%d: failed to take unnamed lock (%d)\n", __LINE__, ret);
exit(1);
}
ret = lxcunlock(lock);
if (ret) {
fprintf(stderr, "%d: failed to put unnamed lock (%d)\n", __LINE__, ret);
exit(1);
}
lxc_putlock(lock);
lock = lxc_newlock("/var/lib/lxc", mycontainername);
if (!lock) {
fprintf(stderr, "%d: failed to get lock\n", __LINE__);
exit(1);
}
struct stat sb;
char *pathname = RUNTIME_PATH "/lock/lxc/var/lib/lxc/";
ret = stat(pathname, &sb);
if (ret != 0) {
fprintf(stderr, "%d: filename %s not created\n", __LINE__,
pathname);
exit(1);
}
lxc_putlock(lock);
test_two_locks();
fprintf(stderr, "all tests passed\n");
exit(ret);
} | CWE-59 | 36 |
static int do_i2c_crc(struct cmd_tbl *cmdtp, int flag, int argc,
char *const argv[])
{
uint chip;
ulong addr;
int alen;
int count;
uchar byte;
ulong crc;
ulong err;
int ret = 0;
#if CONFIG_IS_ENABLED(DM_I2C)
struct udevice *dev;
#endif
if (argc < 4)
return CMD_RET_USAGE;
/*
* Chip is always specified.
*/
chip = hextoul(argv[1], NULL);
/*
* Address is always specified.
*/
addr = hextoul(argv[2], NULL);
alen = get_alen(argv[2], DEFAULT_ADDR_LEN);
if (alen > 3)
return CMD_RET_USAGE;
#if CONFIG_IS_ENABLED(DM_I2C)
ret = i2c_get_cur_bus_chip(chip, &dev);
if (!ret && alen != -1)
ret = i2c_set_chip_offset_len(dev, alen);
if (ret)
return i2c_report_err(ret, I2C_ERR_READ);
#endif
/*
* Count is always specified
*/
count = hextoul(argv[3], NULL);
printf ("CRC32 for %08lx ... %08lx ==> ", addr, addr + count - 1);
/*
* CRC a byte at a time. This is going to be slooow, but hey, the
* memories are small and slow too so hopefully nobody notices.
*/
crc = 0;
err = 0;
while (count-- > 0) {
#if CONFIG_IS_ENABLED(DM_I2C)
ret = dm_i2c_read(dev, addr, &byte, 1);
#else
ret = i2c_read(chip, addr, alen, &byte, 1);
#endif
if (ret)
err++;
crc = crc32(crc, &byte, 1);
addr++;
}
if (err > 0)
i2c_report_err(ret, I2C_ERR_READ);
else
printf ("%08lx\n", crc);
return 0;
} | CWE-787 | 24 |
ast_for_funcdef_impl(struct compiling *c, const node *n0,
asdl_seq *decorator_seq, bool is_async)
{
/* funcdef: 'def' NAME parameters ['->' test] ':' suite */
const node * const n = is_async ? CHILD(n0, 1) : n0;
identifier name;
arguments_ty args;
asdl_seq *body;
expr_ty returns = NULL;
int name_i = 1;
int end_lineno, end_col_offset;
REQ(n, funcdef);
name = NEW_IDENTIFIER(CHILD(n, name_i));
if (!name)
return NULL;
if (forbidden_name(c, name, CHILD(n, name_i), 0))
return NULL;
args = ast_for_arguments(c, CHILD(n, name_i + 1));
if (!args)
return NULL;
if (TYPE(CHILD(n, name_i+2)) == RARROW) {
returns = ast_for_expr(c, CHILD(n, name_i + 3));
if (!returns)
return NULL;
name_i += 2;
}
body = ast_for_suite(c, CHILD(n, name_i + 3));
if (!body)
return NULL;
get_last_end_pos(body, &end_lineno, &end_col_offset);
if (is_async)
return AsyncFunctionDef(name, args, body, decorator_seq, returns,
LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena);
else
return FunctionDef(name, args, body, decorator_seq, returns,
LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena);
} | CWE-125 | 47 |
void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci,
const Proto *p) {
int i;
int actual = cast_int(L->top - ci->func) - 1; /* number of arguments */
int nextra = actual - nfixparams; /* number of extra arguments */
ci->u.l.nextraargs = nextra;
checkstackGC(L, p->maxstacksize + 1);
/* copy function to the top of the stack */
setobjs2s(L, L->top++, ci->func);
/* move fixed parameters to the top of the stack */
for (i = 1; i <= nfixparams; i++) {
setobjs2s(L, L->top++, ci->func + i);
setnilvalue(s2v(ci->func + i)); /* erase original parameter (for GC) */
}
ci->func += actual + 1;
ci->top += actual + 1;
lua_assert(L->top <= ci->top && ci->top <= L->stack_last);
} | CWE-125 | 47 |
forbidden_name(struct compiling *c, identifier name, const node *n,
int full_checks)
{
assert(PyUnicode_Check(name));
if (PyUnicode_CompareWithASCIIString(name, "__debug__") == 0) {
ast_error(c, n, "assignment to keyword");
return 1;
}
if (full_checks) {
const char * const *p;
for (p = FORBIDDEN; *p; p++) {
if (PyUnicode_CompareWithASCIIString(name, *p) == 0) {
ast_error(c, n, "assignment to keyword");
return 1;
}
}
}
return 0;
} | CWE-125 | 47 |
ChunkedDecode(Request *reqPtr, bool update)
{
const Tcl_DString *bufPtr;
const char *end, *chunkStart;
bool success = NS_TRUE;
NS_NONNULL_ASSERT(reqPtr != NULL);
bufPtr = &reqPtr->buffer;
end = bufPtr->string + bufPtr->length;
chunkStart = bufPtr->string + reqPtr->chunkStartOff;
while (reqPtr->chunkStartOff < (size_t)bufPtr->length) {
char *p = strstr(chunkStart, "\r\n");
size_t chunk_length;
if (p == NULL) {
Ns_Log(DriverDebug, "ChunkedDecode: chunk did not find end-of-line");
success = NS_FALSE;
break;
}
*p = '\0';
chunk_length = (size_t)strtol(chunkStart, NULL, 16);
*p = '\r';
if (p + 2 + chunk_length > end) {
Ns_Log(DriverDebug, "ChunkedDecode: chunk length past end of buffer");
success = NS_FALSE;
break;
}
if (update) {
char *writeBuffer = bufPtr->string + reqPtr->chunkWriteOff;
memmove(writeBuffer, p + 2, chunk_length);
reqPtr->chunkWriteOff += chunk_length;
*(writeBuffer + chunk_length) = '\0';
}
reqPtr->chunkStartOff += (size_t)(p - chunkStart) + 4u + chunk_length;
chunkStart = bufPtr->string + reqPtr->chunkStartOff;
}
return success;
} | CWE-787 | 24 |
netsnmp_mibindex_load( void )
{
DIR *dir;
struct dirent *file;
FILE *fp;
char tmpbuf[ 300];
char tmpbuf2[300];
int i;
char *cp;
/*
* Open the MIB index directory, or create it (empty)
*/
snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes",
get_persistent_directory());
tmpbuf[sizeof(tmpbuf)-1] = 0;
dir = opendir( tmpbuf );
if ( dir == NULL ) {
DEBUGMSGTL(("mibindex", "load: (new)\n"));
mkdirhier( tmpbuf, NETSNMP_AGENT_DIRECTORY_MODE, 0);
return;
}
/*
* Create a list of which directory each file refers to
*/
while ((file = readdir( dir ))) {
if ( !isdigit((unsigned char)(file->d_name[0])))
continue;
i = atoi( file->d_name );
snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes/%d",
get_persistent_directory(), i );
tmpbuf[sizeof(tmpbuf)-1] = 0;
fp = fopen( tmpbuf, "r" );
if (!fp)
continue;
cp = fgets( tmpbuf2, sizeof(tmpbuf2), fp );
fclose( fp );
if ( !cp ) {
DEBUGMSGTL(("mibindex", "Empty MIB index (%d)\n", i));
continue;
}
if ( strncmp( tmpbuf2, "DIR ", 4 ) != 0 ) {
DEBUGMSGTL(("mibindex", "Malformed MIB index (%d)\n", i));
continue;
}
tmpbuf2[strlen(tmpbuf2)-1] = 0;
DEBUGMSGTL(("mibindex", "load: (%d) %s\n", i, tmpbuf2));
(void)_mibindex_add( tmpbuf2+4, i ); /* Skip 'DIR ' */
}
closedir( dir );
} | CWE-59 | 36 |
void trustedSetEncryptedDkgPolyAES(int *errStatus, char *errString, uint8_t *encrypted_poly, uint32_t enc_len) {
LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE
CHECK_STATE(encrypted_poly);
memset(getThreadLocalDecryptedDkgPoly(), 0, DKG_BUFER_LENGTH);
int status = AES_decrypt(encrypted_poly, enc_len, (char *) getThreadLocalDecryptedDkgPoly(),
DKG_BUFER_LENGTH);
CHECK_STATUS2("sgx_unseal_data - encrypted_poly failed with status %d")
SET_SUCCESS
clean:
;
LOG_INFO(__FUNCTION__ );
LOG_INFO("SGX call completed");
} | CWE-787 | 24 |
void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick)
{
const char *quote = "`\"\\";
if (!quote_backtick)
quote++;
char *pt = dest;
const char *s = src;
*pt++ = '"';
/* save room for trailing quote-char */
dlen -= 2;
for (; *s && dlen; s++)
{
if (strchr(quote, *s))
{
dlen -= 2;
if (dlen == 0)
break;
*pt++ = '\\';
*pt++ = *s;
}
else
{
*pt++ = *s;
dlen--;
}
}
*pt++ = '"';
*pt = '\0';
} | CWE-191 | 55 |
SPL_METHOD(FilesystemIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
} else {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
} | CWE-190 | 19 |
BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
} | CWE-125 | 47 |
_Unpickler_MemoPut(UnpicklerObject *self, Py_ssize_t idx, PyObject *value)
{
PyObject *old_item;
if (idx >= self->memo_size) {
if (_Unpickler_ResizeMemoList(self, idx * 2) < 0)
return -1;
assert(idx < self->memo_size);
}
Py_INCREF(value);
old_item = self->memo[idx];
self->memo[idx] = value;
if (old_item != NULL) {
Py_DECREF(old_item);
}
else {
self->memo_len++;
}
return 0;
} | CWE-190 | 19 |
decoding_feof(struct tok_state *tok)
{
if (tok->decoding_state != STATE_NORMAL) {
return feof(tok->fp);
} else {
PyObject* buf = tok->decoding_buffer;
if (buf == NULL) {
buf = PyObject_CallObject(tok->decoding_readline, NULL);
if (buf == NULL) {
error_ret(tok);
return 1;
} else {
tok->decoding_buffer = buf;
}
}
return PyObject_Length(buf) == 0;
}
} | CWE-125 | 47 |
static BOOL region16_simplify_bands(REGION16* region)
{
/** Simplify consecutive bands that touch and have the same items
*
* ==================== ====================
* | 1 | | 2 | | | | |
* ==================== | | | |
* | 1 | | 2 | ====> | 1 | | 2 |
* ==================== | | | |
* | 1 | | 2 | | | | |
* ==================== ====================
*
*/
RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp;
int nbRects, finalNbRects;
int bandItems, toMove;
finalNbRects = nbRects = region16_n_rects(region);
if (nbRects < 2)
return TRUE;
band1 = region16_rects_noconst(region);
endPtr = band1 + nbRects;
do
{
band2 = next_band(band1, endPtr, &bandItems);
if (band2 == endPtr)
break;
if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr))
{
/* adjust the bottom of band1 items */
tmp = band1;
while (tmp < band2)
{
tmp->bottom = band2->bottom;
tmp++;
}
/* override band2, we don't move band1 pointer as the band after band2
* may be merged too */
endBand = band2 + bandItems;
toMove = (endPtr - endBand) * sizeof(RECTANGLE_16);
if (toMove)
MoveMemory(band2, endBand, toMove);
finalNbRects -= bandItems;
endPtr -= bandItems;
}
else
{
band1 = band2;
}
}
while (TRUE);
if (finalNbRects != nbRects)
{
int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16));
region->data = realloc(region->data, allocSize);
if (!region->data)
{
region->data = &empty_region;
return FALSE;
}
region->data->nbRects = finalNbRects;
region->data->size = allocSize;
}
return TRUE;
} | CWE-252 | 49 |
pthread_mutex_unlock(pthread_mutex_t *mutex)
{
LeaveCriticalSection(mutex);
return 0;
} | CWE-125 | 47 |
static struct btrfs_device *btrfs_find_device_by_path(
struct btrfs_fs_info *fs_info, const char *device_path)
{
int ret = 0;
struct btrfs_super_block *disk_super;
u64 devid;
u8 *dev_uuid;
struct block_device *bdev;
struct buffer_head *bh;
struct btrfs_device *device;
ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
fs_info->bdev_holder, 0, &bdev, &bh);
if (ret)
return ERR_PTR(ret);
disk_super = (struct btrfs_super_block *)bh->b_data;
devid = btrfs_stack_device_id(&disk_super->dev_item);
dev_uuid = disk_super->dev_item.uuid;
if (btrfs_fs_incompat(fs_info, METADATA_UUID))
device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
disk_super->metadata_uuid);
else
device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
disk_super->fsid);
brelse(bh);
if (!device)
device = ERR_PTR(-ENOENT);
blkdev_put(bdev, FMODE_READ);
return device;
} | CWE-476 | 46 |
static int kvaser_usb_leaf_flush_queue(struct kvaser_usb_net_priv *priv)
{
struct kvaser_cmd *cmd;
int rc;
cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd)
return -ENOMEM;
cmd->id = CMD_FLUSH_QUEUE;
cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_flush_queue);
cmd->u.flush_queue.channel = priv->channel;
cmd->u.flush_queue.flags = 0x00;
rc = kvaser_usb_send_cmd(priv->dev, cmd, cmd->len);
kfree(cmd);
return rc;
} | CWE-908 | 48 |
static bool access_pmu_evcntr(struct kvm_vcpu *vcpu,
struct sys_reg_params *p,
const struct sys_reg_desc *r)
{
u64 idx;
if (!kvm_arm_pmu_v3_ready(vcpu))
return trap_raz_wi(vcpu, p, r);
if (r->CRn == 9 && r->CRm == 13) {
if (r->Op2 == 2) {
/* PMXEVCNTR_EL0 */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = vcpu_sys_reg(vcpu, PMSELR_EL0)
& ARMV8_PMU_COUNTER_MASK;
} else if (r->Op2 == 0) {
/* PMCCNTR_EL0 */
if (pmu_access_cycle_counter_el0_disabled(vcpu))
return false;
idx = ARMV8_PMU_CYCLE_IDX;
} else {
BUG();
}
} else if (r->CRn == 14 && (r->CRm & 12) == 8) {
/* PMEVCNTRn_EL0 */
if (pmu_access_event_counter_el0_disabled(vcpu))
return false;
idx = ((r->CRm & 3) << 3) | (r->Op2 & 7);
} else {
BUG();
}
if (!pmu_counter_idx_valid(vcpu, idx))
return false;
if (p->is_write) {
if (pmu_access_el0_disabled(vcpu))
return false;
kvm_pmu_set_counter_value(vcpu, idx, p->regval);
} else {
p->regval = kvm_pmu_get_counter_value(vcpu, idx);
}
return true;
} | CWE-617 | 51 |
SPL_METHOD(DirectoryIterator, getBasename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *suffix = 0, *fname;
int slen = 0;
size_t flen;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) {
return;
}
php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC);
RETURN_STRINGL(fname, flen, 0);
} | CWE-190 | 19 |
SPL_METHOD(RecursiveDirectoryIterator, getSubPathname)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *sub_name;
int len;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
RETURN_STRINGL(sub_name, len, 0);
} else {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
} | CWE-190 | 19 |
int ssl_init(void) { /* init TLS before parsing configuration file */
#if OPENSSL_VERSION_NUMBER>=0x10100000L
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
OPENSSL_INIT_LOAD_CRYPTO_STRINGS | OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
OPENSSL_config(NULL);
SSL_load_error_strings();
SSL_library_init();
#endif
index_ssl_cli=SSL_get_ex_new_index(0,
"CLI pointer", NULL, NULL, NULL);
index_ssl_ctx_opt=SSL_CTX_get_ex_new_index(0,
"SERVICE_OPTIONS pointer", NULL, NULL, NULL);
index_session_authenticated=SSL_SESSION_get_ex_new_index(0,
"session authenticated", NULL, NULL, NULL);
index_session_connect_address=SSL_SESSION_get_ex_new_index(0,
"session connect address", NULL, cb_dup_addr, cb_free_addr);
if(index_ssl_cli<0 || index_ssl_ctx_opt<0 ||
index_session_authenticated<0 ||
index_session_connect_address<0) {
s_log(LOG_ERR, "Application specific data initialization failed");
return 1;
}
#ifndef OPENSSL_NO_ENGINE
ENGINE_load_builtin_engines();
#endif
#ifndef OPENSSL_NO_DH
dh_params=get_dh2048();
if(!dh_params) {
s_log(LOG_ERR, "Failed to get default DH parameters");
return 1;
}
#endif /* OPENSSL_NO_DH */
return 0;
} | CWE-295 | 52 |
static void perf_syscall_exit(void *ignore, struct pt_regs *regs, long ret)
{
struct syscall_metadata *sys_data;
struct syscall_trace_exit *rec;
struct hlist_head *head;
int syscall_nr;
int rctx;
int size;
syscall_nr = trace_get_syscall_nr(current, regs);
if (syscall_nr < 0)
return;
if (!test_bit(syscall_nr, enabled_perf_exit_syscalls))
return;
sys_data = syscall_nr_to_meta(syscall_nr);
if (!sys_data)
return;
head = this_cpu_ptr(sys_data->exit_event->perf_events);
if (hlist_empty(head))
return;
/* We can probably do that at build time */
size = ALIGN(sizeof(*rec) + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
rec = (struct syscall_trace_exit *)perf_trace_buf_prepare(size,
sys_data->exit_event->event.type, regs, &rctx);
if (!rec)
return;
rec->nr = syscall_nr;
rec->ret = syscall_get_return_value(current, regs);
perf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL);
} | CWE-125 | 47 |
file_rlookup(const char *filename) /* I - Filename */
{
int i; /* Looping var */
cache_t *wc; /* Current cache file */
for (i = web_files, wc = web_cache; i > 0; i --, wc ++)
if (!strcmp(wc->name, filename))
return (wc->url);
return (filename);
} | CWE-476 | 46 |
void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) {
int i;
int nextra = ci->u.l.nextraargs;
if (wanted < 0) {
wanted = nextra; /* get all extra arguments available */
checkstackp(L, nextra, where); /* ensure stack space */
L->top = where + nextra; /* next instruction will need top */
}
for (i = 0; i < wanted && i < nextra; i++)
setobjs2s(L, where + i, ci->func - nextra + i);
for (; i < wanted; i++) /* complete required results with nil */
setnilvalue(s2v(where + i));
} | CWE-125 | 47 |
static bool vtable_is_addr_vtable_start_msvc(RVTableContext *context, ut64 curAddress) {
RAnalRef *xref;
RListIter *xrefIter;
if (!curAddress || curAddress == UT64_MAX) {
return false;
}
if (curAddress && !vtable_is_value_in_text_section (context, curAddress, NULL)) {
return false;
}
// total xref's to curAddress
RList *xrefs = r_anal_xrefs_get (context->anal, curAddress);
if (r_list_empty (xrefs)) {
r_list_free (xrefs);
return false;
}
r_list_foreach (xrefs, xrefIter, xref) {
// section in which currenct xref lies
if (vtable_addr_in_text_section (context, xref->addr)) {
ut8 buf[VTABLE_BUFF_SIZE];
context->anal->iob.read_at (context->anal->iob.io, xref->addr, buf, sizeof(buf));
RAnalOp analop = {0};
r_anal_op (context->anal, &analop, xref->addr, buf, sizeof(buf), R_ANAL_OP_MASK_BASIC);
if (analop.type == R_ANAL_OP_TYPE_MOV
|| analop.type == R_ANAL_OP_TYPE_LEA) {
r_list_free (xrefs);
r_anal_op_fini (&analop);
return true;
}
r_anal_op_fini (&analop);
}
}
r_list_free (xrefs);
return false;
} | CWE-824 | 65 |
process_bitmap_updates(STREAM s)
{
uint16 num_updates;
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, compress, bufsize, size;
uint8 *data, *bmpdata;
int i;
logger(Protocol, Debug, "%s()", __func__);
in_uint16_le(s, num_updates);
for (i = 0; i < num_updates; i++)
{
in_uint16_le(s, left);
in_uint16_le(s, top);
in_uint16_le(s, right);
in_uint16_le(s, bottom);
in_uint16_le(s, width);
in_uint16_le(s, height);
in_uint16_le(s, bpp);
Bpp = (bpp + 7) / 8;
in_uint16_le(s, compress);
in_uint16_le(s, bufsize);
cx = right - left + 1;
cy = bottom - top + 1;
logger(Graphics, Debug,
"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d",
left, top, right, bottom, width, height, Bpp, compress);
if (!compress)
{
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],
width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
continue;
}
if (compress & 0x400)
{
size = bufsize;
}
else
{
in_uint8s(s, 2); /* pad */
in_uint16_le(s, size);
in_uint8s(s, 4); /* line_size, final_size */
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Graphics, Warning,
"process_bitmap_updates(), failed to decompress bitmap");
}
xfree(bmpdata);
}
} | CWE-190 | 19 |
static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
} | CWE-125 | 47 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteSequenceRNNParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* input_weights = GetInput(context, node, kWeightsTensor);
const TfLiteTensor* recurrent_weights =
GetInput(context, node, kRecurrentWeightsTensor);
const TfLiteTensor* bias = GetInput(context, node, kBiasTensor);
// The hidden_state is a variable input tensor that can be modified.
TfLiteTensor* hidden_state =
const_cast<TfLiteTensor*>(GetInput(context, node, kHiddenStateTensor));
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (input_weights->type) {
case kTfLiteFloat32:
return EvalFloat(input, input_weights, recurrent_weights, bias, params,
hidden_state, output);
case kTfLiteUInt8:
case kTfLiteInt8: {
// TODO(mirkov): implement eval with quantized inputs as well.
auto* op_data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* input_quantized = GetTemporary(context, node, 0);
TfLiteTensor* hidden_state_quantized = GetTemporary(context, node, 1);
TfLiteTensor* scaling_factors = GetTemporary(context, node, 2);
TfLiteTensor* accum_scratch = GetTemporary(context, node, 3);
TfLiteTensor* zero_points = GetTemporary(context, node, 4);
TfLiteTensor* row_sums = GetTemporary(context, node, 5);
return EvalHybrid(input, input_weights, recurrent_weights, bias, params,
input_quantized, hidden_state_quantized,
scaling_factors, hidden_state, output, zero_points,
accum_scratch, row_sums, &op_data->compute_row_sums);
}
default:
TF_LITE_KERNEL_LOG(context, "Type %d not currently supported.",
TfLiteTypeGetName(input_weights->type));
return kTfLiteError;
}
return kTfLiteOk;
} | CWE-787 | 24 |
batchCopyElem(batch_obj_t *pDest, batch_obj_t *pSrc) {
memcpy(pDest, pSrc, sizeof(batch_obj_t));
} | CWE-772 | 53 |
err_t verify_signed_hash(const struct RSA_public_key *k
, u_char *s, unsigned int s_max_octets
, u_char **psig
, size_t hash_len
, const u_char *sig_val, size_t sig_len)
{
unsigned int padlen;
/* actual exponentiation; see PKCS#1 v2.0 5.1 */
{
chunk_t temp_s;
MP_INT c;
n_to_mpz(&c, sig_val, sig_len);
oswcrypto.mod_exp(&c, &c, &k->e, &k->n);
temp_s = mpz_to_n(&c, sig_len); /* back to octets */
if(s_max_octets < sig_len) {
return "2""exponentiation failed; too many octets";
}
memcpy(s, temp_s.ptr, sig_len);
pfree(temp_s.ptr);
mpz_clear(&c);
}
/* check signature contents */
/* verify padding (not including any DER digest info! */
padlen = sig_len - 3 - hash_len;
/* now check padding */
DBG(DBG_CRYPT,
DBG_dump("verify_sh decrypted SIG1:", s, sig_len));
DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len));
/* skip padding */
if(s[0] != 0x00
|| s[1] != 0x01
|| s[padlen+2] != 0x00) {
return "3""SIG padding does not check out";
}
s += padlen + 3;
(*psig) = s;
/* return SUCCESS */
return NULL;
} | CWE-347 | 25 |
static SDL_Surface *Create_Surface_Blended(int width, int height, SDL_Color fg, Uint32 *color)
{
const int alignment = Get_Alignement() - 1;
SDL_Surface *textbuf = NULL;
Uint32 bgcolor;
/* Background color */
bgcolor = (fg.r << 16) | (fg.g << 8) | fg.b;
/* Underline/Strikethrough color style */
*color = bgcolor | (fg.a << 24);
/* Create the target surface if required */
if (width != 0) {
/* Create a surface with memory:
* - pitch is rounded to alignment
* - adress is aligned
*/
Sint64 size;
void *pixels, *ptr;
/* Worse case at the end of line pulling 'alignment' extra blank pixels */
Sint64 pitch = (width + alignment) * 4;
pitch += alignment;
pitch &= ~alignment;
size = height * pitch + sizeof (void *) + alignment;
if (size < 0 || size > SDL_MAX_SINT32) {
/* Overflow... */
return NULL;
}
ptr = SDL_malloc((size_t)size);
if (ptr == NULL) {
return NULL;
}
/* address is aligned */
pixels = (void *)(((uintptr_t)ptr + sizeof(void *) + alignment) & ~alignment);
((void **)pixels)[-1] = ptr;
textbuf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 0, pitch, SDL_PIXELFORMAT_ARGB8888);
if (textbuf == NULL) {
SDL_free(ptr);
return NULL;
}
/* Let SDL handle the memory allocation */
textbuf->flags &= ~SDL_PREALLOC;
textbuf->flags |= SDL_SIMD_ALIGNED;
/* Initialize with fg and 0 alpha */
SDL_memset4(pixels, bgcolor, (height * pitch) / 4);
/* Support alpha blending */
if (fg.a != SDL_ALPHA_OPAQUE) {
SDL_SetSurfaceBlendMode(textbuf, SDL_BLENDMODE_BLEND);
}
}
return textbuf; | CWE-787 | 24 |
char *compose_path(ctrl_t *ctrl, char *path)
{
struct stat st;
static char rpath[PATH_MAX];
char *name, *ptr;
char dir[PATH_MAX] = { 0 };
strlcpy(dir, ctrl->cwd, sizeof(dir));
DBG("Compose path from cwd: %s, arg: %s", ctrl->cwd, path ?: "");
if (!path || !strlen(path))
goto check;
if (path) {
if (path[0] != '/') {
if (dir[strlen(dir) - 1] != '/')
strlcat(dir, "/", sizeof(dir));
}
strlcat(dir, path, sizeof(dir));
}
check:
while ((ptr = strstr(dir, "//")))
memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);
if (!chrooted) {
size_t len = strlen(home);
DBG("Server path from CWD: %s", dir);
if (len > 0 && home[len - 1] == '/')
len--;
memmove(dir + len, dir, strlen(dir) + 1);
memcpy(dir, home, len);
DBG("Resulting non-chroot path: %s", dir);
}
/*
* Handle directories slightly differently, since dirname() on a
* directory returns the parent directory. So, just squash ..
*/
if (!stat(dir, &st) && S_ISDIR(st.st_mode)) {
if (!realpath(dir, rpath))
return NULL;
} else {
/*
* Check realpath() of directory containing the file, a
* STOR may want to save a new file. Then append the
* file and return it.
*/
name = basename(path);
ptr = dirname(dir);
memset(rpath, 0, sizeof(rpath));
if (!realpath(ptr, rpath)) {
INFO("Failed realpath(%s): %m", ptr);
return NULL;
}
if (rpath[1] != 0)
strlcat(rpath, "/", sizeof(rpath));
strlcat(rpath, name, sizeof(rpath));
}
if (!chrooted && strncmp(dir, home, strlen(home))) {
DBG("Failed non-chroot dir:%s vs home:%s", dir, home);
return NULL;
}
return rpath;
} | CWE-22 | 2 |
processBatchMultiRuleset(batch_t *pBatch)
{
ruleset_t *currRuleset;
batch_t snglRuleBatch;
int i;
int iStart; /* start index of partial batch */
int iNew; /* index for new (temporary) batch */
DEFiRet;
CHKiRet(batchInit(&snglRuleBatch, pBatch->nElem));
snglRuleBatch.pbShutdownImmediate = pBatch->pbShutdownImmediate;
while(1) { /* loop broken inside */
/* search for first unprocessed element */
for(iStart = 0 ; iStart < pBatch->nElem && pBatch->pElem[iStart].state == BATCH_STATE_DISC ; ++iStart)
/* just search, no action */;
if(iStart == pBatch->nElem)
FINALIZE; /* everything processed */
/* prepare temporary batch */
currRuleset = batchElemGetRuleset(pBatch, iStart);
iNew = 0;
for(i = iStart ; i < pBatch->nElem ; ++i) {
if(batchElemGetRuleset(pBatch, i) == currRuleset) {
batchCopyElem(&(snglRuleBatch.pElem[iNew++]), &(pBatch->pElem[i]));
/* We indicate the element also as done, so it will not be processed again */
pBatch->pElem[i].state = BATCH_STATE_DISC;
}
}
snglRuleBatch.nElem = iNew; /* was left just right by the for loop */
batchSetSingleRuleset(&snglRuleBatch, 1);
/* process temp batch */
processBatch(&snglRuleBatch);
}
batchFree(&snglRuleBatch);
finalize_it:
RETiRet;
} | CWE-772 | 53 |
MONGO_EXPORT bson_bool_t mongo_cmd_authenticate( mongo *conn, const char *db, const char *user, const char *pass ) {
bson from_db;
bson cmd;
const char *nonce;
int result;
mongo_md5_state_t st;
mongo_md5_byte_t digest[16];
char hex_digest[33];
if( mongo_simple_int_command( conn, db, "getnonce", 1, &from_db ) == MONGO_OK ) {
bson_iterator it;
bson_find( &it, &from_db, "nonce" );
nonce = bson_iterator_string( &it );
}
else {
return MONGO_ERROR;
}
mongo_pass_digest( user, pass, hex_digest );
mongo_md5_init( &st );
mongo_md5_append( &st, ( const mongo_md5_byte_t * )nonce, strlen( nonce ) );
mongo_md5_append( &st, ( const mongo_md5_byte_t * )user, strlen( user ) );
mongo_md5_append( &st, ( const mongo_md5_byte_t * )hex_digest, 32 );
mongo_md5_finish( &st, digest );
digest2hex( digest, hex_digest );
bson_init( &cmd );
bson_append_int( &cmd, "authenticate", 1 );
bson_append_string( &cmd, "user", user );
bson_append_string( &cmd, "nonce", nonce );
bson_append_string( &cmd, "key", hex_digest );
bson_finish( &cmd );
bson_destroy( &from_db );
result = mongo_run_command( conn, db, &cmd, NULL );
bson_destroy( &cmd );
return result;
} | CWE-190 | 19 |
SPL_METHOD(DirectoryIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.dirp) {
RETURN_LONG(intern->u.dir.index);
} else {
RETURN_FALSE;
}
} | CWE-190 | 19 |
BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3,
UINT16* flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags)))
return FALSE;
bitmapData = &cache_bitmap_v3->bitmapData;
bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp];
*flags = (cache_bitmap_v3->cacheId & 0x00000003) |
((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078);
Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
Stream_Write_UINT8(s, bitmapData->bpp);
Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */
Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */
Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */
Stream_Write(s, bitmapData->data, bitmapData->length);
return TRUE;
} | CWE-125 | 47 |
static void tiny_dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size)
{
if (!pb_parse(entry, msg, msg_size, msg_tiny)) {
call_msg_failure_handler(FailureType_Failure_UnexpectedMessage,
"Could not parse tiny protocol buffer message");
return;
}
msg_tiny_id = entry->msg_id;
} | CWE-787 | 24 |
SPL_METHOD(DirectoryIterator, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0');
} | CWE-190 | 19 |
static int __init pf_init(void)
{ /* preliminary initialisation */
struct pf_unit *pf;
int unit;
if (disable)
return -EINVAL;
pf_init_units();
if (pf_detect())
return -ENODEV;
pf_busy = 0;
if (register_blkdev(major, name)) {
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++)
put_disk(pf->disk);
return -EBUSY;
}
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
struct gendisk *disk = pf->disk;
if (!pf->present)
continue;
disk->private_data = pf;
add_disk(disk);
}
return 0;
} | CWE-476 | 46 |
forbidden_name(struct compiling *c, identifier name, const node *n,
int full_checks)
{
assert(PyUnicode_Check(name));
if (PyUnicode_CompareWithASCIIString(name, "__debug__") == 0) {
ast_error(c, n, "assignment to keyword");
return 1;
}
if (full_checks) {
const char * const *p;
for (p = FORBIDDEN; *p; p++) {
if (PyUnicode_CompareWithASCIIString(name, *p) == 0) {
ast_error(c, n, "assignment to keyword");
return 1;
}
}
}
return 0;
} | CWE-125 | 47 |
buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
{
char buf[BUFSIZ];
size_t n, range_sz;
ssize_t nread;
if (lseek(fd, range->start, SEEK_SET) == -1)
return (0);
range_sz = range->end - range->start + 1;
while (range_sz) {
n = MINIMUM(range_sz, sizeof(buf));
if ((nread = read(fd, buf, n)) == -1)
return (0);
evbuffer_add(evb, buf, nread);
range_sz -= nread;
}
return (1);
} | CWE-770 | 37 |
mem_log_init(const char* prog_name, const char *banner)
{
size_t log_name_len;
char *log_name;
if (__test_bit(LOG_CONSOLE_BIT, &debug)) {
log_op = stderr;
return;
}
if (log_op)
fclose(log_op);
log_name_len = 5 + strlen(prog_name) + 5 + 7 + 4 + 1; /* "/tmp/" + prog_name + "_mem." + PID + ".log" + '\0" */
log_name = malloc(log_name_len);
if (!log_name) {
log_message(LOG_INFO, "Unable to malloc log file name");
log_op = stderr;
return;
}
snprintf(log_name, log_name_len, "/tmp/%s_mem.%d.log", prog_name, getpid());
log_op = fopen(log_name, "a");
if (log_op == NULL) {
log_message(LOG_INFO, "Unable to open %s for appending", log_name);
log_op = stderr;
}
else {
int fd = fileno(log_op);
/* We don't want any children to inherit the log file */
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
/* Make the log output line buffered. This was to ensure that
* children didn't inherit the buffer, but the CLOEXEC above
* should resolve that. */
setlinebuf(log_op);
fprintf(log_op, "\n");
}
free(log_name);
terminate_banner = banner;
} | CWE-59 | 36 |
getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)
{
static getprivs_ret ret;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_getprivs_ret, &ret);
if ((ret.code = new_server_handle(*arg, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
ret.code = kadm5_get_privs((void *)handle, &ret.privs);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_privs", client_name.value, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
} | CWE-772 | 53 |
process_bitmap_updates(STREAM s)
{
uint16 num_updates;
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, compress, bufsize, size;
uint8 *data, *bmpdata;
int i;
logger(Protocol, Debug, "%s()", __func__);
in_uint16_le(s, num_updates);
for (i = 0; i < num_updates; i++)
{
in_uint16_le(s, left);
in_uint16_le(s, top);
in_uint16_le(s, right);
in_uint16_le(s, bottom);
in_uint16_le(s, width);
in_uint16_le(s, height);
in_uint16_le(s, bpp);
Bpp = (bpp + 7) / 8;
in_uint16_le(s, compress);
in_uint16_le(s, bufsize);
cx = right - left + 1;
cy = bottom - top + 1;
logger(Graphics, Debug,
"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d",
left, top, right, bottom, width, height, Bpp, compress);
if (!compress)
{
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],
width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
continue;
}
if (compress & 0x400)
{
size = bufsize;
}
else
{
in_uint8s(s, 2); /* pad */
in_uint16_le(s, size);
in_uint8s(s, 4); /* line_size, final_size */
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Graphics, Warning,
"process_bitmap_updates(), failed to decompress bitmap");
}
xfree(bmpdata);
}
} | CWE-125 | 47 |
tok_new(void)
{
struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(
sizeof(struct tok_state));
if (tok == NULL)
return NULL;
tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;
tok->done = E_OK;
tok->fp = NULL;
tok->input = NULL;
tok->tabsize = TABSIZE;
tok->indent = 0;
tok->indstack[0] = 0;
tok->atbol = 1;
tok->pendin = 0;
tok->prompt = tok->nextprompt = NULL;
tok->lineno = 0;
tok->level = 0;
tok->altwarning = 1;
tok->alterror = 1;
tok->alttabsize = 1;
tok->altindstack[0] = 0;
tok->decoding_state = STATE_INIT;
tok->decoding_erred = 0;
tok->read_coding_spec = 0;
tok->enc = NULL;
tok->encoding = NULL;
tok->cont_line = 0;
#ifndef PGEN
tok->filename = NULL;
tok->decoding_readline = NULL;
tok->decoding_buffer = NULL;
#endif
tok->async_def = 0;
tok->async_def_indent = 0;
tok->async_def_nl = 0;
return tok;
} | CWE-125 | 47 |
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (1 << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
} | CWE-476 | 46 |
messageFindArgument(const message *m, const char *variable)
{
int i;
size_t len;
assert(m != NULL);
assert(variable != NULL);
len = strlen(variable);
for(i = 0; i < m->numberOfArguments; i++) {
const char *ptr;
ptr = messageGetArgument(m, i);
if((ptr == NULL) || (*ptr == '\0'))
continue;
#ifdef CL_DEBUG
cli_dbgmsg("messageFindArgument: compare %lu bytes of %s with %s\n",
(unsigned long)len, variable, ptr);
#endif
if(strncasecmp(ptr, variable, len) == 0) {
ptr = &ptr[len];
while(isspace(*ptr))
ptr++;
if(*ptr != '=') {
cli_dbgmsg("messageFindArgument: no '=' sign found in MIME header '%s' (%s)\n", variable, messageGetArgument(m, i));
return NULL;
}
if((*++ptr == '"') && (strchr(&ptr[1], '"') != NULL)) {
/* Remove any quote characters */
char *ret = cli_strdup(++ptr);
char *p;
if(ret == NULL)
return NULL;
/*
* fix un-quoting of boundary strings from
* header, occurs if boundary was given as
* 'boundary="_Test_";'
*
* At least two quotes in string, assume
* quoted argument
* end string at next quote
*/
if((p = strchr(ret, '"')) != NULL) {
ret[strlen(ret) - 1] = '\0';
*p = '\0';
}
return ret;
}
return cli_strdup(ptr);
}
}
return NULL;
} | CWE-125 | 47 |
static void __pyx_tp_dealloc_17clickhouse_driver_14bufferedwriter_BufferedWriter(PyObject *o) {
#if CYTHON_USE_TP_FINALIZE
if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) {
if (PyObject_CallFinalizerFromDealloc(o)) return;
}
#endif
{
PyObject *etype, *eval, *etb;
PyErr_Fetch(&etype, &eval, &etb);
++Py_REFCNT(o);
__pyx_pw_17clickhouse_driver_14bufferedwriter_14BufferedWriter_3__dealloc__(o);
--Py_REFCNT(o);
PyErr_Restore(etype, eval, etb);
}
(*Py_TYPE(o)->tp_free)(o);
} | CWE-120 | 44 |
NOEXPORT int ssl_tlsext_ticket_key_cb(SSL *ssl, unsigned char *key_name,
unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc) {
CLI *c;
const EVP_CIPHER *cipher;
int iv_len;
(void)key_name; /* squash the unused parameter warning */
s_log(LOG_DEBUG, "Session ticket processing callback");
c=SSL_get_ex_data(ssl, index_ssl_cli);
if(!HMAC_Init_ex(hctx, (const unsigned char *)(c->opt->ticket_mac->key_val),
c->opt->ticket_mac->key_len, EVP_sha256(), NULL)) {
s_log(LOG_ERR, "HMAC_Init_ex failed");
return -1;
}
if(c->opt->ticket_key->key_len == 16)
cipher = EVP_aes_128_cbc();
else /* c->opt->ticket_key->key_len == 32 */
cipher = EVP_aes_256_cbc();
if(enc) { /* create new session */
/* EVP_CIPHER_iv_length() returns 16 for either cipher EVP_aes_128_cbc() or EVP_aes_256_cbc() */
iv_len = EVP_CIPHER_iv_length(cipher);
if(RAND_bytes(iv, iv_len) <= 0) { /* RAND_bytes error */
s_log(LOG_ERR, "RAND_bytes failed");
return -1;
}
if(!EVP_EncryptInit_ex(ctx, cipher, NULL,
(const unsigned char *)(c->opt->ticket_key->key_val), iv)) {
s_log(LOG_ERR, "EVP_EncryptInit_ex failed");
return -1;
}
} else /* retrieve session */
if(!EVP_DecryptInit_ex(ctx, cipher, NULL,
(const unsigned char *)(c->opt->ticket_key->key_val), iv)) {
s_log(LOG_ERR, "EVP_DecryptInit_ex failed");
return -1;
}
/* By default, in TLSv1.2 and below, a new session ticket */
/* is not issued on a successful resumption. */
/* In TLSv1.3 the default behaviour is to always issue a new ticket on resumption. */
/* This behaviour can NOT be changed if this ticket key callback is in use! */
if(strcmp(SSL_get_version(c->ssl), "TLSv1.3"))
return 1; /* new session ticket is not issued */
else
return 2; /* session ticket should be replaced */
} | CWE-295 | 52 |
char *string_crypt(const char *key, const char *salt) {
assertx(key);
assertx(salt);
char random_salt[12];
if (!*salt) {
memcpy(random_salt,"$1$",3);
ito64(random_salt+3,rand(),8);
random_salt[11] = '\0';
return string_crypt(key, random_salt);
}
auto const saltLen = strlen(salt);
if ((saltLen > sizeof("$2X$00$")) &&
(salt[0] == '$') &&
(salt[1] == '2') &&
(salt[2] >= 'a') && (salt[2] <= 'z') &&
(salt[3] == '$') &&
(salt[4] >= '0') && (salt[4] <= '3') &&
(salt[5] >= '0') && (salt[5] <= '9') &&
(salt[6] == '$')) {
// Bundled blowfish crypt()
char output[61];
static constexpr size_t maxSaltLength = 123;
char paddedSalt[maxSaltLength + 1];
paddedSalt[0] = paddedSalt[maxSaltLength] = '\0';
memset(&paddedSalt[1], '$', maxSaltLength - 1);
memcpy(paddedSalt, salt, std::min(maxSaltLength, saltLen));
paddedSalt[saltLen] = '\0';
if (php_crypt_blowfish_rn(key, paddedSalt, output, sizeof(output))) {
return strdup(output);
}
} else {
// System crypt() function
#ifdef USE_PHP_CRYPT_R
return php_crypt_r(key, salt);
#else
static Mutex mutex;
Lock lock(mutex);
char *crypt_res = crypt(key,salt);
if (crypt_res) {
return strdup(crypt_res);
}
#endif
}
return ((salt[0] == '*') && (salt[1] == '0'))
? strdup("*1") : strdup("*0");
} | CWE-190 | 19 |
ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async)
{
const node * const n = is_async ? CHILD(n0, 1) : n0;
int i, n_items, end_lineno, end_col_offset;
asdl_seq *items, *body;
REQ(n, with_stmt);
n_items = (NCH(n) - 2) / 2;
items = _Py_asdl_seq_new(n_items, c->c_arena);
if (!items)
return NULL;
for (i = 1; i < NCH(n) - 2; i += 2) {
withitem_ty item = ast_for_with_item(c, CHILD(n, i));
if (!item)
return NULL;
asdl_seq_SET(items, (i - 1) / 2, item);
}
body = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!body)
return NULL;
get_last_end_pos(body, &end_lineno, &end_col_offset);
if (is_async)
return AsyncWith(items, body, LINENO(n0), n0->n_col_offset,
end_lineno, end_col_offset, c->c_arena);
else
return With(items, body, LINENO(n), n->n_col_offset,
end_lineno, end_col_offset, c->c_arena);
} | CWE-125 | 47 |
static bool parse_chained_fixups(struct MACH0_(obj_t) *bin, ut32 offset, ut32 size) {
struct dyld_chained_fixups_header header;
if (size < sizeof (header)) {
return false;
}
if (r_buf_fread_at (bin->b, offset, (ut8 *)&header, "7i", 1) != sizeof (header)) {
return false;
}
if (header.fixups_version > 0) {
eprintf ("Unsupported fixups version: %u\n", header.fixups_version);
return false;
}
ut64 starts_at = offset + header.starts_offset;
if (header.starts_offset > size) {
return false;
}
ut32 segs_count;
if ((segs_count = r_buf_read_le32_at (bin->b, starts_at)) == UT32_MAX) {
return false;
}
bin->chained_starts = R_NEWS0 (struct r_dyld_chained_starts_in_segment *, segs_count);
if (!bin->chained_starts) {
return false;
}
bin->fixups_header = header;
bin->fixups_offset = offset;
bin->fixups_size = size;
size_t i;
ut64 cursor = starts_at + sizeof (ut32);
ut64 bsize = r_buf_size (bin->b);
for (i = 0; i < segs_count && cursor + 4 < bsize; i++) {
ut32 seg_off;
if ((seg_off = r_buf_read_le32_at (bin->b, cursor)) == UT32_MAX || !seg_off) {
cursor += sizeof (ut32);
continue;
}
if (i >= bin->nsegs) {
break;
}
struct r_dyld_chained_starts_in_segment *cur_seg = R_NEW0 (struct r_dyld_chained_starts_in_segment);
if (!cur_seg) {
return false;
}
bin->chained_starts[i] = cur_seg;
if (r_buf_fread_at (bin->b, starts_at + seg_off, (ut8 *)cur_seg, "isslis", 1) != 22) {
return false;
}
if (cur_seg->page_count > 0) {
ut16 *page_start = malloc (sizeof (ut16) * cur_seg->page_count);
if (!page_start) {
return false;
}
if (r_buf_fread_at (bin->b, starts_at + seg_off + 22, (ut8 *)page_start, "s", cur_seg->page_count)
!= cur_seg->page_count * 2) {
return false;
}
cur_seg->page_start = page_start;
}
cursor += sizeof (ut32);
}
/* TODO: handle also imports, symbols and multiple starts (32-bit only) */
return true;
} | CWE-125 | 47 |
static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,
double *pv)
{
unsigned int field_type;
unsigned int value_count;
unsigned int value_pos;
unsigned int numer, denom;
field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);
value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);
if(value_count!=1) return 0;
if(field_type!=5) return 0; // 5=Rational (two uint32's)
// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read
// the location where it is stored.
value_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);
if(value_pos > e->d_len-8) return 0;
// Read the actual value.
numer = iw_get_ui32_e(&e->d[value_pos ],e->endian);
denom = iw_get_ui32_e(&e->d[value_pos+4],e->endian);
if(denom==0) return 0;
*pv = ((double)numer)/denom;
return 1;
} | CWE-125 | 47 |
static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct hwsim_new_radio_params param = { 0 };
const char *hwname = NULL;
int ret;
param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG];
param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE];
param.channels = channels;
param.destroy_on_close =
info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE];
if (info->attrs[HWSIM_ATTR_CHANNELS])
param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]);
if (info->attrs[HWSIM_ATTR_NO_VIF])
param.no_vif = true;
if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
hwname = kasprintf(GFP_KERNEL, "%.*s",
nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
(char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]));
if (!hwname)
return -ENOMEM;
param.hwname = hwname;
}
if (info->attrs[HWSIM_ATTR_USE_CHANCTX])
param.use_chanctx = true;
else
param.use_chanctx = (param.channels > 1);
if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2])
param.reg_alpha2 =
nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]);
if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) {
u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]);
if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom))
return -EINVAL;
param.regd = hwsim_world_regdom_custom[idx];
}
ret = mac80211_hwsim_new_radio(info, ¶m);
kfree(hwname);
return ret;
} | CWE-772 | 53 |
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
} | CWE-125 | 47 |
static Jsi_RC ObjListifyCallback(Jsi_Tree *tree, Jsi_TreeEntry *hPtr, void *data)
{
Jsi_Interp *interp = tree->opts.interp;
Jsi_Obj *obj = (Jsi_Obj*)data;
int n;
if (!hPtr->f.bits.dontenum) {
char *ep = NULL, *cp = (char*)Jsi_TreeKeyGet(hPtr);
if (!cp || !isdigit(*cp))
return JSI_OK;
n = (int)strtol(cp, &ep, 0);
if (n<0 || n >= interp->maxArrayList)
return JSI_OK;
hPtr->f.bits.isarrlist = 1;
if (Jsi_ObjArraySizer(interp, obj, n) <= 0)
return Jsi_LogError("too long");
obj->arr[n] = (Jsi_Value*)Jsi_TreeValueGet(hPtr);
// obj->arrCnt++;
}
return JSI_OK;
} | CWE-190 | 19 |
struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms)
return NULL;
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
} | CWE-125 | 47 |
ber_parse_header(STREAM s, int tagval, int *length)
{
int tag, len;
if (tagval > 0xff)
{
in_uint16_be(s, tag);
}
else
{
in_uint8(s, tag);
}
if (tag != tagval)
{
logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag);
return False;
}
in_uint8(s, len);
if (len & 0x80)
{
len &= ~0x80;
*length = 0;
while (len--)
next_be(s, *length);
}
else
*length = len;
return s_check(s);
} | CWE-125 | 47 |
spnego_gss_export_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 ret;
ret = gss_export_sec_context(minor_status,
context_handle,
interprocess_token);
return (ret);
} | CWE-763 | 61 |
mcs_recv_connect_response(STREAM mcs_data)
{
UNUSED(mcs_data);
uint8 result;
int length;
STREAM s;
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
ber_parse_header(s, MCS_CONNECT_RESPONSE, &length);
ber_parse_header(s, BER_TAG_RESULT, &length);
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result);
return False;
}
ber_parse_header(s, BER_TAG_INTEGER, &length);
in_uint8s(s, length); /* connect id */
mcs_parse_domain_params(s);
ber_parse_header(s, BER_TAG_OCTET_STRING, &length);
sec_process_mcs_data(s);
/*
if (length > mcs_data->size)
{
logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size);
length = mcs_data->size;
}
in_uint8a(s, mcs_data->data, length);
mcs_data->p = mcs_data->data;
mcs_data->end = mcs_data->data + length;
*/
return s_check_end(s);
} | CWE-125 | 47 |
delete_buff_tail(buffheader_T *buf, int slen)
{
int len = (int)STRLEN(buf->bh_curr->b_str);
if (len >= slen)
{
buf->bh_curr->b_str[len - slen] = NUL;
buf->bh_space += slen;
}
} | CWE-125 | 47 |
SPL_METHOD(SplFileObject, fgets)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);
} /* }}} */ | CWE-190 | 19 |
ldbm_config_search_entry_callback(Slapi_PBlock *pb __attribute__((unused)),
Slapi_Entry *e,
Slapi_Entry *entryAfter __attribute__((unused)),
int *returncode,
char *returntext,
void *arg)
{
char buf[BUFSIZ];
struct berval *vals[2];
struct berval val;
struct ldbminfo *li = (struct ldbminfo *)arg;
config_info *config;
int scope;
vals[0] = &val;
vals[1] = NULL;
returntext[0] = '\0';
PR_Lock(li->li_config_mutex);
if (pb) {
slapi_pblock_get(pb, SLAPI_SEARCH_SCOPE, &scope);
if (scope == LDAP_SCOPE_BASE) {
char **attrs = NULL;
slapi_pblock_get(pb, SLAPI_SEARCH_ATTRS, &attrs);
if (attrs) {
for (size_t i = 0; attrs[i]; i++) {
if (ldbm_config_moved_attr(attrs[i])) {
slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, "at least one required attribute has been moved to the BDB scecific configuration entry");
break;
}
}
}
}
}
for (config = ldbm_config; config->config_name != NULL; config++) {
/* Go through the ldbm_config table and fill in the entry. */
if (!(config->config_flags & (CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_PREVIOUSLY_SET))) {
/* This config option shouldn't be shown */
continue;
}
ldbm_config_get((void *)li, config, buf);
val.bv_val = buf;
val.bv_len = strlen(buf);
slapi_entry_attr_replace(e, config->config_name, vals);
}
PR_Unlock(li->li_config_mutex);
*returncode = LDAP_SUCCESS;
return SLAPI_DSE_CALLBACK_OK;
} | CWE-203 | 38 |
char *string_crypt(const char *key, const char *salt) {
assertx(key);
assertx(salt);
char random_salt[12];
if (!*salt) {
memcpy(random_salt,"$1$",3);
ito64(random_salt+3,rand(),8);
random_salt[11] = '\0';
return string_crypt(key, random_salt);
}
auto const saltLen = strlen(salt);
if ((saltLen > sizeof("$2X$00$")) &&
(salt[0] == '$') &&
(salt[1] == '2') &&
(salt[2] >= 'a') && (salt[2] <= 'z') &&
(salt[3] == '$') &&
(salt[4] >= '0') && (salt[4] <= '3') &&
(salt[5] >= '0') && (salt[5] <= '9') &&
(salt[6] == '$')) {
// Bundled blowfish crypt()
char output[61];
static constexpr size_t maxSaltLength = 123;
char paddedSalt[maxSaltLength + 1];
paddedSalt[0] = paddedSalt[maxSaltLength] = '\0';
memset(&paddedSalt[1], '$', maxSaltLength - 1);
memcpy(paddedSalt, salt, std::min(maxSaltLength, saltLen));
paddedSalt[saltLen] = '\0';
if (php_crypt_blowfish_rn(key, paddedSalt, output, sizeof(output))) {
return strdup(output);
}
} else {
// System crypt() function
#ifdef USE_PHP_CRYPT_R
return php_crypt_r(key, salt);
#else
static Mutex mutex;
Lock lock(mutex);
char *crypt_res = crypt(key,salt);
if (crypt_res) {
return strdup(crypt_res);
}
#endif
}
return ((salt[0] == '*') && (salt[1] == '0'))
? strdup("*1") : strdup("*0");
} | CWE-787 | 24 |
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
} | CWE-190 | 19 |
PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
} | CWE-125 | 47 |
static void gf_dump_vrml_simple_field(GF_SceneDumper *sdump, GF_FieldInfo field, GF_Node *parent)
{
u32 i, sf_type;
GF_ChildNodeItem *list;
void *slot_ptr;
switch (field.fieldType) {
case GF_SG_VRML_SFNODE:
gf_dump_vrml_node(sdump, field.far_ptr ? *(GF_Node **)field.far_ptr : NULL, 0, NULL);
return;
case GF_SG_VRML_MFNODE:
list = * ((GF_ChildNodeItem **) field.far_ptr);
assert( list );
sdump->indent++;
while (list) {
gf_dump_vrml_node(sdump, list->node, 1, NULL);
list = list->next;
}
sdump->indent--;
return;
case GF_SG_VRML_SFCOMMANDBUFFER:
return;
}
if (gf_sg_vrml_is_sf_field(field.fieldType)) {
if (sdump->XMLDump) StartAttribute(sdump, "value");
gf_dump_vrml_sffield(sdump, field.fieldType, field.far_ptr, 0, parent);
if (sdump->XMLDump) EndAttribute(sdump);
} else {
GenMFField *mffield;
mffield = (GenMFField *) field.far_ptr;
sf_type = gf_sg_vrml_get_sf_type(field.fieldType);
if (!sdump->XMLDump) {
gf_fprintf(sdump->trace, "[");
} else if (sf_type==GF_SG_VRML_SFSTRING) {
gf_fprintf(sdump->trace, " value=\'");
} else {
StartAttribute(sdump, "value");
}
for (i=0; i<mffield->count; i++) {
if (i) gf_fprintf(sdump->trace, " ");
gf_sg_vrml_mf_get_item(field.far_ptr, field.fieldType, &slot_ptr, i);
/*this is to cope with single MFString which shall appear as SF in XMT*/
gf_dump_vrml_sffield(sdump, sf_type, slot_ptr, 1, parent);
}
if (!sdump->XMLDump) {
gf_fprintf(sdump->trace, "]");
} else if (sf_type==GF_SG_VRML_SFSTRING) {
gf_fprintf(sdump->trace, "\'");
} else {
EndAttribute(sdump);
}
}
} | CWE-476 | 46 |
static int DefragMfIpv4Test(void)
{
int retval = 0;
int ip_id = 9;
Packet *p = NULL;
DefragInit();
Packet *p1 = BuildTestPacket(ip_id, 2, 1, 'C', 8);
Packet *p2 = BuildTestPacket(ip_id, 0, 1, 'A', 8);
Packet *p3 = BuildTestPacket(ip_id, 1, 0, 'B', 8);
if (p1 == NULL || p2 == NULL || p3 == NULL) {
goto end;
}
p = Defrag(NULL, NULL, p1, NULL);
if (p != NULL) {
goto end;
}
p = Defrag(NULL, NULL, p2, NULL);
if (p != NULL) {
goto end;
}
/* This should return a packet as MF=0. */
p = Defrag(NULL, NULL, p3, NULL);
if (p == NULL) {
goto end;
}
/* Expected IP length is 20 + 8 + 8 = 36 as only 2 of the
* fragments should be in the re-assembled packet. */
if (IPV4_GET_IPLEN(p) != 36) {
goto end;
}
retval = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
if (p2 != NULL) {
SCFree(p2);
}
if (p3 != NULL) {
SCFree(p3);
}
if (p != NULL) {
SCFree(p);
}
DefragDestroy();
return retval;
} | CWE-358 | 50 |
void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb)
{
int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP);
struct scm_timestamping tss;
int empty = 1;
struct skb_shared_hwtstamps *shhwtstamps =
skb_hwtstamps(skb);
/* Race occurred between timestamp enabling and packet
receiving. Fill in the current time for now. */
if (need_software_tstamp && skb->tstamp == 0)
__net_timestamp(skb);
if (need_software_tstamp) {
if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) {
struct timeval tv;
skb_get_timestamp(skb, &tv);
put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP,
sizeof(tv), &tv);
} else {
struct timespec ts;
skb_get_timestampns(skb, &ts);
put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS,
sizeof(ts), &ts);
}
}
memset(&tss, 0, sizeof(tss));
if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) &&
ktime_to_timespec_cond(skb->tstamp, tss.ts + 0))
empty = 0;
if (shhwtstamps &&
(sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2))
empty = 0;
if (!empty) {
put_cmsg(msg, SOL_SOCKET,
SCM_TIMESTAMPING, sizeof(tss), &tss);
if (skb_is_err_queue(skb) && skb->len &&
(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS))
put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS,
skb->len, skb->data);
}
} | CWE-125 | 47 |
int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next)
{
if (!iter || !next)
return -1;
if (iter->in_range)
{
if ((iter->down && (iter->range_cur == (iter->range_end - 1))) ||
(!iter->down && (iter->range_cur == (iter->range_end + 1))))
{
iter->in_range = 0;
}
}
if (!iter->in_range)
{
iter->substr_cur = iter->substr_end;
if (iter->substr_cur == iter->eostr)
return 1;
while (!*(iter->substr_cur))
iter->substr_cur++;
iter->substr_end = strchr(iter->substr_cur, ',');
if (!iter->substr_end)
iter->substr_end = iter->eostr;
else
*(iter->substr_end) = '\0';
char *range_sep = strchr(iter->substr_cur, ':');
if (range_sep)
*range_sep++ = '\0';
if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0)
return -1;
if (range_sep)
{
if (mutt_str_atoui(range_sep, &iter->range_end) != 0)
return -1;
}
else
iter->range_end = iter->range_cur;
iter->down = (iter->range_end < iter->range_cur);
iter->in_range = 1;
}
*next = iter->range_cur;
if (iter->down)
iter->range_cur--;
else
iter->range_cur++;
return 0;
} | CWE-125 | 47 |
process_bitmap_updates(STREAM s)
{
uint16 num_updates;
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, compress, bufsize, size;
uint8 *data, *bmpdata;
int i;
logger(Protocol, Debug, "%s()", __func__);
in_uint16_le(s, num_updates);
for (i = 0; i < num_updates; i++)
{
in_uint16_le(s, left);
in_uint16_le(s, top);
in_uint16_le(s, right);
in_uint16_le(s, bottom);
in_uint16_le(s, width);
in_uint16_le(s, height);
in_uint16_le(s, bpp);
Bpp = (bpp + 7) / 8;
in_uint16_le(s, compress);
in_uint16_le(s, bufsize);
cx = right - left + 1;
cy = bottom - top + 1;
logger(Graphics, Debug,
"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d",
left, top, right, bottom, width, height, Bpp, compress);
if (!compress)
{
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],
width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
continue;
}
if (compress & 0x400)
{
size = bufsize;
}
else
{
in_uint8s(s, 2); /* pad */
in_uint16_le(s, size);
in_uint8s(s, 4); /* line_size, final_size */
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Graphics, Warning,
"process_bitmap_updates(), failed to decompress bitmap");
}
xfree(bmpdata);
}
} | CWE-191 | 55 |
static int dnxhd_init_vlc(DNXHDContext *ctx, uint32_t cid, int bitdepth)
{
if (cid != ctx->cid) {
const CIDEntry *cid_table = ff_dnxhd_get_cid_table(cid);
if (!cid_table) {
av_log(ctx->avctx, AV_LOG_ERROR, "unsupported cid %"PRIu32"\n", cid);
return AVERROR(ENOSYS);
}
if (cid_table->bit_depth != bitdepth &&
cid_table->bit_depth != DNXHD_VARIABLE) {
av_log(ctx->avctx, AV_LOG_ERROR, "bit depth mismatches %d %d\n",
cid_table->bit_depth, bitdepth);
return AVERROR_INVALIDDATA;
}
ctx->cid_table = cid_table;
av_log(ctx->avctx, AV_LOG_VERBOSE, "Profile cid %"PRIu32".\n", cid);
ff_free_vlc(&ctx->ac_vlc);
ff_free_vlc(&ctx->dc_vlc);
ff_free_vlc(&ctx->run_vlc);
init_vlc(&ctx->ac_vlc, DNXHD_VLC_BITS, 257,
ctx->cid_table->ac_bits, 1, 1,
ctx->cid_table->ac_codes, 2, 2, 0);
init_vlc(&ctx->dc_vlc, DNXHD_DC_VLC_BITS, bitdepth > 8 ? 14 : 12,
ctx->cid_table->dc_bits, 1, 1,
ctx->cid_table->dc_codes, 1, 1, 0);
init_vlc(&ctx->run_vlc, DNXHD_VLC_BITS, 62,
ctx->cid_table->run_bits, 1, 1,
ctx->cid_table->run_codes, 2, 2, 0);
ctx->cid = cid;
}
return 0;
} | CWE-252 | 49 |
cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return 0;
if ( c->prev )
c->prev->next = c->next;
if ( c->next ) c->next->prev = c->prev;
if ( c == array->child )
array->child = c->next;
c->prev = c->next = 0;
return c;
} | CWE-120 | 44 |
smtp_mailaddr(struct mailaddr *maddr, char *line, int mailfrom, char **args,
const char *domain)
{
char *p, *e;
if (line == NULL)
return (0);
if (*line != '<')
return (0);
e = strchr(line, '>');
if (e == NULL)
return (0);
*e++ = '\0';
while (*e == ' ')
e++;
*args = e;
if (!text_to_mailaddr(maddr, line + 1))
return (0);
p = strchr(maddr->user, ':');
if (p != NULL) {
p++;
memmove(maddr->user, p, strlen(p) + 1);
}
if (!valid_localpart(maddr->user) ||
!valid_domainpart(maddr->domain)) {
/* accept empty return-path in MAIL FROM, required for bounces */
if (mailfrom && maddr->user[0] == '\0' && maddr->domain[0] == '\0')
return (1);
/* no user-part, reject */
if (maddr->user[0] == '\0')
return (0);
/* no domain, local user */
if (maddr->domain[0] == '\0') {
(void)strlcpy(maddr->domain, domain,
sizeof(maddr->domain));
return (1);
}
return (0);
}
return (1);
} | CWE-78 | 6 |
ast_for_for_stmt(struct compiling *c, const node *n, int is_async)
{
asdl_seq *_target, *seq = NULL, *suite_seq;
expr_ty expression;
expr_ty target, first;
const node *node_target;
int has_type_comment;
string type_comment;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async for loops are only supported in Python 3.5 and greater");
return NULL;
}
/* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */
REQ(n, for_stmt);
has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT;
if (NCH(n) == 9 + has_type_comment) {
seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment));
if (!seq)
return NULL;
}
node_target = CHILD(n, 1);
_target = ast_for_exprlist(c, node_target, Store);
if (!_target)
return NULL;
/* Check the # of children rather than the length of _target, since
for x, in ... has 1 element in _target, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(_target, 0);
if (NCH(node_target) == 1)
target = first;
else
target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);
expression = ast_for_testlist(c, CHILD(n, 3));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment));
if (!suite_seq)
return NULL;
if (has_type_comment)
type_comment = NEW_TYPE_COMMENT(CHILD(n, 5));
else
type_comment = NULL;
if (is_async)
return AsyncFor(target, expression, suite_seq, seq,
type_comment, LINENO(n), n->n_col_offset,
c->c_arena);
else
return For(target, expression, suite_seq, seq,
type_comment, LINENO(n), n->n_col_offset,
c->c_arena);
} | CWE-125 | 47 |
addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type,
size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex,
size_t dimensionSize) {
/* Check the recursion limit */
if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)
return UA_STATUSCODE_BADENCODINGERROR;
/* Stop recursion: The inner Arrays are written */
status ret;
if(dimensionIndex == (dimensionSize - 1)) {
ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index),
arrayDimensions[dimensionIndex], type);
(*index) += arrayDimensions[dimensionIndex];
return ret;
}
/* Recurse to the next dimension */
ret = writeJsonArrStart(ctx);
for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) {
ret |= writeJsonCommaIfNeeded(ctx);
ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions,
dimensionIndex + 1, dimensionSize);
ctx->commaNeeded[ctx->depth] = true;
if(ret != UA_STATUSCODE_GOOD)
return ret;
}
ret |= writeJsonArrEnd(ctx);
return ret;
} | CWE-787 | 24 |
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
} | CWE-125 | 47 |
static void update_blocked_averages(int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct cfs_rq *cfs_rq, *pos;
const struct sched_class *curr_class;
struct rq_flags rf;
bool done = true;
rq_lock_irqsave(rq, &rf);
update_rq_clock(rq);
/*
* Iterates the task_group tree in a bottom up fashion, see
* list_add_leaf_cfs_rq() for details.
*/
for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
struct sched_entity *se;
/* throttled entities do not contribute to load */
if (throttled_hierarchy(cfs_rq))
continue;
if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
update_tg_load_avg(cfs_rq, 0);
/* Propagate pending load changes to the parent, if any: */
se = cfs_rq->tg->se[cpu];
if (se && !skip_blocked_update(se))
update_load_avg(cfs_rq_of(se), se, 0);
/*
* There can be a lot of idle CPU cgroups. Don't let fully
* decayed cfs_rqs linger on the list.
*/
if (cfs_rq_is_decayed(cfs_rq))
list_del_leaf_cfs_rq(cfs_rq);
/* Don't need periodic decay once load/util_avg are null */
if (cfs_rq_has_blocked(cfs_rq))
done = false;
}
curr_class = rq->curr->sched_class;
update_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);
update_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);
update_irq_load_avg(rq, 0);
/* Don't need periodic decay once load/util_avg are null */
if (others_have_blocked(rq))
done = false;
#ifdef CONFIG_NO_HZ_COMMON
rq->last_blocked_load_update_tick = jiffies;
if (done)
rq->has_blocked_load = 0;
#endif
rq_unlock_irqrestore(rq, &rf);
} | CWE-835 | 42 |
bit_write_MC (Bit_Chain *dat, BITCODE_MC val)
{
int i, j;
int negative = 0;
unsigned char byte[5];
BITCODE_UMC mask = 0x0000007f;
BITCODE_UMC value = (BITCODE_UMC)val;
if (val < 0)
{
negative = 1;
value = (BITCODE_UMC)-val;
}
for (i = 4, j = 0; i >= 0; i--, j += 7)
{
byte[i] = (unsigned char)((value & mask) >> j);
byte[i] |= 0x80;
mask = mask << 7;
}
for (i = 0; i < 4; i++)
if (byte[i] & 0x7f)
break;
if (byte[i] & 0x40)
i--;
byte[i] &= 0x7f;
if (negative)
byte[i] |= 0x40;
for (j = 4; j >= i; j--)
bit_write_RC (dat, byte[j]);
} | CWE-125 | 47 |
juniper_mlfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLC_UI):
case (LLC_UI<<8):
isoclns_print(ndo, p, l2info.length, l2info.caplen);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
} | CWE-125 | 47 |
exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,
unsigned int ds, ExifLong o, ExifLong s)
{
/* Sanity checks */
if ((o + s < o) || (o + s < s) || (o + s > ds) || (o > ds)) {
exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
"Bogus thumbnail offset (%u) or size (%u).",
o, s);
return;
}
if (data->data)
exif_mem_free (data->priv->mem, data->data);
if (!(data->data = exif_data_alloc (data, s))) {
EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", s);
data->size = 0;
return;
}
data->size = s;
memcpy (data->data, d + o, s);
} | CWE-190 | 19 |
SPL_METHOD(SplFileInfo, __construct)
{
spl_filesystem_object *intern;
char *path;
int len;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC);
zend_restore_error_handling(&error_handling TSRMLS_CC);
/* intern->type = SPL_FS_INFO; already set */
} | CWE-190 | 19 |
open_log_file(const char *name, const char *prog, const char *namespace, const char *instance)
{
char *file_name;
if (log_file) {
fclose(log_file);
log_file = NULL;
}
if (!name)
return;
file_name = make_file_name(name, prog, namespace, instance);
log_file = fopen(file_name, "a");
if (log_file) {
int n = fileno(log_file);
fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD));
fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL));
}
FREE(file_name);
} | CWE-59 | 36 |
static void edge_bulk_in_callback(struct urb *urb)
{
struct edgeport_port *edge_port = urb->context;
struct device *dev = &edge_port->port->dev;
unsigned char *data = urb->transfer_buffer;
int retval = 0;
int port_number;
int status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status);
return;
default:
dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status);
}
if (status == -EPIPE)
goto exit;
if (status) {
dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__);
return;
}
port_number = edge_port->port->port_number;
if (edge_port->lsr_event) {
edge_port->lsr_event = 0;
dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n",
__func__, port_number, edge_port->lsr_mask, *data);
handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data);
/* Adjust buffer length/pointer */
--urb->actual_length;
++data;
}
if (urb->actual_length) {
usb_serial_debug_data(dev, __func__, urb->actual_length, data);
if (edge_port->close_pending)
dev_dbg(dev, "%s - close pending, dropping data on the floor\n",
__func__);
else
edge_tty_recv(edge_port->port, data,
urb->actual_length);
edge_port->port->icount.rx += urb->actual_length;
}
exit:
/* continue read unless stopped */
spin_lock(&edge_port->ep_lock);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING)
retval = usb_submit_urb(urb, GFP_ATOMIC);
else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING)
edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED;
spin_unlock(&edge_port->ep_lock);
if (retval)
dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval);
} | CWE-191 | 55 |
choose_windows(s)
const char *s;
{
register int i;
for (i = 0; winchoices[i].procs; i++) {
if ('+' == winchoices[i].procs->name[0])
continue;
if ('-' == winchoices[i].procs->name[0])
continue;
if (!strcmpi(s, winchoices[i].procs->name)) {
windowprocs = *winchoices[i].procs;
if (last_winchoice && last_winchoice->ini_routine)
(*last_winchoice->ini_routine)(WININIT_UNDO);
if (winchoices[i].ini_routine)
(*winchoices[i].ini_routine)(WININIT);
last_winchoice = &winchoices[i];
return;
}
}
if (!windowprocs.win_raw_print)
windowprocs.win_raw_print = def_raw_print;
if (!windowprocs.win_wait_synch)
/* early config file error processing routines call this */
windowprocs.win_wait_synch = def_wait_synch;
if (!winchoices[0].procs) {
raw_printf("No window types?");
nh_terminate(EXIT_FAILURE);
}
if (!winchoices[1].procs) {
config_error_add(
"Window type %s not recognized. The only choice is: %s",
s, winchoices[0].procs->name);
} else {
char buf[BUFSZ];
boolean first = TRUE;
buf[0] = '\0';
for (i = 0; winchoices[i].procs; i++) {
if ('+' == winchoices[i].procs->name[0])
continue;
if ('-' == winchoices[i].procs->name[0])
continue;
Sprintf(eos(buf), "%s%s",
first ? "" : ", ", winchoices[i].procs->name);
first = FALSE;
}
config_error_add("Window type %s not recognized. Choices are: %s",
s, buf);
}
if (windowprocs.win_raw_print == def_raw_print
|| WINDOWPORT("safe-startup"))
nh_terminate(EXIT_SUCCESS);
} | CWE-120 | 44 |
int main()
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, "heap_overflow.tga");
im = gdImageCreateFromTgaPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
return gdNumFailures();
} | CWE-125 | 47 |
static const char *parse_array( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '[' ) {
/* Not an array! */
ep = value;
return 0;
}
item->type = cJSON_Array;
value = skip( value + 1 );
if ( *value == ']' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! ( value = skip( parse_value( child, skip( value ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_value( child, skip( value+1 ) ) ) ) )
return 0; /* memory fail */
}
if ( *value == ']' )
return value + 1; /* end of array */
/* Malformed. */
ep = value;
return 0;
} | CWE-120 | 44 |
ber_parse_header(STREAM s, int tagval, int *length)
{
int tag, len;
if (tagval > 0xff)
{
in_uint16_be(s, tag);
}
else
{
in_uint8(s, tag);
}
if (tag != tagval)
{
logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag);
return False;
}
in_uint8(s, len);
if (len & 0x80)
{
len &= ~0x80;
*length = 0;
while (len--)
next_be(s, *length);
}
else
*length = len;
return s_check(s);
} | CWE-191 | 55 |
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen) {
if (!message) {
LOG_ERROR("Null message in AES_encrypt");
return -1;
}
if (!encr_message) {
LOG_ERROR("Null encr message in AES_encrypt");
return -2;
}
if (length < SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE) {
LOG_ERROR("length < SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE");
return -1;
}
uint64_t len = length - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE;
if (msgLen < len) {
LOG_ERROR("Output buffer not large enough");
return -2;
}
sgx_status_t status = sgx_rijndael128GCM_decrypt(&AES_key,
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len,
(unsigned char*) message,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0,
(sgx_aes_gcm_128bit_tag_t *)encr_message);
return status;
} | CWE-787 | 24 |
static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) {
if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj))
return Jsi_LogError("expected array object");
Jsi_Value *v;
Jsi_Obj *obj = _this->d.obj;
Jsi_ObjListifyArray(interp, obj);
uint n = Jsi_ObjGetLength(interp, obj);
assert(n <= obj->arrCnt);
if (n<=0) {
Jsi_ValueMakeUndef(interp, ret);
} else {
n--;
v = obj->arr[0];
memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*));
obj->arr[n] = NULL;
Jsi_ValueDup2(interp, ret, v);
Jsi_DecrRefCount(interp, v);
Jsi_ObjSetLength(interp, obj, n);
}
return JSI_OK;
} | CWE-190 | 19 |
static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)
{
size_t n;
uint32_t types = up->types;
p->types = types;
for (n = 0; n < TEE_NUM_PARAMS; n++) {
uintptr_t a = up->vals[n * 2];
size_t b = up->vals[n * 2 + 1];
switch (TEE_PARAM_TYPE_GET(types, n)) {
case TEE_PARAM_TYPE_MEMREF_INPUT:
case TEE_PARAM_TYPE_MEMREF_OUTPUT:
case TEE_PARAM_TYPE_MEMREF_INOUT:
p->u[n].mem.mobj = &mobj_virt;
p->u[n].mem.offs = a;
p->u[n].mem.size = b;
break;
case TEE_PARAM_TYPE_VALUE_INPUT:
case TEE_PARAM_TYPE_VALUE_INOUT:
p->u[n].val.a = a;
p->u[n].val.b = b;
break;
default:
memset(&p->u[n], 0, sizeof(p->u[n]));
break;
}
}
} | CWE-787 | 24 |
netsnmp_mibindex_new( const char *dirname )
{
FILE *fp;
char tmpbuf[300];
char *cp;
int i;
cp = netsnmp_mibindex_lookup( dirname );
if (!cp) {
i = _mibindex_add( dirname, -1 );
snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes/%d",
get_persistent_directory(), i );
tmpbuf[sizeof(tmpbuf)-1] = 0;
cp = tmpbuf;
}
DEBUGMSGTL(("mibindex", "new: %s (%s)\n", dirname, cp ));
fp = fopen( cp, "w" );
if (fp)
fprintf( fp, "DIR %s\n", dirname );
return fp;
} | CWE-59 | 36 |
mcs_parse_domain_params(STREAM s)
{
int length;
ber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);
in_uint8s(s, length);
return s_check(s);
} | CWE-787 | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.