code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
int mount_proc_if_needed(const char *rootfs) { char path[MAXPATHLEN]; char link[20]; int linklen, ret; int mypid; ret = snprintf(path, MAXPATHLEN, "%s/proc/self", rootfs); if (ret < 0 || ret >= MAXPATHLEN) { SYSERROR("proc path name too long"); return -1; } memset(link, 0, 20); linklen = readlink(path, link, 20); mypid = (int)getpid(); INFO("I am %d, /proc/self points to '%s'", mypid, link); ret = snprintf(path, MAXPATHLEN, "%s/proc", rootfs); if (ret < 0 || ret >= MAXPATHLEN) { SYSERROR("proc path name too long"); return -1; } if (linklen < 0) /* /proc not mounted */ goto domount; if (atoi(link) != mypid) { /* wrong /procs mounted */ umount2(path, MNT_DETACH); /* ignore failure */ goto domount; } /* the right proc is already mounted */ return 0; domount: if (mount("proc", path, "proc", 0, NULL)) return -1; INFO("Mounted /proc in container for security transition"); return 1; }
CWE-59
36
static int kvaser_usb_leaf_set_opt_mode(const 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_SET_CTRL_MODE; cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_ctrl_mode); cmd->u.ctrl_mode.tid = 0xff; cmd->u.ctrl_mode.channel = priv->channel; if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) cmd->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_SILENT; else cmd->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_NORMAL; rc = kvaser_usb_send_cmd(priv->dev, cmd, cmd->len); kfree(cmd); return rc; }
CWE-908
48
IPV6DefragReverseSimpleTest(void) { DefragContext *dc = NULL; Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p3, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p1, NULL); if (reassembled == NULL) goto end; /* 40 bytes in we should find 8 bytes of A. */ for (i = 40; i < 40 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 48; i < 48 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 56; i < 56 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; }
CWE-358
50
static int mcryptd_create_hash(struct crypto_template *tmpl, struct rtattr **tb, struct mcryptd_queue *queue) { struct hashd_instance_ctx *ctx; struct ahash_instance *inst; struct hash_alg_common *halg; struct crypto_alg *alg; u32 type = 0; u32 mask = 0; int err; mcryptd_check_internal(tb, &type, &mask); halg = ahash_attr_alg(tb[1], type, mask); if (IS_ERR(halg)) return PTR_ERR(halg); alg = &halg->base; pr_debug("crypto: mcryptd hash alg: %s\n", alg->cra_name); inst = mcryptd_alloc_instance(alg, ahash_instance_headroom(), sizeof(*ctx)); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; ctx = ahash_instance_ctx(inst); ctx->queue = queue; err = crypto_init_ahash_spawn(&ctx->spawn, halg, ahash_crypto_instance(inst)); if (err) goto out_free_inst; type = CRYPTO_ALG_ASYNC; if (alg->cra_flags & CRYPTO_ALG_INTERNAL) type |= CRYPTO_ALG_INTERNAL; inst->alg.halg.base.cra_flags = type; inst->alg.halg.digestsize = halg->digestsize; inst->alg.halg.statesize = halg->statesize; inst->alg.halg.base.cra_ctxsize = sizeof(struct mcryptd_hash_ctx); inst->alg.halg.base.cra_init = mcryptd_hash_init_tfm; inst->alg.halg.base.cra_exit = mcryptd_hash_exit_tfm; inst->alg.init = mcryptd_hash_init_enqueue; inst->alg.update = mcryptd_hash_update_enqueue; inst->alg.final = mcryptd_hash_final_enqueue; inst->alg.finup = mcryptd_hash_finup_enqueue; inst->alg.export = mcryptd_hash_export; inst->alg.import = mcryptd_hash_import; inst->alg.setkey = mcryptd_hash_setkey; inst->alg.digest = mcryptd_hash_digest_enqueue; err = ahash_register_instance(tmpl, inst); if (err) { crypto_drop_ahash(&ctx->spawn); out_free_inst: kfree(inst); } out_put_alg: crypto_mod_put(alg); return err; }
CWE-476
46
LogLuvClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* * For consistency, we always want to write out the same * bitspersample and sampleformat for our TIFF file, * regardless of the data format being used by the application. * Since this routine is called after tags have been set but * before they have been recorded in the file, we reset them here. */ td->td_samplesperpixel = (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3; td->td_bitspersample = 16; td->td_sampleformat = SAMPLEFORMAT_INT; }
CWE-125
47
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-125
47
static RList *r_bin_wasm_get_data_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmDataEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; size_t n = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmDataEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(n = consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } ptr->offset.len = n; if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) { free (ptr); return ret; } ptr->data = sec->payload_data + i; r_list_append (ret, ptr); r += 1; } return ret; }
CWE-125
47
const char *cJSON_GetErrorPtr( void ) { return ep; }
CWE-120
44
static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } }
CWE-190
19
static CURLcode pop3_parse_url_path(struct connectdata *conn) { /* the pop3 struct is already inited in pop3_connect() */ struct pop3_conn *pop3c = &conn->proto.pop3c; struct SessionHandle *data = conn->data; const char *path = data->state.path; /* url decode the path and use this mailbox */ pop3c->mailbox = curl_easy_unescape(data, path, 0, NULL); if(!pop3c->mailbox) return CURLE_OUT_OF_MEMORY; return CURLE_OK; }
CWE-89
0
static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si) { s32 pps_id; /*s->current_picture.reference= h->nal_ref_idc != 0;*/ gf_bs_read_ue_log(bs, "first_mb_in_slice"); si->slice_type = gf_bs_read_ue_log(bs, "slice_type"); if (si->slice_type > 9) return -1; pps_id = gf_bs_read_ue_log(bs, "pps_id"); if (pps_id > 255) return -1; si->pps = &avc->pps[pps_id]; si->pps->id = pps_id; if (!si->pps->slice_group_count) return -2; si->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT]; if (!si->sps->log2_max_frame_num) return -2; si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, "frame_num"); si->field_pic_flag = 0; if (si->sps->frame_mbs_only_flag) { /*s->picture_structure= PICT_FRAME;*/ } else { si->field_pic_flag = gf_bs_read_int_log(bs, 1, "field_pic_flag"); if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, "bottom_field_flag"); } if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag) si->idr_pic_id = gf_bs_read_ue_log(bs, "idr_pic_id"); if (si->sps->poc_type == 0) { si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, "poc_lsb"); if (si->pps->pic_order_present && !si->field_pic_flag) { si->delta_poc_bottom = gf_bs_read_se_log(bs, "delta_poc_bottom"); } } else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) { si->delta_poc[0] = gf_bs_read_se_log(bs, "delta_poc0"); if ((si->pps->pic_order_present == 1) && !si->field_pic_flag) si->delta_poc[1] = gf_bs_read_se_log(bs, "delta_poc1"); } if (si->pps->redundant_pic_cnt_present) { si->redundant_pic_cnt = gf_bs_read_ue_log(bs, "redundant_pic_cnt"); } return 0; }
CWE-120
44
static int list_devices(struct file *filp, struct dm_ioctl *param, size_t param_size) { unsigned int i; struct hash_cell *hc; size_t len, needed = 0; struct gendisk *disk; struct dm_name_list *orig_nl, *nl, *old_nl = NULL; uint32_t *event_nr; down_write(&_hash_lock); /* * Loop through all the devices working out how much * space we need. */ for (i = 0; i < NUM_BUCKETS; i++) { list_for_each_entry (hc, _name_buckets + i, name_list) { needed += align_val(offsetof(struct dm_name_list, name) + strlen(hc->name) + 1); needed += align_val(sizeof(uint32_t)); } } /* * Grab our output buffer. */ nl = orig_nl = get_result_buffer(param, param_size, &len); if (len < needed) { param->flags |= DM_BUFFER_FULL_FLAG; goto out; } param->data_size = param->data_start + needed; nl->dev = 0; /* Flags no data */ /* * Now loop through filling out the names. */ for (i = 0; i < NUM_BUCKETS; i++) { list_for_each_entry (hc, _name_buckets + i, name_list) { if (old_nl) old_nl->next = (uint32_t) ((void *) nl - (void *) old_nl); disk = dm_disk(hc->md); nl->dev = huge_encode_dev(disk_devt(disk)); nl->next = 0; strcpy(nl->name, hc->name); old_nl = nl; event_nr = align_ptr(nl->name + strlen(hc->name) + 1); *event_nr = dm_get_event_nr(hc->md); nl = align_ptr(event_nr + 1); } } /* * If mismatch happens, security may be compromised due to buffer * overflow, so it's better to crash. */ BUG_ON((char *)nl - (char *)orig_nl != needed); out: up_write(&_hash_lock); return 0; }
CWE-787
24
MONGO_EXPORT void __mongo_set_error( mongo *conn, mongo_error_t err, const char *str, int errcode ) { int errstr_size, str_size; conn->err = err; conn->errcode = errcode; if( str ) { str_size = strlen( str ) + 1; errstr_size = str_size > MONGO_ERR_LEN ? MONGO_ERR_LEN : str_size; memcpy( conn->errstr, str, errstr_size ); conn->errstr[errstr_size-1] = '\0'; } }
CWE-190
19
static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer) { struct k_itimer *timr; unsigned long flags; int si_private = 0; enum hrtimer_restart ret = HRTIMER_NORESTART; timr = container_of(timer, struct k_itimer, it.real.timer); spin_lock_irqsave(&timr->it_lock, flags); timr->it_active = 0; if (timr->it_interval != 0) si_private = ++timr->it_requeue_pending; if (posix_timer_event(timr, si_private)) { /* * signal was not sent because of sig_ignor * we will not get a call back to restart it AND * it should be restarted. */ if (timr->it_interval != 0) { ktime_t now = hrtimer_cb_get_time(timer); /* * FIXME: What we really want, is to stop this * timer completely and restart it in case the * SIG_IGN is removed. This is a non trivial * change which involves sighand locking * (sigh !), which we don't want to do late in * the release cycle. * * For now we just let timers with an interval * less than a jiffie expire every jiffie to * avoid softirq starvation in case of SIG_IGN * and a very small interval, which would put * the timer right back on the softirq pending * list. By moving now ahead of time we trick * hrtimer_forward() to expire the timer * later, while we still maintain the overrun * accuracy, but have some inconsistency in * the timer_gettime() case. This is at least * better than a starved softirq. A more * complex fix which solves also another related * inconsistency is already in the pipeline. */ #ifdef CONFIG_HIGH_RES_TIMERS { ktime_t kj = NSEC_PER_SEC / HZ; if (timr->it_interval < kj) now = ktime_add(now, kj); } #endif timr->it_overrun += (unsigned int) hrtimer_forward(timer, now, timr->it_interval); ret = HRTIMER_RESTART; ++timr->it_requeue_pending; timr->it_active = 1; } } unlock_timer(timr, flags); return ret; }
CWE-190
19
static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize) { /* If this function is being called, the buffer should not have been initialized yet. */ assert(!stream->bufbase_); if (bufmode != JAS_STREAM_UNBUF) { /* The full- or line-buffered mode is being employed. */ if (!buf) { /* The caller has not specified a buffer to employ, so allocate one. */ if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + JAS_STREAM_MAXPUTBACK))) { stream->bufmode_ |= JAS_STREAM_FREEBUF; stream->bufsize_ = JAS_STREAM_BUFSIZE; } else { /* The buffer allocation has failed. Resort to unbuffered operation. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } } else { /* The caller has specified a buffer to employ. */ /* The buffer must be large enough to accommodate maximum putback. */ assert(bufsize > JAS_STREAM_MAXPUTBACK); stream->bufbase_ = JAS_CAST(uchar *, buf); stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; } } else { /* The unbuffered mode is being employed. */ /* A buffer should not have been supplied by the caller. */ assert(!buf); /* Use a trivial one-character buffer. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; stream->ptr_ = stream->bufstart_; stream->cnt_ = 0; stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; }
CWE-190
19
hb_set_clear (hb_set_t *set) { if (unlikely (hb_object_is_immutable (set))) return; set->clear (); }
CWE-787
24
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, 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 isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; }
CWE-835
42
WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ ctx->commaNeeded[++ctx->depth] = false; return writeChar(ctx, '['); }
CWE-787
24
static int jas_iccputsint(jas_stream_t *out, int n, longlong val) { ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); }
CWE-190
19
static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx, struct iw_exif_state *e, iw_uint32 ifd) { unsigned int tag_count; unsigned int i; unsigned int tag_pos; unsigned int tag_id; unsigned int v; double v_dbl; if(ifd<8 || ifd>e->d_len-18) return; tag_count = iw_get_ui16_e(&e->d[ifd],e->endian); if(tag_count>1000) return; // Sanity check. for(i=0;i<tag_count;i++) { tag_pos = ifd+2+i*12; if(tag_pos+12 > e->d_len) return; // Avoid overruns. tag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian); switch(tag_id) { case 274: // 274 = Orientation if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_orientation = v; } break; case 296: // 296 = ResolutionUnit if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_density_unit = v; } break; case 282: // 282 = XResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_x = v_dbl; } break; case 283: // 283 = YResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_y = v_dbl; } break; } } }
CWE-125
47
read_old_length(cdk_stream_t inp, int ctb, size_t * r_len, size_t * r_size) { int llen = ctb & 0x03; if (llen == 0) { *r_len = cdk_stream_getc(inp); (*r_size)++; } else if (llen == 1) { *r_len = read_16(inp); (*r_size) += 2; } else if (llen == 2) { *r_len = read_32(inp); (*r_size) += 4; } else { *r_len = 0; *r_size = 0; } }
CWE-125
47
void luaD_call (lua_State *L, StkId func, int nresults) { lua_CFunction f; retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ f = clCvalue(s2v(func))->f; goto Cfunc; case LUA_VLCF: /* light C function */ f = fvalue(s2v(func)); Cfunc: { int n; /* number of returns */ CallInfo *ci = next_ci(L); checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ ci->nresults = nresults; ci->callstatus = CIST_C; ci->top = L->top + LUA_MINSTACK; ci->func = func; L->ci = ci; lua_assert(ci->top <= L->stack_last); if (L->hookmask & LUA_MASKCALL) { int narg = cast_int(L->top - func) - 1; luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); } lua_unlock(L); n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); luaD_poscall(L, ci, n); break; } case LUA_VLCL: { /* Lua function */ CallInfo *ci = next_ci(L); Proto *p = clLvalue(s2v(func))->p; int narg = cast_int(L->top - func) - 1; /* number of real arguments */ int nfixparams = p->numparams; int fsize = p->maxstacksize; /* frame size */ checkstackp(L, fsize, func); ci->nresults = nresults; ci->u.l.savedpc = p->code; /* starting point */ ci->callstatus = 0; ci->top = func + 1 + fsize; ci->func = func; L->ci = ci; for (; narg < nfixparams; narg++) setnilvalue(s2v(L->top++)); /* complete missing arguments */ lua_assert(ci->top <= L->stack_last); luaV_execute(L, ci); /* run the function */ break; } default: { /* not a function */ checkstackp(L, 1, func); /* space for metamethod */ luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ goto retry; /* try again with metamethod */ } } }
CWE-787
24
static int do_i2c_read(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]) { uint chip; uint devaddr, length; int alen; u_char *memaddr; int ret; #if CONFIG_IS_ENABLED(DM_I2C) struct udevice *dev; #endif if (argc != 5) return CMD_RET_USAGE; /* * I2C chip address */ chip = hextoul(argv[1], NULL); /* * I2C data address within the chip. This can be 1 or * 2 bytes long. Some day it might be 3 bytes long :-). */ devaddr = hextoul(argv[2], NULL); alen = get_alen(argv[2], DEFAULT_ADDR_LEN); if (alen > 3) return CMD_RET_USAGE; /* * Length is the number of objects, not number of bytes. */ length = hextoul(argv[3], NULL); /* * memaddr is the address where to store things in memory */ memaddr = (u_char *)hextoul(argv[4], NULL); #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) ret = dm_i2c_read(dev, devaddr, memaddr, length); #else ret = i2c_read(chip, devaddr, alen, memaddr, length); #endif if (ret) return i2c_report_err(ret, I2C_ERR_READ); return 0; }
CWE-787
24
int build_segment_manager(struct f2fs_sb_info *sbi) { struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); struct f2fs_sm_info *sm_info; int err; sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL); if (!sm_info) return -ENOMEM; /* init sm info */ sbi->sm_info = sm_info; sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr); sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr); sm_info->segment_count = le32_to_cpu(raw_super->segment_count); sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main); sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr); sm_info->rec_prefree_segments = sm_info->main_segments * DEF_RECLAIM_PREFREE_SEGMENTS / 100; if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS) sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS; if (!test_opt(sbi, LFS)) sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC; sm_info->min_ipu_util = DEF_MIN_IPU_UTIL; sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS; sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS; sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS; INIT_LIST_HEAD(&sm_info->sit_entry_set); if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) { err = create_flush_cmd_control(sbi); if (err) return err; } err = create_discard_cmd_control(sbi); if (err) return err; err = build_sit_info(sbi); if (err) return err; err = build_free_segmap(sbi); if (err) return err; err = build_curseg(sbi); if (err) return err; /* reinit free segmap based on SIT */ build_sit_entries(sbi); init_free_segmap(sbi); err = build_dirty_segmap(sbi); if (err) return err; init_min_max_mtime(sbi); return 0; }
CWE-476
46
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns) { int r; static const char resp[] = "<u:%sResponse " "xmlns:u=\"%s\">" "<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>" "</u:%sResponse>"; char body[512]; int bodylen; struct NameValueParserData data; char * int_ip, * int_port, * rem_host, * rem_port, * protocol; int opt=0; /*int proto=0;*/ unsigned short iport, rport; if (GETFLAG(IPV6FCFWDISABLEDMASK)) { SoapError(h, 702, "FirewallDisabled"); return; } ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); int_ip = GetValueFromNameValueList(&data, "InternalClient"); int_port = GetValueFromNameValueList(&data, "InternalPort"); rem_host = GetValueFromNameValueList(&data, "RemoteHost"); rem_port = GetValueFromNameValueList(&data, "RemotePort"); protocol = GetValueFromNameValueList(&data, "Protocol"); if (!int_port || !ext_port || !protocol) { ClearNameValueList(&data); SoapError(h, 402, "Invalid Args"); return; } rport = (unsigned short)atoi(rem_port); iport = (unsigned short)atoi(int_port); /*proto = atoi(protocol);*/ syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol); /* TODO */ r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/ switch(r) { case 1: /* success */ bodylen = snprintf(body, sizeof(body), resp, action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/, opt, action); BuildSendAndCloseSoapResp(h, body, bodylen); break; case -5: /* Protocol not supported */ SoapError(h, 705, "ProtocolNotSupported"); break; default: SoapError(h, 501, "ActionFailed"); } ClearNameValueList(&data); }
CWE-476
46
static VALUE read_memory(VALUE klass, VALUE content) { xmlSchemaPtr schema; xmlSchemaParserCtxtPtr ctx = xmlSchemaNewMemParserCtxt( (const char *)StringValuePtr(content), (int)RSTRING_LEN(content) ); VALUE rb_schema; VALUE errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS xmlSchemaSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif schema = xmlSchemaParse(ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlSchemaFreeParserCtxt(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
MONGO_EXPORT gridfs_offset gridfile_read( gridfile *gfile, gridfs_offset size, char *buf ) { mongo_cursor *chunks; bson chunk; int first_chunk; int last_chunk; int total_chunks; gridfs_offset chunksize; gridfs_offset contentlength; gridfs_offset bytes_left; int i; bson_iterator it; gridfs_offset chunk_len; const char *chunk_data; contentlength = gridfile_get_contentlength( gfile ); chunksize = gridfile_get_chunksize( gfile ); size = ( contentlength - gfile->pos < size ) ? contentlength - gfile->pos : size; bytes_left = size; first_chunk = ( gfile->pos )/chunksize; last_chunk = ( gfile->pos+size-1 )/chunksize; total_chunks = last_chunk - first_chunk + 1; chunks = gridfile_get_chunks( gfile, first_chunk, total_chunks ); for ( i = 0; i < total_chunks; i++ ) { mongo_cursor_next( chunks ); chunk = chunks->current; bson_find( &it, &chunk, "data" ); chunk_len = bson_iterator_bin_len( &it ); chunk_data = bson_iterator_bin_data( &it ); if ( i == 0 ) { chunk_data += ( gfile->pos )%chunksize; chunk_len -= ( gfile->pos )%chunksize; } if ( bytes_left > chunk_len ) { memcpy( buf, chunk_data, chunk_len ); bytes_left -= chunk_len; buf += chunk_len; } else { memcpy( buf, chunk_data, bytes_left ); } } mongo_cursor_destroy( chunks ); gfile->pos = gfile->pos + size; return size; }
CWE-190
19
static void sycc422_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; unsigned int maxw, maxh, max; int offset, upb; unsigned int i, j; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * (size_t)max); d1 = g = (int*)malloc(sizeof(int) * (size_t)max); d2 = b = (int*)malloc(sizeof(int) * (size_t)max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i=0U; i < maxh; ++i) { for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } if (j < maxw) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; #if defined(USE_JPWL) || defined(USE_MJ2) img->comps[1].w = maxw; img->comps[1].h = maxh; img->comps[2].w = maxw; img->comps[2].h = maxh; #else img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh; img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh; #endif img->comps[1].dx = img->comps[0].dx; img->comps[2].dx = img->comps[0].dx; img->comps[1].dy = img->comps[0].dy; img->comps[2].dy = img->comps[0].dy; return; fails: if(r) free(r); if(g) free(g); if(b) free(b); }/* sycc422_to_rgb() */
CWE-125
47
static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); err = -EINVAL; ds = salg->digestsize; ss = salg->statesize; alg = &salg->base; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; }
CWE-787
24
init_normalization(struct compiling *c) { PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); if (!m) return 0; c->c_normalize = PyObject_GetAttrString(m, "normalize"); Py_DECREF(m); if (!c->c_normalize) return 0; c->c_normalize_args = Py_BuildValue("(sN)", "NFKC", Py_None); if (!c->c_normalize_args) { Py_CLEAR(c->c_normalize); return 0; } PyTuple_SET_ITEM(c->c_normalize_args, 1, NULL); return 1; }
CWE-125
47
PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { size_t retlen; char *ret; enum entity_charset charset; const entity_ht *inverse_map = NULL; size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen); if (all) { charset = determine_charset(hint_charset TSRMLS_CC); } else { charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */ } /* don't use LIMIT_ALL! */ if (oldlen > new_size) { /* overflow, refuse to do anything */ ret = estrndup((char*)old, oldlen); retlen = oldlen; goto empty_source; } ret = emalloc(new_size); *ret = '\0'; retlen = oldlen; if (retlen == 0) { goto empty_source; } inverse_map = unescape_inverse_map(all, flags); /* replace numeric entities */ traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset); empty_source: *newlen = retlen; return ret; }
CWE-190
19
zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; }
CWE-190
19
static Jsi_Value *jsi_treeFmtKey(Jsi_MapEntry* h, struct Jsi_MapOpts *opts, int flags) { Jsi_TreeEntry* hPtr = (Jsi_TreeEntry*)h; void *key = Jsi_TreeKeyGet(hPtr); if (opts->keyType == JSI_KEYS_ONEWORD) return Jsi_ValueNewNumber(opts->interp, (Jsi_Number)(intptr_t)key); char nbuf[100]; snprintf(nbuf, sizeof(nbuf), "%p", key); return Jsi_ValueNewStringDup(opts->interp, nbuf); }
CWE-120
44
ast_for_with_stmt(struct compiling *c, const node *n, int is_async) { int i, n_items, nch_minus_type, has_type_comment; asdl_seq *items, *body; string type_comment; if (is_async && c->c_feature_version < 5) { ast_error(c, n, "Async with statements are only supported in Python 3.5 and greater"); return NULL; } REQ(n, with_stmt); has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT; nch_minus_type = NCH(n) - has_type_comment; n_items = (nch_minus_type - 2) / 2; items = _Ta3_asdl_seq_new(n_items, c->c_arena); if (!items) return NULL; for (i = 1; i < nch_minus_type - 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; if (has_type_comment) type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2)); else type_comment = NULL; if (is_async) return AsyncWith(items, body, type_comment, LINENO(n), n->n_col_offset, c->c_arena); else return With(items, body, type_comment, LINENO(n), n->n_col_offset, c->c_arena); }
CWE-125
47
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-125
47
lldpd_alloc_mgmt(int family, void *addrptr, size_t addrsize, u_int32_t iface) { struct lldpd_mgmt *mgmt; log_debug("alloc", "allocate a new management address (family: %d)", family); if (family <= LLDPD_AF_UNSPEC || family >= LLDPD_AF_LAST) { errno = EAFNOSUPPORT; return NULL; } if (addrsize > LLDPD_MGMT_MAXADDRSIZE) { errno = EOVERFLOW; return NULL; } mgmt = calloc(1, sizeof(struct lldpd_mgmt)); if (mgmt == NULL) { errno = ENOMEM; return NULL; } mgmt->m_family = family; assert(addrsize <= LLDPD_MGMT_MAXADDRSIZE); memcpy(&mgmt->m_addr, addrptr, addrsize); mgmt->m_addrsize = addrsize; mgmt->m_iface = iface; return mgmt; }
CWE-617
51
char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. */ if(length == SIZE_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; }
CWE-787
24
SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */
CWE-190
19
static LUA_FUNCTION(openssl_x509_check_email) { X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509"); if (lua_isstring(L, 2)) { const char *email = lua_tostring(L, 2); lua_pushboolean(L, X509_check_email(cert, email, strlen(email), 0)); } else { lua_pushboolean(L, 0); } return 1; }
CWE-295
52
batchCopyElem(batch_obj_t *pDest, batch_obj_t *pSrc) { memcpy(pDest, pSrc, sizeof(batch_obj_t)); }
CWE-772
53
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, 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
uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg, char *buffer) { // Swap data begins 164 chars into data buffer: // offset = deposit function hash + address + address + uint256 uint16_t offset = 4 + (5 * 32); int16_t len = msg->data_length - offset; if (msg->has_data_length && len > 0) { memcpy(buffer, msg->data_initial_chunk.bytes + offset, len); // String length must be < 255 characters return len < 256 ? (uint8_t)len : 0; } return 0; }
CWE-787
24
void imap_quote_string(char *dest, size_t dlen, const char *src) { static const char 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-78
6
static int l2cap_build_conf_req(struct sock *sk, void *data) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_conf_req *req = data; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; void *ptr = req->data; BT_DBG("sk %p", sk); switch (pi->mode) { case L2CAP_MODE_BASIC: if (pi->imtu != L2CAP_DEFAULT_MTU) l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->imtu); break; case L2CAP_MODE_ERTM: rfc.mode = L2CAP_MODE_ERTM; rfc.txwin_size = L2CAP_DEFAULT_RX_WINDOW; rfc.max_transmit = L2CAP_DEFAULT_MAX_RECEIVE; rfc.retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO); rfc.monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO); rfc.max_pdu_size = cpu_to_le16(L2CAP_DEFAULT_MAX_RX_APDU); l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc); break; } /* FIXME: Need actual value of the flush timeout */ //if (flush_to != L2CAP_DEFAULT_FLUSH_TO) // l2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO, 2, pi->flush_to); req->dcid = cpu_to_le16(pi->dcid); req->flags = cpu_to_le16(0); return ptr - data; }
CWE-787
24
static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if ((temp_buffer & 0xffffff00) != 0x100) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer < 0x120) VO++; else if (temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; }
CWE-476
46
evtchn_port_t evtchn_from_irq(unsigned irq) { if (WARN(irq >= nr_irqs, "Invalid irq %d!\n", irq)) return 0; return info_for_irq(irq)->evtchn; }
CWE-476
46
pci_lintr_assert(struct pci_vdev *dev) { assert(dev->lintr.pin > 0); pthread_mutex_lock(&dev->lintr.lock); if (dev->lintr.state == IDLE) { if (pci_lintr_permitted(dev)) { dev->lintr.state = ASSERTED; pci_irq_assert(dev); } else dev->lintr.state = PENDING; } pthread_mutex_unlock(&dev->lintr.lock); }
CWE-617
51
static char* cJSON_strdup( const char* str ) { size_t len; char* copy; len = strlen( str ) + 1; if ( ! ( copy = (char*) cJSON_malloc( len ) ) ) return 0; memcpy( copy, str, len ); return copy; }
CWE-120
44
void unbind_ports(void) { SERVICE_OPTIONS *opt; s_poll_init(fds, 1); CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_SECTIONS]); opt=service_options.next; service_options.next=NULL; service_free(&service_options); while(opt) { unsigned i; s_log(LOG_DEBUG, "Unbinding service [%s]", opt->servname); for(i=0; i<opt->local_addr.num; ++i) unbind_port(opt, i); /* exec+connect service */ if(opt->exec_name && opt->connect_addr.names) { /* create exec+connect services */ /* FIXME: this is just a crude workaround */ /* is it better to kill the service? */ /* FIXME: this won't work with FORK threads */ opt->option.retry=0; } /* purge session cache of the old SSL_CTX object */ /* this workaround won't be needed anymore after */ /* delayed deallocation calls SSL_CTX_free() */ if(opt->ctx) SSL_CTX_flush_sessions(opt->ctx, (long)time(NULL)+opt->session_timeout+1); s_log(LOG_DEBUG, "Service [%s] closed", opt->servname); { SERVICE_OPTIONS *garbage=opt; opt=opt->next; garbage->next=NULL; service_free(garbage); } } CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SECTIONS]); }
CWE-295
52
int ecall_answer(struct ecall *ecall, enum icall_call_type call_type, bool audio_cbr) { int err = 0; if (!ecall) return EINVAL; #ifdef ECALL_CBR_ALWAYS_ON audio_cbr = true; #endif info("ecall(%p): answer on pending econn %p call_type=%d\n", ecall, ecall->econn, call_type); if (!ecall->econn) { warning("ecall: answer: econn does not exist!\n"); return ENOENT; } if (ECONN_PENDING_INCOMING != econn_current_state(ecall->econn)) { info("ecall(%p): answer: invalid state (%s)\n", ecall, econn_state_name(econn_current_state(ecall->econn))); return EPROTO; } if (!ecall->flow) { warning("ecall: answer: no mediaflow\n"); return EPROTO; } ecall->call_type = call_type; IFLOW_CALL(ecall->flow, set_call_type, call_type); ecall->audio_cbr = audio_cbr; IFLOW_CALL(ecall->flow, set_audio_cbr, audio_cbr); #if 0 if (ecall->props_local) { const char *vstate_string = call_type == ICALL_CALL_TYPE_VIDEO ? "true" : "false"; int err2 = econn_props_update(ecall->props_local, "videosend", vstate_string); if (err2) { warning("ecall(%p): econn_props_update(videosend)", " failed (%m)\n", ecall, err2); /* Non fatal, carry on */ } } #endif err = generate_or_gather_answer(ecall, ecall->econn); if (err) { warning("ecall: answer: failed to gather_or_answer\n"); goto out; } ecall->answered = true; ecall->audio_setup_time = -1; ecall->call_estab_time = -1; ecall->ts_answered = tmr_jiffies(); out: return err; }
CWE-134
54
delete_policy_2_svc(dpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, 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; } prime_arg = arg->name; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, NULL, NULL)) { log_unauth("kadm5_delete_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_DELETE; } else { ret.code = kadm5_delete_policy((void *)handle, arg->name); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), 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
static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; //assert(m->buf_); assert(bufsize >= 0); JAS_DBGLOG(100, ("mem_resize(%p, %d)\n", m, bufsize)); if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, ("mem_resize realloc failed\n")); return -1; } JAS_DBGLOG(100, ("mem_resize realloc succeeded\n")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; }
CWE-190
19
accept_ice_connection (GIOChannel *source, GIOCondition condition, GsmIceConnectionData *data) { IceListenObj listener; IceConn ice_conn; IceAcceptStatus status; GsmClient *client; GsmXsmpServer *server; listener = data->listener; server = data->server; g_debug ("GsmXsmpServer: accept_ice_connection()"); ice_conn = IceAcceptConnection (listener, &status); if (status != IceAcceptSuccess) { g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status); return TRUE; } client = gsm_xsmp_client_new (ice_conn); ice_conn->context = client; gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client)); /* the store will own the ref */ g_object_unref (client); return TRUE; }
CWE-835
42
static u16 read_16(cdk_stream_t s) { byte buf[2]; size_t nread; assert(s != NULL); stream_read(s, buf, 2, &nread); if (nread != 2) return (u16) - 1; return buf[0] << 8 | buf[1]; }
CWE-125
47
static int cJSON_strcasecmp( const char *s1, const char *s2 ) { if ( ! s1 ) return ( s1 == s2 ) ? 0 : 1; if ( ! s2 ) return 1; for ( ; tolower(*s1) == tolower(*s2); ++s1, ++s2) if( *s1 == 0 ) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); }
CWE-120
44
SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); }
CWE-190
19
static void numtostr(js_State *J, const char *fmt, int w, double n) { char buf[32], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); }
CWE-787
24
wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep)) { return (-1); } n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); }
CWE-125
47
int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_write(bio, obj_txt, len); BIO_write(bio, "\n", 1); return 1; }
CWE-125
47
void dmar_free_irte(const struct intr_source *intr_src, uint16_t index) { struct dmar_drhd_rt *dmar_unit; union dmar_ir_entry *ir_table, *ir_entry; union pci_bdf sid; if (intr_src->is_msi) { dmar_unit = device_to_dmaru((uint8_t)intr_src->src.msi.bits.b, intr_src->src.msi.fields.devfun); } else { dmar_unit = ioapic_to_dmaru(intr_src->src.ioapic_id, &sid); } if (is_dmar_unit_valid(dmar_unit, sid)) { ir_table = (union dmar_ir_entry *)hpa2hva(dmar_unit->ir_table_addr); ir_entry = ir_table + index; ir_entry->bits.remap.present = 0x0UL; iommu_flush_cache(ir_entry, sizeof(union dmar_ir_entry)); dmar_invalid_iec(dmar_unit, index, 0U, false); if (!is_irte_reserved(dmar_unit, index)) { spinlock_obtain(&dmar_unit->lock); bitmap_clear_nolock(index & 0x3FU, &dmar_unit->irte_alloc_bitmap[index >> 6U]); spinlock_release(&dmar_unit->lock); } } }
CWE-120
44
static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; }
CWE-190
19
static int prealloc_elems_and_freelist(struct bpf_stack_map *smap) { u32 elem_size = sizeof(struct stack_map_bucket) + smap->map.value_size; int err; smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries, smap->map.numa_node); if (!smap->elems) return -ENOMEM; err = pcpu_freelist_init(&smap->freelist); if (err) goto free_elems; pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size, smap->map.max_entries); return 0; free_elems: bpf_map_area_free(smap->elems); return err; }
CWE-190
19
static inline int mount_entry_on_generic(struct mntent *mntent, const char* path) { unsigned long mntflags; char *mntdata; int ret; bool optional = hasmntopt(mntent, "optional") != NULL; ret = mount_entry_create_dir_file(mntent, path); if (ret < 0) return optional ? 0 : -1; cull_mntent_opt(mntent); if (parse_mntopts(mntent->mnt_opts, &mntflags, &mntdata) < 0) { free(mntdata); return -1; } ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags, mntdata, optional); free(mntdata); return ret; }
CWE-59
36
PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi( const void *buf, pj_size_t length, pjmedia_rtcp_fb_rpsi *rpsi) { pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf; pj_uint8_t *p; pj_uint8_t padlen; pj_size_t rpsi_len; PJ_ASSERT_RETURN(buf && rpsi, PJ_EINVAL); PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL); /* RPSI uses pt==RTCP_PSFB and FMT==3 */ if (hdr->pt != RTCP_PSFB || hdr->count != 3) return PJ_ENOTFOUND; rpsi_len = (pj_ntohs((pj_uint16_t)hdr->length)-2) * 4; if (length < rpsi_len + 12) return PJ_ETOOSMALL; p = (pj_uint8_t*)hdr + sizeof(*hdr); padlen = *p++; rpsi->pt = (*p++ & 0x7F); rpsi->rpsi_bit_len = rpsi_len*8 - 16 - padlen; pj_strset(&rpsi->rpsi, (char*)p, (rpsi->rpsi_bit_len + 7)/8); return PJ_SUCCESS; }
CWE-787
24
SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); }
CWE-190
19
init_syntax_once () { register int c; static int done; if (done) return; bzero (re_syntax_table, sizeof re_syntax_table); for (c = 'a'; c <= 'z'; c++) re_syntax_table[c] = Sword; for (c = 'A'; c <= 'Z'; c++) re_syntax_table[c] = Sword; for (c = '0'; c <= '9'; c++) re_syntax_table[c] = Sword; re_syntax_table['_'] = Sword; done = 1; }
CWE-252
49
Jsi_RC Jsi_RegExpMatch(Jsi_Interp *interp, Jsi_Value *pattern, const char *v, int *rc, Jsi_DString *dStr) { Jsi_Regex *re; int regexec_flags = 0; if (rc) *rc = 0; if (pattern == NULL || pattern->vt != JSI_VT_OBJECT || pattern->d.obj->ot != JSI_OT_REGEXP) return Jsi_LogError("expected pattern"); re = pattern->d.obj->d.robj; regex_t *reg = &re->reg; regmatch_t pos = {}; if (dStr) Jsi_DSInit(dStr); int r = regexec(reg, v, 1, &pos, regexec_flags); if (r >= REG_BADPAT) { char buf[100]; regerror(r, reg, buf, sizeof(buf)); return Jsi_LogError("error while matching pattern: %s", buf); } if (r != REG_NOMATCH) { if (rc) *rc = 1; if (dStr && pos.rm_so >= 0 && pos.rm_eo >= 0 && pos.rm_eo >= pos.rm_so) Jsi_DSAppendLen(dStr, v + pos.rm_so, pos.rm_eo - pos.rm_so); } return JSI_OK; }
CWE-120
44
validate_commit_metadata (GVariant *commit_data, const char *ref, const char *required_metadata, gsize required_metadata_size, gboolean require_xa_metadata, GError **error) { g_autoptr(GVariant) commit_metadata = NULL; g_autoptr(GVariant) xa_metadata_v = NULL; const char *xa_metadata = NULL; gsize xa_metadata_size = 0; commit_metadata = g_variant_get_child_value (commit_data, 0); if (commit_metadata != NULL) { xa_metadata_v = g_variant_lookup_value (commit_metadata, "xa.metadata", G_VARIANT_TYPE_STRING); if (xa_metadata_v) xa_metadata = g_variant_get_string (xa_metadata_v, &xa_metadata_size); } if ((xa_metadata == NULL && require_xa_metadata) || (xa_metadata != NULL && (xa_metadata_size != required_metadata_size || memcmp (xa_metadata, required_metadata, xa_metadata_size) != 0))) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED, _("Commit metadata for %s not matching expected metadata"), ref); return FALSE; } return TRUE; }
CWE-276
45
static void load_xref_from_plaintext(FILE *fp, xref_t *xref) { int i, buf_idx, obj_id, added_entries; char c, buf[32] = {0}; long start, pos; start = ftell(fp); /* Get number of entries */ pos = xref->end; fseek(fp, pos, SEEK_SET); while (ftell(fp) != 0) if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S'))) break; else SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n"); SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n"); xref->n_entries = atoi(buf + strlen("ize ")); xref->entries = calloc(1, xref->n_entries * sizeof(struct _xref_entry)); /* Load entry data */ obj_id = 0; fseek(fp, xref->start + strlen("xref"), SEEK_SET); added_entries = 0; for (i=0; i<xref->n_entries; i++) { /* Advance past newlines. */ c = fgetc(fp); while (c == '\n' || c == '\r') c = fgetc(fp); /* Collect data up until the following newline. */ buf_idx = 0; while (c != '\n' && c != '\r' && !feof(fp) && !ferror(fp) && buf_idx < sizeof(buf)) { buf[buf_idx++] = c; c = fgetc(fp); } if (buf_idx >= sizeof(buf)) { ERR("Failed to locate newline character. " "This might be a corrupt PDF.\n"); exit(EXIT_FAILURE); } buf[buf_idx] = '\0'; /* Went to far and hit start of trailer */ if (strchr(buf, 't')) break; /* Entry or object id */ if (strlen(buf) > 17) { xref->entries[i].obj_id = obj_id++; xref->entries[i].offset = atol(strtok(buf, " ")); xref->entries[i].gen_num = atoi(strtok(NULL, " ")); xref->entries[i].f_or_n = buf[17]; ++added_entries; } else { obj_id = atoi(buf); --i; } } xref->n_entries = added_entries; fseek(fp, start, SEEK_SET); }
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
hb_set_invert (hb_set_t *set) { if (unlikely (hb_object_is_immutable (set))) return; set->invert (); }
CWE-787
24
static void ram_block_add(struct uc_struct *uc, RAMBlock *new_block) { RAMBlock *block; RAMBlock *last_block = NULL; new_block->offset = find_ram_offset(uc, new_block->max_length); if (!new_block->host) { new_block->host = phys_mem_alloc(uc, new_block->max_length, &new_block->mr->align); if (!new_block->host) { // error_setg_errno(errp, errno, // "cannot set up guest memory '%s'", // memory_region_name(new_block->mr)); return; } // memory_try_enable_merging(new_block->host, new_block->max_length); } /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ, * QLIST (which has an RCU-friendly variant) does not have insertion at * tail, so save the last element in last_block. */ RAMBLOCK_FOREACH(block) { last_block = block; if (block->max_length < new_block->max_length) { break; } } if (block) { QLIST_INSERT_BEFORE(block, new_block, next); } else if (last_block) { QLIST_INSERT_AFTER(last_block, new_block, next); } else { /* list is empty */ QLIST_INSERT_HEAD(&uc->ram_list.blocks, new_block, next); } uc->ram_list.mru_block = NULL; /* Write list before version */ //smp_wmb(); cpu_physical_memory_set_dirty_range(new_block->offset, new_block->used_length, DIRTY_CLIENTS_ALL); }
CWE-476
46
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size) { unsigned int u = 0; LineContribType *res; int overflow_error = 0; res = (LineContribType *) gdMalloc(sizeof(LineContribType)); if (!res) { return NULL; } res->WindowSize = windows_size; res->LineLength = line_length; if (overflow2(line_length, sizeof(ContributionType))) { gdFree(res); return NULL; } res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType)); if (res->ContribRow == NULL) { gdFree(res); return NULL; } for (u = 0 ; u < line_length ; u++) { if (overflow2(windows_size, sizeof(double))) { overflow_error = 1; } else { res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double)); } if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) { unsigned int i; u--; for (i=0;i<=u;i++) { gdFree(res->ContribRow[i].Weights); } gdFree(res->ContribRow); gdFree(res); return NULL; } } return res; }
CWE-191
55
static char *print_string( cJSON *item ) { return print_string_ptr( item->valuestring ); }
CWE-120
44
zfs_fastaccesschk_execute(znode_t *zdp, cred_t *cr) { boolean_t owner = B_FALSE; boolean_t groupmbr = B_FALSE; boolean_t is_attr; uid_t uid = crgetuid(cr); if (zdp->z_pflags & ZFS_AV_QUARANTINED) return (1); is_attr = ((zdp->z_pflags & ZFS_XATTR) && (ZTOV(zdp)->v_type == VDIR)); if (is_attr) return (1); if (zdp->z_pflags & ZFS_NO_EXECS_DENIED) return (0); mutex_enter(&zdp->z_acl_lock); if (FUID_INDEX(zdp->z_uid) != 0 || FUID_INDEX(zdp->z_gid) != 0) { goto out_slow; } if (uid == zdp->z_uid) { owner = B_TRUE; if (zdp->z_mode & S_IXUSR) { goto out; } else { goto out_slow; } } if (groupmember(zdp->z_gid, cr)) { groupmbr = B_TRUE; if (zdp->z_mode & S_IXGRP) { goto out; } else { goto out_slow; } } if (!owner && !groupmbr) { if (zdp->z_mode & S_IXOTH) { goto out; } } out: mutex_exit(&zdp->z_acl_lock); return (0); out_slow: mutex_exit(&zdp->z_acl_lock); return (1); }
CWE-276
45
static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } }
CWE-787
24
GF_Err gf_isom_set_extraction_slc(GF_ISOFile *the_file, u32 trackNumber, u32 StreamDescriptionIndex, const GF_SLConfig *slConfig) { GF_TrackBox *trak; GF_SampleEntryBox *entry; GF_Err e; GF_SLConfig **slc; trak = gf_isom_get_track_from_file(the_file, trackNumber); if (!trak) return GF_BAD_PARAM; e = Media_GetSampleDesc(trak->Media, StreamDescriptionIndex, &entry, NULL); if (e) return e; //we must be sure we are not using a remote ESD switch (entry->type) { case GF_ISOM_BOX_TYPE_MP4S: if (((GF_MPEGSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM; slc = & ((GF_MPEGSampleEntryBox *)entry)->slc; break; case GF_ISOM_BOX_TYPE_MP4A: if (((GF_MPEGAudioSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM; slc = & ((GF_MPEGAudioSampleEntryBox *)entry)->slc; break; case GF_ISOM_BOX_TYPE_MP4V: if (((GF_MPEGVisualSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM; slc = & ((GF_MPEGVisualSampleEntryBox *)entry)->slc; break; default: return GF_BAD_PARAM; } if (*slc) { gf_odf_desc_del((GF_Descriptor *)*slc); *slc = NULL; } if (!slConfig) return GF_OK; //finally duplicate the SL return gf_odf_desc_copy((GF_Descriptor *) slConfig, (GF_Descriptor **) slc); }
CWE-476
46
static inline int crypto_rng_generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen) { return tfm->generate(tfm, src, slen, dst, dlen); }
CWE-476
46
pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = calloc(1, sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = malloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = malloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; }
CWE-787
24
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
kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) return code; code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; }
CWE-617
51
static void copyIPv6IfDifferent(void * dest, const void * src) { if(dest != src) { memcpy(dest, src, sizeof(struct in6_addr)); } }
CWE-476
46
static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, bigint *modulus, bigint *pub_exp) { int i, size; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; i = 10; /* start at the first possible non-padded byte */ while (block[i++] && i < sig_len); size = sig_len - i; /* get only the bit we want */ if (size > 0) { int len; const uint8_t *sig_ptr = get_signature(&block[i], &len); if (sig_ptr) { bir = bi_import(ctx, sig_ptr, len); } } free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; }
CWE-347
25
rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; }
CWE-787
24
static Jsi_RC jsi_ArraySizeOfCmd(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"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; }
CWE-190
19
cJSON *cJSON_CreateFalse( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_False; return item; }
CWE-120
44
BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { int i; BYTE iBitmapFormat; BOOL compressed = FALSE; if (!Stream_EnsureRemainingCapacity(s, update_approximate_cache_brush_order(cache_brush, flags))) return FALSE; iBitmapFormat = BPP_BMF[cache_brush->bpp]; Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); return FALSE; } for (i = 7; i >= 0; i--) { Stream_Write_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp)) return FALSE; } else { /* uncompressed brush */ int scanline = (cache_brush->bpp / 8) * 8; for (i = 7; i >= 0; i--) { Stream_Write(s, &cache_brush->data[i * scanline], scanline); } } } } return TRUE; }
CWE-125
47
ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* async_funcdef: ASYNC funcdef */ REQ(n, async_funcdef); REQ(CHILD(n, 0), ASYNC); REQ(CHILD(n, 1), funcdef); return ast_for_funcdef_impl(c, CHILD(n, 1), decorator_seq, 1 /* is_async */); }
CWE-125
47
static char *print_number( cJSON *item ) { char *str; double f, f2; int64_t i; str = (char*) cJSON_malloc( 64 ); if ( str ) { f = item->valuefloat; i = f; f2 = i; if ( f2 == f && item->valueint >= LLONG_MIN && item->valueint <= LLONG_MAX ) sprintf( str, "%lld", (long long) item->valueint ); else sprintf( str, "%g", item->valuefloat ); } return str; }
CWE-120
44
expr_context_name(expr_context_ty ctx) { switch (ctx) { case Load: return "Load"; case Store: return "Store"; case Del: return "Del"; case AugLoad: return "AugLoad"; case AugStore: return "AugStore"; case Param: return "Param"; default: assert(0); return "(unknown)"; } }
CWE-125
47
static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, bigint *modulus, bigint *pub_exp) { int i, size; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; i = 10; /* start at the first possible non-padded byte */ while (block[i++] && i < sig_len); size = sig_len - i; /* get only the bit we want */ if (size > 0) { int len; const uint8_t *sig_ptr = get_signature(&block[i], &len); if (sig_ptr) { bir = bi_import(ctx, sig_ptr, len); } } free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; }
CWE-347
25
search_impl(i_ctx_t *i_ctx_p, bool forward) { os_ptr op = osp; os_ptr op1 = op - 1; uint size = r_size(op); uint count; byte *pat; byte *ptr; byte ch; int incr = forward ? 1 : -1; check_read_type(*op1, t_string); check_read_type(*op, t_string); if (size > r_size(op1)) { /* can't match */ make_false(op); return 0; } count = r_size(op1) - size; ptr = op1->value.bytes; if (size == 0) goto found; if (!forward) ptr += count; pat = op->value.bytes; ch = pat[0]; do { if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size))) goto found; ptr += incr; } while (count--); /* No match */ make_false(op); return 0; found: op->tas.type_attrs = op1->tas.type_attrs; op->value.bytes = ptr; r_set_size(op, size); push(2); op[-1] = *op1; r_set_size(op - 1, ptr - op[-1].value.bytes); op1->value.bytes = ptr + size; r_set_size(op1, count + (!forward ? (size - 1) : 0)); make_true(op); return 0; }
CWE-787
24
void l2tp_packet_print(const struct l2tp_packet_t *pack, void (*print)(const char *fmt, ...)) { const struct l2tp_attr_t *attr; const struct l2tp_dict_value_t *val; if (pack->hdr.ver == 2) { print("[L2TP tid=%u sid=%u", ntohs(pack->hdr.tid), ntohs(pack->hdr.sid)); log_ppp_debug(" Ns=%u Nr=%u", ntohs(pack->hdr.Ns), ntohs(pack->hdr.Nr)); } else { print("[L2TP cid=%u", pack->hdr.cid); log_ppp_debug(" Ns=%u Nr=%u", ntohs(pack->hdr.Ns), ntohs(pack->hdr.Nr)); } list_for_each_entry(attr, &pack->attrs, entry) { print(" <%s", attr->attr->name); val = l2tp_dict_find_value(attr->attr, attr->val); if (val) print(" %s", val->name); else if (attr->H) print(" (hidden, %hu bytes)", attr->length); else { switch (attr->attr->type) { case ATTR_TYPE_INT16: print(" %i", attr->val.int16); break; case ATTR_TYPE_INT32: print(" %i", attr->val.int32); break; case ATTR_TYPE_STRING: print(" %s", attr->val.string); break; } } print(">"); } print("]\n"); }
CWE-120
44
static char *mongo_data_append( char *start , const void *data , int len ) { memcpy( start , data , len ); return start + len; }
CWE-190
19
static wStream* rdg_receive_packet(rdpRdg* rdg) { wStream* s; const size_t header = sizeof(RdgPacketHeader); size_t packetLength; assert(header <= INT_MAX); s = Stream_New(NULL, 1024); if (!s) return NULL; if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header)) { Stream_Free(s, TRUE); return NULL; } Stream_Seek(s, 4); Stream_Read_UINT32(s, packetLength); if ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength)) { Stream_Free(s, TRUE); return NULL; } if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s) + header, (int)packetLength - (int)header)) { Stream_Free(s, TRUE); return NULL; } Stream_SetLength(s, packetLength); return s; }
CWE-125
47
GF_Err text_box_size(GF_Box *s) { GF_TextSampleEntryBox *ptr = (GF_TextSampleEntryBox*)s; /*base + this + string length*/ s->size += 51 + 1; if (ptr->textName) s->size += strlen(ptr->textName); return GF_OK; }
CWE-476
46
static void cmd_parse_lsub (IMAP_DATA* idata, char* s) { char buf[STRING]; char errstr[STRING]; BUFFER err, token; ciss_url_t url; IMAP_LIST list; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) { /* caller will handle response itself */ cmd_parse_list (idata, s); return; } if (!option (OPTIMAPCHECKSUBSCRIBED)) return; idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &list; cmd_parse_list (idata, s); idata->cmddata = NULL; /* noselect is for a gmail quirk (#3445) */ if (!list.name || list.noselect) return; dprint (3, (debugfile, "Subscribing to %s\n", list.name)); strfcpy (buf, "mailboxes \"", sizeof (buf)); mutt_account_tourl (&idata->conn->account, &url); /* escape \ and " */ imap_quote_string(errstr, sizeof (errstr), list.name); url.path = errstr + 1; url.path[strlen(url.path) - 1] = '\0'; if (!mutt_strcmp (url.user, ImapUser)) url.user = NULL; url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0); safe_strcat (buf, sizeof (buf), "\""); mutt_buffer_init (&token); mutt_buffer_init (&err); err.data = errstr; err.dsize = sizeof (errstr); if (mutt_parse_rc_line (buf, &token, &err)) dprint (1, (debugfile, "Error adding subscribed mailbox: %s\n", errstr)); FREE (&token.data); }
CWE-78
6
static Jsi_RC WebSocketVersionCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { const char *verStr = NULL; verStr = lws_get_library_version(); if (verStr) { char buf[100], *cp; snprintf(buf, sizeof(buf), "%s", verStr); cp = Jsi_Strchr(buf, ' '); if (cp) *cp = 0; Jsi_ValueMakeStringDup(interp, ret, buf); } return JSI_OK; }
CWE-120
44
NOEXPORT void reload_config() { static int delay=10; /* 10ms */ #ifdef HAVE_CHROOT struct stat sb; #endif /* HAVE_CHROOT */ if(options_parse(CONF_RELOAD)) { s_log(LOG_ERR, "Failed to reload the configuration file"); return; } unbind_ports(); log_flush(LOG_MODE_BUFFER); #ifdef HAVE_CHROOT /* we don't close SINK_SYSLOG if chroot is enabled and * there is no /dev/log inside it, which could allow * openlog(3) to reopen the syslog socket later */ if(global_options.chroot_dir && stat("/dev/log", &sb)) log_close(SINK_OUTFILE); else #endif /* HAVE_CHROOT */ log_close(SINK_SYSLOG|SINK_OUTFILE); /* there is no race condition here: * client threads are not allowed to use global options */ options_free(); options_apply(); /* we hope that a sane openlog(3) implementation won't * attempt to reopen /dev/log if it's already open */ log_open(SINK_SYSLOG|SINK_OUTFILE); log_flush(LOG_MODE_CONFIGURED); ui_config_reloaded(); /* we use "|" instead of "||" to attempt initialization of both subsystems */ if(bind_ports() | exec_connect_start()) { s_poll_sleep(delay/1000, delay%1000); /* sleep to avoid log trashing */ signal_post(SIGNAL_RELOAD_CONFIG); /* retry */ delay*=2; if(delay > 10000) /* 10s */ delay=10000; } else { delay=10; /* 10ms */ } }
CWE-295
52
repodata_schema2id(Repodata *data, Id *schema, int create) { int h, len, i; Id *sp, cid; Id *schematahash; if (!*schema) return 0; /* XXX: allow empty schema? */ if ((schematahash = data->schematahash) == 0) { data->schematahash = schematahash = solv_calloc(256, sizeof(Id)); for (i = 1; i < data->nschemata; i++) { for (sp = data->schemadata + data->schemata[i], h = 0; *sp;) h = h * 7 + *sp++; h &= 255; schematahash[h] = i; } data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK); } for (sp = schema, len = 0, h = 0; *sp; len++) h = h * 7 + *sp++; h &= 255; len++; cid = schematahash[h]; if (cid) { if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; /* cache conflict, do a slow search */ for (cid = 1; cid < data->nschemata; cid++) if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; } /* a new one */ if (!create) return 0; data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK); /* add schema */ memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id)); data->schemata[data->nschemata] = data->schemadatalen; data->schemadatalen += len; schematahash[h] = data->nschemata; #if 0 fprintf(stderr, "schema2id: new schema\n"); #endif return data->nschemata++; }
CWE-125
47