func
stringlengths
12
2.67k
cwe
stringclasses
7 values
__index_level_0__
int64
0
20k
TEST_F(ConnectionHandlerTest, TransportProtocolDefault) { TestListener* test_listener = addListener(1, true, false, "test_listener"); Network::MockListener* listener = new Network::MockListener(); Network::ListenerCallbacks* listener_callbacks; EXPECT_CALL(dispatcher_, createListener_(_, _, _)) .WillOnce( Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* { listener_callbacks = &cb; return listener; })); EXPECT_CALL(test_listener->socket_, localAddress()); handler_->addListener(*test_listener); Network::MockConnectionSocket* accepted_socket = new NiceMock<Network::MockConnectionSocket>(); EXPECT_CALL(*accepted_socket, detectedTransportProtocol()) .WillOnce(Return(absl::string_view(""))); EXPECT_CALL(*accepted_socket, setDetectedTransportProtocol(absl::string_view("raw_buffer"))); EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(nullptr)); listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket}); EXPECT_CALL(*listener, onDestroy()); }
safe
100
void RunJob() override { CIRCSock* pIRCSock = m_pNetwork->GetIRCSock(); auto uFrequency = m_pNetwork->GetUser()->GetPingFrequency(); if (pIRCSock && pIRCSock->GetTimeSinceLastDataTransaction() >= uFrequency) { pIRCSock->PutIRC("PING :ZNC"); } const vector<CClient*>& vClients = m_pNetwork->GetClients(); for (CClient* pClient : vClients) { if (pClient->GetTimeSinceLastDataTransaction() >= uFrequency) { pClient->PutClient("PING :ZNC"); } } // Restart timer for the case if the period had changed. Usually this is // noop Start(m_pNetwork->GetUser()->GetPingSlack()); }
safe
101
void OSD::send_beacon(const ceph::coarse_mono_clock::time_point& now) { const auto& monmap = monc->monmap; // send beacon to mon even if we are just connected, and the monmap is not // initialized yet by then. if (monmap.epoch > 0 && monmap.get_required_features().contains_all( ceph::features::mon::FEATURE_LUMINOUS)) { dout(20) << __func__ << " sending" << dendl; MOSDBeacon* beacon = nullptr; { Mutex::Locker l{min_last_epoch_clean_lock}; beacon = new MOSDBeacon(osdmap->get_epoch(), min_last_epoch_clean); std::swap(beacon->pgs, min_last_epoch_clean_pgs); last_sent_beacon = now; } monc->send_mon_message(beacon); } else { dout(20) << __func__ << " not sending" << dendl; } }
safe
102
void EvalQuantizedPerChannel16x8( TfLiteContext* context, const TfLiteTransposeConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* weights, const TfLiteTensor* transposed_weights, const TfLiteTensor* bias, TfLiteTensor* col2im, TfLiteTensor* output, TfLiteTensor* scratch_buffer) { tflite::ConvParams op_params; op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width_offset = data->padding.width_offset; op_params.padding_values.height_offset = data->padding.height_offset; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; // Need to flip the sign of input offset to add it directly to the quantized // buffer. op_params.input_offset = -input->params.zero_point; op_params.output_offset = output->params.zero_point; op_params.quantized_activation_min = data->output_activation_min; op_params.quantized_activation_max = data->output_activation_max; // Need to add optimized kernel reference_integer_ops::TransposeConv( op_params, data->per_channel_output_multiplier.data(), data->per_channel_output_shift.data(), GetTensorShape(input), GetTensorData<int16>(input), GetTensorShape(weights), GetTensorData<int8>(weights), GetTensorShape(bias), GetTensorData<int64_t>(bias), GetTensorShape(output), GetTensorData<int16>(output), GetTensorShape(col2im), GetTensorData<int8>(col2im), GetTensorData<int64_t>(scratch_buffer)); }
safe
103
R_API RBinJavaStackMapFrameMetas *r_bin_java_determine_stack_frame_type(ut8 tag) { ut8 type_value = 0; if (tag < 64) { type_value = R_BIN_JAVA_STACK_FRAME_SAME; } else if (tag < 128) { type_value = R_BIN_JAVA_STACK_FRAME_SAME_LOCALS_1; } else if (247 < tag && tag < 251) { type_value = R_BIN_JAVA_STACK_FRAME_CHOP; } else if (tag == 251) { type_value = R_BIN_JAVA_STACK_FRAME_SAME_FRAME_EXTENDED; } else if (251 < tag && tag < 255) { type_value = R_BIN_JAVA_STACK_FRAME_APPEND; } else if (tag == 255) { type_value = R_BIN_JAVA_STACK_FRAME_FULL_FRAME; } else { type_value = R_BIN_JAVA_STACK_FRAME_RESERVED; } return &R_BIN_JAVA_STACK_MAP_FRAME_METAS[type_value]; }
safe
104
static void virtio_serial_save_device(VirtIODevice *vdev, QEMUFile *f) { VirtIOSerial *s = VIRTIO_SERIAL(vdev); VirtIOSerialPort *port; uint32_t nr_active_ports; unsigned int i, max_nr_ports; struct virtio_console_config config; /* The config space (ignored on the far end in current versions) */ get_config(vdev, (uint8_t *)&config); qemu_put_be16s(f, &config.cols); qemu_put_be16s(f, &config.rows); qemu_put_be32s(f, &config.max_nr_ports); /* The ports map */ max_nr_ports = s->serial.max_virtserial_ports; for (i = 0; i < (max_nr_ports + 31) / 32; i++) { qemu_put_be32s(f, &s->ports_map[i]); } /* Ports */ nr_active_ports = 0; QTAILQ_FOREACH(port, &s->ports, next) { nr_active_ports++; } qemu_put_be32s(f, &nr_active_ports); /* * Items in struct VirtIOSerialPort. */ QTAILQ_FOREACH(port, &s->ports, next) { uint32_t elem_popped; qemu_put_be32s(f, &port->id); qemu_put_byte(f, port->guest_connected); qemu_put_byte(f, port->host_connected); elem_popped = 0; if (port->elem.out_num) { elem_popped = 1; } qemu_put_be32s(f, &elem_popped); if (elem_popped) { qemu_put_be32s(f, &port->iov_idx); qemu_put_be64s(f, &port->iov_offset); qemu_put_buffer(f, (unsigned char *)&port->elem, sizeof(port->elem)); } } }
safe
105
static unichar_t **GListField_NameCompletion(GGadget *t,int from_tab) { const unichar_t *spt; unichar_t **ret; GTextInfo **ti; int32 len; int i, cnt, doit, match_len; spt = _GGadgetGetTitle(t); if ( spt==NULL ) return( NULL ); match_len = u_strlen(spt); ti = GGadgetGetList(t,&len); ret = NULL; for ( doit=0; doit<2; ++doit ) { cnt=0; for ( i=0; i<len; ++i ) { if ( ti[i]->text && u_strncmp(ti[i]->text,spt,match_len)==0 ) { if ( doit ) ret[cnt] = u_copy(ti[i]->text); ++cnt; } } if ( doit ) ret[cnt] = NULL; else if ( cnt==0 ) return( NULL ); else ret = malloc((cnt+1)*sizeof(unichar_t *)); } return( ret ); }
safe
106
rtadv_process_packet (u_char *buf, unsigned int len, ifindex_t ifindex, int hoplimit, vrf_id_t vrf_id) { struct icmp6_hdr *icmph; struct interface *ifp; struct zebra_if *zif; /* Interface search. */ ifp = if_lookup_by_index_vrf (ifindex, vrf_id); if (ifp == NULL) { zlog_warn ("Unknown interface index: %d, vrf %u", ifindex, vrf_id); return; } if (if_is_loopback (ifp)) return; /* Check interface configuration. */ zif = ifp->info; if (! zif->rtadv.AdvSendAdvertisements) return; /* ICMP message length check. */ if (len < sizeof (struct icmp6_hdr)) { zlog_warn ("Invalid ICMPV6 packet length: %d", len); return; } icmph = (struct icmp6_hdr *) buf; /* ICMP message type check. */ if (icmph->icmp6_type != ND_ROUTER_SOLICIT && icmph->icmp6_type != ND_ROUTER_ADVERT) { zlog_warn ("Unwanted ICMPV6 message type: %d", icmph->icmp6_type); return; } /* Hoplimit check. */ if (hoplimit >= 0 && hoplimit != 255) { zlog_warn ("Invalid hoplimit %d for router advertisement ICMP packet", hoplimit); return; } /* Check ICMP message type. */ if (icmph->icmp6_type == ND_ROUTER_SOLICIT) rtadv_process_solicit (ifp); else if (icmph->icmp6_type == ND_ROUTER_ADVERT) rtadv_process_advert (); return; }
safe
107
static int tda9874a_checkit(struct CHIPSTATE *chip) { int dic,sic; /* device id. and software id. codes */ if(-1 == (dic = chip_read2(chip,TDA9874A_DIC))) return 0; if(-1 == (sic = chip_read2(chip,TDA9874A_SIC))) return 0; v4l_dbg(1, debug, chip->c, "tda9874a_checkit(): DIC=0x%X, SIC=0x%X.\n", dic, sic); if((dic == 0x11)||(dic == 0x07)) { v4l_info(chip->c, "found tda9874%s.\n", (dic == 0x11) ? "a":"h"); tda9874a_dic = dic; /* remember device id. */ return 1; } return 0; /* not found */ }
safe
108
static int coroutine_fn iscsi_co_truncate(BlockDriverState *bs, int64_t offset, bool exact, PreallocMode prealloc, Error **errp) { IscsiLun *iscsilun = bs->opaque; int64_t cur_length; Error *local_err = NULL; if (prealloc != PREALLOC_MODE_OFF) { error_setg(errp, "Unsupported preallocation mode '%s'", PreallocMode_str(prealloc)); return -ENOTSUP; } if (iscsilun->type != TYPE_DISK) { error_setg(errp, "Cannot resize non-disk iSCSI devices"); return -ENOTSUP; } iscsi_readcapacity_sync(iscsilun, &local_err); if (local_err != NULL) { error_propagate(errp, local_err); return -EIO; } cur_length = iscsi_getlength(bs); if (offset != cur_length && exact) { error_setg(errp, "Cannot resize iSCSI devices"); return -ENOTSUP; } else if (offset > cur_length) { error_setg(errp, "Cannot grow iSCSI devices"); return -EINVAL; } if (iscsilun->allocmap != NULL) { iscsi_allocmap_init(iscsilun, bs->open_flags); } return 0; }
safe
109
static int read_raw_super_block(struct f2fs_sb_info *sbi, struct f2fs_super_block **raw_super, int *valid_super_block, int *recovery) { struct super_block *sb = sbi->sb; int block; struct buffer_head *bh; struct f2fs_super_block *super; int err = 0; super = kzalloc(sizeof(struct f2fs_super_block), GFP_KERNEL); if (!super) return -ENOMEM; for (block = 0; block < 2; block++) { bh = sb_bread(sb, block); if (!bh) { f2fs_msg(sb, KERN_ERR, "Unable to read %dth superblock", block + 1); err = -EIO; continue; } /* sanity checking of raw super */ if (sanity_check_raw_super(sbi, bh)) { f2fs_msg(sb, KERN_ERR, "Can't find valid F2FS filesystem in %dth superblock", block + 1); err = -EINVAL; brelse(bh); continue; } if (!*raw_super) { memcpy(super, bh->b_data + F2FS_SUPER_OFFSET, sizeof(*super)); *valid_super_block = block; *raw_super = super; } brelse(bh); } /* Fail to read any one of the superblocks*/ if (err < 0) *recovery = 1; /* No valid superblock */ if (!*raw_super) kfree(super); else err = 0; return err; }
safe
110
xmlBufferCreateSize(size_t size) { xmlBufferPtr ret; if (size >= UINT_MAX) return(NULL); ret = (xmlBufferPtr) xmlMalloc(sizeof(xmlBuffer)); if (ret == NULL) { xmlTreeErrMemory("creating buffer"); return(NULL); } ret->use = 0; ret->alloc = xmlBufferAllocScheme; ret->size = (size ? size + 1 : 0); /* +1 for ending null */ if (ret->size){ ret->content = (xmlChar *) xmlMallocAtomic(ret->size * sizeof(xmlChar)); if (ret->content == NULL) { xmlTreeErrMemory("creating buffer"); xmlFree(ret); return(NULL); } ret->content[0] = 0; } else ret->content = NULL; ret->contentIO = NULL; return(ret); }
safe
111
u_int8_t ndpi_extra_dissection_possible(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int16_t proto = flow->detected_protocol_stack[1] ? flow->detected_protocol_stack[1] : flow->detected_protocol_stack[0]; #if 0 printf("[DEBUG] %s(%u.%u): %u\n", __FUNCTION__, flow->detected_protocol_stack[0], flow->detected_protocol_stack[1], proto); #endif switch (proto) { case NDPI_PROTOCOL_TLS: if(!flow->l4.tcp.tls.certificate_processed) return(1); /* TODO: add check for TLS 1.3 */ break; case NDPI_PROTOCOL_HTTP: if((flow->host_server_name[0] == '\0') || (flow->http.response_status_code == 0)) return(1); break; case NDPI_PROTOCOL_DNS: if(flow->protos.dns.num_answers == 0) return(1); break; case NDPI_PROTOCOL_FTP_CONTROL: case NDPI_PROTOCOL_MAIL_POP: case NDPI_PROTOCOL_MAIL_IMAP: case NDPI_PROTOCOL_MAIL_SMTP: if(flow->protos.ftp_imap_pop_smtp.password[0] == '\0') return(1); break; case NDPI_PROTOCOL_SSH: if((flow->protos.ssh.hassh_client[0] == '\0') || (flow->protos.ssh.hassh_server[0] == '\0')) return(1); break; case NDPI_PROTOCOL_TELNET: if(!flow->protos.telnet.password_detected) return(1); break; } return(0); }
safe
112
static int tipc_socketpair(struct socket *sock1, struct socket *sock2) { struct tipc_sock *tsk2 = tipc_sk(sock2->sk); struct tipc_sock *tsk1 = tipc_sk(sock1->sk); u32 onode = tipc_own_addr(sock_net(sock1->sk)); tsk1->peer.family = AF_TIPC; tsk1->peer.addrtype = TIPC_SOCKET_ADDR; tsk1->peer.scope = TIPC_NODE_SCOPE; tsk1->peer.addr.id.ref = tsk2->portid; tsk1->peer.addr.id.node = onode; tsk2->peer.family = AF_TIPC; tsk2->peer.addrtype = TIPC_SOCKET_ADDR; tsk2->peer.scope = TIPC_NODE_SCOPE; tsk2->peer.addr.id.ref = tsk1->portid; tsk2->peer.addr.id.node = onode; tipc_sk_finish_conn(tsk1, tsk2->portid, onode); tipc_sk_finish_conn(tsk2, tsk1->portid, onode); return 0; }
safe
113
static int fts3PendingTermsAddOne( Fts3Table *p, int iCol, int iPos, Fts3Hash *pHash, /* Pending terms hash table to add entry to */ const char *zToken, int nToken ){ PendingList *pList; int rc = SQLITE_OK; pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); if( pList ){ p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); } if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ /* Malloc failed while inserting the new entry. This can only ** happen if there was no previous entry for this token. */ assert( 0==fts3HashFind(pHash, zToken, nToken) ); sqlite3_free(pList); rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); } return rc; }
safe
114
server_unresponsive(struct TCP_Server_Info *server) { /* * We need to wait 2 echo intervals to make sure we handle such * situations right: * 1s client sends a normal SMB request * 2s client gets a response * 30s echo workqueue job pops, and decides we got a response recently * and don't need to send another * ... * 65s kernel_recvmsg times out, and we see that we haven't gotten * a response in >60s. */ if (server->tcpStatus == CifsGood && time_after(jiffies, server->lstrp + 2 * SMB_ECHO_INTERVAL)) { cifs_dbg(VFS, "Server %s has not responded in %d seconds. Reconnecting...\n", server->hostname, (2 * SMB_ECHO_INTERVAL) / HZ); cifs_reconnect(server); wake_up(&server->response_q); return true; } return false; }
safe
115
static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm) { int L1, L2, L3; L1 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the try block */ L2 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the catch block */ cstm(J, F, finallystm); /* inline finally block */ emit(J, F, OP_THROW); /* rethrow exception */ } label(J, F, L2); if (F->strict) { checkfutureword(J, F, catchvar); if (!strcmp(catchvar->string, "arguments")) jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode"); if (!strcmp(catchvar->string, "eval")) jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode"); } emitline(J, F, catchvar); emitstring(J, F, OP_CATCH, catchvar->string); cstm(J, F, catchstm); emit(J, F, OP_ENDCATCH); emit(J, F, OP_ENDTRY); L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */ } label(J, F, L1); cstm(J, F, trystm); emit(J, F, OP_ENDTRY); label(J, F, L3); cstm(J, F, finallystm); }
safe
116
const char *format, ...) _PRINTF_ATTRIBUTE(5,6) { va_list ap; int count; struct ldb_message **res; const char *attrs[2] = { NULL, NULL }; struct dom_sid *sid; attrs[0] = attr_name; va_start(ap, format); count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap); va_end(ap); if (count > 1) { DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", attr_name, format, count)); } if (count != 1) { talloc_free(res); return NULL; } sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name); talloc_free(res); return sid; }
safe
117
static int tun_attach(struct tun_struct *tun, struct file *file) { struct tun_file *tfile = file->private_data; const struct cred *cred = current_cred(); int err; ASSERT_RTNL(); /* Check permissions */ if (((tun->owner != -1 && cred->euid != tun->owner) || (tun->group != -1 && !in_egroup_p(tun->group))) && !capable(CAP_NET_ADMIN)) return -EPERM; netif_tx_lock_bh(tun->dev); err = -EINVAL; if (tfile->tun) goto out; err = -EBUSY; if (tun->tfile) goto out; err = 0; tfile->tun = tun; tun->tfile = tfile; dev_hold(tun->dev); sock_hold(tun->sk); atomic_inc(&tfile->count); out: netif_tx_unlock_bh(tun->dev); return err; }
safe
118
static void fr_set_link_state(int reliable, struct net_device *dev) { hdlc_device *hdlc = dev_to_hdlc(dev); pvc_device *pvc = state(hdlc)->first_pvc; state(hdlc)->reliable = reliable; if (reliable) { netif_dormant_off(dev); state(hdlc)->n391cnt = 0; /* Request full status */ state(hdlc)->dce_changed = 1; if (state(hdlc)->settings.lmi == LMI_NONE) { while (pvc) { /* Activate all PVCs */ pvc_carrier(1, pvc); pvc->state.exist = pvc->state.active = 1; pvc->state.new = 0; pvc = pvc->next; } } } else { netif_dormant_on(dev); while (pvc) { /* Deactivate all PVCs */ pvc_carrier(0, pvc); pvc->state.exist = pvc->state.active = 0; pvc->state.new = 0; if (!state(hdlc)->settings.dce) pvc->state.bandwidth = 0; pvc = pvc->next; } } }
safe
119
static int ldb_msg_partition(struct ldb_module *module, enum ldb_request_type optype, struct ldb_message *local, struct ldb_message *remote, const struct ldb_message *msg) { /* const char * const names[]; */ struct ldb_context *ldb; unsigned int i; int ret; ldb = ldb_module_get_ctx(module); for (i = 0; i < msg->num_elements; i++) { /* Skip 'IS_MAPPED' */ if (ldb_attr_cmp(msg->elements[i].name, IS_MAPPED) == 0) { ldb_debug(ldb, LDB_DEBUG_WARNING, "ldb_map: " "Skipping attribute '%s'", msg->elements[i].name); continue; } ret = ldb_msg_el_partition(module, optype, local, remote, msg, msg->elements[i].name, &msg->elements[i]); if (ret) { return ret; } } return 0; }
safe
120
imapx_gather_existing_uids_cb (guint32 uid, gpointer user_data) { GatherExistingUidsData *geud = user_data; gchar *uid_str; g_return_val_if_fail (geud != NULL, FALSE); g_return_val_if_fail (geud->is != NULL, FALSE); g_return_val_if_fail (geud->summary != NULL, FALSE); geud->n_uids++; uid_str = g_strdup_printf ("%u", uid); if (camel_folder_summary_check_uid (geud->summary, uid_str)) { e (geud->is->priv->tagprefix, "vanished known UID: %u\n", uid); if (!geud->uid_list) g_mutex_lock (&geud->is->priv->changes_lock); geud->uid_list = g_list_prepend (geud->uid_list, uid_str); camel_folder_change_info_remove_uid (geud->is->priv->changes, uid_str); } else { e (geud->is->priv->tagprefix, "vanished unknown UID: %u\n", uid); g_free (uid_str); } return TRUE; }
safe
121
init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass) { MonoError error; MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error); if (!mono_error_ok (&error)) { char *name = mono_type_get_full_name (klass); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name)); g_free (name); mono_error_cleanup (&error); return; } if (!ctx->max_stack) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset)); return; } stack_init (ctx, code); ensure_stack_size (code, 1); set_stack_value (ctx, code->stack, type, FALSE); ctx->exception_types = g_slist_prepend (ctx->exception_types, type); code->size = 1; code->flags |= IL_CODE_FLAG_WAS_TARGET; if (mono_type_is_generic_argument (type)) code->stack->stype |= BOXED_MASK; }
safe
122
routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2) { or_options_t *options = get_options(); config_line_t *cl; if (options->EnforceDistinctSubnets && routers_in_same_network_family(r1,r2)) return 1; if (router_in_nickname_smartlist(r1->declared_family, r2) && router_in_nickname_smartlist(r2->declared_family, r1)) return 1; for (cl = options->NodeFamilies; cl; cl = cl->next) { if (router_nickname_is_in_list(r1, cl->value) && router_nickname_is_in_list(r2, cl->value)) return 1; } return 0; }
safe
123
static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; }
safe
124
static void rose_idletimer_expiry(struct timer_list *t) { struct rose_sock *rose = from_timer(rose, t, idletimer); struct sock *sk = &rose->sock; bh_lock_sock(sk); rose_clear_queues(sk); rose_write_internal(sk, ROSE_CLEAR_REQUEST); rose_sk(sk)->state = ROSE_STATE_2; rose_start_t3timer(sk); sk->sk_state = TCP_CLOSE; sk->sk_err = 0; sk->sk_shutdown |= SEND_SHUTDOWN; if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DEAD); } bh_unlock_sock(sk); sock_put(sk); }
safe
125
BOOL transport_tsg_connect(rdpTransport* transport, const char* hostname, UINT16 port) { rdpTsg* tsg = tsg_new(transport); tsg->transport = transport; transport->tsg = tsg; transport->SplitInputOutput = TRUE; if (transport->TlsIn == NULL) transport->TlsIn = tls_new(transport->settings); transport->TlsIn->sockfd = transport->TcpIn->sockfd; if (transport->TlsOut == NULL) transport->TlsOut = tls_new(transport->settings); transport->TlsOut->sockfd = transport->TcpOut->sockfd; if (tls_connect(transport->TlsIn) != TRUE) return FALSE; if (tls_connect(transport->TlsOut) != TRUE) return FALSE; if (!tsg_connect(tsg, hostname, port)) return FALSE; return TRUE; }
safe
126
static void parse_grep(const char *str) { int len; char *cp = (char *)str, *cp2; /* sanity check: we should have been called with the \ first */ if (*cp != '|') return; cp++; while (isspace(*cp)) cp++; if (!str_has_prefix(cp, "grep ")) { kdb_printf("invalid 'pipe', see grephelp\n"); return; } cp += 5; while (isspace(*cp)) cp++; cp2 = strchr(cp, '\n'); if (cp2) *cp2 = '\0'; /* remove the trailing newline */ len = strlen(cp); if (len == 0) { kdb_printf("invalid 'pipe', see grephelp\n"); return; } /* now cp points to a nonzero length search string */ if (*cp == '"') { /* allow it be "x y z" by removing the "'s - there must be two of them */ cp++; cp2 = strchr(cp, '"'); if (!cp2) { kdb_printf("invalid quoted string, see grephelp\n"); return; } *cp2 = '\0'; /* end the string where the 2nd " was */ } kdb_grep_leading = 0; if (*cp == '^') { kdb_grep_leading = 1; cp++; } len = strlen(cp); kdb_grep_trailing = 0; if (*(cp+len-1) == '$') { kdb_grep_trailing = 1; *(cp+len-1) = '\0'; } len = strlen(cp); if (!len) return; if (len >= KDB_GREP_STRLEN) { kdb_printf("search string too long\n"); return; } strcpy(kdb_grep_string, cp); kdb_grepping_flag++; return; }
safe
127
static void rtl8xxxu_set_linktype(struct rtl8xxxu_priv *priv, enum nl80211_iftype linktype) { u8 val8; val8 = rtl8xxxu_read8(priv, REG_MSR); val8 &= ~MSR_LINKTYPE_MASK; switch (linktype) { case NL80211_IFTYPE_UNSPECIFIED: val8 |= MSR_LINKTYPE_NONE; break; case NL80211_IFTYPE_ADHOC: val8 |= MSR_LINKTYPE_ADHOC; break; case NL80211_IFTYPE_STATION: val8 |= MSR_LINKTYPE_STATION; break; case NL80211_IFTYPE_AP: val8 |= MSR_LINKTYPE_AP; break; default: goto out; } rtl8xxxu_write8(priv, REG_MSR, val8); out: return; }
safe
128
static int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = (unsigned char *)wpmd->data; if (bytecnt >= 3) { wpc->config.flags &= 0xff; wpc->config.flags |= (int32_t) *byteptr++ << 8; wpc->config.flags |= (int32_t) *byteptr++ << 16; wpc->config.flags |= (int32_t) *byteptr++ << 24; bytecnt -= 3; if (bytecnt && (wpc->config.flags & CONFIG_EXTRA_MODE)) { wpc->config.xmode = *byteptr++; bytecnt--; } // we used an extra config byte here for the 5.0.0 alpha, so still // honor it now (but this has been replaced with NEW_CONFIG) if (bytecnt) { wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr; wpc->version_five = 1; } } return TRUE; }
safe
129
nfs3svc_encode_writeres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_writeres *resp) { struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); p = encode_wcc_data(rqstp, p, &resp->fh); if (resp->status == 0) { *p++ = htonl(resp->count); *p++ = htonl(resp->committed); *p++ = htonl(nn->nfssvc_boot.tv_sec); *p++ = htonl(nn->nfssvc_boot.tv_usec); } return xdr_ressize_check(rqstp, p); }
safe
130
static UINT rdpei_send_touch_event_pdu(RDPEI_CHANNEL_CALLBACK* callback, RDPINPUT_TOUCH_FRAME* frame) { UINT status; wStream* s; UINT32 pduLength; pduLength = 64 + (frame->contactCount * 64); s = Stream_New(NULL, pduLength); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } Stream_Seek(s, RDPINPUT_HEADER_LENGTH); /** * the time that has elapsed (in milliseconds) from when the oldest touch frame * was generated to when it was encoded for transmission by the client. */ rdpei_write_4byte_unsigned( s, (UINT32)frame->frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */ rdpei_write_2byte_unsigned(s, 1); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */ if ((status = rdpei_write_touch_frame(s, frame))) { WLog_ERR(TAG, "rdpei_write_touch_frame failed with error %" PRIu32 "!", status); Stream_Free(s, TRUE); return status; } Stream_SealLength(s); pduLength = Stream_Length(s); status = rdpei_send_pdu(callback, s, EVENTID_TOUCH, pduLength); Stream_Free(s, TRUE); return status; }
safe
131
static __init int rb_write_something(struct rb_test_data *data, bool nested) { struct ring_buffer_event *event; struct rb_item *item; bool started; int event_len; int size; int len; int cnt; /* Have nested writes different that what is written */ cnt = data->cnt + (nested ? 27 : 0); /* Multiply cnt by ~e, to make some unique increment */ size = (data->cnt * 68 / 25) % (sizeof(rb_string) - 1); len = size + sizeof(struct rb_item); started = rb_test_started; /* read rb_test_started before checking buffer enabled */ smp_rmb(); event = ring_buffer_lock_reserve(data->buffer, len); if (!event) { /* Ignore dropped events before test starts. */ if (started) { if (nested) data->bytes_dropped += len; else data->bytes_dropped_nested += len; } return len; } event_len = ring_buffer_event_length(event); if (RB_WARN_ON(data->buffer, event_len < len)) goto out; item = ring_buffer_event_data(event); item->size = size; memcpy(item->str, rb_string, size); if (nested) { data->bytes_alloc_nested += event_len; data->bytes_written_nested += len; data->events_nested++; if (!data->min_size_nested || len < data->min_size_nested) data->min_size_nested = len; if (len > data->max_size_nested) data->max_size_nested = len; } else { data->bytes_alloc += event_len; data->bytes_written += len; data->events++; if (!data->min_size || len < data->min_size) data->max_size = len; if (len > data->max_size) data->max_size = len; } out: ring_buffer_unlock_commit(data->buffer, event); return 0; }
safe
132
TEST_F(QuicUnencryptedServerTransportTest, FirstPacketProcessedCallback) { getFakeHandshakeLayer()->allowZeroRttKeys(); EXPECT_CALL(connCallback, onFirstPeerPacketProcessed()).Times(1); recvClientHello(); loopForWrites(); AckBlocks acks; acks.insert(0); auto aead = getInitialCipher(); auto headerCipher = getInitialHeaderCipher(); EXPECT_CALL(connCallback, onFirstPeerPacketProcessed()).Times(0); deliverData(packetToBufCleartext( createAckPacket( server->getNonConstConn(), clientNextInitialPacketNum, acks, PacketNumberSpace::Initial, aead.get()), *aead, *headerCipher, clientNextInitialPacketNum)); }
safe
133
int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, unsigned char *p) { int i, j = 0; const SSL_CIPHER *c; unsigned char *q; int empty_reneg_info_scsv = !s->renegotiate; /* Set disabled masks for this session */ ssl_set_client_disabled(s); if (sk == NULL) return (0); q = p; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); /* Skip disabled ciphers */ if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED)) continue; j = s->method->put_cipher_by_char(c, p); p += j; } /* * If p == q, no ciphers; caller indicates an error. Otherwise, add * applicable SCSVs. */ if (p != q) { if (empty_reneg_info_scsv) { static SSL_CIPHER scsv = { 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; j = s->method->put_cipher_by_char(&scsv, p); p += j; } if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) { static SSL_CIPHER scsv = { 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; j = s->method->put_cipher_by_char(&scsv, p); p += j; } } return (p - q); }
safe
134
gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this, int ms, HANDLE thread) { MonoInternalThread *cur_thread = mono_thread_internal_current (); gboolean ret; mono_thread_current_check_pending_interrupt (); ensure_synch_cs_set (this); EnterCriticalSection (this->synch_cs); if ((this->state & ThreadState_Unstarted) != 0) { LeaveCriticalSection (this->synch_cs); mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started.")); return FALSE; } LeaveCriticalSection (this->synch_cs); if(ms== -1) { ms=INFINITE; } THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms)); mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin); ret=WaitForSingleObjectEx (thread, ms, TRUE); mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin); if(ret==WAIT_OBJECT_0) { THREAD_DEBUG (g_message ("%s: join successful", __func__)); return(TRUE); } THREAD_DEBUG (g_message ("%s: join failed", __func__)); return(FALSE); }
safe
135
STATIC void S_delete_recursion_entry(pTHX_ void *key) { /* Deletes the entry used to detect recursion when expanding user-defined * properties. This is a function so it can be set up to be called even if * the program unexpectedly quits */ dVAR; SV ** current_entry; const STRLEN key_len = strlen((const char *) key); DECLARATION_FOR_GLOBAL_CONTEXT; SWITCH_TO_GLOBAL_CONTEXT; /* If the entry is one of these types, it is a permanent entry, and not the * one used to detect recursions. This function should delete only the * recursion entry */ current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0); if ( current_entry && ! is_invlist(*current_entry) && ! SvPOK(*current_entry)) { (void) hv_delete(PL_user_def_props, (const char *) key, key_len, G_DISCARD); } RESTORE_CONTEXT;
safe
136
static void yurex_interrupt(struct urb *urb) { struct usb_yurex *dev = urb->context; unsigned char *buf = dev->int_buffer; int status = urb->status; unsigned long flags; int retval, i; switch (status) { case 0: /*success*/ break; case -EOVERFLOW: dev_err(&dev->interface->dev, "%s - overflow with length %d, actual length is %d\n", __func__, YUREX_BUF_SIZE, dev->urb->actual_length); case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: case -EILSEQ: /* The device is terminated, clean up */ return; default: dev_err(&dev->interface->dev, "%s - unknown status received: %d\n", __func__, status); goto exit; } /* handle received message */ switch (buf[0]) { case CMD_COUNT: case CMD_READ: if (buf[6] == CMD_EOF) { spin_lock_irqsave(&dev->lock, flags); dev->bbu = 0; for (i = 1; i < 6; i++) { dev->bbu += buf[i]; if (i != 5) dev->bbu <<= 8; } dev_dbg(&dev->interface->dev, "%s count: %lld\n", __func__, dev->bbu); spin_unlock_irqrestore(&dev->lock, flags); kill_fasync(&dev->async_queue, SIGIO, POLL_IN); } else dev_dbg(&dev->interface->dev, "data format error - no EOF\n"); break; case CMD_ACK: dev_dbg(&dev->interface->dev, "%s ack: %c\n", __func__, buf[1]); wake_up_interruptible(&dev->waitq); break; } exit: retval = usb_submit_urb(dev->urb, GFP_ATOMIC); if (retval) { dev_err(&dev->interface->dev, "%s - usb_submit_urb failed: %d\n", __func__, retval); } }
safe
137
rehash(table) register st_table *table; { register st_table_entry *ptr, *next, **new_bins; int i, old_num_bins = table->num_bins, new_num_bins; unsigned int hash_val; new_num_bins = new_size(old_num_bins+1); new_bins = (st_table_entry**)Calloc(new_num_bins, sizeof(st_table_entry*)); for(i = 0; i < old_num_bins; i++) { ptr = table->bins[i]; while (ptr != 0) { next = ptr->next; hash_val = ptr->hash % new_num_bins; ptr->next = new_bins[hash_val]; new_bins[hash_val] = ptr; ptr = next; } } free(table->bins); table->num_bins = new_num_bins; table->bins = new_bins; }
safe
138
ConnectionDone(struct Curl_easy *data, struct connectdata *conn) { /* data->multi->maxconnects can be negative, deal with it. */ size_t maxconnects = (data->multi->maxconnects < 0) ? data->multi->num_easy * 4: data->multi->maxconnects; struct connectdata *conn_candidate = NULL; /* Mark the current connection as 'unused' */ conn->inuse = FALSE; if(maxconnects > 0 && data->state.conn_cache->num_connections > maxconnects) { infof(data, "Connection cache is full, closing the oldest one.\n"); conn_candidate = Curl_oldest_idle_connection(data); if(conn_candidate) { /* Set the connection's owner correctly */ conn_candidate->data = data; /* the winner gets the honour of being disconnected */ (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE); } } return (conn_candidate == conn) ? FALSE : TRUE; }
safe
139
ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info) { MonoDomain *domain = mono_domain_get (); MonoMethodSignature* sig; MONO_ARCH_SAVE_REGS; sig = mono_method_signature (method); if (!sig) { g_assert (mono_loader_get_last_error ()); mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ())); } MONO_STRUCT_SETREF (info, parent, mono_type_get_object (domain, &method->klass->byval_arg)); MONO_STRUCT_SETREF (info, ret, mono_type_get_object (domain, sig->ret)); info->attrs = method->flags; info->implattrs = method->iflags; if (sig->call_convention == MONO_CALL_DEFAULT) info->callconv = sig->sentinelpos >= 0 ? 2 : 1; else { if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0) info->callconv = 2; else info->callconv = 1; } info->callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6); }
safe
140
STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s) { STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers; int i; ciphers = SSL_get_ciphers(s); if (!ciphers) return NULL; ssl_set_client_disabled(s); for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i); if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED)) { if (!sk) sk = sk_SSL_CIPHER_new_null(); if (!sk) return NULL; if (!sk_SSL_CIPHER_push(sk, c)) { sk_SSL_CIPHER_free(sk); return NULL; } } } return sk; }
safe
141
static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) { const char __user *fname; int ret; if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL)) return -EINVAL; if (unlikely(sqe->ioprio || sqe->buf_index)) return -EINVAL; if (unlikely(req->flags & REQ_F_FIXED_FILE)) return -EBADF; /* open.how should be already initialised */ if (!(req->open.how.flags & O_PATH) && force_o_largefile()) req->open.how.flags |= O_LARGEFILE; req->open.dfd = READ_ONCE(sqe->fd); fname = u64_to_user_ptr(READ_ONCE(sqe->addr)); req->open.filename = getname(fname); if (IS_ERR(req->open.filename)) { ret = PTR_ERR(req->open.filename); req->open.filename = NULL; return ret; } req->open.file_slot = READ_ONCE(sqe->file_index); if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC)) return -EINVAL; req->open.nofile = rlimit(RLIMIT_NOFILE); req->flags |= REQ_F_NEED_CLEANUP; return 0; }
safe
142
static int checkout_action_common( int *action, checkout_data *data, const git_diff_delta *delta, const git_index_entry *wd) { git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE; if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0) *action = (*action & ~CHECKOUT_ACTION__REMOVE); if ((*action & CHECKOUT_ACTION__UPDATE_BLOB) != 0) { if (S_ISGITLINK(delta->new_file.mode)) *action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB) | CHECKOUT_ACTION__UPDATE_SUBMODULE; /* to "update" a symlink, we must remove the old one first */ if (delta->new_file.mode == GIT_FILEMODE_LINK && wd != NULL) *action |= CHECKOUT_ACTION__REMOVE; /* if the file is on disk and doesn't match our mode, force update */ if (wd && GIT_PERMS_IS_EXEC(wd->mode) != GIT_PERMS_IS_EXEC(delta->new_file.mode)) *action |= CHECKOUT_ACTION__REMOVE; notify = GIT_CHECKOUT_NOTIFY_UPDATED; } if ((*action & CHECKOUT_ACTION__CONFLICT) != 0) notify = GIT_CHECKOUT_NOTIFY_CONFLICT; return checkout_notify(data, notify, delta, wd); }
safe
143
f_tempname(typval_T *argvars UNUSED, typval_T *rettv) { static int x = 'A'; rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_tempname(x, FALSE); /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different * names. Skip 'I' and 'O', they are used for shell redirection. */ do { if (x == 'Z') x = '0'; else if (x == '9') x = 'A'; else { #ifdef EBCDIC if (x == 'I') x = 'J'; else if (x == 'R') x = 'S'; else #endif ++x; } } while (x == 'I' || x == 'O'); }
safe
144
static double mp_get(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; double *ptrd = &_mp_arg(1); const unsigned int sizs = (unsigned int)mp.opcode[3], sizd = (unsigned int)mp.opcode[4]; const bool to_string = (bool)mp.opcode[5]; CImg<charT> ss(sizs + 1); cimg_for_inX(ss,0,ss.width() - 1,i) ss[i] = (char)ptrs[i]; ss.back() = 0; if (sizd) cimg_mp_func_get(ptrd + 1,sizd,to_string,ss._data); else cimg_mp_func_get(ptrd,0,to_string,ss._data); return cimg::type<double>::nan(); }
safe
145
PHP_FUNCTION(dom_document_save_html_file) { zval *id; xmlDoc *docp; int file_len, bytes, format; dom_object *intern; dom_doc_propsptr doc_props; char *file; const char *encoding; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Op", &id, dom_document_class_entry, &file, &file_len) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); encoding = (const char *) htmlGetMetaEncoding(docp); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; bytes = htmlSaveFileFormat(file, docp, encoding, format); if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); }
safe
146
int rad_dict_load(const char *fname) { int r = -1; if (!dict) { dict = malloc(sizeof(*dict)); if (!dict) { log_emerg("radius: out of memory\n"); return -1; } INIT_LIST_HEAD(&dict->items); INIT_LIST_HEAD(&dict->vendors); } path = _malloc(PATH_MAX); if (!path) { log_emerg("radius: out of memory\n"); goto out_free_dict; } fname1 = _malloc(PATH_MAX); if (!fname1) { log_emerg("radius: out of memory\n"); goto out_free_path; } buf = _malloc(BUF_SIZE); if (!buf) { log_emerg("radius: out of memory\n"); goto out_free_fname1; } strcpy(path, fname); r = dict_load(fname); out_free_fname1: _free(fname1); out_free_path: _free(path); out_free_dict: if (r) rad_dict_free(dict); return r; }
safe
147
static void agent_auth_cb(struct agent *agent, DBusError *derr, void *user_data) { struct btd_adapter *adapter = user_data; struct service_auth *auth = g_queue_pop_head(adapter->auths); if (!auth) { DBG("No pending authorization"); return; } auth->cb(derr, auth->user_data); if (auth->agent) agent_unref(auth->agent); g_free(auth); /* Stop processing if queue is empty */ if (g_queue_is_empty(adapter->auths)) { if (adapter->auth_idle_id > 0) g_source_remove(adapter->auth_idle_id); return; } if (adapter->auth_idle_id > 0) return; adapter->auth_idle_id = g_idle_add(process_auth_queue, adapter); }
safe
148
dotraplinkage void do_double_fault(struct pt_regs *regs, long error_code) { static const char str[] = "double fault"; struct task_struct *tsk = current; #ifdef CONFIG_X86_ESPFIX64 extern unsigned char native_irq_return_iret[]; /* * If IRET takes a non-IST fault on the espfix64 stack, then we * end up promoting it to a doublefault. In that case, modify * the stack to make it look like we just entered the #GP * handler from user space, similar to bad_iret. * * No need for ist_enter here because we don't use RCU. */ if (((long)regs->sp >> PGDIR_SHIFT) == ESPFIX_PGD_ENTRY && regs->cs == __KERNEL_CS && regs->ip == (unsigned long)native_irq_return_iret) { struct pt_regs *normal_regs = task_pt_regs(current); /* Fake a #GP(0) from userspace. */ memmove(&normal_regs->ip, (void *)regs->sp, 5*8); normal_regs->orig_ax = 0; /* Missing (lost) #GP error code */ regs->ip = (unsigned long)general_protection; regs->sp = (unsigned long)&normal_regs->orig_ax; return; } #endif ist_enter(regs); notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV); tsk->thread.error_code = error_code; tsk->thread.trap_nr = X86_TRAP_DF; #ifdef CONFIG_DOUBLEFAULT df_debug(regs, error_code); #endif /* * This is always a kernel trap and never fixable (and thus must * never return). */ for (;;) die(str, regs, error_code); }
safe
149
sec_update(uint8 * key, uint8 * update_key) { uint8 shasig[20]; RDSSL_SHA1 sha1; RDSSL_MD5 md5; RDSSL_RC4 update; rdssl_sha1_init(&sha1); rdssl_sha1_update(&sha1, update_key, g_rc4_key_len); rdssl_sha1_update(&sha1, pad_54, 40); rdssl_sha1_update(&sha1, key, g_rc4_key_len); rdssl_sha1_final(&sha1, shasig); rdssl_md5_init(&md5); rdssl_md5_update(&md5, update_key, g_rc4_key_len); rdssl_md5_update(&md5, pad_92, 48); rdssl_md5_update(&md5, shasig, 20); rdssl_md5_final(&md5, key); rdssl_rc4_set_key(&update, key, g_rc4_key_len); rdssl_rc4_crypt(&update, key, key, g_rc4_key_len); if (g_rc4_key_len == 8) sec_make_40bit(key); }
safe
150
ofputil_decode_meter_config(struct ofpbuf *msg, struct ofputil_meter_config *mc, struct ofpbuf *bands) { const struct ofp13_meter_config *omc; enum ofperr err; /* Pull OpenFlow headers for the first call. */ if (!msg->header) { ofpraw_pull_assert(msg); } if (!msg->size) { return EOF; } omc = ofpbuf_try_pull(msg, sizeof *omc); if (!omc) { VLOG_WARN_RL(&bad_ofmsg_rl, "OFPMP_METER_CONFIG reply has %"PRIu32" leftover bytes at end", msg->size); return OFPERR_OFPBRC_BAD_LEN; } ofpbuf_clear(bands); err = ofputil_pull_bands(msg, ntohs(omc->length) - sizeof *omc, &mc->n_bands, bands); if (err) { return err; } mc->meter_id = ntohl(omc->meter_id); mc->flags = ntohs(omc->flags); mc->bands = bands->data; return 0; }
safe
151
int sm_looptest_show_switch_lfts(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) { fm_mgr_config_errno_t res; fm_msg_ret_code_t ret_code; uint8_t data[BUF_SZ]; int index=-1; fm_config_interation_data_t interationData; int start; if (argc > 1) { printf("Error: only 1 argument expected\n"); return 0; } if (argc == 1) { index = atol(argv[0]); } memset(&interationData, 0, sizeof(fm_config_interation_data_t)); interationData.start = start = 1; interationData.index = index; while (!interationData.done) { memcpy(data, &interationData, sizeof(fm_config_interation_data_t)); if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_SM_LOOP_TEST_SHOW_LFTS, mgr, BUF_SZ, data, &ret_code)) != FM_CONF_OK) { fprintf(stderr, "sm_looptest_show_switch_lfts: Failed to retrieve data: \n" "\tError:(%d) %s \n\tRet code:(%d) %s\n", res, fm_mgr_get_error_str(res),ret_code, fm_mgr_get_resp_error_str(ret_code)); return 0; } if (start) { start = 0; if (index == -1) printf("Successfully sent Loop Test LFT show for node index (all) to local SM instance\n"); else printf("Successfully sent Loop Test LFT show for node index %d to local SM instance\n", index); } memcpy(&interationData, data, sizeof(fm_config_interation_data_t)); printf("%s", interationData.intermediateBuffer); } return 0; }
safe
152
int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) { word32 val, inIdx = 0, outIdx = 0; int w = 0; if (out == NULL || in == NULL || outSz < 4 || inSz < 2) return BAD_FUNC_ARG; /* The first byte expands into b/40 dot b%40. */ val = in[inIdx++]; w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40); if (w < 0) { w = BUFFER_E; goto exit; } outIdx += w; val = 0; while (inIdx < inSz && outIdx < outSz) { /* extract the next OID digit from in to val */ /* first bit is used to set if value is coded on 1 or multiple bytes */ if (in[inIdx] & 0x80) { val += in[inIdx] & 0x7F; val *= 128; } else { /* write val as text into out */ val += in[inIdx]; w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val); if (w < 0 || (word32)w > outSz - outIdx) { w = BUFFER_E; goto exit; } outIdx += w; val = 0; } inIdx++; } if (outIdx == outSz) outIdx--; out[outIdx] = 0; w = (int)outIdx; exit: return w; }
safe
153
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; }
safe
154
psutil_proc_args(PyObject *self, PyObject *args) { int pid; PyObject *py_retlist = PyList_New(0); PyObject *py_arg = NULL; struct procsinfo procbuf; long arg_max; char *argbuf = NULL; char *curarg = NULL; int ret; if (py_retlist == NULL) return NULL; if (!PyArg_ParseTuple(args, "i", &pid)) goto error; arg_max = sysconf(_SC_ARG_MAX); argbuf = malloc(arg_max); if (argbuf == NULL) { PyErr_NoMemory(); goto error; } procbuf.pi_pid = pid; ret = getargs(&procbuf, sizeof(procbuf), argbuf, ARG_MAX); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } curarg = argbuf; /* getargs will always append an extra NULL to end the arg list, * even if the buffer is not big enough (even though it is supposed * to be) so the following 'while' is safe */ while (*curarg != '\0') { py_arg = PyUnicode_DecodeFSDefault(curarg); if (!py_arg) goto error; if (PyList_Append(py_retlist, py_arg)) goto error; Py_DECREF(py_arg); curarg = strchr(curarg, '\0') + 1; } free(argbuf); return py_retlist; error: if (argbuf != NULL) free(argbuf); Py_XDECREF(py_retlist); Py_XDECREF(py_arg); return NULL; }
safe
155
Value ExpressionSplit::evaluate(const Document& root, Variables* variables) const { Value inputArg = _children[0]->evaluate(root, variables); Value separatorArg = _children[1]->evaluate(root, variables); if (inputArg.nullish() || separatorArg.nullish()) { return Value(BSONNULL); } uassert(40085, str::stream() << "$split requires an expression that evaluates to a string as a first " "argument, found: " << typeName(inputArg.getType()), inputArg.getType() == BSONType::String); uassert(40086, str::stream() << "$split requires an expression that evaluates to a string as a second " "argument, found: " << typeName(separatorArg.getType()), separatorArg.getType() == BSONType::String); std::string input = inputArg.getString(); std::string separator = separatorArg.getString(); uassert(40087, "$split requires a non-empty separator", !separator.empty()); std::vector<Value> output; // Keep track of the index at which the current output string began. size_t splitStartIndex = 0; // Iterate through 'input' and check to see if 'separator' matches at any point. for (size_t i = 0; i < input.size();) { if (stringHasTokenAtIndex(i, input, separator)) { // We matched; add the current string to our output and jump ahead. StringData splitString(input.c_str() + splitStartIndex, i - splitStartIndex); output.push_back(Value(splitString)); i += separator.size(); splitStartIndex = i; } else { // We did not match, continue to the next character. ++i; } } StringData splitString(input.c_str() + splitStartIndex, input.size() - splitStartIndex); output.push_back(Value(splitString)); return Value(output); }
safe
156
static void sun8i_a23_get_pll1_factors(struct factors_request *req) { u8 div; /* Normalize value to a 6M multiple */ div = req->rate / 6000000; req->rate = 6000000 * div; /* m is always zero for pll1 */ req->m = 0; /* k is 1 only on these cases */ if (req->rate >= 768000000 || req->rate == 42000000 || req->rate == 54000000) req->k = 1; else req->k = 0; /* p will be 2 for divs under 20 and odd divs under 32 */ if (div < 20 || (div < 32 && (div & 1))) req->p = 2; /* p will be 1 for even divs under 32, divs under 40 and odd pairs * of divs between 40-62 */ else if (div < 40 || (div < 64 && (div & 2))) req->p = 1; /* any other entries have p = 0 */ else req->p = 0; /* calculate a suitable n based on k and p */ div <<= req->p; div /= (req->k + 1); req->n = div / 4 - 1; }
safe
157
TEE_Result tee_mmu_vbuf_to_mobj_offs(const struct user_ta_ctx *utc, const void *va, size_t size, struct mobj **mobj, size_t *offs) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (!r->mobj) continue; if (core_is_buffer_inside(va, size, r->va, r->size)) { size_t poffs; poffs = mobj_get_phys_offs(r->mobj, CORE_MMU_USER_PARAM_SIZE); *mobj = r->mobj; *offs = (vaddr_t)va - r->va + r->offset - poffs; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; }
safe
158
static int map_files_d_revalidate(struct dentry *dentry, unsigned int flags) { unsigned long vm_start, vm_end; bool exact_vma_exists = false; struct mm_struct *mm = NULL; struct task_struct *task; struct inode *inode; int status = 0; if (flags & LOOKUP_RCU) return -ECHILD; inode = d_inode(dentry); task = get_proc_task(inode); if (!task) goto out_notask; mm = mm_access(task, PTRACE_MODE_READ_FSCREDS); if (IS_ERR_OR_NULL(mm)) goto out; if (!dname_to_vma_addr(dentry, &vm_start, &vm_end)) { down_read(&mm->mmap_sem); exact_vma_exists = !!find_exact_vma(mm, vm_start, vm_end); up_read(&mm->mmap_sem); } mmput(mm); if (exact_vma_exists) { task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid); security_task_to_inode(task, inode); status = 1; } out: put_task_struct(task); out_notask: return status; }
safe
159
static void flush_old_files(struct files_struct * files) { long j = -1; struct fdtable *fdt; spin_lock(&files->file_lock); for (;;) { unsigned long set, i; j++; i = j * __NFDBITS; fdt = files_fdtable(files); if (i >= fdt->max_fds) break; set = fdt->close_on_exec[j]; if (!set) continue; fdt->close_on_exec[j] = 0; spin_unlock(&files->file_lock); for ( ; set ; i++,set >>= 1) { if (set & 1) { sys_close(i); } } spin_lock(&files->file_lock); } spin_unlock(&files->file_lock); }
safe
160
RGWPutObjProcessor *RGWPutObj::select_processor(RGWObjectCtx& obj_ctx, bool *is_multipart) { RGWPutObjProcessor *processor; bool multipart = s->info.args.exists("uploadId"); uint64_t part_size = s->cct->_conf->rgw_obj_stripe_size; if (!multipart) { processor = new RGWPutObjProcessor_Atomic(obj_ctx, s->bucket_info, s->bucket, s->object.name, part_size, s->req_id, s->bucket_info.versioning_enabled()); (static_cast<RGWPutObjProcessor_Atomic *>(processor))->set_olh_epoch(olh_epoch); (static_cast<RGWPutObjProcessor_Atomic *>(processor))->set_version_id(version_id); } else { processor = new RGWPutObjProcessor_Multipart(obj_ctx, s->bucket_info, part_size, s); } if (is_multipart) { *is_multipart = multipart; } return processor; }
safe
161
get_inode_and_dev (struct cpio_file_stat *hdr, struct stat *st) { if (renumber_inodes_option) { if (st->st_nlink > 1) { struct inode_val *ival = find_inode_val (st->st_ino, major (st->st_dev), minor (st->st_dev)); if (!ival) ival = add_inode (st->st_ino, NULL, major (st->st_dev), minor (st->st_dev)); hdr->c_ino = ival->trans_inode; } else hdr->c_ino = next_inode++; } else hdr->c_ino = st->st_ino; if (ignore_devno_option) { hdr->c_dev_maj = 0; hdr->c_dev_min = 0; } else { hdr->c_dev_maj = major (st->st_dev); hdr->c_dev_min = minor (st->st_dev); } }
safe
162
scanner_add_reference (parser_context_t *context_p, /**< context */ scanner_context_t *scanner_context_p) /**< scanner context */ { lexer_lit_location_t *lit_location_p = scanner_add_custom_literal (context_p, scanner_context_p->active_literal_pool_p, &context_p->token.lit_location); #if JERRY_ESNEXT lit_location_p->type |= SCANNER_LITERAL_IS_USED; #endif /* JERRY_ESNEXT */ if (scanner_context_p->active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH) { lit_location_p->type |= SCANNER_LITERAL_NO_REG; } scanner_detect_eval_call (context_p, scanner_context_p); } /* scanner_add_reference */
safe
163
static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8) return -EOPNOTSUPP; if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0) return 0; x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x == NULL) return 0; spin_lock_bh(&x->lock); if (x->km.state == XFRM_STATE_ACQ) { x->km.state = XFRM_STATE_ERROR; wake_up(&net->xfrm.km_waitq); } spin_unlock_bh(&x->lock); xfrm_state_put(x); return 0; }
safe
164
int bnxt_re_add_gid(const struct ib_gid_attr *attr, void **context) { int rc; u32 tbl_idx = 0; u16 vlan_id = 0xFFFF; struct bnxt_re_gid_ctx *ctx, **ctx_tbl; struct bnxt_re_dev *rdev = to_bnxt_re_dev(attr->device, ibdev); struct bnxt_qplib_sgid_tbl *sgid_tbl = &rdev->qplib_res.sgid_tbl; rc = rdma_read_gid_l2_fields(attr, &vlan_id, NULL); if (rc) return rc; rc = bnxt_qplib_add_sgid(sgid_tbl, (struct bnxt_qplib_gid *)&attr->gid, rdev->qplib_res.netdev->dev_addr, vlan_id, true, &tbl_idx); if (rc == -EALREADY) { ctx_tbl = sgid_tbl->ctx; ctx_tbl[tbl_idx]->refcnt++; *context = ctx_tbl[tbl_idx]; return 0; } if (rc < 0) { dev_err(rdev_to_dev(rdev), "Failed to add GID: %#x", rc); return rc; } ctx = kmalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx_tbl = sgid_tbl->ctx; ctx->idx = tbl_idx; ctx->refcnt = 1; ctx_tbl[tbl_idx] = ctx; *context = ctx; return rc; }
safe
165
static int php_zlib_decode(const char *in_buf, size_t in_len, char **out_buf, size_t *out_len, int encoding, size_t max_len TSRMLS_DC) { int status = Z_DATA_ERROR; z_stream Z; memset(&Z, 0, sizeof(z_stream)); Z.zalloc = php_zlib_alloc; Z.zfree = php_zlib_free; if (in_len) { retry_raw_inflate: status = inflateInit2(&Z, encoding); if (Z_OK == status) { Z.next_in = (Bytef *) in_buf; Z.avail_in = in_len + 1; /* NOTE: data must be zero terminated */ switch (status = php_zlib_inflate_rounds(&Z, max_len, out_buf, out_len)) { case Z_STREAM_END: inflateEnd(&Z); return SUCCESS; case Z_DATA_ERROR: /* raw deflated data? */ if (PHP_ZLIB_ENCODING_ANY == encoding) { inflateEnd(&Z); encoding = PHP_ZLIB_ENCODING_RAW; goto retry_raw_inflate; } } inflateEnd(&Z); } } *out_buf = NULL; *out_len = 0; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", zError(status)); return FAILURE; }
safe
166
static void free_utc(struct user_ta_ctx *utc) { struct user_ta_elf *elf; tee_pager_rem_uta_areas(utc); TAILQ_FOREACH(elf, &utc->elfs, link) release_ta_memory_by_mobj(elf->mobj_code); release_ta_memory_by_mobj(utc->mobj_stack); release_ta_memory_by_mobj(utc->mobj_exidx); /* * Close sessions opened by this TA * Note that tee_ta_close_session() removes the item * from the utc->open_sessions list. */ while (!TAILQ_EMPTY(&utc->open_sessions)) { tee_ta_close_session(TAILQ_FIRST(&utc->open_sessions), &utc->open_sessions, KERN_IDENTITY); } vm_info_final(utc); mobj_free(utc->mobj_stack); mobj_free(utc->mobj_exidx); free_elfs(&utc->elfs); /* Free cryp states created by this TA */ tee_svc_cryp_free_states(utc); /* Close cryp objects opened by this TA */ tee_obj_close_all(utc); /* Free emums created by this TA */ tee_svc_storage_close_all_enum(utc); free(utc); }
safe
167
static bool check_equality_for_exist2in(Item_func *func, bool allow_subselect, Item_ident **local_field, Item **outer_exp) { Item **args; if (func->functype() != Item_func::EQ_FUNC) return FALSE; DBUG_ASSERT(func->argument_count() == 2); args= func->arguments(); if (args[0]->real_type() == Item::FIELD_ITEM && args[0]->all_used_tables() != OUTER_REF_TABLE_BIT && args[1]->all_used_tables() == OUTER_REF_TABLE_BIT && (allow_subselect || !args[1]->has_subquery())) { /* It is Item_field or Item_direct_view_ref) */ DBUG_ASSERT(args[0]->type() == Item::FIELD_ITEM || args[0]->type() == Item::REF_ITEM); *local_field= (Item_ident *)args[0]; *outer_exp= args[1]; return TRUE; } else if (args[1]->real_type() == Item::FIELD_ITEM && args[1]->all_used_tables() != OUTER_REF_TABLE_BIT && args[0]->all_used_tables() == OUTER_REF_TABLE_BIT && (allow_subselect || !args[0]->has_subquery())) { /* It is Item_field or Item_direct_view_ref) */ DBUG_ASSERT(args[1]->type() == Item::FIELD_ITEM || args[1]->type() == Item::REF_ITEM); *local_field= (Item_ident *)args[1]; *outer_exp= args[0]; return TRUE; } return FALSE; }
safe
168
get_xdg_dir_from_prefix (const char *prefix, const char **where, const char **dir) { if (strcmp (prefix, "xdg-data") == 0) { if (where) *where = "data"; if (dir) *dir = g_get_user_data_dir (); return TRUE; } if (strcmp (prefix, "xdg-cache") == 0) { if (where) *where = "cache"; if (dir) *dir = g_get_user_cache_dir (); return TRUE; } if (strcmp (prefix, "xdg-config") == 0) { if (where) *where = "config"; if (dir) *dir = g_get_user_config_dir (); return TRUE; } return FALSE; }
safe
169
int handle_ud(struct kvm_vcpu *vcpu) { static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX }; int emul_type = EMULTYPE_TRAP_UD; char sig[5]; /* ud2; .ascii "kvm" */ struct x86_exception e; if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0))) return 1; if (force_emulation_prefix && kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu), sig, sizeof(sig), &e) == 0 && memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) { kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig)); emul_type = EMULTYPE_TRAP_UD_FORCED; } return kvm_emulate_instruction(vcpu, emul_type); }
safe
170
int __init create_node_manager_caches(void) { nat_entry_slab = f2fs_kmem_cache_create("nat_entry", sizeof(struct nat_entry)); if (!nat_entry_slab) goto fail; free_nid_slab = f2fs_kmem_cache_create("free_nid", sizeof(struct free_nid)); if (!free_nid_slab) goto destroy_nat_entry; nat_entry_set_slab = f2fs_kmem_cache_create("nat_entry_set", sizeof(struct nat_entry_set)); if (!nat_entry_set_slab) goto destroy_free_nid; return 0; destroy_free_nid: kmem_cache_destroy(free_nid_slab); destroy_nat_entry: kmem_cache_destroy(nat_entry_slab); fail: return -ENOMEM; }
safe
171
set_syslog_parameters(const char *ident, int facility) { /* * guc.c is likely to call us repeatedly with same parameters, so don't * thrash the syslog connection unnecessarily. Also, we do not re-open * the connection until needed, since this routine will get called whether * or not Log_destination actually mentions syslog. * * Note that we make our own copy of the ident string rather than relying * on guc.c's. This may be overly paranoid, but it ensures that we cannot * accidentally free a string that syslog is still using. */ if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 || syslog_facility != facility) { if (openlog_done) { closelog(); openlog_done = false; } if (syslog_ident) free(syslog_ident); syslog_ident = strdup(ident); /* if the strdup fails, we will cope in write_syslog() */ syslog_facility = facility; } }
safe
172
int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp, struct bpf_prog *xdp_prog) { struct redirect_info *ri = this_cpu_ptr(&redirect_info); struct net_device *fwd; u32 index = ri->ifindex; int err; if (ri->map) return xdp_do_redirect_map(dev, xdp, xdp_prog); fwd = dev_get_by_index_rcu(dev_net(dev), index); ri->ifindex = 0; if (unlikely(!fwd)) { err = -EINVAL; goto err; } err = __bpf_tx_xdp(fwd, NULL, xdp, 0); if (unlikely(err)) goto err; _trace_xdp_redirect(dev, xdp_prog, index); return 0; err: _trace_xdp_redirect_err(dev, xdp_prog, index, err); return err; }
safe
173
static int bnx2x_gunzip_init(struct bnx2x *bp) { bp->gunzip_buf = dma_alloc_coherent(&bp->pdev->dev, FW_BUF_SIZE, &bp->gunzip_mapping, GFP_KERNEL); if (bp->gunzip_buf == NULL) goto gunzip_nomem1; bp->strm = kmalloc(sizeof(*bp->strm), GFP_KERNEL); if (bp->strm == NULL) goto gunzip_nomem2; bp->strm->workspace = vmalloc(zlib_inflate_workspacesize()); if (bp->strm->workspace == NULL) goto gunzip_nomem3; return 0; gunzip_nomem3: kfree(bp->strm); bp->strm = NULL; gunzip_nomem2: dma_free_coherent(&bp->pdev->dev, FW_BUF_SIZE, bp->gunzip_buf, bp->gunzip_mapping); bp->gunzip_buf = NULL; gunzip_nomem1: BNX2X_ERR("Cannot allocate firmware buffer for un-compression\n"); return -ENOMEM; }
safe
174
void comps_objrtree_values_walk(COMPS_ObjRTree * rt, void* udata, void (*walk_f)(void*, COMPS_Object*)) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, NULL); comps_hslist_append(tmplist, rt->subnodes, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = (COMPS_HSList*)it->data; for (it = tmp_subnodes->first; it != NULL; it=it->next) { if (((COMPS_ObjRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, ((COMPS_ObjRTreeData*)it->data)->subnodes, 0); } if (((COMPS_ObjRTreeData*)it->data)->data != NULL) { walk_f(udata, ((COMPS_ObjRTreeData*)it->data)->data); } } } comps_hslist_destroy(&tmplist); }
safe
175
static int verify_not_halted(struct usbtest_dev *tdev, int ep, struct urb *urb) { int retval; u16 status; /* shouldn't look or act halted */ retval = usb_get_std_status(urb->dev, USB_RECIP_ENDPOINT, ep, &status); if (retval < 0) { ERROR(tdev, "ep %02x couldn't get no-halt status, %d\n", ep, retval); return retval; } if (status != 0) { ERROR(tdev, "ep %02x bogus status: %04x != 0\n", ep, status); return -EINVAL; } retval = simple_io(tdev, urb, 1, 0, 0, __func__); if (retval != 0) return -EINVAL; return 0; }
safe
176
script_get(exarg_T *eap UNUSED, char_u *cmd UNUSED) { #ifdef FEAT_EVAL list_T *l; listitem_T *li; char_u *s; garray_T ga; if (cmd[0] != '<' || cmd[1] != '<' || eap->getline == NULL) return NULL; cmd += 2; l = heredoc_get(eap, cmd, TRUE, FALSE); if (l == NULL) return NULL; ga_init2(&ga, 1, 0x400); FOR_ALL_LIST_ITEMS(l, li) { s = tv_get_string(&li->li_tv); ga_concat(&ga, s); ga_append(&ga, '\n'); } ga_append(&ga, NUL); list_free(l); return (char_u *)ga.ga_data; #else return NULL; #endif }
safe
177
SECURITY_STATUS SEC_ENTRY VerifySignature(PCtxtHandle phContext, PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*) sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (table->VerifySignature == NULL) return SEC_E_UNSUPPORTED_FUNCTION; status = table->VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP); return status; }
safe
178
static ssize_t ucma_init_qp_attr(struct ucma_file *file, const char __user *inbuf, int in_len, int out_len) { struct rdma_ucm_init_qp_attr cmd; struct ib_uverbs_qp_attr resp; struct ucma_context *ctx; struct ib_qp_attr qp_attr; int ret; if (out_len < sizeof(resp)) return -ENOSPC; if (copy_from_user(&cmd, inbuf, sizeof(cmd))) return -EFAULT; if (cmd.qp_state > IB_QPS_ERR) return -EINVAL; ctx = ucma_get_ctx_dev(file, cmd.id); if (IS_ERR(ctx)) return PTR_ERR(ctx); resp.qp_attr_mask = 0; memset(&qp_attr, 0, sizeof qp_attr); qp_attr.qp_state = cmd.qp_state; ret = rdma_init_qp_attr(ctx->cm_id, &qp_attr, &resp.qp_attr_mask); if (ret) goto out; ib_copy_qp_attr_to_user(ctx->cm_id->device, &resp, &qp_attr); if (copy_to_user(u64_to_user_ptr(cmd.response), &resp, sizeof(resp))) ret = -EFAULT; out: ucma_put_ctx(ctx); return ret; }
safe
179
TEST_F(EncryptedRecordTest, TestWriteAppDataInPlace) { TLSMessage msg{ContentType::application_data, getBuf("1234567890", 5, 17)}; EXPECT_CALL(*writeAead_, _encrypt(_, _, 0)) .WillOnce(Invoke([](std::unique_ptr<IOBuf>& buf, const IOBuf*, uint64_t) { // footer should have been written w/o chaining EXPECT_FALSE(buf->isChained()); expectSame(buf, "123456789017"); // we need to return room for the header return getBuf("abcd1234abcd", 5, 0); })); auto buf = write_.write(std::move(msg)); EXPECT_FALSE(buf.data->isChained()); expectSame(buf.data, "1703030006abcd1234abcd"); }
safe
180
static st_plugin_int *plugin_insert_or_reuse(struct st_plugin_int *plugin) { uint i; struct st_plugin_int *tmp; DBUG_ENTER("plugin_insert_or_reuse"); for (i= 0; i < plugin_array.elements; i++) { tmp= *dynamic_element(&plugin_array, i, struct st_plugin_int **); if (tmp->state == PLUGIN_IS_FREED) { memcpy(tmp, plugin, sizeof(struct st_plugin_int)); DBUG_RETURN(tmp); } } if (insert_dynamic(&plugin_array, (uchar*)&plugin)) DBUG_RETURN(0); tmp= *dynamic_element(&plugin_array, plugin_array.elements - 1, struct st_plugin_int **)= (struct st_plugin_int *) memdup_root(&plugin_mem_root, (uchar*)plugin, sizeof(struct st_plugin_int)); DBUG_RETURN(tmp); }
safe
181
GF_Err gf_isom_set_ipod_compatible(GF_ISOFile *the_file, u32 trackNumber) { GF_TrackBox *trak; GF_Err e; GF_MPEGVisualSampleEntryBox *entry; e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE); if (e) return e; trak = gf_isom_get_track_from_file(the_file, trackNumber); if (!trak || !trak->Media) return GF_BAD_PARAM; entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, 0); if (!entry) return GF_OK; switch (entry->type) { case GF_ISOM_BOX_TYPE_AVC1: case GF_ISOM_BOX_TYPE_AVC2: case GF_ISOM_BOX_TYPE_AVC3: case GF_ISOM_BOX_TYPE_AVC4: case GF_ISOM_BOX_TYPE_SVC1: case GF_ISOM_BOX_TYPE_MVC1: case GF_ISOM_BOX_TYPE_HVC1: case GF_ISOM_BOX_TYPE_HEV1: case GF_ISOM_BOX_TYPE_HVT1: break; default: return GF_OK; } if (!entry->ipod_ext) entry->ipod_ext = (GF_UnknownUUIDBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_UUID); memcpy(entry->ipod_ext->uuid, GF_ISOM_IPOD_EXT, sizeof(u8)*16); entry->ipod_ext->dataSize = 0; return GF_OK; }
safe
182
static void moveresults (lua_State *L, StkId res, int nres, int wanted) { StkId firstresult; int i; switch (wanted) { /* handle typical cases separately */ case 0: /* no values needed */ L->top = res; return; case 1: /* one value needed */ if (nres == 0) /* no results? */ setnilvalue(s2v(res)); /* adjust with nil */ else setobjs2s(L, res, L->top - nres); /* move it to proper place */ L->top = res + 1; return; case LUA_MULTRET: wanted = nres; /* we want all results */ break; default: /* multiple results (or to-be-closed variables) */ if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */ ptrdiff_t savedres = savestack(L, res); luaF_close(L, res, LUA_OK); /* may change the stack */ res = restorestack(L, savedres); wanted = codeNresults(wanted); /* correct value */ if (wanted == LUA_MULTRET) wanted = nres; } break; } firstresult = L->top - nres; /* index of first result */ /* move all results to correct place */ for (i = 0; i < nres && i < wanted; i++) setobjs2s(L, res + i, firstresult + i); for (; i < wanted; i++) /* complete wanted number of results */ setnilvalue(s2v(res + i)); L->top = res + wanted; /* top points after the last result */ }
safe
183
void addClusterMonitorPrivileges(PrivilegeVector* privileges) { Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forClusterResource(), clusterMonitorRoleClusterActions)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forAnyNormalResource(), clusterMonitorRoleDatabaseActions)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forDatabaseName("config"), clusterMonitorRoleDatabaseActions)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forDatabaseName("local"), clusterMonitorRoleDatabaseActions)); addReadOnlyDbPrivileges(privileges, "config"); addReadOnlyDbPrivileges(privileges, "local"); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forExactNamespace(NamespaceString("local", "system.replset")), ActionType::find)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forExactNamespace(NamespaceString("local", "replset.election")), ActionType::find)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forExactNamespace(NamespaceString("local", "replset.minvalid")), ActionType::find)); Privilege::addPrivilegeToPrivilegeVector( privileges, Privilege(ResourcePattern::forCollectionName("system.profile"), ActionType::find)); }
safe
184
static void cms_env_set_version(CMS_EnvelopedData *env) { int i; CMS_RecipientInfo *ri; /* * Can't set version higher than 4 so if 4 or more already nothing to do. */ if (env->version >= 4) return; cms_env_set_originfo_version(env); if (env->version >= 3) return; for (i = 0; i < sk_CMS_RecipientInfo_num(env->recipientInfos); i++) { ri = sk_CMS_RecipientInfo_value(env->recipientInfos, i); if (ri->type == CMS_RECIPINFO_PASS || ri->type == CMS_RECIPINFO_OTHER) { env->version = 3; return; } else if (ri->type != CMS_RECIPINFO_TRANS || ri->d.ktri->version != 0) { env->version = 2; } } if (env->originatorInfo || env->unprotectedAttrs) env->version = 2; if (env->version == 2) return; env->version = 0; }
safe
185
inline void ReferenceChecker::visit(Reference &ope) { auto it = std::find(params_.begin(), params_.end(), ope.name_); if (it != params_.end()) { return; } if (!grammar_.count(ope.name_)) { error_s[ope.name_] = ope.s_; error_message[ope.name_] = "'" + ope.name_ + "' is not defined."; } else { const auto &rule = grammar_.at(ope.name_); if (rule.is_macro) { if (!ope.is_macro_ || ope.args_.size() != rule.params.size()) { error_s[ope.name_] = ope.s_; error_message[ope.name_] = "incorrect number of arguments."; } } else if (ope.is_macro_) { error_s[ope.name_] = ope.s_; error_message[ope.name_] = "'" + ope.name_ + "' is not macro."; } } }
safe
186
static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (read_seqcount_retry(&old->d_seq, nd->seq)) goto failed; nd->path.dentry = parent; nd->seq = seq; break; } if (!follow_up_rcu(&nd->path)) break; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } while (d_mountpoint(nd->path.dentry)) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); if (read_seqretry(&mount_lock, nd->m_seq)) goto failed; } nd->inode = inode; return 0; failed: nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); return -ECHILD; }
safe
187
_XkbCreateIndicatorMap(DeviceIntPtr dev, Atom indicator, int ledClass, int ledID, XkbIndicatorMapPtr * map_return, int *led_return, Bool dryRun) { XkbSrvLedInfoPtr sli; XkbIndicatorMapPtr map; int led; sli = XkbFindSrvLedInfo(dev, ledClass, ledID, XkbXI_IndicatorsMask); if (!sli) return BadAlloc; map = _XkbFindNamedIndicatorMap(sli, indicator, &led); if (!map) { /* find first unused indicator maps and assign the name to it */ for (led = 0, map = NULL; (led < XkbNumIndicators) && (map == NULL); led++) { if ((sli->names) && (sli->maps) && (sli->names[led] == None) && (!XkbIM_InUse(&sli->maps[led]))) { map = &sli->maps[led]; if (!dryRun) sli->names[led] = indicator; break; } } } if (!map) return BadAlloc; *led_return = led; *map_return = map; return Success; }
safe
188
static void xfrm6_tunnel_free_spi(struct net *net, xfrm_address_t *saddr) { struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net); struct xfrm6_tunnel_spi *x6spi; struct hlist_node *n; spin_lock_bh(&xfrm6_tunnel_spi_lock); hlist_for_each_entry_safe(x6spi, n, &xfrm6_tn->spi_byaddr[xfrm6_tunnel_spi_hash_byaddr(saddr)], list_byaddr) { if (xfrm6_addr_equal(&x6spi->addr, saddr)) { if (refcount_dec_and_test(&x6spi->refcnt)) { hlist_del_rcu(&x6spi->list_byaddr); hlist_del_rcu(&x6spi->list_byspi); call_rcu(&x6spi->rcu_head, x6spi_destroy_rcu); break; } } } spin_unlock_bh(&xfrm6_tunnel_spi_lock); }
safe
189
static u32 vmx_exec_control(struct vcpu_vmx *vmx) { u32 exec_control = vmcs_config.cpu_based_exec_ctrl; if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT) exec_control &= ~CPU_BASED_MOV_DR_EXITING; if (!cpu_need_tpr_shadow(&vmx->vcpu)) { exec_control &= ~CPU_BASED_TPR_SHADOW; #ifdef CONFIG_X86_64 exec_control |= CPU_BASED_CR8_STORE_EXITING | CPU_BASED_CR8_LOAD_EXITING; #endif } if (!enable_ept) exec_control |= CPU_BASED_CR3_STORE_EXITING | CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_INVLPG_EXITING; return exec_control; }
safe
190
void start_tty(struct tty_struct *tty) { unsigned long flags; spin_lock_irqsave(&tty->ctrl_lock, flags); if (!tty->stopped || tty->flow_stopped) { spin_unlock_irqrestore(&tty->ctrl_lock, flags); return; } tty->stopped = 0; if (tty->link && tty->link->packet) { tty->ctrl_status &= ~TIOCPKT_STOP; tty->ctrl_status |= TIOCPKT_START; wake_up_interruptible_poll(&tty->link->read_wait, POLLIN); } spin_unlock_irqrestore(&tty->ctrl_lock, flags); if (tty->ops->start) (tty->ops->start)(tty); /* If we have a running line discipline it may need kicking */ tty_wakeup(tty); }
safe
191
load_newobj(UnpicklerObject *self) { PyObject *args = NULL; PyObject *clsraw = NULL; PyTypeObject *cls; /* clsraw cast to its true type */ PyObject *obj; PickleState *st = _Pickle_GetGlobalState(); /* Stack is ... cls argtuple, and we want to call * cls.__new__(cls, *argtuple). */ PDATA_POP(self->stack, args); if (args == NULL) goto error; if (!PyTuple_Check(args)) { PyErr_SetString(st->UnpicklingError, "NEWOBJ expected an arg " "tuple."); goto error; } PDATA_POP(self->stack, clsraw); cls = (PyTypeObject *)clsraw; if (cls == NULL) goto error; if (!PyType_Check(cls)) { PyErr_SetString(st->UnpicklingError, "NEWOBJ class argument " "isn't a type object"); goto error; } if (cls->tp_new == NULL) { PyErr_SetString(st->UnpicklingError, "NEWOBJ class argument " "has NULL tp_new"); goto error; } /* Call __new__. */ obj = cls->tp_new(cls, args, NULL); if (obj == NULL) goto error; Py_DECREF(args); Py_DECREF(clsraw); PDATA_PUSH(self->stack, obj, -1); return 0; error: Py_XDECREF(args); Py_XDECREF(clsraw); return -1; }
safe
192
ossl_cipher_update(int argc, VALUE *argv, VALUE self) { EVP_CIPHER_CTX *ctx; unsigned char *in; long in_len, out_len; VALUE data, str; rb_scan_args(argc, argv, "11", &data, &str); if (!RTEST(rb_attr_get(self, id_key_set))) ossl_raise(eCipherError, "key not set"); StringValue(data); in = (unsigned char *)RSTRING_PTR(data); if ((in_len = RSTRING_LEN(data)) == 0) ossl_raise(rb_eArgError, "data must not be empty"); GetCipher(self, ctx); out_len = in_len+EVP_CIPHER_CTX_block_size(ctx); if (out_len <= 0) { ossl_raise(rb_eRangeError, "data too big to make output buffer: %ld bytes", in_len); } if (NIL_P(str)) { str = rb_str_new(0, out_len); } else { StringValue(str); rb_str_resize(str, out_len); } if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len)) ossl_raise(eCipherError, NULL); assert(out_len < RSTRING_LEN(str)); rb_str_set_len(str, out_len); return str; }
safe
193
int udp_gro_complete(struct sk_buff *skb, int nhoff) { struct udp_offload_priv *uo_priv; __be16 newlen = htons(skb->len - nhoff); struct udphdr *uh = (struct udphdr *)(skb->data + nhoff); int err = -ENOSYS; uh->len = newlen; rcu_read_lock(); uo_priv = rcu_dereference(udp_offload_base); for (; uo_priv != NULL; uo_priv = rcu_dereference(uo_priv->next)) { if (net_eq(read_pnet(&uo_priv->net), dev_net(skb->dev)) && uo_priv->offload->port == uh->dest && uo_priv->offload->callbacks.gro_complete) break; } if (uo_priv) { NAPI_GRO_CB(skb)->proto = uo_priv->offload->ipproto; err = uo_priv->offload->callbacks.gro_complete(skb, nhoff + sizeof(struct udphdr), uo_priv->offload); } rcu_read_unlock(); if (skb->remcsum_offload) skb_shinfo(skb)->gso_type |= SKB_GSO_TUNNEL_REMCSUM; skb->encapsulation = 1; skb_set_inner_mac_header(skb, nhoff + sizeof(struct udphdr)); return err; }
safe
194
psutil_cpu_times(PyObject *self, PyObject *args) { double idle, kernel, user, system; FILETIME idle_time, kernel_time, user_time; if (!GetSystemTimes(&idle_time, &kernel_time, &user_time)) return PyErr_SetFromWindowsErr(0); idle = (double)((HI_T * idle_time.dwHighDateTime) + \ (LO_T * idle_time.dwLowDateTime)); user = (double)((HI_T * user_time.dwHighDateTime) + \ (LO_T * user_time.dwLowDateTime)); kernel = (double)((HI_T * kernel_time.dwHighDateTime) + \ (LO_T * kernel_time.dwLowDateTime)); // Kernel time includes idle time. // We return only busy kernel time subtracting idle time from // kernel time. system = (kernel - idle); return Py_BuildValue("(ddd)", user, system, idle); }
safe
195
static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in) { jpc_dec_t *dec; if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) { return 0; } dec->image = 0; dec->xstart = 0; dec->ystart = 0; dec->xend = 0; dec->yend = 0; dec->tilewidth = 0; dec->tileheight = 0; dec->tilexoff = 0; dec->tileyoff = 0; dec->numhtiles = 0; dec->numvtiles = 0; dec->numtiles = 0; dec->tiles = 0; dec->curtile = 0; dec->numcomps = 0; dec->in = in; dec->cp = 0; dec->maxlyrs = impopts->maxlyrs; dec->maxpkts = impopts->maxpkts; dec->numpkts = 0; dec->ppmseqno = 0; dec->state = 0; dec->cmpts = 0; dec->pkthdrstreams = 0; dec->ppmstab = 0; dec->curtileendoff = 0; dec->max_samples = impopts->max_samples; return dec; }
safe
196
static int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst, const struct desc_struct *cs_desc) { enum x86emul_mode mode = ctxt->mode; int rc; #ifdef CONFIG_X86_64 if (ctxt->mode >= X86EMUL_MODE_PROT16) { if (cs_desc->l) { u64 efer = 0; ctxt->ops->get_msr(ctxt, MSR_EFER, &efer); if (efer & EFER_LMA) mode = X86EMUL_MODE_PROT64; } else mode = X86EMUL_MODE_PROT32; /* temporary value */ } #endif if (mode == X86EMUL_MODE_PROT16 || mode == X86EMUL_MODE_PROT32) mode = cs_desc->d ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16; rc = assign_eip(ctxt, dst, mode); if (rc == X86EMUL_CONTINUE) ctxt->mode = mode; return rc; }
safe
197
int ext4_walk_page_buffers(handle_t *handle, struct buffer_head *head, unsigned from, unsigned to, int *partial, int (*fn)(handle_t *handle, struct buffer_head *bh)) { struct buffer_head *bh; unsigned block_start, block_end; unsigned blocksize = head->b_size; int err, ret = 0; struct buffer_head *next; for (bh = head, block_start = 0; ret == 0 && (bh != head || !block_start); block_start = block_end, bh = next) { next = bh->b_this_page; block_end = block_start + blocksize; if (block_end <= from || block_start >= to) { if (partial && !buffer_uptodate(bh)) *partial = 1; continue; } err = (*fn)(handle, bh); if (!ret) ret = err; } return ret; }
safe
198
void r_bin_wasm_destroy (RBinFile *arch) { RBinWasmObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return; } bin = arch->o->bin_obj; r_buf_free (bin->buf); r_list_free (bin->g_sections); r_list_free (bin->g_types); r_list_free (bin->g_imports); r_list_free (bin->g_exports); r_list_free (bin->g_tables); r_list_free (bin->g_memories); r_list_free (bin->g_globals); r_list_free (bin->g_codes); r_list_free (bin->g_datas); free (bin->g_start); free (bin); arch->o->bin_obj = NULL; }
safe
200