code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) { Sfdouble_t d; char *last; if (*str == 0) { if (ptr) *ptr = (char *)str; return 0; } errno = 0; d = number(str, &last, shp->inarith ? 0 : 10, NULL); if (*last) { if (*last != '.' || last[1] != '.') { d = strval(shp, str, &last, arith, mode); Varsubscript = true; } if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str); } else if (!d && *str == '-') { d = -0.0; } if (ptr) *ptr = last; return d; }
Class
2
static inline void fsnotify_oldname_free(const unsigned char *old_name) { kfree(old_name); }
Class
2
int options_parse(CONF_TYPE type) { SERVICE_OPTIONS *section; options_defaults(); section=&new_service_options; if(options_file(configuration_file, type, &section)) return 1; if(init_section(1, &section)) return 1; s_log(LOG_NOTICE, "Configuration successful"); return 0; }
Base
1
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; }
Base
1
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); }
Variant
0
mlx5_fw_fatal_reporter_dump(struct devlink_health_reporter *reporter, struct devlink_fmsg *fmsg, void *priv_ctx) { struct mlx5_core_dev *dev = devlink_health_reporter_priv(reporter); u32 crdump_size = dev->priv.health.crdump_size; u32 *cr_data; u32 data_size; u32 offset; int err; if (!mlx5_core_is_pf(dev)) return -EPERM; cr_data = kvmalloc(crdump_size, GFP_KERNEL); if (!cr_data) return -ENOMEM; err = mlx5_crdump_collect(dev, cr_data); if (err) return err; if (priv_ctx) { struct mlx5_fw_reporter_ctx *fw_reporter_ctx = priv_ctx; err = mlx5_fw_reporter_ctx_pairs_put(fmsg, fw_reporter_ctx); if (err) goto free_data; } err = devlink_fmsg_arr_pair_nest_start(fmsg, "crdump_data"); if (err) goto free_data; for (offset = 0; offset < crdump_size; offset += data_size) { if (crdump_size - offset < MLX5_CR_DUMP_CHUNK_SIZE) data_size = crdump_size - offset; else data_size = MLX5_CR_DUMP_CHUNK_SIZE; err = devlink_fmsg_binary_put(fmsg, (char *)cr_data + offset, data_size); if (err) goto free_data; } err = devlink_fmsg_arr_pair_nest_end(fmsg); free_data: kvfree(cr_data); return err; }
Variant
0
void ZydisFormatterBufferInit(ZydisFormatterBuffer* buffer, char* user_buffer, ZyanUSize length) { ZYAN_ASSERT(buffer); ZYAN_ASSERT(user_buffer); ZYAN_ASSERT(length); buffer->is_token_list = ZYAN_FALSE; buffer->string.flags = ZYAN_STRING_HAS_FIXED_CAPACITY; buffer->string.vector.allocator = ZYAN_NULL; buffer->string.vector.element_size = sizeof(char); buffer->string.vector.size = 1; buffer->string.vector.capacity = length; buffer->string.vector.data = user_buffer; *user_buffer = '\0'; }
Variant
0
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; }
Base
1
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { unsigned nbuf; unsigned idx; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_dev *fud; size_t rem; ssize_t ret; fud = fuse_get_dev(out); if (!fud) return -EPERM; pipe_lock(pipe); bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer), GFP_KERNEL); if (!bufs) { pipe_unlock(pipe); return -ENOMEM; } nbuf = 0; rem = 0; for (idx = 0; idx < pipe->nrbufs && rem < len; idx++) rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len; ret = -EINVAL; if (rem < len) { pipe_unlock(pipe); goto out; } rem = len; while (rem) { struct pipe_buffer *ibuf; struct pipe_buffer *obuf; BUG_ON(nbuf >= pipe->buffers); BUG_ON(!pipe->nrbufs); ibuf = &pipe->bufs[pipe->curbuf]; obuf = &bufs[nbuf]; if (rem >= ibuf->len) { *obuf = *ibuf; ibuf->ops = NULL; pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1); pipe->nrbufs--; } else { pipe_buf_get(pipe, ibuf); *obuf = *ibuf; obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } nbuf++; rem -= obuf->len; } pipe_unlock(pipe); fuse_copy_init(&cs, 0, NULL); cs.pipebufs = bufs; cs.nr_segs = nbuf; cs.pipe = pipe; if (flags & SPLICE_F_MOVE) cs.move_pages = 1; ret = fuse_dev_do_write(fud, &cs, len); pipe_lock(pipe); for (idx = 0; idx < nbuf; idx++) pipe_buf_release(pipe, &bufs[idx]); pipe_unlock(pipe); out: kvfree(bufs); return ret; }
Variant
0
static void perf_output_wakeup(struct perf_output_handle *handle) { atomic_set(&handle->rb->poll, POLL_IN); if (handle->nmi) { handle->event->pending_wakeup = 1; irq_work_queue(&handle->event->pending); } else perf_event_wakeup(handle->event); }
Class
2
static pyc_object *get_list_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 (list size out of range)\n"); return NULL; } if (error) { return NULL; } ret = get_array_object_generic (buffer, n); if (ret) { ret->type = TYPE_LIST; return ret; } return NULL; }
Base
1
static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; struct sockaddr_ieee802154 *saddr; saddr = (struct sockaddr_ieee802154 *)msg->msg_name; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* FIXME: skip headers if necessary ?! */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_ts_and_drops(msg, sk, skb); if (saddr) { saddr->family = AF_IEEE802154; saddr->addr = mac_cb(skb)->sa; } if (addr_len) *addr_len = sizeof(*saddr); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: if (err) return err; return copied; }
Class
2
SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */
Base
1
void esp32EthEnableIrq(NetInterface *interface) { //Valid Ethernet PHY or switch driver? if(interface->phyDriver != NULL) { //Enable Ethernet PHY interrupts interface->phyDriver->enableIrq(interface); } else if(interface->switchDriver != NULL) { //Enable Ethernet switch interrupts interface->switchDriver->enableIrq(interface); } else { //Just for sanity } }
Class
2
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return true; case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; }
Base
1
AsyncFor(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena) { stmt_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for AsyncFor"); return NULL; } if (!iter) { PyErr_SetString(PyExc_ValueError, "field iter is required for AsyncFor"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AsyncFor_kind; p->v.AsyncFor.target = target; p->v.AsyncFor.iter = iter; p->v.AsyncFor.body = body; p->v.AsyncFor.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; p->end_lineno = end_lineno; p->end_col_offset = end_col_offset; return p; }
Base
1
static void dns_resolver_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) { int err = PTR_ERR(key->payload.data[dns_key_error]); if (err) seq_printf(m, ": %d", err); else seq_printf(m, ": %u", key->datalen); } }
Class
2
setup_secureChannel(void) { TestingPolicy(&dummyPolicy, dummyCertificate, &fCalled, &keySizes); UA_SecureChannel_init(&testChannel, &UA_ConnectionConfig_default); UA_SecureChannel_setSecurityPolicy(&testChannel, &dummyPolicy, &dummyCertificate); testingConnection = createDummyConnection(65535, &sentData); UA_Connection_attachSecureChannel(&testingConnection, &testChannel); testChannel.connection = &testingConnection; testChannel.state = UA_SECURECHANNELSTATE_OPEN; }
Base
1
static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; }
Base
1
static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name; struct ipxhdr *ipx = NULL; struct sk_buff *skb; int copied, rc; lock_sock(sk); /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -ENOTCONN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) goto out; ipx = ipx_hdr(skb); copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr); if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov, copied); if (rc) goto out_free; if (skb->tstamp.tv64) sk->sk_stamp = skb->tstamp; msg->msg_namelen = sizeof(*sipx); if (sipx) { sipx->sipx_family = AF_IPX; sipx->sipx_port = ipx->ipx_source.sock; memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN); sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net; sipx->sipx_type = ipx->ipx_type; sipx->sipx_zero = 0; } rc = copied; out_free: skb_free_datagram(sk, skb); out: release_sock(sk); return rc; }
Class
2
static int oidc_request_post_preserved_restore(request_rec *r, const char *original_url) { oidc_debug(r, "enter: original_url=%s", original_url); const char *method = "postOnLoad"; const char *script = apr_psprintf(r->pool, " <script type=\"text/javascript\">\n" " function str_decode(string) {\n" " try {\n" " result = decodeURIComponent(string);\n" " } catch (e) {\n" " result = unescape(string);\n" " }\n" " return result;\n" " }\n" " function %s() {\n" " var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n" " sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n" " for (var key in mod_auth_openidc_preserve_post_params) {\n" " var input = document.createElement(\"input\");\n" " input.name = str_decode(key);\n" " input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n" " input.type = \"hidden\";\n" " document.forms[0].appendChild(input);\n" " }\n" " document.forms[0].action = '%s';\n" " document.forms[0].submit();\n" " }\n" " </script>\n", method, original_url); const char *body = " <p>Restoring...</p>\n" " <form method=\"post\"></form>\n"; return oidc_util_html_send(r, "Restoring...", script, method, body, OK); }
Base
1
header_put_byte (SF_PRIVATE *psf, char x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 1) psf->header [psf->headindex++] = x ; } /* header_put_byte */
Class
2
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); }
Base
1
file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len += 20) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; }
Class
2
static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int err; struct sk_buff *skb; struct sock *sk = sock->sk; err = -EIO; if (sk->sk_state & PPPOX_BOUND) goto end; msg->msg_namelen = 0; err = 0; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) goto end; if (len > skb->len) len = skb->len; else if (len < skb->len) msg->msg_flags |= MSG_TRUNC; err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len); if (likely(err == 0)) err = len; kfree_skb(skb); end: return err; }
Class
2
*/ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; }
Base
1
DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; }
Class
2
static int getStrrtokenPos(char* str, int savedPos) { int result =-1; int i; for(i=savedPos-1; i>=0; i--) { if(isIDSeparator(*(str+i)) ){ /* delimiter found; check for singleton */ if(i>=2 && isIDSeparator(*(str+i-2)) ){ /* a singleton; so send the position of token before the singleton */ result = i-2; } else { result = i; } break; } } if(result < 1){ /* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */ result =-1; } return result; }
Base
1
static inline int mk_vhost_fdt_close(struct session_request *sr) { int id; unsigned int hash; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return close(sr->fd_file); } id = sr->vhost_fdt_id; hash = sr->vhost_fdt_hash; ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return close(sr->fd_file); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and check if we should close */ hc->readers--; if (hc->readers == 0) { hc->fd = -1; hc->hash = 0; ht->av_slots++; return close(sr->fd_file); } else { return 0; } } return close(sr->fd_file); }
Class
2
get_matching_model_microcode(int cpu, unsigned long start, void *data, size_t size, struct mc_saved_data *mc_saved_data, unsigned long *mc_saved_in_initrd, struct ucode_cpu_info *uci) { u8 *ucode_ptr = data; unsigned int leftover = size; enum ucode_state state = UCODE_OK; unsigned int mc_size; struct microcode_header_intel *mc_header; struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT]; unsigned int mc_saved_count = mc_saved_data->mc_saved_count; int i; while (leftover) { mc_header = (struct microcode_header_intel *)ucode_ptr; mc_size = get_totalsize(mc_header); if (!mc_size || mc_size > leftover || microcode_sanity_check(ucode_ptr, 0) < 0) break; leftover -= mc_size; /* * Since APs with same family and model as the BSP may boot in * the platform, we need to find and save microcode patches * with the same family and model as the BSP. */ if (matching_model_microcode(mc_header, uci->cpu_sig.sig) != UCODE_OK) { ucode_ptr += mc_size; continue; } _save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count); ucode_ptr += mc_size; } if (leftover) { state = UCODE_ERROR; goto out; } if (mc_saved_count == 0) { state = UCODE_NFOUND; goto out; } for (i = 0; i < mc_saved_count; i++) mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start; mc_saved_data->mc_saved_count = mc_saved_count; out: return state; }
Class
2
GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex) { GF_DataEntryURLBox *entry; GF_DataMap *map; GF_Err e; if (!mdia || !dataEntryIndex || dataEntryIndex > gf_list_count(mdia->information->dataInformation->dref->child_boxes)) return GF_BAD_PARAM; entry = (GF_DataEntryURLBox*)gf_list_get(mdia->information->dataInformation->dref->child_boxes, dataEntryIndex - 1); if (!entry) return GF_ISOM_INVALID_FILE; if (entry->flags == 1) return GF_OK; //ok, not self contained, let's go for it... //we don't know what's a URN yet if (entry->type == GF_ISOM_BOX_TYPE_URN) return GF_NOT_SUPPORTED; if (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) { e = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map); } else { e = gf_isom_datamap_new(entry->location, mdia->mediaTrack->moov->mov->fileName, GF_ISOM_DATA_MAP_READ, &map); } if (e) return e; gf_isom_datamap_del(map); return GF_OK; }
Base
1
static mongo_message *mongo_message_create( int len , int id , int responseTo , int op ) { mongo_message *mm = ( mongo_message * )bson_malloc( len ); if ( !id ) id = rand(); /* native endian (converted on send) */ mm->head.len = len; mm->head.id = id; mm->head.responseTo = responseTo; mm->head.op = op; return mm; }
Base
1
static bool check_underflow(const struct ip6t_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->ipv6)) return false; t = ip6t_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; }
Class
2
static uint64_t unpack_timestamp(const struct efi_time *timestamp) { uint64_t val = 0; uint16_t year = le32_to_cpu(timestamp->year); /* pad1, nanosecond, timezone, daylight and pad2 are meant to be zero */ val |= ((uint64_t) timestamp->pad1 & 0xFF) << 0; val |= ((uint64_t) timestamp->second & 0xFF) << (1*8); val |= ((uint64_t) timestamp->minute & 0xFF) << (2*8); val |= ((uint64_t) timestamp->hour & 0xFF) << (3*8); val |= ((uint64_t) timestamp->day & 0xFF) << (4*8); val |= ((uint64_t) timestamp->month & 0xFF) << (5*8); val |= ((uint64_t) year) << (6*8); return val; }
Base
1
archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { /* We cannot use the standard wcstombs() here because it * cannot tell us how big the output buffer should be. So * I've built a loop around wcrtomb() or wctomb() that * converts a character at a time and resizes the string as * needed. We prefer wcrtomb() when it's available because * it's thread-safe. */ int n, ret_val = 0; char *p; char *end; #if HAVE_WCRTOMB mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ wctomb(NULL, L'\0'); #endif /* * Allocate buffer for MBS. * We need this allocation here since it is possible that * as->s is still NULL. */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; while (*w != L'\0' && len > 0) { if (p >= end) { as->length = p - as->s; as->s[as->length] = '\0'; /* Re-allocate buffer for MBS. */ if (archive_string_ensure(as, as->length + len * 2 + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; } #if HAVE_WCRTOMB n = wcrtomb(p, *w++, &shift_state); #else n = wctomb(p, *w++); #endif if (n == -1) { if (errno == EILSEQ) { /* Skip an illegal wide char. */ *p++ = '?'; ret_val = -1; } else { ret_val = -1; break; } } else p += n; len--; } as->length = p - as->s; as->s[as->length] = '\0'; return (ret_val); }
Base
1
void addReply(redisClient *c, robj *obj) { if (_installWriteEvent(c) != REDIS_OK) return; redisAssert(!server.vm_enabled || obj->storage == REDIS_VM_MEMORY); /* This is an important place where we can avoid copy-on-write * when there is a saving child running, avoiding touching the * refcount field of the object if it's not needed. * * If the encoding is RAW and there is room in the static buffer * we'll be able to send the object to the client without * messing with its page. */ if (obj->encoding == REDIS_ENCODING_RAW) { if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK) _addReplyObjectToList(c,obj); } else { /* FIXME: convert the long into string and use _addReplyToBuffer() * instead of calling getDecodedObject. As this place in the * code is too performance critical. */ obj = getDecodedObject(obj); if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK) _addReplyObjectToList(c,obj); decrRefCount(obj); } }
Class
2
static bool blk_kick_flush(struct request_queue *q, struct blk_flush_queue *fq) { struct list_head *pending = &fq->flush_queue[fq->flush_pending_idx]; struct request *first_rq = list_first_entry(pending, struct request, flush.list); struct request *flush_rq = fq->flush_rq; /* C1 described at the top of this file */ if (fq->flush_pending_idx != fq->flush_running_idx || list_empty(pending)) return false; /* C2 and C3 */ if (!list_empty(&fq->flush_data_in_flight) && time_before(jiffies, fq->flush_pending_since + FLUSH_PENDING_TIMEOUT)) return false; /* * Issue flush and toggle pending_idx. This makes pending_idx * different from running_idx, which means flush is in flight. */ fq->flush_pending_idx ^= 1; blk_rq_init(q, flush_rq); /* * Borrow tag from the first request since they can't * be in flight at the same time. */ if (q->mq_ops) { flush_rq->mq_ctx = first_rq->mq_ctx; flush_rq->tag = first_rq->tag; } flush_rq->cmd_type = REQ_TYPE_FS; flush_rq->cmd_flags = WRITE_FLUSH | REQ_FLUSH_SEQ; flush_rq->rq_disk = first_rq->rq_disk; flush_rq->end_io = flush_end_io; return blk_flush_queue_rq(flush_rq, false); }
Class
2
static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int error = 0; if (sk->sk_state & PPPOX_BOUND) { error = -EIO; goto end; } skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &error); if (error < 0) goto end; m->msg_namelen = 0; if (skb) { total_len = min_t(size_t, total_len, skb->len); error = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len); if (error == 0) { consume_skb(skb); return total_len; } } kfree_skb(skb); end: return error; }
Class
2
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); }
Base
1
static BOOL region16_simplify_bands(REGION16* region) { /** Simplify consecutive bands that touch and have the same items * * ==================== ==================== * | 1 | | 2 | | | | | * ==================== | | | | * | 1 | | 2 | ====> | 1 | | 2 | * ==================== | | | | * | 1 | | 2 | | | | | * ==================== ==================== * */ RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp; int nbRects, finalNbRects; int bandItems, toMove; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) return TRUE; band1 = region16_rects_noconst(region); endPtr = band1 + nbRects; do { band2 = next_band(band1, endPtr, &bandItems); if (band2 == endPtr) break; if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr)) { /* adjust the bottom of band1 items */ tmp = band1; while (tmp < band2) { tmp->bottom = band2->bottom; tmp++; } /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); finalNbRects -= bandItems; endPtr -= bandItems; } else { band1 = band2; } } while (TRUE); if (finalNbRects != nbRects) { int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); region->data = realloc(region->data, allocSize); if (!region->data) { region->data = &empty_region; return FALSE; } region->data->nbRects = finalNbRects; region->data->size = allocSize; } return TRUE; }
Variant
0
static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { PadContext *s = inlink->dst->priv; AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0], w + (s->w - s->in_w), h + (s->h - s->in_h)); int plane; if (!frame) return NULL; frame->width = w; frame->height = h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int hsub = s->draw.hsub[plane]; int vsub = s->draw.vsub[plane]; frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] + (s->y >> vsub) * frame->linesize[plane]; } return frame; }
Class
2
char *string_crypt(const char *key, const char *salt) { assertx(key); assertx(salt); char random_salt[12]; if (!*salt) { memcpy(random_salt,"$1$",3); ito64(random_salt+3,rand(),8); random_salt[11] = '\0'; return string_crypt(key, random_salt); } auto const saltLen = strlen(salt); if ((saltLen > sizeof("$2X$00$")) && (salt[0] == '$') && (salt[1] == '2') && (salt[2] >= 'a') && (salt[2] <= 'z') && (salt[3] == '$') && (salt[4] >= '0') && (salt[4] <= '3') && (salt[5] >= '0') && (salt[5] <= '9') && (salt[6] == '$')) { // Bundled blowfish crypt() char output[61]; static constexpr size_t maxSaltLength = 123; char paddedSalt[maxSaltLength + 1]; paddedSalt[0] = paddedSalt[maxSaltLength] = '\0'; memset(&paddedSalt[1], '$', maxSaltLength - 1); memcpy(paddedSalt, salt, std::min(maxSaltLength, saltLen)); paddedSalt[saltLen] = '\0'; if (php_crypt_blowfish_rn(key, paddedSalt, output, sizeof(output))) { return strdup(output); } } else { // System crypt() function #ifdef USE_PHP_CRYPT_R return php_crypt_r(key, salt); #else static Mutex mutex; Lock lock(mutex); char *crypt_res = crypt(key,salt); if (crypt_res) { return strdup(crypt_res); } #endif } return ((salt[0] == '*') && (salt[1] == '0')) ? strdup("*1") : strdup("*0"); }
Base
1
static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; mutex_lock(&tu->tread_sem); if (tu->timeri) { /* too late */ mutex_unlock(&tu->tread_sem); return -EBUSY; } if (get_user(xarg, p)) { mutex_unlock(&tu->tread_sem); return -EFAULT; } tu->tread = xarg ? 1 : 0; mutex_unlock(&tu->tread_sem); return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; }
Class
2
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)); }
Base
1
unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return -1L; if (v8086_mode(regs)) /* * Base is simply the segment selector shifted 4 * bits to the right. */ return (unsigned long)(sel << 4); if (user_64bit_mode(regs)) { /* * Only FS or GS will have a base address, the rest of * the segments' bases are forced to 0. */ unsigned long base; if (seg_reg_idx == INAT_SEG_REG_FS) rdmsrl(MSR_FS_BASE, base); else if (seg_reg_idx == INAT_SEG_REG_GS) /* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ rdmsrl(MSR_KERNEL_GS_BASE, base); else base = 0; return base; } /* In protected mode the segment selector cannot be null. */ if (!sel) return -1L; desc = get_desc(sel); if (!desc) return -1L; return get_desc_base(desc); }
Variant
0
static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; struct sockaddr_ieee802154 *saddr; saddr = (struct sockaddr_ieee802154 *)msg->msg_name; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* FIXME: skip headers if necessary ?! */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_ts_and_drops(msg, sk, skb); if (saddr) { saddr->family = AF_IEEE802154; saddr->addr = mac_cb(skb)->sa; } if (addr_len) *addr_len = sizeof(*saddr); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: if (err) return err; return copied; }
Class
2
GIT_INLINE(bool) only_spaces_and_dots(const char *path) { const char *c = path; for (;; c++) { if (*c == '\0') return true; if (*c != ' ' && *c != '.') return false; } return true; }
Class
2
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } }
Base
1
static int read_fragment_table(long long *directory_table_end) { int res, i; int bytes = SQUASHFS_FRAGMENT_BYTES(sBlk.s.fragments); int indexes = SQUASHFS_FRAGMENT_INDEXES(sBlk.s.fragments); long long fragment_table_index[indexes]; TRACE("read_fragment_table: %d fragments, reading %d fragment indexes " "from 0x%llx\n", sBlk.s.fragments, indexes, sBlk.s.fragment_table_start); if(sBlk.s.fragments == 0) { *directory_table_end = sBlk.s.fragment_table_start; return TRUE; } fragment_table = malloc(bytes); if(fragment_table == NULL) EXIT_UNSQUASH("read_fragment_table: failed to allocate " "fragment table\n"); res = read_fs_bytes(fd, sBlk.s.fragment_table_start, SQUASHFS_FRAGMENT_INDEX_BYTES(sBlk.s.fragments), fragment_table_index); if(res == FALSE) { ERROR("read_fragment_table: failed to read fragment table " "index\n"); return FALSE; } SQUASHFS_INSWAP_FRAGMENT_INDEXES(fragment_table_index, indexes); for(i = 0; i < indexes; i++) { int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE : bytes & (SQUASHFS_METADATA_SIZE - 1); int length = read_block(fd, fragment_table_index[i], NULL, expected, ((char *) fragment_table) + (i * SQUASHFS_METADATA_SIZE)); TRACE("Read fragment table block %d, from 0x%llx, length %d\n", i, fragment_table_index[i], length); if(length == FALSE) { ERROR("read_fragment_table: failed to read fragment " "table index\n"); return FALSE; } } for(i = 0; i < sBlk.s.fragments; i++) SQUASHFS_INSWAP_FRAGMENT_ENTRY(&fragment_table[i]); *directory_table_end = fragment_table_index[0]; return TRUE; }
Base
1
For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena) { stmt_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for For"); return NULL; } if (!iter) { PyErr_SetString(PyExc_ValueError, "field iter is required for For"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = For_kind; p->v.For.target = target; p->v.For.iter = iter; p->v.For.body = body; p->v.For.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; p->end_lineno = end_lineno; p->end_col_offset = end_col_offset; return p; }
Base
1
PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->decoderow != NULL); assert(sp->decodepfunc != NULL); if ((*sp->decoderow)(tif, op0, occ0, s)) { (*sp->decodepfunc)(tif, op0, occ0); return 1; } else return 0; }
Class
2
create_pty_only(term_T *term, jobopt_T *options) { HANDLE hPipeIn = INVALID_HANDLE_VALUE; HANDLE hPipeOut = INVALID_HANDLE_VALUE; char in_name[80], out_name[80]; channel_T *channel = NULL; create_vterm(term, term->tl_rows, term->tl_cols); vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d", GetCurrentProcessId(), curbuf->b_fnum); hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_MESSAGE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, NMPWAIT_NOWAIT, NULL); if (hPipeIn == INVALID_HANDLE_VALUE) goto failed; vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d", GetCurrentProcessId(), curbuf->b_fnum); hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND, PIPE_TYPE_MESSAGE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, 0, NULL); if (hPipeOut == INVALID_HANDLE_VALUE) goto failed; ConnectNamedPipe(hPipeIn, NULL); ConnectNamedPipe(hPipeOut, NULL); term->tl_job = job_alloc(); if (term->tl_job == NULL) goto failed; ++term->tl_job->jv_refcount; /* behave like the job is already finished */ term->tl_job->jv_status = JOB_FINISHED; channel = add_channel(); if (channel == NULL) goto failed; term->tl_job->jv_channel = channel; channel->ch_keep_open = TRUE; channel->ch_named_pipe = TRUE; channel_set_pipes(channel, (sock_T)hPipeIn, (sock_T)hPipeOut, (sock_T)hPipeOut); channel_set_job(channel, term->tl_job, options); term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name); term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name); return OK; failed: if (hPipeIn != NULL) CloseHandle(hPipeIn); if (hPipeOut != NULL) CloseHandle(hPipeOut); return FAIL; }
Base
1
static int check_passwd(unsigned char *passwd, size_t length) { struct digest *d = NULL; unsigned char *passwd1_sum; unsigned char *passwd2_sum; int ret = 0; int hash_len; if (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) { hash_len = PBKDF2_LENGTH; } else { d = digest_alloc(PASSWD_SUM); if (!d) { pr_err("No such digest: %s\n", PASSWD_SUM ? PASSWD_SUM : "NULL"); return -ENOENT; } hash_len = digest_length(d); } passwd1_sum = calloc(hash_len * 2, sizeof(unsigned char)); if (!passwd1_sum) return -ENOMEM; passwd2_sum = passwd1_sum + hash_len; if (is_passwd_env_enable()) ret = read_env_passwd(passwd2_sum, hash_len); else if (is_passwd_default_enable()) ret = read_default_passwd(passwd2_sum, hash_len); else ret = -EINVAL; if (ret < 0) goto err; if (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) { char *key = passwd2_sum + PBKDF2_SALT_LEN; char *salt = passwd2_sum; int keylen = PBKDF2_LENGTH - PBKDF2_SALT_LEN; ret = pkcs5_pbkdf2_hmac_sha1(passwd, length, salt, PBKDF2_SALT_LEN, PBKDF2_COUNT, keylen, passwd1_sum); if (ret) goto err; if (strncmp(passwd1_sum, key, keylen) == 0) ret = 1; } else { ret = digest_digest(d, passwd, length, passwd1_sum); if (ret) goto err; if (strncmp(passwd1_sum, passwd2_sum, hash_len) == 0) ret = 1; } err: free(passwd1_sum); digest_free(d); return ret; }
Base
1
static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); }
Class
2
GF_Err ilst_item_box_read(GF_Box *s,GF_BitStream *bs) { GF_Err e; u32 sub_type; GF_Box *a = NULL; GF_ListItemBox *ptr = (GF_ListItemBox *)s; /*iTunes way: there's a data atom containing the data*/ sub_type = gf_bs_peek_bits(bs, 32, 4); if (sub_type == GF_ISOM_BOX_TYPE_DATA ) { e = gf_isom_box_parse(&a, bs); if (!e && ptr->size < a->size) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[isom] not enough bytes in box %s: %d left, reading %d (file %s, line %d)\n", gf_4cc_to_str(ptr->type), ptr->size, a->size, __FILE__, __LINE__ )); \ e = GF_ISOM_INVALID_FILE; } if (e) { if (a) gf_isom_box_del(a); return e; } ISOM_DECREASE_SIZE(ptr, a->size); if (a && ptr->data) gf_isom_box_del_parent(&ptr->child_boxes, (GF_Box *) ptr->data); /* otherwise a->data will always overflow */ if (a && a->size > 4 && a->type != GF_ISOM_BOX_TYPE_VOID) { ptr->data = (GF_DataBox *)a; if (!ptr->child_boxes) ptr->child_boxes = gf_list_new(); gf_list_add(ptr->child_boxes, ptr->data); } else { ptr->data = NULL; gf_isom_box_del(a); } } /*QT way*/ else { u64 pos = gf_bs_get_position(bs); u64 prev_size = s->size; /*try parsing as generic box list*/ e = gf_isom_box_array_read(s, bs, NULL); if (e==GF_OK) return GF_OK; //reset content and retry - this deletes ptr->data !! gf_isom_box_array_del(s->child_boxes); s->child_boxes=NULL; gf_bs_seek(bs, pos); s->size = prev_size; ptr->data = (GF_DataBox *)gf_isom_box_new_parent(&ptr->child_boxes, GF_ISOM_BOX_TYPE_DATA); //nope, check qt-style ptr->data->qt_style = GF_TRUE; ISOM_DECREASE_SIZE(ptr, 2); ptr->data->dataSize = gf_bs_read_u16(bs); gf_bs_read_u16(bs); ptr->data->data = (char *) gf_malloc(sizeof(char)*(ptr->data->dataSize + 1)); gf_bs_read_data(bs, ptr->data->data, ptr->data->dataSize); ptr->data->data[ptr->data->dataSize] = 0; ISOM_DECREASE_SIZE(ptr, ptr->data->dataSize); } return GF_OK; }
Base
1
ast_for_for_stmt(struct compiling *c, const node *n, int is_async) { asdl_seq *_target, *seq = NULL, *suite_seq; expr_ty expression; expr_ty target, first; const node *node_target; int has_type_comment; string type_comment; if (is_async && c->c_feature_version < 5) { ast_error(c, n, "Async for loops are only supported in Python 3.5 and greater"); return NULL; } /* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */ REQ(n, for_stmt); has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT; if (NCH(n) == 9 + has_type_comment) { seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment)); if (!seq) return NULL; } node_target = CHILD(n, 1); _target = ast_for_exprlist(c, node_target, Store); if (!_target) return NULL; /* Check the # of children rather than the length of _target, since for x, in ... has 1 element in _target, but still requires a Tuple. */ first = (expr_ty)asdl_seq_GET(_target, 0); if (NCH(node_target) == 1) target = first; else target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena); expression = ast_for_testlist(c, CHILD(n, 3)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment)); if (!suite_seq) return NULL; if (has_type_comment) type_comment = NEW_TYPE_COMMENT(CHILD(n, 5)); else type_comment = NULL; if (is_async) return AsyncFor(target, expression, suite_seq, seq, type_comment, LINENO(n), n->n_col_offset, c->c_arena); else return For(target, expression, suite_seq, seq, type_comment, LINENO(n), n->n_col_offset, c->c_arena); }
Base
1
struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag) { struct request *rq = tags->rqs[tag]; /* mq_ctx of flush rq is always cloned from the corresponding req */ struct blk_flush_queue *fq = blk_get_flush_queue(rq->q, rq->mq_ctx); if (!is_flush_request(rq, fq, tag)) return rq; return fq->flush_rq; }
Class
2
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); }
Base
1
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; }
Variant
0
void enc28j60SelectBank(NetInterface *interface, uint16_t address) { uint16_t bank; Enc28j60Context *context; //Point to the driver context context = (Enc28j60Context *) interface->nicContext; //Get the bank number from the specified address bank = address & REG_BANK_MASK; //Rewrite the bank number only if a change is detected if(bank != context->currentBank) { //Select specified bank switch(bank) { case BANK_0: //Select bank 0 enc28j60ClearBit(interface, ENC28J60_REG_ECON1, ECON1_BSEL1 | ECON1_BSEL0); break; case BANK_1: //Select bank 1 enc28j60SetBit(interface, ENC28J60_REG_ECON1, ECON1_BSEL0); enc28j60ClearBit(interface, ENC28J60_REG_ECON1, ECON1_BSEL1); break; case BANK_2: //Select bank 2 enc28j60ClearBit(interface, ENC28J60_REG_ECON1, ECON1_BSEL0); enc28j60SetBit(interface, ENC28J60_REG_ECON1, ECON1_BSEL1); break; case BANK_3: //Select bank 3 enc28j60SetBit(interface, ENC28J60_REG_ECON1, ECON1_BSEL1 | ECON1_BSEL0); break; default: //Invalid bank break; } //Save bank number context->currentBank = bank; } }
Class
2
static LUA_FUNCTION(openssl_x509_check_ip_asc) { X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509"); if (lua_isstring(L, 2)) { const char *ip_asc = lua_tostring(L, 2); lua_pushboolean(L, X509_check_ip_asc(cert, ip_asc, 0)); } else { lua_pushboolean(L, 0); } return 1; }
Base
1
local void init_block(s) deflate_state *s; { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; s->last_lit = s->matches = 0; }
Base
1
void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *name = d->name; struct device dev = d->udev->dev; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); dev_info(&dev, "%s: '%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, name); }
Class
2
GF_Box *mp4s_box_new() { ISOM_DECL_BOX_ALLOC(GF_MPEGSampleEntryBox, GF_ISOM_BOX_TYPE_MP4S); gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp); tmp->internal_type = GF_ISOM_SAMPLE_ENTRY_MP4S; return (GF_Box *)tmp; }
Base
1
int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac) { struct cm_id_private *cm_id_priv; cm_id_priv = container_of(id, struct cm_id_private, id); if (smac != NULL) memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac)); if (alt_smac != NULL) memcpy(cm_id_priv->alt_av.smac, alt_smac, sizeof(cm_id_priv->alt_av.smac)); return 0; }
Class
2
ast2obj_alias(void* _o) { alias_ty o = (alias_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(alias_type, NULL, NULL); if (!result) return NULL; value = ast2obj_identifier(o->name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_identifier(o->asname); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_asname, value) == -1) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; }
Base
1
Bool rfbOptPamAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if ((!strcmp(s->name, "unixlogin") || !strcmp(&s->name[strlen(s->name) - 5], "plain")) && s->enabled) return TRUE; } return FALSE; }
Base
1
static void Sp_match(js_State *J) { js_Regexp *re; const char *text; int len; const char *a, *b, *c, *e; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!(re->flags & JS_REGEXP_G)) { js_RegExp_prototype_exec(J, re, text); return; } re->last = 0; js_newarray(J); len = 0; a = text; e = text + strlen(text); while (a <= e) { if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0)) break; b = m.sub[0].sp; c = m.sub[0].ep; js_pushlstring(J, b, c - b); js_setindex(J, -2, len++); a = c; if (c - b == 0) ++a; } if (len == 0) { js_pop(J, 1); js_pushnull(J); } }
Class
2
uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); return MP4buffer; } } return NULL; }
Base
1
TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &a)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = uaddr; a < (uaddr + len); a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; }
Base
1
static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *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; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { free (ptr); return ret; } ut32 j = 0; while (i < len && j < ptr->num_elem ) { // TODO: allocate space and fill entry ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; }
Base
1
static int amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); pinctrl_unregister(gpio_dev->pctrl); return 0; }
Variant
0
DU_getStringDOElement(DcmItem *obj, DcmTagKey t, char *s, size_t bufsize) { DcmByteString *elem; DcmStack stack; OFCondition ec = EC_Normal; char* aString; ec = obj->search(t, stack); elem = (DcmByteString*) stack.top(); if (ec == EC_Normal && elem != NULL) { if (elem->getLength() == 0) { s[0] = '\0'; } else { ec = elem->getString(aString); OFStandard::strlcpy(s, aString, bufsize); } } return (ec == EC_Normal); }
Base
1
static void Np_toString(js_State *J) { char buf[32]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[100]; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } }
Base
1
PHP_FUNCTION( locale_get_region ) { get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
Base
1
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); }
Class
2
__must_hold(&ctx->completion_lock) { u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts); spin_lock_irq(&ctx->timeout_lock); while (!list_empty(&ctx->timeout_list)) { u32 events_needed, events_got; struct io_kiocb *req = list_first_entry(&ctx->timeout_list, struct io_kiocb, timeout.list); if (io_is_timeout_noseq(req)) break; /* * Since seq can easily wrap around over time, subtract * the last seq at which timeouts were flushed before comparing. * Assuming not more than 2^31-1 events have happened since, * these subtractions won't have wrapped, so we can check if * target is in [last_seq, current_seq] by comparing the two. */ events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush; events_got = seq - ctx->cq_last_tm_flush; if (events_got < events_needed) break; list_del_init(&req->timeout.list); io_kill_timeout(req, 0); } ctx->cq_last_tm_flush = seq; spin_unlock_irq(&ctx->timeout_lock); }
Variant
0
int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr_storage *address, int mode) { int size, ct, err; if (m->msg_namelen) { if (mode == VERIFY_READ) { void __user *namep; namep = (void __user __force *) m->msg_name; err = move_addr_to_kernel(namep, m->msg_namelen, address); if (err < 0) return err; } m->msg_name = address; } else { m->msg_name = NULL; } size = m->msg_iovlen * sizeof(struct iovec); if (copy_from_user(iov, (void __user __force *) m->msg_iov, size)) return -EFAULT; m->msg_iov = iov; err = 0; for (ct = 0; ct < m->msg_iovlen; ct++) { size_t len = iov[ct].iov_len; if (len > INT_MAX - err) { len = INT_MAX - err; iov[ct].iov_len = len; } err += len; } return err; }
Class
2
static int cbs_av1_read_uvlc(CodedBitstreamContext *ctx, GetBitContext *gbc, const char *name, uint32_t *write_to, uint32_t range_min, uint32_t range_max) { uint32_t value; int position, zeroes, i, j; char bits[65]; if (ctx->trace_enable) position = get_bits_count(gbc); zeroes = i = 0; while (1) { if (get_bits_left(gbc) < zeroes + 1) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid uvlc code at " "%s: bitstream ended.\n", name); return AVERROR_INVALIDDATA; } if (get_bits1(gbc)) { bits[i++] = '1'; break; } else { bits[i++] = '0'; ++zeroes; } } if (zeroes >= 32) { value = MAX_UINT_BITS(32); } else { value = get_bits_long(gbc, zeroes); for (j = 0; j < zeroes; j++) bits[i++] = (value >> (zeroes - j - 1) & 1) ? '1' : '0'; value += (1 << zeroes) - 1; } if (ctx->trace_enable) { bits[i] = 0; ff_cbs_trace_syntax_element(ctx, position, name, NULL, bits, value); } if (value < range_min || value > range_max) { av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: " "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n", name, value, range_min, range_max); return AVERROR_INVALIDDATA; } *write_to = value; return 0; }
Variant
0
prepenv(const struct rule *rule) { static const char *safeset[] = { "DISPLAY", "HOME", "LOGNAME", "MAIL", "PATH", "TERM", "USER", "USERNAME", NULL }; struct env *env; env = createenv(rule); /* if we started with blank, fill some defaults then apply rules */ if (!(rule->options & KEEPENV)) fillenv(env, safeset); if (rule->envlist) fillenv(env, rule->envlist); return flattenenv(env); }
Base
1
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); }
Base
1
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); }
Base
1
static int dnxhd_init_vlc(DNXHDContext *ctx, uint32_t cid, int bitdepth) { if (cid != ctx->cid) { const CIDEntry *cid_table = ff_dnxhd_get_cid_table(cid); if (!cid_table) { av_log(ctx->avctx, AV_LOG_ERROR, "unsupported cid %"PRIu32"\n", cid); return AVERROR(ENOSYS); } if (cid_table->bit_depth != bitdepth && cid_table->bit_depth != DNXHD_VARIABLE) { av_log(ctx->avctx, AV_LOG_ERROR, "bit depth mismatches %d %d\n", cid_table->bit_depth, bitdepth); return AVERROR_INVALIDDATA; } ctx->cid_table = cid_table; av_log(ctx->avctx, AV_LOG_VERBOSE, "Profile cid %"PRIu32".\n", cid); ff_free_vlc(&ctx->ac_vlc); ff_free_vlc(&ctx->dc_vlc); ff_free_vlc(&ctx->run_vlc); init_vlc(&ctx->ac_vlc, DNXHD_VLC_BITS, 257, ctx->cid_table->ac_bits, 1, 1, ctx->cid_table->ac_codes, 2, 2, 0); init_vlc(&ctx->dc_vlc, DNXHD_DC_VLC_BITS, bitdepth > 8 ? 14 : 12, ctx->cid_table->dc_bits, 1, 1, ctx->cid_table->dc_codes, 1, 1, 0); init_vlc(&ctx->run_vlc, DNXHD_VLC_BITS, 62, ctx->cid_table->run_bits, 1, 1, ctx->cid_table->run_codes, 2, 2, 0); ctx->cid = cid; } return 0; }
Base
1
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 }
Base
1
static int find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1<<i)) return i; } return 0; }
Pillar
3
int get_evtchn_to_irq(evtchn_port_t evtchn) { if (evtchn >= xen_evtchn_max_channels()) return -1; if (evtchn_to_irq[EVTCHN_ROW(evtchn)] == NULL) return -1; return evtchn_to_irq[EVTCHN_ROW(evtchn)][EVTCHN_COL(evtchn)]; }
Base
1
Map1toN(SDL_PixelFormat * src, Uint8 Rmod, Uint8 Gmod, Uint8 Bmod, Uint8 Amod, SDL_PixelFormat * dst) { Uint8 *map; int i; int bpp; SDL_Palette *pal = src->palette; bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel); map = (Uint8 *) SDL_malloc(pal->ncolors * bpp); if (map == NULL) { SDL_OutOfMemory(); return (NULL); } /* We memory copy to the pixel map so the endianness is preserved */ for (i = 0; i < pal->ncolors; ++i) { Uint8 R = (Uint8) ((pal->colors[i].r * Rmod) / 255); Uint8 G = (Uint8) ((pal->colors[i].g * Gmod) / 255); Uint8 B = (Uint8) ((pal->colors[i].b * Bmod) / 255); Uint8 A = (Uint8) ((pal->colors[i].a * Amod) / 255); ASSEMBLE_RGBA(&map[i * bpp], dst->BytesPerPixel, dst, (Uint32)R, (Uint32)G, (Uint32)B, (Uint32)A); } return (map); }
Base
1
struct dst_entry *inet_csk_route_req(struct sock *sk, const struct request_sock *req) { struct rtable *rt; const struct inet_request_sock *ireq = inet_rsk(req); struct ip_options *opt = inet_rsk(req)->opt; struct net *net = sock_net(sk); struct flowi4 fl4; flowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->srr) ? opt->faddr : ireq->rmt_addr, ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport); security_req_classify_flow(req, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) goto route_err; return &rt->dst; route_err: ip_rt_put(rt); no_route: IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES); return NULL; }
Class
2
static unsigned char *read_chunk(struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk_num) { struct mspack_system *sys = self->system; unsigned char *buf; /* check arguments - most are already checked by chmd_fast_find */ if (chunk_num > chm->num_chunks) return NULL; /* ensure chunk cache is available */ if (!chm->chunk_cache) { size_t size = sizeof(unsigned char *) * chm->num_chunks; if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } memset(chm->chunk_cache, 0, size); } /* try to answer out of chunk cache */ if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num]; /* need to read chunk - allocate memory for it */ if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } /* seek to block and read it */ if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)), MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) { self->error = MSPACK_ERR_READ; sys->free(buf); return NULL; } /* check the signature. Is is PMGL or PMGI? */ if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) && ((buf[3] == 0x4C) || (buf[3] == 0x49)))) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } /* all OK. Store chunk in cache and return it */ return chm->chunk_cache[chunk_num] = buf; }
Base
1
def test_received_preq_error(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(len(inst.server.tasks), 1) self.assertTrue(inst.requests)
Base
1
def get(self, arg,word=None): #print "match auto" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") #jsonp result = rtxcomplete.prefix(word,limit) result = callback+"("+json.dumps(result)+");" #jsonp #result = json.dumps(result) #typeahead self.write(result) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[2] self.write("error")
Base
1
def get_problem_responses(request, course_id): """ Initiate generation of a CSV file containing all student answers to a given problem. Responds with JSON {"status": "... status message ..."} if initiation is successful (or generation task is already running). Responds with BadRequest if problem location is faulty. """ course_key = CourseKey.from_string(course_id) problem_location = request.GET.get('problem_location', '') try: problem_key = UsageKey.from_string(problem_location) # Are we dealing with an "old-style" problem location? run = problem_key.run if not run: problem_key = course_key.make_usage_key_from_deprecated_string(problem_location) if problem_key.course_key != course_key: raise InvalidKeyError(type(problem_key), problem_key) except InvalidKeyError: return JsonResponseBadRequest(_("Could not find problem with this location.")) try: instructor_task.api.submit_calculate_problem_responses_csv(request, course_key, problem_location) success_status = _( "The problem responses report is being created." " To view the status of the report, see Pending Tasks below." ) return JsonResponse({"status": success_status}) except AlreadyRunningError: already_running_status = _( "A problem responses report generation task is already in progress. " "Check the 'Pending Tasks' table for the status of the task. " "When completed, the report will be available for download in the table below." ) return JsonResponse({"status": already_running_status})
Compound
4
def _ssl_wrap_socket( sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
Class
2
def login(): callback = url_for(".callback", _external=True) next_path = request.args.get( "next", url_for("redash.index", org_slug=session.get("org_slug")) ) logger.debug("Callback url: %s", callback) logger.debug("Next is: %s", next_path) return google_remote_app().authorize(callback=callback, state=next_path)
Base
1
def feed_categoryindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('id'))\ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() elements = [] if off == 0: elements.append({'id': "00", 'name':_("All")}) shift = 1 for entry in entries[ off + shift - 1: int(off + int(config.config_books_per_page) - shift)]: elements.append({'id': entry.id, 'name': entry.id}) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries) + 1) return render_xml_template('feed.xml', letterelements=elements, folder='opds.feed_letter_category', pagination=pagination)
Base
1
def ends_with(field: Term, value: str) -> Criterion: return field.like(f"%{value}")
Base
1
def test_progress(self, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save" in driver.page_source driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//button[@name='save_continue']") with wait_for_page_load(driver, timeout=10): save_button.click() response = json.loads(driver.find_elements(By.CSS_SELECTOR, "pre")[0].text) assert response["POST"]["progress"] == "1"
Base
1
def __init__(self, servers, connect_timeout=CONN_TIMEOUT, io_timeout=IO_TIMEOUT, tries=TRY_COUNT):
Base
1
def test_file_insert(self, request, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" with wait_for_page_load(driver, timeout=10): file_input.submit() assert storage.exists("tmp/%s.txt" % request.node.name) with pytest.raises(NoSuchElementException): error = driver.find_element(By.XPATH, "//body[@JSError]") pytest.fail(error.get_attribute("JSError"))
Base
1
def feed_seriesindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all() elements = [] if off == 0: elements.append({'id': "00", 'name':_("All")}) shift = 1 for entry in entries[ off + shift - 1: int(off + int(config.config_books_per_page) - shift)]: elements.append({'id': entry.id, 'name': entry.id}) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries) + 1) return render_xml_template('feed.xml', letterelements=elements, folder='opds.feed_letter_series', pagination=pagination)
Base
1