code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
if (client->priv->protocol_timeout > 0) {
g_source_remove (client->priv->protocol_timeout);
}
} | CWE-835 | 42 |
INST_HANDLER (sbrx) { // SBRC Rr, b
// SBRS Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
} | CWE-125 | 47 |
s32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)
{
u32 pps_id;
si->irap_or_gdr_pic = gf_bs_read_int_log(bs, 1, "irap_or_gdr_pic");
si->non_ref_pic = gf_bs_read_int_log(bs, 1, "non_ref_pic");
if (si->irap_or_gdr_pic)
si->gdr_pic = gf_bs_read_int_log(bs, 1, "gdr_pic");
if ((si->inter_slice_allowed_flag = gf_bs_read_int_log(bs, 1, "inter_slice_allowed_flag")))
si->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, "intra_slice_allowed_flag");
pps_id = gf_bs_read_ue_log(bs, "pps_id");
if (pps_id >= 64)
return -1;
si->pps = &vvc->pps[pps_id];
si->sps = &vvc->sps[si->pps->sps_id];
si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, "poc_lsb");
si->recovery_point_valid = 0;
si->gdr_recovery_count = 0;
if (si->gdr_pic) {
si->recovery_point_valid = 1;
si->gdr_recovery_count = gf_bs_read_ue_log(bs, "gdr_recovery_count");
}
gf_bs_read_int_log(bs, si->sps->ph_num_extra_bits, "ph_extra_bits");
if (si->sps->poc_msb_cycle_flag) {
if ( (si->poc_msb_cycle_present_flag = gf_bs_read_int_log(bs, 1, "poc_msb_cycle_present_flag"))) {
si->poc_msb_cycle = gf_bs_read_int_log(bs, si->sps->poc_msb_cycle_len, "poc_msb_cycle");
}
}
return 0;
} | CWE-787 | 24 |
static pj_status_t get_name_len(int rec_counter, const pj_uint8_t *pkt,
const pj_uint8_t *start, const pj_uint8_t *max,
int *parsed_len, int *name_len)
{
const pj_uint8_t *p;
pj_status_t status;
/* Limit the number of recursion */
if (rec_counter > 10) {
/* Too many name recursion */
return PJLIB_UTIL_EDNSINNAMEPTR;
}
*name_len = *parsed_len = 0;
p = start;
while (*p) {
if ((*p & 0xc0) == 0xc0) {
/* Compression is found! */
int ptr_len = 0;
int dummy;
pj_uint16_t offset;
/* Get the 14bit offset */
pj_memcpy(&offset, p, 2);
offset ^= pj_htons((pj_uint16_t)(0xc0 << 8));
offset = pj_ntohs(offset);
/* Check that offset is valid */
if (offset >= max - pkt)
return PJLIB_UTIL_EDNSINNAMEPTR;
/* Get the name length from that offset. */
status = get_name_len(rec_counter+1, pkt, pkt + offset, max,
&dummy, &ptr_len);
if (status != PJ_SUCCESS)
return status;
*parsed_len += 2;
*name_len += ptr_len;
return PJ_SUCCESS;
} else {
unsigned label_len = *p;
/* Check that label length is valid */
if (pkt+label_len > max)
return PJLIB_UTIL_EDNSINNAMEPTR;
p += (label_len + 1);
*parsed_len += (label_len + 1);
if (*p != 0)
++label_len;
*name_len += label_len;
if (p >= max)
return PJLIB_UTIL_EDNSINSIZE;
}
}
++p;
(*parsed_len)++;
return PJ_SUCCESS;
} | CWE-120 | 44 |
ikev2_t_print(netdissect_options *ndo, int tcount,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep)
{
const struct ikev2_t *p;
struct ikev2_t t;
uint16_t t_id;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
p = (const struct ikev2_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical);
t_id = ntohs(t.t_id);
map = NULL;
nmap = 0;
switch (t.t_type) {
case IV2_T_ENCR:
idstr = STR_OR_ID(t_id, esp_p_map);
map = encr_t_map;
nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]);
break;
case IV2_T_PRF:
idstr = STR_OR_ID(t_id, prf_p_map);
break;
case IV2_T_INTEG:
idstr = STR_OR_ID(t_id, integ_p_map);
break;
case IV2_T_DH:
idstr = STR_OR_ID(t_id, dh_p_map);
break;
case IV2_T_ESN:
idstr = STR_OR_ID(t_id, esn_p_map);
break;
default:
idstr = NULL;
break;
}
if (idstr)
ND_PRINT((ndo," #%u type=%s id=%s ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
idstr));
else
ND_PRINT((ndo," #%u type=%s id=%u ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
} | CWE-125 | 47 |
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
}
}
} | CWE-787 | 24 |
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
ND_PRINT((ndo," len=%d method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (1 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < len) {
if(!ike_show_somedata(ndo, authdata, ep)) goto trunc;
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
} | CWE-835 | 42 |
PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len,
pjstun_msg *msg)
{
pj_uint16_t msg_type, msg_len;
char *p_attr;
PJ_CHECK_STACK();
msg->hdr = (pjstun_msg_hdr*)buf;
msg_type = pj_ntohs(msg->hdr->type);
switch (msg_type) {
case PJSTUN_BINDING_REQUEST:
case PJSTUN_BINDING_RESPONSE:
case PJSTUN_BINDING_ERROR_RESPONSE:
case PJSTUN_SHARED_SECRET_REQUEST:
case PJSTUN_SHARED_SECRET_RESPONSE:
case PJSTUN_SHARED_SECRET_ERROR_RESPONSE:
break;
default:
PJ_LOG(4,(THIS_FILE, "Error: unknown msg type %d", msg_type));
return PJLIB_UTIL_ESTUNINMSGTYPE;
}
msg_len = pj_ntohs(msg->hdr->length);
if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) {
PJ_LOG(4,(THIS_FILE, "Error: invalid msg_len %d (expecting %d)",
msg_len, buf_len - sizeof(pjstun_msg_hdr)));
return PJLIB_UTIL_ESTUNINMSGLEN;
}
msg->attr_count = 0;
p_attr = (char*)buf + sizeof(pjstun_msg_hdr);
while (msg_len > 0) {
pjstun_attr_hdr **attr = &msg->attr[msg->attr_count];
pj_uint32_t len;
pj_uint16_t attr_type;
*attr = (pjstun_attr_hdr*)p_attr;
len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr);
len = (len + 3) & ~3;
if (msg_len < len) {
PJ_LOG(4,(THIS_FILE, "Error: length mismatch in attr %d",
msg->attr_count));
return PJLIB_UTIL_ESTUNINATTRLEN;
}
attr_type = pj_ntohs((*attr)->type);
if (attr_type > PJSTUN_ATTR_REFLECTED_FROM &&
attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR)
{
PJ_LOG(5,(THIS_FILE, "Warning: unknown attr type %x in attr %d. "
"Attribute was ignored.",
attr_type, msg->attr_count));
}
msg_len = (pj_uint16_t)(msg_len - len);
p_attr += len;
++msg->attr_count;
}
return PJ_SUCCESS;
} | CWE-120 | 44 |
int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname,
int lookup, struct fscrypt_name *fname)
{
int ret = 0, bigname = 0;
memset(fname, 0, sizeof(struct fscrypt_name));
fname->usr_fname = iname;
if (!dir->i_sb->s_cop->is_encrypted(dir) ||
fscrypt_is_dot_dotdot(iname)) {
fname->disk_name.name = (unsigned char *)iname->name;
fname->disk_name.len = iname->len;
return 0;
}
ret = fscrypt_get_crypt_info(dir);
if (ret && ret != -EOPNOTSUPP)
return ret;
if (dir->i_crypt_info) {
ret = fscrypt_fname_alloc_buffer(dir, iname->len,
&fname->crypto_buf);
if (ret)
return ret;
ret = fname_encrypt(dir, iname, &fname->crypto_buf);
if (ret)
goto errout;
fname->disk_name.name = fname->crypto_buf.name;
fname->disk_name.len = fname->crypto_buf.len;
return 0;
}
if (!lookup)
return -ENOKEY;
/*
* We don't have the key and we are doing a lookup; decode the
* user-supplied name
*/
if (iname->name[0] == '_')
bigname = 1;
if ((bigname && (iname->len != 33)) || (!bigname && (iname->len > 43)))
return -ENOENT;
fname->crypto_buf.name = kmalloc(32, GFP_KERNEL);
if (fname->crypto_buf.name == NULL)
return -ENOMEM;
ret = digest_decode(iname->name + bigname, iname->len - bigname,
fname->crypto_buf.name);
if (ret < 0) {
ret = -ENOENT;
goto errout;
}
fname->crypto_buf.len = ret;
if (bigname) {
memcpy(&fname->hash, fname->crypto_buf.name, 4);
memcpy(&fname->minor_hash, fname->crypto_buf.name + 4, 4);
} else {
fname->disk_name.name = fname->crypto_buf.name;
fname->disk_name.len = fname->crypto_buf.len;
}
return 0;
errout:
fscrypt_fname_free_buffer(&fname->crypto_buf);
return ret;
} | CWE-476 | 46 |
static Jsi_RC jsi_ArrayForeachCmd(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_Obj *obj;
int curlen;
uint i;
Jsi_Value *func, *vpargs;
func = Jsi_ValueArrayIndex(interp, args, 0);
if (!Jsi_ValueIsFunction(interp, func))
return Jsi_LogError("expected function");
Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1);
Jsi_Value *nthis = NULL;
if (!sthis)
sthis = nthis = Jsi_ValueNew1(interp);
obj = _this->d.obj;
curlen = Jsi_ObjGetLength(interp, obj);
if (curlen < 0) {
Jsi_ObjSetLength(interp, obj, 0);
}
Jsi_ObjListifyArray(interp, obj);
Jsi_RC rc = JSI_OK;
Jsi_Value *vobjs[3];
Jsi_Func *fptr = func->d.obj->d.fobj->func;
int maa = (fptr->argnames?fptr->argnames->argCnt:0);
if (maa>3)
maa = 3;
for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) {
if (!obj->arr[i]) continue;
vobjs[0] = obj->arr[i];
vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL);
vobjs[2] = _this;
vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0));
Jsi_IncrRefCount(interp, vpargs);
rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis);
Jsi_DecrRefCount(interp, vpargs);
}
if (nthis)
Jsi_DecrRefCount(interp, nthis);
return rc;
} | CWE-190 | 19 |
cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c )
return cJSON_DetachItemFromArray( object, i );
return 0;
} | CWE-120 | 44 |
alloc_limit_assert (char *fn_name, size_t size)
{
if (alloc_limit && size > alloc_limit)
{
alloc_limit_failure (fn_name, size);
exit (-1);
}
} | CWE-190 | 19 |
int sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc)
{
struct scsi_device *SDev;
struct scsi_sense_hdr sshdr;
int result, err = 0, retries = 0;
SDev = cd->device;
retry:
if (!scsi_block_when_processing_errors(SDev)) {
err = -ENODEV;
goto out;
}
result = scsi_execute(SDev, cgc->cmd, cgc->data_direction,
cgc->buffer, cgc->buflen,
(unsigned char *)cgc->sense, &sshdr,
cgc->timeout, IOCTL_RETRIES, 0, 0, NULL);
/* Minimal error checking. Ignore cases we know about, and report the rest. */
if (driver_byte(result) != 0) {
switch (sshdr.sense_key) {
case UNIT_ATTENTION:
SDev->changed = 1;
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"disc change detected.\n");
if (retries++ < 10)
goto retry;
err = -ENOMEDIUM;
break;
case NOT_READY: /* This happens if there is no disc in drive */
if (sshdr.asc == 0x04 &&
sshdr.ascq == 0x01) {
/* sense: Logical unit is in process of becoming ready */
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready yet.\n");
if (retries++ < 10) {
/* sleep 2 sec and try again */
ssleep(2);
goto retry;
} else {
/* 20 secs are enough? */
err = -ENOMEDIUM;
break;
}
}
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready. Make sure there "
"is a disc in the drive.\n");
err = -ENOMEDIUM;
break;
case ILLEGAL_REQUEST:
err = -EIO;
if (sshdr.asc == 0x20 &&
sshdr.ascq == 0x00)
/* sense: Invalid command operation code */
err = -EDRIVE_CANT_DO_THIS;
break;
default:
err = -EIO;
}
}
/* Wake up a process waiting for device */
out:
cgc->stat = err;
return err;
} | CWE-787 | 24 |
static void xcopy_pt_undepend_remotedev(struct xcopy_op *xop)
{
struct se_device *remote_dev;
if (xop->op_origin == XCOL_SOURCE_RECV_OP)
remote_dev = xop->dst_dev;
else
remote_dev = xop->src_dev;
pr_debug("Calling configfs_undepend_item for"
" remote_dev: %p remote_dev->dev_group: %p\n",
remote_dev, &remote_dev->dev_group.cg_item);
target_undepend_item(&remote_dev->dev_group.cg_item);
} | CWE-22 | 2 |
void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)
{
const struct k_clock *kc = timr->kclock;
ktime_t now, remaining, iv;
struct timespec64 ts64;
bool sig_none;
sig_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE;
iv = timr->it_interval;
/* interval timer ? */
if (iv) {
cur_setting->it_interval = ktime_to_timespec64(iv);
} else if (!timr->it_active) {
/*
* SIGEV_NONE oneshot timers are never queued. Check them
* below.
*/
if (!sig_none)
return;
}
/*
* The timespec64 based conversion is suboptimal, but it's not
* worth to implement yet another callback.
*/
kc->clock_get(timr->it_clock, &ts64);
now = timespec64_to_ktime(ts64);
/*
* When a requeue is pending or this is a SIGEV_NONE timer move the
* expiry time forward by intervals, so expiry is > now.
*/
if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none))
timr->it_overrun += kc->timer_forward(timr, now);
remaining = kc->timer_remaining(timr, now);
/* Return 0 only, when the timer is expired and not pending */
if (remaining <= 0) {
/*
* A single shot SIGEV_NONE timer must return 0, when
* it is expired !
*/
if (!sig_none)
cur_setting->it_value.tv_nsec = 1;
} else {
cur_setting->it_value = ktime_to_timespec64(remaining);
}
} | CWE-125 | 47 |
static const char *parse_value( cJSON *item, const char *value )
{
if ( ! value )
return 0; /* Fail on null. */
if ( ! strncmp( value, "null", 4 ) ) {
item->type = cJSON_NULL;
return value + 4;
}
if ( ! strncmp( value, "false", 5 ) ) {
item->type = cJSON_False;
return value + 5;
}
if ( ! strncmp( value, "true", 4 ) ) {
item->type = cJSON_True;
item->valueint = 1;
return value + 4;
}
if ( *value == '\"' )
return parse_string( item, value );
if ( *value == '-' || ( *value >= '0' && *value <= '9' ) )
return parse_number( item, value );
if ( *value == '[' )
return parse_array( item, value );
if ( *value == '{' )
return parse_object( item, value );
/* Fail. */
ep = value;
return 0;
} | CWE-120 | 44 |
MONGO_EXPORT int mongo_insert_batch( mongo *conn, const char *ns,
const bson **bsons, int count, mongo_write_concern *custom_write_concern,
int flags ) {
mongo_message *mm;
mongo_write_concern *write_concern = NULL;
int i;
char *data;
int overhead = 16 + 4 + strlen( ns ) + 1;
int size = overhead;
if( mongo_validate_ns( conn, ns ) != MONGO_OK )
return MONGO_ERROR;
for( i=0; i<count; i++ ) {
size += bson_size( bsons[i] );
if( mongo_bson_valid( conn, bsons[i], 1 ) != MONGO_OK )
return MONGO_ERROR;
}
if( ( size - overhead ) > conn->max_bson_size ) {
conn->err = MONGO_BSON_TOO_LARGE;
return MONGO_ERROR;
}
if( mongo_choose_write_concern( conn, custom_write_concern,
&write_concern ) == MONGO_ERROR ) {
return MONGO_ERROR;
}
mm = mongo_message_create( size , 0 , 0 , MONGO_OP_INSERT );
data = &mm->data;
if( flags & MONGO_CONTINUE_ON_ERROR )
data = mongo_data_append32( data, &ONE );
else
data = mongo_data_append32( data, &ZERO );
data = mongo_data_append( data, ns, strlen( ns ) + 1 );
for( i=0; i<count; i++ ) {
data = mongo_data_append( data, bsons[i]->data, bson_size( bsons[i] ) );
}
/* TODO: refactor so that we can send the insert message
* and the getlasterror messages together. */
if( write_concern ) {
if( mongo_message_send( conn, mm ) == MONGO_ERROR ) {
return MONGO_ERROR;
}
return mongo_check_last_error( conn, ns, write_concern );
}
else {
return mongo_message_send( conn, mm );
}
} | CWE-190 | 19 |
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 |
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 |
static void array_cleanup( char* arr[] , int arr_size)
{
int i=0;
for( i=0; i< arr_size; i++ ){
if( arr[i*2] ){
efree( arr[i*2]);
}
}
efree(arr);
} | CWE-125 | 47 |
AsyncWith(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, int
end_lineno, int end_col_offset, PyArena *arena)
{
stmt_ty p;
p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
if (!p)
return NULL;
p->kind = AsyncWith_kind;
p->v.AsyncWith.items = items;
p->v.AsyncWith.body = body;
p->lineno = lineno;
p->col_offset = col_offset;
p->end_lineno = end_lineno;
p->end_col_offset = end_col_offset;
return p;
} | 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-125 | 47 |
static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
{
struct kvm_run *run = vcpu->run;
struct kvm_mmio_fragment *frag;
unsigned len;
BUG_ON(!vcpu->mmio_needed);
/* Complete previous fragment */
frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
len = min(8u, frag->len);
if (!vcpu->mmio_is_write)
memcpy(frag->data, run->mmio.data, len);
if (frag->len <= 8) {
/* Switch to the next fragment. */
frag++;
vcpu->mmio_cur_fragment++;
} else {
/* Go forward to the next mmio piece. */
frag->data += len;
frag->gpa += len;
frag->len -= len;
}
if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
vcpu->mmio_needed = 0;
/* FIXME: return into emulator if single-stepping. */
if (vcpu->mmio_is_write)
return 1;
vcpu->mmio_read_completed = 1;
return complete_emulated_io(vcpu);
}
run->exit_reason = KVM_EXIT_MMIO;
run->mmio.phys_addr = frag->gpa;
if (vcpu->mmio_is_write)
memcpy(run->mmio.data, frag->data, min(8u, frag->len));
run->mmio.len = min(8u, frag->len);
run->mmio.is_write = vcpu->mmio_is_write;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
return 0;
} | CWE-120 | 44 |
void rdp_read_flow_control_pdu(wStream* s, UINT16* type)
{
/*
* Read flow control PDU - documented in FlowPDU section in T.128
* http://www.itu.int/rec/T-REC-T.128-199802-S/en
* The specification for the PDU has pad8bits listed BEFORE pduTypeFlow.
* However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow.
* Switched the order of these two fields to match this observation.
*/
UINT8 pduType;
Stream_Read_UINT8(s, pduType); /* pduTypeFlow */
*type = pduType;
Stream_Seek_UINT8(s); /* pad8bits */
Stream_Seek_UINT8(s); /* flowIdentifier */
Stream_Seek_UINT8(s); /* flowNumber */
Stream_Seek_UINT16(s); /* pduSource */
} | CWE-125 | 47 |
static PyObject *__pyx_pw_17clickhouse_driver_14bufferedreader_14BufferedReader_5read(PyObject *__pyx_v_self, PyObject *__pyx_arg_unread) {
Py_ssize_t __pyx_v_unread;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("read (wrapper)", 0);
assert(__pyx_arg_unread); {
__pyx_v_unread = __Pyx_PyIndex_AsSsize_t(__pyx_arg_unread); if (unlikely((__pyx_v_unread == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 25, __pyx_L3_error)
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L3_error:;
__Pyx_AddTraceback("clickhouse_driver.bufferedreader.BufferedReader.read", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_17clickhouse_driver_14bufferedreader_14BufferedReader_4read(((struct __pyx_obj_17clickhouse_driver_14bufferedreader_BufferedReader *)__pyx_v_self), ((Py_ssize_t)__pyx_v_unread));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
} | CWE-120 | 44 |
TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
{
static const char module[] = "TIFFReadEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint32 rowsperstrip;
uint32 stripsperplane;
uint32 stripinplane;
uint16 plane;
uint32 rows;
tmsize_t stripsize;
if (!TIFFCheckRead(tif,0))
return((tmsize_t)(-1));
if (strip>=td->td_nstrips)
{
TIFFErrorExt(tif->tif_clientdata,module,
"%lu: Strip out of range, max %lu",(unsigned long)strip,
(unsigned long)td->td_nstrips);
return((tmsize_t)(-1));
}
/*
* Calculate the strip size according to the number of
* rows in the strip (check for truncated last strip on any
* of the separations).
*/
rowsperstrip=td->td_rowsperstrip;
if (rowsperstrip>td->td_imagelength)
rowsperstrip=td->td_imagelength;
stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip);
stripinplane=(strip%stripsperplane);
plane=(uint16)(strip/stripsperplane);
rows=td->td_imagelength-stripinplane*rowsperstrip;
if (rows>rowsperstrip)
rows=rowsperstrip;
stripsize=TIFFVStripSize(tif,rows);
if (stripsize==0)
return((tmsize_t)(-1));
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE &&
size!=(tmsize_t)(-1) && size >= stripsize &&
!isMapped(tif) &&
((tif->tif_flags&TIFF_NOREADRAW)==0) )
{
if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize)
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(buf,stripsize);
(*tif->tif_postdecode)(tif,buf,stripsize);
return (stripsize);
}
if ((size!=(tmsize_t)(-1))&&(size<stripsize))
stripsize=size;
if (!TIFFFillStrip(tif,strip))
return((tmsize_t)(-1));
if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0)
return((tmsize_t)(-1));
(*tif->tif_postdecode)(tif,buf,stripsize);
return(stripsize);
} | CWE-369 | 60 |
cJSON *cJSON_Parse( const char *value )
{
cJSON *c;
ep = 0;
if ( ! ( c = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! parse_value( c, skip( value ) ) ) {
cJSON_Delete( c );
return 0;
}
return c;
} | CWE-120 | 44 |
setup_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
client->priv->protocol_timeout = g_timeout_add_seconds (5,
(GSourceFunc)_client_protocol_timeout,
client);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
} | CWE-835 | 42 |
RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) {
int i;
if (!bin) {
return NULL;
}
RList *segments = r_list_newf (free);
for (i = 0; i < bin->ne_header->SegCount; i++) {
RBinSection *bs = R_NEW0 (RBinSection);
if (!bs) {
return segments;
}
NE_image_segment_entry *se = &bin->segment_entries[i];
bs->size = se->length;
bs->vsize = se->minAllocSz ? se->minAllocSz : 64000;
bs->bits = R_SYS_BITS_16;
bs->is_data = se->flags & IS_DATA;
bs->perm = __translate_perms (se->flags);
bs->paddr = (ut64)se->offset * bin->alignment;
bs->name = r_str_newf ("%s.%" PFMT64d, se->flags & IS_MOVEABLE ? "MOVEABLE" : "FIXED", bs->paddr);
bs->is_segment = true;
r_list_append (segments, bs);
}
bin->segments = segments;
return segments;
} | CWE-476 | 46 |
static int input_default_setkeycode(struct input_dev *dev,
const struct input_keymap_entry *ke,
unsigned int *old_keycode)
{
unsigned int index;
int error;
int i;
if (!dev->keycodesize)
return -EINVAL;
if (ke->flags & INPUT_KEYMAP_BY_INDEX) {
index = ke->index;
} else {
error = input_scancode_to_scalar(ke, &index);
if (error)
return error;
}
if (index >= dev->keycodemax)
return -EINVAL;
if (dev->keycodesize < sizeof(ke->keycode) &&
(ke->keycode >> (dev->keycodesize * 8)))
return -EINVAL;
switch (dev->keycodesize) {
case 1: {
u8 *k = (u8 *)dev->keycode;
*old_keycode = k[index];
k[index] = ke->keycode;
break;
}
case 2: {
u16 *k = (u16 *)dev->keycode;
*old_keycode = k[index];
k[index] = ke->keycode;
break;
}
default: {
u32 *k = (u32 *)dev->keycode;
*old_keycode = k[index];
k[index] = ke->keycode;
break;
}
}
__clear_bit(*old_keycode, dev->keybit);
__set_bit(ke->keycode, dev->keybit);
for (i = 0; i < dev->keycodemax; i++) {
if (input_fetch_keycode(dev, i) == *old_keycode) {
__set_bit(*old_keycode, dev->keybit);
break; /* Setting the bit twice is useless, so break */
}
}
return 0;
} | CWE-787 | 24 |
test_function (char * (*my_asnprintf) (char *, size_t *, const char *, ...))
{
char buf[8];
int size;
for (size = 0; size <= 8; size++)
{
size_t length = size;
char *result = my_asnprintf (NULL, &length, "%d", 12345);
ASSERT (result != NULL);
ASSERT (strcmp (result, "12345") == 0);
ASSERT (length == 5);
free (result);
}
for (size = 0; size <= 8; size++)
{
size_t length;
char *result;
memcpy (buf, "DEADBEEF", 8);
length = size;
result = my_asnprintf (buf, &length, "%d", 12345);
ASSERT (result != NULL);
ASSERT (strcmp (result, "12345") == 0);
ASSERT (length == 5);
if (size < 6)
ASSERT (result != buf);
ASSERT (memcmp (buf + size, &"DEADBEEF"[size], 8 - size) == 0);
if (result != buf)
free (result);
}
} | CWE-787 | 24 |
SPL_METHOD(SplFileObject, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
/* Do not read the next line to support correct counting with fgetc()
if (!intern->current_line) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
} */
RETURN_LONG(intern->u.file.current_line_num);
} /* }}} */ | CWE-190 | 19 |
init_ctx_new(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred,
gss_ctx_id_t *ctx,
send_token_flag *tokflag)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = NULL;
sc = create_spnego_ctx();
if (sc == NULL)
return GSS_S_FAILURE;
/* determine negotiation mech set */
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,
&sc->mech_set);
if (ret != GSS_S_COMPLETE)
goto cleanup;
/* Set an initial internal mech to make the first context token. */
sc->internal_mech = &sc->mech_set->elements[0];
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
/*
* The actual context is not yet determined, set the output
* context handle to refer to the spnego context itself.
*/
sc->ctx_handle = GSS_C_NO_CONTEXT;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
*tokflag = INIT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
cleanup:
release_spnego_ctx(&sc);
return ret;
} | CWE-763 | 61 |
spnego_gss_wrap_size_limit(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
OM_uint32 req_output_size,
OM_uint32 *max_input_size)
{
OM_uint32 ret;
ret = gss_wrap_size_limit(minor_status,
context_handle,
conf_req_flag,
qop_req,
req_output_size,
max_input_size);
return (ret);
} | CWE-763 | 61 |
trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret,
uint32_t enc_len,
uint8_t *decrypted_dkg_secret) {
LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE
CHECK_STATE(encrypted_dkg_secret);
CHECK_STATE(decrypted_dkg_secret);
int status = AES_decrypt(encrypted_dkg_secret, enc_len, (char *) decrypted_dkg_secret,
3072);
CHECK_STATUS2("aes decrypt data - encrypted_dkg_secret failed with status %d")
SET_SUCCESS
clean:
;
LOG_INFO(__FUNCTION__ );
LOG_INFO("SGX call completed");
} | CWE-787 | 24 |
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 |
sysServices_handler(snmp_varbind_t *varbind, uint32_t *oid)
{
snmp_api_set_time_ticks(varbind, oid, clock_seconds() * 100);
} | CWE-125 | 47 |
NOEXPORT int init_section(int eof, SERVICE_OPTIONS **section_ptr) {
char *errstr;
#ifndef USE_WIN32
(*section_ptr)->option.log_stderr=new_global_options.option.log_stderr;
#endif /* USE_WIN32 */
if(*section_ptr==&new_service_options) {
/* end of global options or inetd mode -> initialize globals */
errstr=parse_global_option(CMD_INITIALIZE, NULL, NULL);
if(errstr) {
s_log(LOG_ERR, "Global options: %s", errstr);
return 1;
}
}
if(*section_ptr!=&new_service_options || eof) {
/* end service section or inetd mode -> initialize service */
if(*section_ptr==&new_service_options)
s_log(LOG_INFO, "Initializing inetd mode configuration");
else
s_log(LOG_INFO, "Initializing service [%s]",
(*section_ptr)->servname);
errstr=parse_service_option(CMD_INITIALIZE, section_ptr, NULL, NULL);
if(errstr) {
if(*section_ptr==&new_service_options)
s_log(LOG_ERR, "Inetd mode: %s", errstr);
else
s_log(LOG_ERR, "Service [%s]: %s",
(*section_ptr)->servname, errstr);
return 1;
}
}
return 0;
} | CWE-295 | 52 |
static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
} | CWE-125 | 47 |
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,
unsigned int *pv)
{
unsigned int field_type;
unsigned int value_count;
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==3) { // SHORT (uint16)
*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);
return 1;
}
else if(field_type==4) { // LONG (uint32)
*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);
return 1;
}
return 0;
} | CWE-125 | 47 |
static int uas_find_uas_alt_setting(struct usb_interface *intf)
{
int i;
for (i = 0; i < intf->num_altsetting; i++) {
struct usb_host_interface *alt = &intf->altsetting[i];
if (uas_is_interface(alt))
return alt->desc.bAlternateSetting;
}
return -ENODEV;
} | CWE-125 | 47 |
static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
} | CWE-369 | 60 |
cpStripToTile(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int inskew)
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0)
*out++ = *in++;
out += outskew;
in += inskew;
}
} | CWE-190 | 19 |
qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
u32 level, const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & level))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_info("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
} | CWE-125 | 47 |
static void write_version(
FILE *fp,
const char *fname,
const char *dirname,
xref_t *xref)
{
long start;
char *c, *new_fname, data;
FILE *new_fp;
start = ftell(fp);
/* Create file */
if ((c = strstr(fname, ".pdf")))
*c = '\0';
new_fname = malloc(strlen(fname) + strlen(dirname) + 16);
snprintf(new_fname, strlen(fname) + strlen(dirname) + 16,
"%s/%s-version-%d.pdf", dirname, fname, xref->version);
if (!(new_fp = fopen(new_fname, "w")))
{
ERR("Could not create file '%s'\n", new_fname);
fseek(fp, start, SEEK_SET);
free(new_fname);
return;
}
/* Copy original PDF */
fseek(fp, 0, SEEK_SET);
while (fread(&data, 1, 1, fp))
fwrite(&data, 1, 1, new_fp);
/* Emit an older startxref, refering to an older version. */
fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start);
/* Clean */
fclose(new_fp);
free(new_fname);
fseek(fp, start, SEEK_SET);
} | CWE-787 | 24 |
FstringParser_Finish(FstringParser *state, struct compiling *c,
const node *n)
{
asdl_seq *seq;
FstringParser_check_invariants(state);
/* If we're just a constant string with no expressions, return
that. */
if(state->expr_list.size == 0) {
if (!state->last_str) {
/* Create a zero length string. */
state->last_str = PyUnicode_FromStringAndSize(NULL, 0);
if (!state->last_str)
goto error;
}
return make_str_node_and_del(&state->last_str, c, n);
}
/* Create a Str node out of last_str, if needed. It will be the
last node in our expression list. */
if (state->last_str) {
expr_ty str = make_str_node_and_del(&state->last_str, c, n);
if (!str || ExprList_Append(&state->expr_list, str) < 0)
goto error;
}
/* This has already been freed. */
assert(state->last_str == NULL);
seq = ExprList_Finish(&state->expr_list, c->c_arena);
if (!seq)
goto error;
/* If there's only one expression, return it. Otherwise, we need
to join them together. */
if (seq->size == 1)
return seq->elements[0];
return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena);
error:
FstringParser_Dealloc(state);
return NULL;
} | CWE-125 | 47 |
static char *__filterShell(const char *arg) {
r_return_val_if_fail (arg, NULL);
char *a = malloc (strlen (arg) + 1);
if (!a) {
return NULL;
}
char *b = a;
while (*arg) {
switch (*arg) {
case '@':
case '`':
case '|':
case ';':
case '\n':
break;
default:
*b++ = *arg;
break;
}
arg++;
}
*b = 0;
return a;
} | CWE-78 | 6 |
static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
} | CWE-787 | 24 |
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 |
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
} | CWE-125 | 47 |
webSocketsHasDataInBuffer(rfbClientPtr cl)
{
ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;
if (wsctx && wsctx->readbuflen)
return TRUE;
return (cl->sslctx && rfbssl_pending(cl) > 0);
} | CWE-787 | 24 |
static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)
{
switch (mode) {
case KD_GRAPHICS:
break;
case KD_TEXT0:
case KD_TEXT1:
mode = KD_TEXT;
fallthrough;
case KD_TEXT:
break;
default:
return -EINVAL;
}
/* FIXME: this needs the console lock extending */
if (vc->vc_mode == mode)
return 0;
vc->vc_mode = mode;
if (vc->vc_num != fg_console)
return 0;
/* explicitly blank/unblank the screen if switching modes */
console_lock();
if (mode == KD_TEXT)
do_unblank_screen(1);
else
do_blank_screen(1);
console_unlock();
return 0;
} | CWE-125 | 47 |
R_API int r_socket_block_time(RSocket *s, int block, int sec, int usec) {
#if __UNIX__
int ret, flags;
#endif
if (!s) {
return false;
}
#if __UNIX__
flags = fcntl (s->fd, F_GETFL, 0);
if (flags < 0) {
return false;
}
ret = fcntl (s->fd, F_SETFL, block?
(flags & ~O_NONBLOCK):
(flags | O_NONBLOCK));
if (ret < 0) {
return false;
}
#elif __WINDOWS__
ioctlsocket (s->fd, FIONBIO, (u_long FAR*)&block);
#endif
if (sec > 0 || usec > 0) {
struct timeval tv = {0};
tv.tv_sec = sec;
tv.tv_usec = usec;
if (setsockopt (s->fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof (tv)) < 0) {
return false;
}
}
return true;
} | CWE-78 | 6 |
SPL_METHOD(SplTempFileObject, __construct)
{
long max_memory = PHP_STREAM_MAX_MEM;
char tmp_fname[48];
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
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, "|l", &max_memory) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (max_memory < 0) {
intern->file_name = "php://memory";
intern->file_name_len = 12;
} else if (ZEND_NUM_ARGS()) {
intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory);
intern->file_name = tmp_fname;
} else {
intern->file_name = "php://temp";
intern->file_name_len = 10;
}
intern->u.file.open_mode = "wb";
intern->u.file.open_mode_len = 1;
intern->u.file.zcontext = NULL;
if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) {
intern->_path_len = 0;
intern->_path = estrndup("", 0);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */ | CWE-190 | 19 |
static const char *parse_number( cJSON *item, const char *num )
{
int64_t i = 0;
double f = 0;
int isint = 1;
int sign = 1, scale = 0, subscale = 0, signsubscale = 1;
/* Could use sscanf for this? */
if ( *num == '-' ) {
/* Has sign. */
sign = -1;
++num;
}
if ( *num == '0' )
/* Is zero. */
++num;
if ( *num >= '1' && *num<='9' ) {
/* Number. */
do {
i = ( i * 10 ) + ( *num - '0' );
f = ( f * 10.0 ) + ( *num - '0' );
++num;
} while ( *num >= '0' && *num <= '9' );
}
if ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) {
/* Fractional part. */
isint = 0;
++num;
do {
f = ( f * 10.0 ) + ( *num++ - '0' );
scale--;
} while ( *num >= '0' && *num <= '9' );
}
if ( *num == 'e' || *num == 'E' ) {
/* Exponent. */
isint = 0;
++num;
if ( *num == '+' )
++num;
else if ( *num == '-' ) {
/* With sign. */
signsubscale = -1;
++num;
}
while ( *num >= '0' && *num <= '9' )
subscale = ( subscale * 10 ) + ( *num++ - '0' );
}
/* Put it together. */
if ( isint ) {
/* Int: number = +/- number */
i = sign * i;
item->valueint = i;
item->valuefloat = i;
} else {
/* Float: number = +/- number.fraction * 10^+/- exponent */
f = sign * f * ipow( 10.0, scale + subscale * signsubscale );
item->valueint = f;
item->valuefloat = f;
}
item->type = cJSON_Number;
return num;
} | CWE-120 | 44 |
static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
{
if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
(vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
struct kvm_run *kvm_run = vcpu->run;
unsigned long eip = kvm_get_linear_rip(vcpu);
u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
vcpu->arch.guest_debug_dr7,
vcpu->arch.eff_db);
if (dr6 != 0) {
kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
kvm_run->debug.arch.pc = eip;
kvm_run->debug.arch.exception = DB_VECTOR;
kvm_run->exit_reason = KVM_EXIT_DEBUG;
*r = 0;
return true;
}
}
if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
!(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
unsigned long eip = kvm_get_linear_rip(vcpu);
u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
vcpu->arch.dr7,
vcpu->arch.db);
if (dr6 != 0) {
kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
*r = 1;
return true;
}
}
return false;
} | CWE-476 | 46 |
void gdImageFill(gdImagePtr im, int x, int y, int nc)
{
int l, x1, x2, dy;
int oc; /* old pixel value */
int wx2,wy2;
int alphablending_bak;
/* stack of filled segments */
/* struct seg stack[FILL_MAX],*sp = stack;; */
struct seg *stack = NULL;
struct seg *sp;
if (!im->trueColor && nc > (im->colorsTotal -1)) {
return;
}
alphablending_bak = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (nc==gdTiled){
_gdImageFillTiled(im,x,y,nc);
im->alphaBlendingFlag = alphablending_bak;
return;
}
wx2=im->sx;wy2=im->sy;
oc = gdImageGetPixel(im, x, y);
if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) {
im->alphaBlendingFlag = alphablending_bak;
return;
}
/* Do not use the 4 neighbors implementation with
* small images
*/
if (im->sx < 4) {
int ix = x, iy = y, c;
do {
do {
c = gdImageGetPixel(im, ix, iy);
if (c != oc) {
goto done;
}
gdImageSetPixel(im, ix, iy, nc);
} while(ix++ < (im->sx -1));
ix = x;
} while(iy++ < (im->sy -1));
goto done;
}
stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1);
sp = stack;
/* required! */
FILL_PUSH(y,x,x,1);
/* seed segment (popped 1st) */
FILL_PUSH(y+1, x, x, -1);
while (sp>stack) {
FILL_POP(y, x1, x2, dy);
for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) {
gdImageSetPixel(im,x, y, nc);
}
if (x>=x1) {
goto skip;
}
l = x+1;
/* leak on left? */
if (l<x1) {
FILL_PUSH(y, l, x1-1, -dy);
}
x = x1+1;
do {
for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) {
gdImageSetPixel(im, x, y, nc);
}
FILL_PUSH(y, l, x-1, dy);
/* leak on right? */
if (x>x2+1) {
FILL_PUSH(y, x2+1, x-1, -dy);
}
skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++);
l = x;
} while (x<=x2);
}
efree(stack);
done:
im->alphaBlendingFlag = alphablending_bak;
} | CWE-190 | 19 |
static void vgacon_scrollback_switch(int vc_num)
{
if (!scrollback_persistent)
vc_num = 0;
if (!vgacon_scrollbacks[vc_num].data) {
vgacon_scrollback_init(vc_num);
} else {
if (scrollback_persistent) {
vgacon_scrollback_cur = &vgacon_scrollbacks[vc_num];
} else {
size_t size = CONFIG_VGACON_SOFT_SCROLLBACK_SIZE * 1024;
vgacon_scrollback_reset(vc_num, size);
}
}
} | CWE-125 | 47 |
static inline int process_numeric_entity(const char **buf, unsigned *code_point)
{
long code_l;
int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */
char *endptr;
if (hexadecimal && (**buf != '\0'))
(*buf)++;
/* strtol allows whitespace and other stuff in the beginning
* we're not interested */
if ((hexadecimal && !isxdigit(**buf)) ||
(!hexadecimal && !isdigit(**buf))) {
return FAILURE;
}
code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10);
/* we're guaranteed there were valid digits, so *endptr > buf */
*buf = endptr;
if (**buf != ';')
return FAILURE;
/* many more are invalid, but that depends on whether it's HTML
* (and which version) or XML. */
if (code_l > 0x10FFFFL)
return FAILURE;
if (code_point != NULL)
*code_point = (unsigned)code_l;
return SUCCESS;
} | CWE-190 | 19 |
static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data)
{
struct l2cap_conf_req *req = (struct l2cap_conf_req *) data;
u16 dcid, flags;
u8 rsp[64];
struct sock *sk;
int len;
dcid = __le16_to_cpu(req->dcid);
flags = __le16_to_cpu(req->flags);
BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags);
sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid);
if (!sk)
return -ENOENT;
if (sk->sk_state == BT_DISCONN)
goto unlock;
/* Reject if config buffer is too small. */
len = cmd_len - sizeof(*req);
if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) {
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_REJECT, flags), rsp);
goto unlock;
}
/* Store config. */
memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len);
l2cap_pi(sk)->conf_len += len;
if (flags & 0x0001) {
/* Incomplete config. Send empty response. */
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
l2cap_build_conf_rsp(sk, rsp,
L2CAP_CONF_SUCCESS, 0x0001), rsp);
goto unlock;
}
/* Complete config. */
len = l2cap_parse_conf_req(sk, rsp);
if (len < 0)
goto unlock;
l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);
/* Reset config buffer. */
l2cap_pi(sk)->conf_len = 0;
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE))
goto unlock;
if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) {
sk->sk_state = BT_CONNECTED;
l2cap_chan_ready(sk);
goto unlock;
}
if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) {
u8 buf[64];
l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
l2cap_build_conf_req(sk, buf), buf);
}
unlock:
bh_unlock_sock(sk);
return 0;
} | CWE-787 | 24 |
static void put_crypt_info(struct fscrypt_info *ci)
{
if (!ci)
return;
key_put(ci->ci_keyring_key);
crypto_free_skcipher(ci->ci_ctfm);
kmem_cache_free(fscrypt_info_cachep, ci);
} | CWE-476 | 46 |
static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
UINT32 new_len;
BYTE* new_data;
CACHE_BITMAP_V3_ORDER* cache_bitmap_v3;
if (!update || !s)
return NULL;
cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!cache_bitmap_v3)
goto fail;
cache_bitmap_v3->cacheId = flags & 0x00000003;
cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7;
bitsPerPixelId = (flags & 0x00000078) >> 3;
cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId];
if (Stream_GetRemainingLength(s) < 21)
goto fail;
Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
bitmapData = &cache_bitmap_v3->bitmapData;
Stream_Read_UINT8(s, bitmapData->bpp);
if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp);
goto fail;
}
Stream_Seek_UINT8(s); /* reserved1 (1 byte) */
Stream_Seek_UINT8(s); /* reserved2 (1 byte) */
Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Read_UINT32(s, new_len); /* length (4 bytes) */
if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len))
goto fail;
new_data = (BYTE*)realloc(bitmapData->data, new_len);
if (!new_data)
goto fail;
bitmapData->data = new_data;
bitmapData->length = new_len;
Stream_Read(s, bitmapData->data, bitmapData->length);
return cache_bitmap_v3;
fail:
free_cache_bitmap_v3_order(update->context, cache_bitmap_v3);
return NULL;
} | CWE-125 | 47 |
void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
global_State *g = G(L);
lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
if (keepinvariant(g)) { /* must keep invariant? */
reallymarkobject(g, v); /* restore invariant */
if (isold(o)) {
lua_assert(!isold(v)); /* white object could not be old */
setage(v, G_OLD0); /* restore generational invariant */
}
}
else { /* sweep phase */
lua_assert(issweepphase(g));
makewhite(g, o); /* mark main obj. as white to avoid other barriers */
}
} | CWE-763 | 61 |
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
RASN1Object *object;
RCMS *container;
if (!buffer || !length) {
return NULL;
}
container = R_NEW0 (RCMS);
if (!container) {
return NULL;
}
object = r_asn1_create_object (buffer, length);
if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {
r_asn1_free_object (object);
free (container);
return NULL;
}
container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
r_asn1_free_object (object);
return container;
} | CWE-476 | 46 |
cJSON *cJSON_CreateInt( int64_t num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
} | CWE-120 | 44 |
int mutt_from_base64 (char *out, const char *in)
{
int len = 0;
register unsigned char digit1, digit2, digit3, digit4;
do
{
digit1 = in[0];
if (digit1 > 127 || base64val (digit1) == BAD)
return -1;
digit2 = in[1];
if (digit2 > 127 || base64val (digit2) == BAD)
return -1;
digit3 = in[2];
if (digit3 > 127 || ((digit3 != '=') && (base64val (digit3) == BAD)))
return -1;
digit4 = in[3];
if (digit4 > 127 || ((digit4 != '=') && (base64val (digit4) == BAD)))
return -1;
in += 4;
/* digits are already sanity-checked */
*out++ = (base64val(digit1) << 2) | (base64val(digit2) >> 4);
len++;
if (digit3 != '=')
{
*out++ = ((base64val(digit2) << 4) & 0xf0) | (base64val(digit3) >> 2);
len++;
if (digit4 != '=')
{
*out++ = ((base64val(digit3) << 6) & 0xc0) | base64val(digit4);
len++;
}
}
}
while (*in && digit4 != '=');
return len;
} | CWE-120 | 44 |
snmp_ber_encode_null(unsigned char *out, uint32_t *out_len, uint8_t type)
{
(*out_len)++;
*out-- = 0x00;
out = snmp_ber_encode_type(out, out_len, type);
return out;
} | CWE-125 | 47 |
PHP_FUNCTION( locale_get_region )
{
get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
} | CWE-125 | 47 |
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,
unsigned int *pv)
{
unsigned int field_type;
unsigned int value_count;
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==3) { // SHORT (uint16)
*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);
return 1;
}
else if(field_type==4) { // LONG (uint32)
*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);
return 1;
}
return 0;
} | CWE-125 | 47 |
static void jsiSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv) {
SqlFunc *p = (SqlFunc*)sqlite3_user_data(context);
int i;
int rc;
Jsi_Interp *interp = p->interp;
Jsi_Value *vpargs, *itemsStatic[100], **items = itemsStatic, *ret;
if (argc>100)
items = (Jsi_Value**)Jsi_Calloc(argc, sizeof(Jsi_Value*));
for(i=0; i<argc; i++) {
items[i] = dbGetValueGet(interp, argv[i]);
}
vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, items, argc, 0));
Jsi_IncrRefCount(interp, vpargs);
ret = Jsi_ValueNew1(interp);
rc = Jsi_FunctionInvoke(interp, p->tocall, vpargs, &ret, NULL);
Jsi_DecrRefCount(interp, vpargs);
if (items != itemsStatic)
Jsi_Free(items);
bool b;
if( rc != JSI_OK) {
char buf[250];
snprintf(buf, sizeof(buf), "error in function: %.200s", p->zName);
sqlite3_result_error(context, buf, -1);
} else if (Jsi_ValueIsBoolean(interp, ret)) {
Jsi_GetBoolFromValue(interp, ret, &b);
sqlite3_result_int(context, b);
} else if (Jsi_ValueIsNumber(interp, ret)) {
Jsi_Number d;
// if (Jsi_GetIntFromValueBase(interp, ret, &i, 0, JSI_NO_ERRMSG);
// sqlite3_result_int64(context, v);
Jsi_GetNumberFromValue(interp, ret, &d);
sqlite3_result_double(context, (double)d);
} else {
const char * data;
if (!(data = Jsi_ValueGetStringLen(interp, ret, &i))) {
//TODO: handle objects???
data = Jsi_ValueToString(interp, ret, NULL);
i = Jsi_Strlen(data);
}
sqlite3_result_text(context, (char *)data, i, SQLITE_TRANSIENT );
}
Jsi_DecrRefCount(interp, ret);
} | CWE-120 | 44 |
static VALUE from_document(VALUE klass, VALUE document)
{
xmlDocPtr doc;
xmlRelaxNGParserCtxtPtr ctx;
xmlRelaxNGPtr schema;
VALUE errors;
VALUE rb_schema;
Data_Get_Struct(document, xmlDoc, doc);
/* In case someone passes us a node. ugh. */
doc = doc->doc;
ctx = xmlRelaxNGNewDocParserCtxt(doc);
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
xmlRelaxNGSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlRelaxNGParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlRelaxNGFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
return rb_schema;
} | CWE-611 | 13 |
static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zval *arg1;
zend_error_handling error_handling;
if (!file_path || !file_path_len) {
#if defined(PHP_WIN32)
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path");
if (file_path && !use_copy) {
efree(file_path);
}
#else
if (file_path && !use_copy) {
efree(file_path);
}
file_path_len = 1;
file_path = "/";
#endif
return NULL;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return intern;
} /* }}} */ | CWE-190 | 19 |
resolve_op_from_commit (FlatpakTransaction *self,
FlatpakTransactionOperation *op,
const char *checksum,
GFile *sideload_path,
GVariant *commit_data)
{
g_autoptr(GBytes) metadata_bytes = NULL;
g_autoptr(GVariant) commit_metadata = NULL;
const char *xa_metadata = NULL;
guint64 download_size = 0;
guint64 installed_size = 0;
commit_metadata = g_variant_get_child_value (commit_data, 0);
g_variant_lookup (commit_metadata, "xa.metadata", "&s", &xa_metadata);
if (xa_metadata == NULL)
g_message ("Warning: No xa.metadata in local commit %s ref %s", checksum, flatpak_decomposed_get_ref (op->ref));
else
metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));
if (g_variant_lookup (commit_metadata, "xa.download-size", "t", &download_size))
op->download_size = GUINT64_FROM_BE (download_size);
if (g_variant_lookup (commit_metadata, "xa.installed-size", "t", &installed_size))
op->installed_size = GUINT64_FROM_BE (installed_size);
g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE, "s", &op->eol);
g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE_REBASE, "s", &op->eol_rebase);
resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);
} | CWE-276 | 45 |
check_restricted(void)
{
if (restricted)
{
emsg(_("E145: Shell commands not allowed in rvim"));
return TRUE;
}
return FALSE;
} | CWE-78 | 6 |
int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) {
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
} | CWE-476 | 46 |
process_plane(uint8 * in, int width, int height, uint8 * out, int size)
{
UNUSED(size);
int indexw;
int indexh;
int code;
int collen;
int replen;
int color;
int x;
int revcode;
uint8 * last_line;
uint8 * this_line;
uint8 * org_in;
uint8 * org_out;
org_in = in;
org_out = out;
last_line = 0;
indexh = 0;
while (indexh < height)
{
out = (org_out + width * height * 4) - ((indexh + 1) * width * 4);
color = 0;
this_line = out;
indexw = 0;
if (last_line == 0)
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
color = CVAL(in);
*out = color;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
*out = color;
out += 4;
indexw++;
replen--;
}
}
}
else
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
x = CVAL(in);
if (x & 1)
{
x = x >> 1;
x = x + 1;
color = -x;
}
else
{
x = x >> 1;
color = x;
}
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
replen--;
}
}
}
indexh++;
last_line = this_line;
}
return (int) (in - org_in);
} | CWE-191 | 55 |
void AV1_RewriteESDescriptorEx(GF_MPEGVisualSampleEntryBox *av1, GF_MediaBox *mdia)
{
GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)av1, GF_FALSE);
if (av1->emul_esd) gf_odf_desc_del((GF_Descriptor *)av1->emul_esd);
av1->emul_esd = gf_odf_desc_esd_new(2);
av1->emul_esd->decoderConfig->streamType = GF_STREAM_VISUAL;
av1->emul_esd->decoderConfig->objectTypeIndication = GF_CODECID_AV1;
if (btrt) {
av1->emul_esd->decoderConfig->bufferSizeDB = btrt->bufferSizeDB;
av1->emul_esd->decoderConfig->avgBitrate = btrt->avgBitrate;
av1->emul_esd->decoderConfig->maxBitrate = btrt->maxBitrate;
}
if (av1->av1_config) {
GF_AV1Config *av1_cfg = AV1_DuplicateConfig(av1->av1_config->config);
if (av1_cfg) {
gf_odf_av1_cfg_write(av1_cfg, &av1->emul_esd->decoderConfig->decoderSpecificInfo->data, &av1->emul_esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_odf_av1_cfg_del(av1_cfg);
}
}
} | CWE-476 | 46 |
void cJSON_AddItemToObject( cJSON *object, const char *string, cJSON *item )
{
if ( ! item )
return;
if ( item->string )
cJSON_free( item->string );
item->string = cJSON_strdup( string );
cJSON_AddItemToArray( object, item );
} | CWE-120 | 44 |
arg(identifier arg, expr_ty annotation, int lineno, int col_offset, int
end_lineno, int end_col_offset, PyArena *arena)
{
arg_ty p;
if (!arg) {
PyErr_SetString(PyExc_ValueError,
"field arg is required for arg");
return NULL;
}
p = (arg_ty)PyArena_Malloc(arena, sizeof(*p));
if (!p)
return NULL;
p->arg = arg;
p->annotation = annotation;
p->lineno = lineno;
p->col_offset = col_offset;
p->end_lineno = end_lineno;
p->end_col_offset = end_col_offset;
return p;
} | CWE-125 | 47 |
isoclns_print(netdissect_options *ndo,
const uint8_t *p, u_int length, u_int caplen)
{
if (caplen <= 1) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (caplen > 1)
print_unknown_data(ndo, p, "\n\t", caplen);
break;
}
} | CWE-125 | 47 |
void set_module_sig_enforced(void)
{
sig_enforce = true;
} | CWE-347 | 25 |
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 |
void gitn_box_del(GF_Box *s)
{
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *)s;
if (ptr == NULL) return;
for (i=0; i<ptr->nb_entries; i++) {
if (ptr->entries[i].name) gf_free(ptr->entries[i].name);
}
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr); | CWE-476 | 46 |
ast_for_atom_expr(struct compiling *c, const node *n)
{
int i, nch, start = 0;
expr_ty e, tmp;
REQ(n, atom_expr);
nch = NCH(n);
if (TYPE(CHILD(n, 0)) == AWAIT) {
if (c->c_feature_version < 5) {
ast_error(c, n,
"Await expressions are only supported in Python 3.5 and greater");
return NULL;
}
start = 1;
assert(nch > 1);
}
e = ast_for_atom(c, CHILD(n, start));
if (!e)
return NULL;
if (nch == 1)
return e;
if (start && nch == 2) {
return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
}
for (i = start + 1; i < nch; i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) != trailer)
break;
tmp = ast_for_trailer(c, ch, e);
if (!tmp)
return NULL;
tmp->lineno = e->lineno;
tmp->col_offset = e->col_offset;
e = tmp;
}
if (start) {
/* there was an AWAIT */
return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
return e;
}
} | CWE-125 | 47 |
linkaddr_string(netdissect_options *ndo, const u_char *ep,
const unsigned int type, const unsigned int len)
{
register u_int i;
register char *cp;
register struct enamemem *tp;
if (len == 0)
return ("<empty>");
if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN)
return (etheraddr_string(ndo, ep));
if (type == LINKADDR_FRELAY)
return (q922_string(ndo, ep, len));
tp = lookup_bytestring(ndo, ep, len);
if (tp->e_name)
return (tp->e_name);
tp->e_name = cp = (char *)malloc(len*3);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo, "linkaddr_string: malloc");
*cp++ = hex[*ep >> 4];
*cp++ = hex[*ep++ & 0xf];
for (i = len-1; i > 0 ; --i) {
*cp++ = ':';
*cp++ = hex[*ep >> 4];
*cp++ = hex[*ep++ & 0xf];
}
*cp = '\0';
return (tp->e_name);
} | CWE-125 | 47 |
static bool vgacon_scroll(struct vc_data *c, unsigned int t, unsigned int b,
enum con_scroll dir, unsigned int lines)
{
unsigned long oldo;
unsigned int delta;
if (t || b != c->vc_rows || vga_is_gfx || c->vc_mode != KD_TEXT)
return false;
if (!vga_hardscroll_enabled || lines >= c->vc_rows / 2)
return false;
vgacon_restore_screen(c);
oldo = c->vc_origin;
delta = lines * c->vc_size_row;
if (dir == SM_UP) {
vgacon_scrollback_update(c, t, lines);
if (c->vc_scr_end + delta >= vga_vram_end) {
scr_memcpyw((u16 *) vga_vram_base,
(u16 *) (oldo + delta),
c->vc_screenbuf_size - delta);
c->vc_origin = vga_vram_base;
vga_rolled_over = oldo - vga_vram_base;
} else
c->vc_origin += delta;
scr_memsetw((u16 *) (c->vc_origin + c->vc_screenbuf_size -
delta), c->vc_video_erase_char,
delta);
} else {
if (oldo - delta < vga_vram_base) {
scr_memmovew((u16 *) (vga_vram_end -
c->vc_screenbuf_size +
delta), (u16 *) oldo,
c->vc_screenbuf_size - delta);
c->vc_origin = vga_vram_end - c->vc_screenbuf_size;
vga_rolled_over = 0;
} else
c->vc_origin -= delta;
c->vc_scr_end = c->vc_origin + c->vc_screenbuf_size;
scr_memsetw((u16 *) (c->vc_origin), c->vc_video_erase_char,
delta);
}
c->vc_scr_end = c->vc_origin + c->vc_screenbuf_size;
c->vc_visible_origin = c->vc_origin;
vga_set_mem_top(c);
c->vc_pos = (c->vc_pos - oldo) + c->vc_origin;
return true;
} | CWE-125 | 47 |
static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
} | CWE-125 | 47 |
static const char *parse_string( cJSON *item, const char *str )
{
const char *ptr = str + 1;
char *ptr2;
char *out;
int len = 0;
unsigned uc, uc2;
if ( *str != '\"' ) {
/* Not a string! */
ep = str;
return 0;
}
/* Skip escaped quotes. */
while ( *ptr != '\"' && *ptr && ++len )
if ( *ptr++ == '\\' )
ptr++;
if ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) )
return 0;
ptr = str + 1;
ptr2 = out;
while ( *ptr != '\"' && *ptr ) {
if ( *ptr != '\\' )
*ptr2++ = *ptr++;
else {
ptr++;
switch ( *ptr ) {
case 'b': *ptr2++ ='\b'; break;
case 'f': *ptr2++ ='\f'; break;
case 'n': *ptr2++ ='\n'; break;
case 'r': *ptr2++ ='\r'; break;
case 't': *ptr2++ ='\t'; break;
case 'u':
/* Transcode utf16 to utf8. */
/* Get the unicode char. */
sscanf( ptr + 1,"%4x", &uc );
ptr += 4;
/* Check for invalid. */
if ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 )
break;
/* UTF16 surrogate pairs. */
if ( uc >= 0xD800 && uc <= 0xDBFF ) {
if ( ptr[1] != '\\' || ptr[2] != 'u' )
/* Missing second-half of surrogate. */
break;
sscanf( ptr + 3, "%4x", &uc2 );
ptr += 6;
if ( uc2 < 0xDC00 || uc2 > 0xDFFF )
/* Invalid second-half of surrogate. */
break;
uc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF );
}
len = 4;
if ( uc < 0x80 )
len = 1;
else if ( uc < 0x800 )
len = 2;
else if ( uc < 0x10000 )
len = 3;
ptr2 += len;
switch ( len ) {
case 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;
case 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;
case 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6;
case 1: *--ptr2 = ( uc | firstByteMark[len] );
}
ptr2 += len;
break;
default: *ptr2++ = *ptr; break;
}
++ptr;
}
}
*ptr2 = 0;
if ( *ptr == '\"' )
++ptr;
item->valuestring = out;
item->type = cJSON_String;
return ptr;
} | CWE-120 | 44 |
static pyc_object *get_tuple_object(RBuffer *buffer) {
pyc_object *ret = NULL;
bool error = false;
ut32 n = 0;
n = get_ut32 (buffer, &error);
if (n > ST32_MAX) {
eprintf ("bad marshal data (tuple size out of range)\n");
return NULL;
}
if (error) {
return NULL;
}
ret = get_array_object_generic (buffer, n);
if (ret) {
ret->type = TYPE_TUPLE;
return ret;
}
return NULL;
} | CWE-825 | 64 |
static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files,
rpmpsm psm, int nodigest, int *setmeta,
int * firsthardlink)
{
int rc = 0;
int numHardlinks = rpmfiFNlink(fi);
if (numHardlinks > 1) {
/* Create first hardlinked file empty */
if (*firsthardlink < 0) {
*firsthardlink = rpmfiFX(fi);
rc = expandRegular(fi, dest, psm, nodigest, 1);
} else {
/* Create hard links for others */
char *fn = rpmfilesFN(files, *firsthardlink);
rc = link(fn, dest);
if (rc < 0) {
rc = RPMERR_LINK_FAILED;
}
free(fn);
}
}
/* Write normal files or fill the last hardlinked (already
existing) file with content */
if (numHardlinks<=1) {
if (!rc)
rc = expandRegular(fi, dest, psm, nodigest, 0);
} else if (rpmfiArchiveHasContent(fi)) {
if (!rc)
rc = expandRegular(fi, dest, psm, nodigest, 0);
*firsthardlink = -1;
} else {
*setmeta = 0;
}
return rc;
} | CWE-59 | 36 |
ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* funcdef: 'def' NAME parameters ['->' test] ':' suite */
return ast_for_funcdef_impl(c, n, decorator_seq,
0 /* is_async */);
} | CWE-125 | 47 |
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 |
static punycode_uint decode_digit(punycode_uint cp)
{
return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 :
cp - 97 < 26 ? cp - 97 : base;
} | CWE-190 | 19 |
string_object_to_c_ast(const char *s, PyObject *filename, int start,
PyCompilerFlags *flags, int feature_version,
PyArena *arena)
{
mod_ty mod;
PyCompilerFlags localflags;
perrdetail err;
int iflags = PARSER_FLAGS(flags);
node *n = Ta3Parser_ParseStringObject(s, filename,
&_Ta3Parser_Grammar, start, &err,
&iflags);
if (flags == NULL) {
localflags.cf_flags = 0;
flags = &localflags;
}
if (n) {
flags->cf_flags |= iflags & PyCF_MASK;
mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena);
Ta3Node_Free(n);
}
else {
err_input(&err);
mod = NULL;
}
err_free(&err);
return mod;
} | CWE-125 | 47 |
static void bpf_adj_branches(struct bpf_prog *prog, u32 pos, u32 delta)
{
struct bpf_insn *insn = prog->insnsi;
u32 i, insn_cnt = prog->len;
bool pseudo_call;
u8 code;
int off;
for (i = 0; i < insn_cnt; i++, insn++) {
code = insn->code;
if (BPF_CLASS(code) != BPF_JMP)
continue;
if (BPF_OP(code) == BPF_EXIT)
continue;
if (BPF_OP(code) == BPF_CALL) {
if (insn->src_reg == BPF_PSEUDO_CALL)
pseudo_call = true;
else
continue;
} else {
pseudo_call = false;
}
off = pseudo_call ? insn->imm : insn->off;
/* Adjust offset of jmps if we cross boundaries. */
if (i < pos && i + off + 1 > pos)
off += delta;
else if (i > pos + delta && i + off + 1 <= pos + delta)
off -= delta;
if (pseudo_call)
insn->imm = off;
else
insn->off = off;
}
} | CWE-120 | 44 |
spnego_gss_wrap_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov_length(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
} | CWE-763 | 61 |
static int msg_parse_fetch (IMAP_HEADER *h, char *s)
{
char tmp[SHORT_STRING];
char *ptmp;
if (!s)
return -1;
while (*s)
{
SKIPWS (s);
if (ascii_strncasecmp ("FLAGS", s, 5) == 0)
{
if ((s = msg_parse_flags (h, s)) == NULL)
return -1;
}
else if (ascii_strncasecmp ("UID", s, 3) == 0)
{
s += 3;
SKIPWS (s);
if (mutt_atoui (s, &h->data->uid) < 0)
return -1;
s = imap_next_word (s);
}
else if (ascii_strncasecmp ("INTERNALDATE", s, 12) == 0)
{
s += 12;
SKIPWS (s);
if (*s != '\"')
{
dprint (1, (debugfile, "msg_parse_fetch(): bogus INTERNALDATE entry: %s\n", s));
return -1;
}
s++;
ptmp = tmp;
while (*s && *s != '\"')
*ptmp++ = *s++;
if (*s != '\"')
return -1;
s++; /* skip past the trailing " */
*ptmp = 0;
h->received = imap_parse_date (tmp);
}
else if (ascii_strncasecmp ("RFC822.SIZE", s, 11) == 0)
{
s += 11;
SKIPWS (s);
ptmp = tmp;
while (isdigit ((unsigned char) *s))
*ptmp++ = *s++;
*ptmp = 0;
if (mutt_atol (tmp, &h->content_length) < 0)
return -1;
}
else if (!ascii_strncasecmp ("BODY", s, 4) ||
!ascii_strncasecmp ("RFC822.HEADER", s, 13))
{
/* handle above, in msg_fetch_header */
return -2;
}
else if (*s == ')')
s++; /* end of request */
else if (*s)
{
/* got something i don't understand */
imap_error ("msg_parse_fetch", s);
return -1;
}
}
return 0;
} | CWE-787 | 24 |
int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
} else {
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
write = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
if (value != NULL) {
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
write = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
} | CWE-190 | 19 |
static struct phy *serdes_simple_xlate(struct device *dev,
struct of_phandle_args *args)
{
struct serdes_ctrl *ctrl = dev_get_drvdata(dev);
unsigned int port, idx, i;
if (args->args_count != 2)
return ERR_PTR(-EINVAL);
port = args->args[0];
idx = args->args[1];
for (i = 0; i <= SERDES_MAX; i++) {
struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]);
if (idx != macro->idx)
continue;
/* SERDES6G(0) is the only SerDes capable of QSGMII */
if (idx != SERDES6G(0) && macro->port >= 0)
return ERR_PTR(-EBUSY);
macro->port = port;
return ctrl->phys[i];
}
return ERR_PTR(-ENODEV);
} | CWE-125 | 47 |
cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/')
separator = *src++;
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
} | CWE-22 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.