idx
int64
func
string
target
int64
310,079
NCURSES_SP_NAME(mcprint) (NCURSES_SP_DCLx char *data, int len) /* ship binary character data to the printer via mc4/mc5/mc5p */ { int result; char *mybuf, *switchon; size_t onsize, offsize; size_t need; errno = 0; if (!HasTInfoTerminal(SP_PARM) || len <= 0 || (!prtr_non && (!prtr_on || !prtr_off))) { errno = ENODEV; return (ERR); } if (prtr_non) { switchon = TIPARM_1(prtr_non, len); onsize = strlen(switchon); offsize = 0; } else { switchon = prtr_on; onsize = strlen(prtr_on); offsize = strlen(prtr_off); } need = onsize + (size_t) len + offsize; if (switchon == 0 || (mybuf = typeMalloc(char, need + 1)) == 0) { errno = ENOMEM; return (ERR); } _nc_STRCPY(mybuf, switchon, need); memcpy(mybuf + onsize, data, (size_t) len); if (offsize) _nc_STRCPY(mybuf + onsize + len, prtr_off, need); /* * We're relying on the atomicity of UNIX writes here. The * danger is that output from a refresh() might get interspersed * with the printer data after the write call returns but before the * data has actually been shipped to the terminal. If the write(2) * operation is truly atomic we're protected from this. */ result = (int) write(TerminalOf(SP_PARM)->Filedes, mybuf, need); /* * By giving up our scheduler slot here we increase the odds that the * kernel will ship the contiguous clist items from the last write * immediately. */ #ifndef _WIN32 (void) sleep(0); #endif free(mybuf); return (result); }
0
242,583
read_header(void *data, unsigned int datasize, PE_COFF_LOADER_IMAGE_CONTEXT *context) { EFI_IMAGE_DOS_HEADER *DosHdr = data; EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr = data; unsigned long HeaderWithoutDataDir, SectionHeaderOffset, OptHeaderSize; unsigned long FileAlignment = 0; UINT16 DllFlags; if (datasize < sizeof (PEHdr->Pe32)) { perror(L"Invalid image\n"); return EFI_UNSUPPORTED; } if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) PEHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((char *)data + DosHdr->e_lfanew); if (!image_is_loadable(PEHdr)) { perror(L"Platform does not support this image\n"); return EFI_UNSUPPORTED; } if (image_is_64_bit(PEHdr)) { context->NumberOfRvaAndSizes = PEHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes; context->SizeOfHeaders = PEHdr->Pe32Plus.OptionalHeader.SizeOfHeaders; context->ImageSize = PEHdr->Pe32Plus.OptionalHeader.SizeOfImage; context->SectionAlignment = PEHdr->Pe32Plus.OptionalHeader.SectionAlignment; FileAlignment = PEHdr->Pe32Plus.OptionalHeader.FileAlignment; OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER64); } else { context->NumberOfRvaAndSizes = PEHdr->Pe32.OptionalHeader.NumberOfRvaAndSizes; context->SizeOfHeaders = PEHdr->Pe32.OptionalHeader.SizeOfHeaders; context->ImageSize = (UINT64)PEHdr->Pe32.OptionalHeader.SizeOfImage; context->SectionAlignment = PEHdr->Pe32.OptionalHeader.SectionAlignment; FileAlignment = PEHdr->Pe32.OptionalHeader.FileAlignment; OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER32); } if (FileAlignment % 2 != 0) { perror(L"File Alignment is invalid (%d)\n", FileAlignment); return EFI_UNSUPPORTED; } if (FileAlignment == 0) FileAlignment = 0x200; if (context->SectionAlignment == 0) context->SectionAlignment = PAGE_SIZE; if (context->SectionAlignment < FileAlignment) context->SectionAlignment = FileAlignment; context->NumberOfSections = PEHdr->Pe32.FileHeader.NumberOfSections; if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < context->NumberOfRvaAndSizes) { perror(L"Image header too small\n"); return EFI_UNSUPPORTED; } HeaderWithoutDataDir = OptHeaderSize - sizeof (EFI_IMAGE_DATA_DIRECTORY) * EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES; if (((UINT32)PEHdr->Pe32.FileHeader.SizeOfOptionalHeader - HeaderWithoutDataDir) != context->NumberOfRvaAndSizes * sizeof (EFI_IMAGE_DATA_DIRECTORY)) { perror(L"Image header overflows data directory\n"); return EFI_UNSUPPORTED; } SectionHeaderOffset = DosHdr->e_lfanew + sizeof (UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) + PEHdr->Pe32.FileHeader.SizeOfOptionalHeader; if (((UINT32)context->ImageSize - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER <= context->NumberOfSections) { perror(L"Image sections overflow image size\n"); return EFI_UNSUPPORTED; } if ((context->SizeOfHeaders - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER < (UINT32)context->NumberOfSections) { perror(L"Image sections overflow section headers\n"); return EFI_UNSUPPORTED; } if ((((UINT8 *)PEHdr - (UINT8 *)data) + sizeof(EFI_IMAGE_OPTIONAL_HEADER_UNION)) > datasize) { perror(L"Invalid image\n"); return EFI_UNSUPPORTED; } if (PEHdr->Te.Signature != EFI_IMAGE_NT_SIGNATURE) { perror(L"Unsupported image type\n"); return EFI_UNSUPPORTED; } if (PEHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) { perror(L"Unsupported image - Relocations have been stripped\n"); return EFI_UNSUPPORTED; } context->PEHdr = PEHdr; if (image_is_64_bit(PEHdr)) { context->ImageAddress = PEHdr->Pe32Plus.OptionalHeader.ImageBase; context->EntryPoint = PEHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint; context->RelocDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]; context->SecDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; DllFlags = PEHdr->Pe32Plus.OptionalHeader.DllCharacteristics; } else { context->ImageAddress = PEHdr->Pe32.OptionalHeader.ImageBase; context->EntryPoint = PEHdr->Pe32.OptionalHeader.AddressOfEntryPoint; context->RelocDir = &PEHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]; context->SecDir = &PEHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; DllFlags = PEHdr->Pe32.OptionalHeader.DllCharacteristics; } if ((mok_policy & MOK_POLICY_REQUIRE_NX) && !(DllFlags & EFI_IMAGE_DLLCHARACTERISTICS_NX_COMPAT)) { perror(L"Policy requires NX, but image does not support NX\n"); return EFI_UNSUPPORTED; } context->FirstSection = (EFI_IMAGE_SECTION_HEADER *)((char *)PEHdr + PEHdr->Pe32.FileHeader.SizeOfOptionalHeader + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER)); if (context->ImageSize < context->SizeOfHeaders) { perror(L"Invalid image\n"); return EFI_UNSUPPORTED; } if ((unsigned long)((UINT8 *)context->SecDir - (UINT8 *)data) > (datasize - sizeof(EFI_IMAGE_DATA_DIRECTORY))) { perror(L"Invalid image\n"); return EFI_UNSUPPORTED; } if (context->SecDir->VirtualAddress > datasize || (context->SecDir->VirtualAddress == datasize && context->SecDir->Size > 0)) { perror(L"Malformed security header\n"); return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; }
0
359,201
BPF_CALL_4(bpf_ringbuf_output, struct bpf_map *, map, void *, data, u64, size, u64, flags) { struct bpf_ringbuf_map *rb_map; void *rec; if (unlikely(flags & ~(BPF_RB_NO_WAKEUP | BPF_RB_FORCE_WAKEUP))) return -EINVAL; rb_map = container_of(map, struct bpf_ringbuf_map, map); rec = __bpf_ringbuf_reserve(rb_map->rb, size); if (!rec) return -EAGAIN; memcpy(rec, data, size); bpf_ringbuf_commit(rec, flags, false /* discard */); return 0; }
0
294,414
expect_numeric(VALUE x) { if (!k_numeric_p(x)) rb_raise(rb_eTypeError, "expected numeric"); }
0
234,732
static int devid_cmp(void *priv, const struct list_head *a, const struct list_head *b) { const struct btrfs_device *dev1, *dev2; dev1 = list_entry(a, struct btrfs_device, dev_list); dev2 = list_entry(b, struct btrfs_device, dev_list); if (dev1->devid < dev2->devid) return -1; else if (dev1->devid > dev2->devid) return 1; return 0; }
0
366,232
static int do_umount_root(struct super_block *sb) { int ret = 0; down_write(&sb->s_umount); if (!sb_rdonly(sb)) { struct fs_context *fc; fc = fs_context_for_reconfigure(sb->s_root, SB_RDONLY, SB_RDONLY); if (IS_ERR(fc)) { ret = PTR_ERR(fc); } else { ret = parse_monolithic_mount_data(fc, NULL); if (!ret) ret = reconfigure_super(fc); put_fs_context(fc); } } up_write(&sb->s_umount); return ret; }
0
384,278
gs_heap_free_string(gs_memory_t * mem, byte * data, uint nbytes, client_name_t cname) { /****** SHOULD CHECK SIZE IF DEBUGGING ******/ gs_heap_free_object(mem, data, cname); }
0
503,876
SCM_DEFINE (scm_closedir, "closedir", 1, 0, 0, (SCM port), "Close the directory stream @var{port}.\n" "The return value is unspecified.") #define FUNC_NAME s_scm_closedir { SCM_VALIDATE_DIR (1, port); if (SCM_DIR_OPEN_P (port)) { int sts; SCM_SYSCALL (sts = closedir ((DIR *) SCM_SMOB_DATA_1 (port))); if (sts != 0) SCM_SYSERROR; SCM_SET_SMOB_DATA_0 (port, scm_tc16_dir); } return SCM_UNSPECIFIED; }
0
317,312
static void smack_netlbl_delete(struct sock *sk) { struct socket_smack *ssp = sk->sk_security; /* * Take the label off the socket if one is set. */ if (ssp->smk_state != SMK_NETLBL_LABELED) return; local_bh_disable(); bh_lock_sock_nested(sk); netlbl_sock_delattr(sk); bh_unlock_sock(sk); local_bh_enable(); ssp->smk_state = SMK_NETLBL_UNLABELED; }
0
257,707
int mod_wstunnel_frame_recv(handler_ctx *hctx) { #ifdef _MOD_WEBSOCKET_SPEC_RFC_6455_ if (hctx->hybivers >= 8) return recv_rfc_6455(hctx); #endif /* _MOD_WEBSOCKET_SPEC_RFC_6455_ */ #ifdef _MOD_WEBSOCKET_SPEC_IETF_00_ if (0 == hctx->hybivers) return recv_ietf_00(hctx); #endif /* _MOD_WEBSOCKET_SPEC_IETF_00_ */ return -1; }
0
400,116
IdKeyPair UserTerminalRouter::acceptNewConnection() { lock_guard<recursive_mutex> guard(routerMutex); LOG(INFO) << "Listening to id/key FIFO"; int terminalFd = socketHandler->accept(serverFd); if (terminalFd < 0) { if (GetErrno() != EAGAIN && GetErrno() != EWOULDBLOCK) { FATAL_FAIL(-1); // STFATAL with the error } else { return IdKeyPair({"", ""}); // Nothing to accept this time } } LOG(INFO) << "Connected"; try { Packet packet; if (!socketHandler->readPacket(terminalFd, &packet)) { STFATAL << "Missing user info packet"; } if (packet.getHeader() != TerminalPacketType::TERMINAL_USER_INFO) { STFATAL << "Got an invalid packet header: " << int(packet.getHeader()); } TerminalUserInfo tui = stringToProto<TerminalUserInfo>(packet.getPayload()); tui.set_fd(terminalFd); idInfoMap[tui.id()] = tui; return IdKeyPair({tui.id(), tui.passkey()}); } catch (const std::runtime_error &re) { STFATAL << "Router can't talk to terminal: " << re.what(); } STFATAL << "Should never get here"; return IdKeyPair({"", ""}); }
0
231,657
TEST_P( QuicServerTransportAllowMigrationTest, ReceiveReorderedDataFromChangedPeerAddress) { auto data = IOBuf::copyBuffer("bad data"); auto firstPacket = packetToBuf(createStreamPacket( *clientConnectionId, *server->getConn().serverConnectionId, clientNextAppDataPacketNum++, 2, *data, 0 /* cipherOverhead */, 0 /* largestAcked */)); auto secondPacket = packetToBuf(createStreamPacket( *clientConnectionId, *server->getConn().serverConnectionId, clientNextAppDataPacketNum++, 6, *data, 0 /* cipherOverhead */, 0 /* largestAcked */)); // Receive second packet first deliverData(std::move(secondPacket)); auto peerAddress = server->getConn().peerAddress; // Receive first packet later from a different address folly::SocketAddress newPeer("100.101.102.103", 23456); deliverData(std::move(firstPacket), true, &newPeer); // No migration for reordered packet EXPECT_EQ(server->getConn().peerAddress, peerAddress); }
0
432,187
static void address_space_set_flatview(AddressSpace *as) { FlatView *old_view = address_space_to_flatview(as); MemoryRegion *physmr = memory_region_get_flatview_root(as->root); FlatView *new_view = g_hash_table_lookup(as->uc->flat_views, physmr); assert(new_view); if (old_view == new_view) { return; } flatview_ref(new_view); if (!QTAILQ_EMPTY(&as->listeners)) { FlatView tmpview = { .nr = 0 }, *old_view2 = old_view; if (!old_view2) { old_view2 = &tmpview; } address_space_update_topology_pass(as, old_view2, new_view, false); address_space_update_topology_pass(as, old_view2, new_view, true); } as->current_map = new_view; if (old_view) { flatview_unref(old_view); } }
0
246,471
RPVector *r_bin_wasm_get_types(RBinWasmObj *bin) { r_return_val_if_fail (bin && bin->g_sections, NULL); return bin->g_types? bin->g_types: parse_unique_subsec_vec_by_id (bin, R_BIN_WASM_SECTION_TYPE); }
0
380,952
insertchar( int c, // character to insert or NUL int flags, // INSCHAR_FORMAT, etc. int second_indent) // indent for second line if >= 0 { int textwidth; char_u *p; int fo_ins_blank; int force_format = flags & INSCHAR_FORMAT; textwidth = comp_textwidth(force_format); fo_ins_blank = has_format_option(FO_INS_BLANK); /* * Try to break the line in two or more pieces when: * - Always do this if we have been called to do formatting only. * - Always do this when 'formatoptions' has the 'a' flag and the line * ends in white space. * - Otherwise: * - Don't do this if inserting a blank * - Don't do this if an existing character is being replaced, unless * we're in MODE_VREPLACE state. * - Do this if the cursor is not on the line where insert started * or - 'formatoptions' doesn't have 'l' or the line was not too long * before the insert. * - 'formatoptions' doesn't have 'b' or a blank was inserted at or * before 'textwidth' */ if (textwidth > 0 && (force_format || (!VIM_ISWHITE(c) && !((State & REPLACE_FLAG) && !(State & VREPLACE_FLAG) && *ml_get_cursor() != NUL) && (curwin->w_cursor.lnum != Insstart.lnum || ((!has_format_option(FO_INS_LONG) || Insstart_textlen <= (colnr_T)textwidth) && (!fo_ins_blank || Insstart_blank_vcol <= (colnr_T)textwidth )))))) { // Format with 'formatexpr' when it's set. Use internal formatting // when 'formatexpr' isn't set or it returns non-zero. #if defined(FEAT_EVAL) int do_internal = TRUE; colnr_T virtcol = get_nolist_virtcol() + char2cells(c != NUL ? c : gchar_cursor()); if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0 && (force_format || virtcol > (colnr_T)textwidth)) { do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0); // It may be required to save for undo again, e.g. when setline() // was called. ins_need_undo = TRUE; } if (do_internal) #endif internal_format(textwidth, second_indent, flags, c == NUL, c); } if (c == NUL) // only formatting was wanted return; // Check whether this character should end a comment. if (did_ai && c == end_comment_pending) { char_u *line; char_u lead_end[COM_MAX_LEN]; // end-comment string int middle_len, end_len; int i; /* * Need to remove existing (middle) comment leader and insert end * comment leader. First, check what comment leader we can find. */ i = get_leader_len(line = ml_get_curline(), &p, FALSE, TRUE); if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) // Just checking { // Skip middle-comment string while (*p && p[-1] != ':') // find end of middle flags ++p; middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ","); // Don't count trailing white space for middle_len while (middle_len > 0 && VIM_ISWHITE(lead_end[middle_len - 1])) --middle_len; // Find the end-comment string while (*p && p[-1] != ':') // find end of end flags ++p; end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ","); // Skip white space before the cursor i = curwin->w_cursor.col; while (--i >= 0 && VIM_ISWHITE(line[i])) ; i++; // Skip to before the middle leader i -= middle_len; // Check some expected things before we go on if (i >= 0 && lead_end[end_len - 1] == end_comment_pending) { // Backspace over all the stuff we want to replace backspace_until_column(i); // Insert the end-comment string, except for the last // character, which will get inserted as normal later. ins_bytes_len(lead_end, end_len - 1); } } } end_comment_pending = NUL; did_ai = FALSE; did_si = FALSE; can_si = FALSE; can_si_back = FALSE; /* * If there's any pending input, grab up to INPUT_BUFLEN at once. * This speeds up normal text input considerably. * Don't do this when 'cindent' or 'indentexpr' is set, because we might * need to re-indent at a ':', or any other character (but not what * 'paste' is set).. * Don't do this when there an InsertCharPre autocommand is defined, * because we need to fire the event for every character. * Do the check for InsertCharPre before the call to vpeekc() because the * InsertCharPre autocommand could change the input buffer. */ #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif if ( !ISSPECIAL(c) && (!has_mbyte || (*mb_char2len)(c) == 1) && !has_insertcharpre() && vpeekc() != NUL && !(State & REPLACE_FLAG) && !cindent_on() #ifdef FEAT_RIGHTLEFT && !p_ri #endif ) { #define INPUT_BUFLEN 100 char_u buf[INPUT_BUFLEN + 1]; int i; colnr_T virtcol = 0; buf[0] = c; i = 1; if (textwidth > 0) virtcol = get_nolist_virtcol(); /* * Stop the string when: * - no more chars available * - finding a special character (command key) * - buffer is full * - running into the 'textwidth' boundary * - need to check for abbreviation: A non-word char after a word-char */ while ( (c = vpeekc()) != NUL && !ISSPECIAL(c) && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1) && i < INPUT_BUFLEN && (textwidth == 0 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth) && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1]))) { #ifdef FEAT_RIGHTLEFT c = vgetc(); if (p_hkmap && KeyTyped) c = hkmap(c); // Hebrew mode mapping buf[i++] = c; #else buf[i++] = vgetc(); #endif } #ifdef FEAT_DIGRAPHS do_digraph(-1); // clear digraphs do_digraph(buf[i-1]); // may be the start of a digraph #endif buf[i] = NUL; ins_str(buf); if (flags & INSCHAR_CTRLV) { redo_literal(*buf); i = 1; } else i = 0; if (buf[i] != NUL) AppendToRedobuffLit(buf + i, -1); } else { int cc; if (has_mbyte && (cc = (*mb_char2len)(c)) > 1) { char_u buf[MB_MAXBYTES + 1]; (*mb_char2bytes)(c, buf); buf[cc] = NUL; ins_char_bytes(buf, cc); AppendCharToRedobuff(c); } else { ins_char(c); if (flags & INSCHAR_CTRLV) redo_literal(c); else AppendCharToRedobuff(c); } } }
0
199,984
ex_substitute(exarg_T *eap) { linenr_T lnum; long i = 0; regmmatch_T regmatch; static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, 0}; #ifdef FEAT_EVAL subflags_T subflags_save; #endif int save_do_all; // remember user specified 'g' flag int save_do_ask; // remember user specified 'c' flag char_u *pat = NULL, *sub = NULL; // init for GCC int delimiter; int sublen; int got_quit = FALSE; int got_match = FALSE; int temp; int which_pat; char_u *cmd; int save_State; linenr_T first_line = 0; // first changed line linenr_T last_line= 0; // below last changed line AFTER the // change linenr_T old_line_count = curbuf->b_ml.ml_line_count; linenr_T line2; long nmatch; // number of lines in match char_u *sub_firstline; // allocated copy of first sub line int endcolumn = FALSE; // cursor in last column when done pos_T old_cursor = curwin->w_cursor; int start_nsubs; #ifdef FEAT_EVAL int save_ma = 0; #endif cmd = eap->arg; if (!global_busy) { sub_nsubs = 0; sub_nlines = 0; } start_nsubs = sub_nsubs; if (eap->cmdidx == CMD_tilde) which_pat = RE_LAST; // use last used regexp else which_pat = RE_SUBST; // use last substitute regexp // new pattern and substitution if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd) && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL) { // don't accept alphanumeric for separator if (check_regexp_delim(*cmd) == FAIL) return; #ifdef FEAT_EVAL if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg) == FAIL) return; #endif /* * undocumented vi feature: * "\/sub/" and "\?sub?" use last used search pattern (almost like * //sub/r). "\&sub&" use last substitute pattern (like //sub/). */ if (*cmd == '\\') { ++cmd; if (vim_strchr((char_u *)"/?&", *cmd) == NULL) { emsg(_(e_backslash_should_be_followed_by)); return; } if (*cmd != '&') which_pat = RE_SEARCH; // use last '/' pattern pat = (char_u *)""; // empty search pattern delimiter = *cmd++; // remember delimiter character } else // find the end of the regexp { which_pat = RE_LAST; // use last used regexp delimiter = *cmd++; // remember delimiter character pat = cmd; // remember start of search pat cmd = skip_regexp_ex(cmd, delimiter, magic_isset(), &eap->arg, NULL, NULL); if (cmd[0] == delimiter) // end delimiter found *cmd++ = NUL; // replace it with a NUL } /* * Small incompatibility: vi sees '\n' as end of the command, but in * Vim we want to use '\n' to find/substitute a NUL. */ sub = cmd; // remember the start of the substitution cmd = skip_substitute(cmd, delimiter); if (!eap->skip) { // In POSIX vi ":s/pat/%/" uses the previous subst. string. if (STRCMP(sub, "%") == 0 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL) { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } sub = old_sub; } else { vim_free(old_sub); old_sub = vim_strsave(sub); } } } else if (!eap->skip) // use previous pattern and substitution { if (old_sub == NULL) // there is no previous command { emsg(_(e_no_previous_substitute_regular_expression)); return; } pat = NULL; // search_regcomp() will use previous pattern sub = old_sub; // Vi compatibility quirk: repeating with ":s" keeps the cursor in the // last column after using "$". endcolumn = (curwin->w_curswant == MAXCOL); } // Recognize ":%s/\n//" and turn it into a join command, which is much // more efficient. // TODO: find a generic solution to make line-joining operations more // efficient, avoid allocating a string that grows in size. if (pat != NULL && STRCMP(pat, "\\n") == 0 && *sub == NUL && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l' || *cmd == 'p' || *cmd == '#')))) { linenr_T joined_lines_count; if (eap->skip) return; curwin->w_cursor.lnum = eap->line1; if (*cmd == 'l') eap->flags = EXFLAG_LIST; else if (*cmd == '#') eap->flags = EXFLAG_NR; else if (*cmd == 'p') eap->flags = EXFLAG_PRINT; // The number of lines joined is the number of lines in the range plus // one. One less when the last line is included. joined_lines_count = eap->line2 - eap->line1 + 1; if (eap->line2 < curbuf->b_ml.ml_line_count) ++joined_lines_count; if (joined_lines_count > 1) { (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE); sub_nsubs = joined_lines_count - 1; sub_nlines = 1; (void)do_sub_msg(FALSE); ex_may_print(eap); } if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) save_re_pat(RE_SUBST, pat, magic_isset()); // put pattern in history add_to_history(HIST_SEARCH, pat, TRUE, NUL); return; } /* * Find trailing options. When '&' is used, keep old options. */ if (*cmd == '&') ++cmd; else { #ifdef FEAT_EVAL if (in_vim9script()) { // ignore 'gdefault' and 'edcompatible' subflags.do_all = FALSE; subflags.do_ask = FALSE; } else #endif if (!p_ed) { if (p_gd) // default is global on subflags.do_all = TRUE; else subflags.do_all = FALSE; subflags.do_ask = FALSE; } subflags.do_error = TRUE; subflags.do_print = FALSE; subflags.do_list = FALSE; subflags.do_count = FALSE; subflags.do_number = FALSE; subflags.do_ic = 0; } while (*cmd) { /* * Note that 'g' and 'c' are always inverted, also when p_ed is off. * 'r' is never inverted. */ if (*cmd == 'g') subflags.do_all = !subflags.do_all; else if (*cmd == 'c') subflags.do_ask = !subflags.do_ask; else if (*cmd == 'n') subflags.do_count = TRUE; else if (*cmd == 'e') subflags.do_error = !subflags.do_error; else if (*cmd == 'r') // use last used regexp which_pat = RE_LAST; else if (*cmd == 'p') subflags.do_print = TRUE; else if (*cmd == '#') { subflags.do_print = TRUE; subflags.do_number = TRUE; } else if (*cmd == 'l') { subflags.do_print = TRUE; subflags.do_list = TRUE; } else if (*cmd == 'i') // ignore case subflags.do_ic = 'i'; else if (*cmd == 'I') // don't ignore case subflags.do_ic = 'I'; else break; ++cmd; } if (subflags.do_count) subflags.do_ask = FALSE; save_do_all = subflags.do_all; save_do_ask = subflags.do_ask; /* * check for a trailing count */ cmd = skipwhite(cmd); if (VIM_ISDIGIT(*cmd)) { i = getdigits(&cmd); if (i <= 0 && !eap->skip && subflags.do_error) { emsg(_(e_positive_count_required)); return; } eap->line1 = eap->line2; eap->line2 += i - 1; if (eap->line2 > curbuf->b_ml.ml_line_count) eap->line2 = curbuf->b_ml.ml_line_count; } /* * check for trailing command or garbage */ cmd = skipwhite(cmd); if (*cmd && *cmd != '"') // if not end-of-line or comment { set_nextcmd(eap, cmd); if (eap->nextcmd == NULL) { semsg(_(e_trailing_characters_str), cmd); return; } } if (eap->skip) // not executing commands, only parsing return; if (!subflags.do_count && !curbuf->b_p_ma) { // Substitution is not allowed in non-'modifiable' buffer emsg(_(e_cannot_make_changes_modifiable_is_off)); return; } if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL) { if (subflags.do_error) emsg(_(e_invalid_command)); return; } // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' if (subflags.do_ic == 'i') regmatch.rmm_ic = TRUE; else if (subflags.do_ic == 'I') regmatch.rmm_ic = FALSE; sub_firstline = NULL; /* * ~ in the substitute pattern is replaced with the old pattern. * We do it here once to avoid it to be replaced over and over again. * But don't do it when it starts with "\=", then it's an expression. */ if (!(sub[0] == '\\' && sub[1] == '=')) sub = regtilde(sub, magic_isset()); /* * Check for a match on each line. */ line2 = eap->line2; for (lnum = eap->line1; lnum <= line2 && !(got_quit #if defined(FEAT_EVAL) || aborting() #endif ); ++lnum) { nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0, NULL, NULL); if (nmatch) { colnr_T copycol; colnr_T matchcol; colnr_T prev_matchcol = MAXCOL; char_u *new_end, *new_start = NULL; unsigned new_start_len = 0; char_u *p1; int did_sub = FALSE; int lastone; int len, copy_len, needed_len; long nmatch_tl = 0; // nr of lines matched below lnum int do_again; // do it again after joining lines int skip_match = FALSE; linenr_T sub_firstlnum; // nr of first sub line #ifdef FEAT_PROP_POPUP int apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE; colnr_T total_added = 0; #endif /* * The new text is build up step by step, to avoid too much * copying. There are these pieces: * sub_firstline The old text, unmodified. * copycol Column in the old text where we started * looking for a match; from here old text still * needs to be copied to the new text. * matchcol Column number of the old text where to look * for the next match. It's just after the * previous match or one further. * prev_matchcol Column just after the previous match (if any). * Mostly equal to matchcol, except for the first * match and after skipping an empty match. * regmatch.*pos Where the pattern matched in the old text. * new_start The new text, all that has been produced so * far. * new_end The new text, where to append new text. * * lnum The line number where we found the start of * the match. Can be below the line we searched * when there is a \n before a \zs in the * pattern. * sub_firstlnum The line number in the buffer where to look * for a match. Can be different from "lnum" * when the pattern or substitute string contains * line breaks. * * Special situations: * - When the substitute string contains a line break, the part up * to the line break is inserted in the text, but the copy of * the original line is kept. "sub_firstlnum" is adjusted for * the inserted lines. * - When the matched pattern contains a line break, the old line * is taken from the line at the end of the pattern. The lines * in the match are deleted later, "sub_firstlnum" is adjusted * accordingly. * * The new text is built up in new_start[]. It has some extra * room to avoid using alloc()/free() too often. new_start_len is * the length of the allocated memory at new_start. * * Make a copy of the old line, so it won't be taken away when * updating the screen or handling a multi-line match. The "old_" * pointers point into this copy. */ sub_firstlnum = lnum; copycol = 0; matchcol = 0; // At first match, remember current cursor position. if (!got_match) { setpcmark(); got_match = TRUE; } /* * Loop until nothing more to replace in this line. * 1. Handle match with empty string. * 2. If do_ask is set, ask for confirmation. * 3. substitute the string. * 4. if do_all is set, find next match * 5. break if there isn't another match in this line */ for (;;) { // Advance "lnum" to the line where the match starts. The // match does not start in the first line when there is a line // break before \zs. if (regmatch.startpos[0].lnum > 0) { lnum += regmatch.startpos[0].lnum; sub_firstlnum += regmatch.startpos[0].lnum; nmatch -= regmatch.startpos[0].lnum; VIM_CLEAR(sub_firstline); } // Match might be after the last line for "\n\zs" matching at // the end of the last line. if (lnum > curbuf->b_ml.ml_line_count) break; if (sub_firstline == NULL) { sub_firstline = vim_strsave(ml_get(sub_firstlnum)); if (sub_firstline == NULL) { vim_free(new_start); goto outofmem; } } // Save the line number of the last change for the final // cursor position (just like Vi). curwin->w_cursor.lnum = lnum; do_again = FALSE; /* * 1. Match empty string does not count, except for first * match. This reproduces the strange vi behaviour. * This also catches endless loops. */ if (matchcol == prev_matchcol && regmatch.endpos[0].lnum == 0 && matchcol == regmatch.endpos[0].col) { if (sub_firstline[matchcol] == NUL) // We already were at the end of the line. Don't look // for a match in this line again. skip_match = TRUE; else { // search for a match at next column if (has_mbyte) matchcol += mb_ptr2len(sub_firstline + matchcol); else ++matchcol; } goto skip; } // Normally we continue searching for a match just after the // previous match. matchcol = regmatch.endpos[0].col; prev_matchcol = matchcol; /* * 2. If do_count is set only increase the counter. * If do_ask is set, ask for confirmation. */ if (subflags.do_count) { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":s/\nB\@=//gc" get stuck. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); nmatch = 1; skip_match = TRUE; } sub_nsubs++; did_sub = TRUE; #ifdef FEAT_EVAL // Skip the substitution, unless an expression is used, // then it is evaluated in the sandbox. if (!(sub[0] == '\\' && sub[1] == '=')) #endif goto skip; } if (subflags.do_ask) { int typed = 0; // change State to CONFIRM, so that the mouse works // properly save_State = State; State = CONFIRM; setmouse(); // disable mouse in xterm curwin->w_cursor.col = regmatch.startpos[0].col; if (curwin->w_p_crb) do_check_cursorbind(); // When 'cpoptions' contains "u" don't sync undo when // asking for confirmation. if (vim_strchr(p_cpo, CPO_UNDO) != NULL) ++no_u_sync; /* * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. */ while (subflags.do_ask) { if (exmode_active) { char_u *resp; colnr_T sc, ec; print_line_no_prefix(lnum, subflags.do_number, subflags.do_list); getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL); curwin->w_cursor.col = regmatch.endpos[0].col - 1; if (curwin->w_cursor.col < 0) curwin->w_cursor.col = 0; getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec); curwin->w_cursor.col = regmatch.startpos[0].col; if (subflags.do_number || curwin->w_p_nu) { int numw = number_width(curwin) + 1; sc += numw; ec += numw; } msg_start(); for (i = 0; i < (long)sc; ++i) msg_putchar(' '); for ( ; i <= (long)ec; ++i) msg_putchar('^'); resp = getexmodeline('?', NULL, 0, TRUE); if (resp != NULL) { typed = *resp; vim_free(resp); } } else { char_u *orig_line = NULL; int len_change = 0; int save_p_lz = p_lz; #ifdef FEAT_FOLDING int save_p_fen = curwin->w_p_fen; curwin->w_p_fen = FALSE; #endif // Invert the matched string. // Remove the inversion afterwards. temp = RedrawingDisabled; RedrawingDisabled = 0; // avoid calling update_screen() in vgetorpeek() p_lz = FALSE; if (new_start != NULL) { // There already was a substitution, we would // like to show this to the user. We cannot // really update the line, it would change // what matches. Temporarily replace the line // and change it back afterwards. orig_line = vim_strsave(ml_get(lnum)); if (orig_line != NULL) { char_u *new_line = concat_str(new_start, sub_firstline + copycol); if (new_line == NULL) VIM_CLEAR(orig_line); else { // Position the cursor relative to the // end of the line, the previous // substitute may have inserted or // deleted characters before the // cursor. len_change = (int)STRLEN(new_line) - (int)STRLEN(orig_line); curwin->w_cursor.col += len_change; ml_replace(lnum, new_line, FALSE); } } } search_match_lines = regmatch.endpos[0].lnum - regmatch.startpos[0].lnum; search_match_endcol = regmatch.endpos[0].col + len_change; highlight_match = TRUE; update_topline(); validate_cursor(); update_screen(SOME_VALID); highlight_match = FALSE; redraw_later(SOME_VALID); #ifdef FEAT_FOLDING curwin->w_p_fen = save_p_fen; #endif if (msg_row == Rows - 1) msg_didout = FALSE; // avoid a scroll-up msg_starthere(); i = msg_scroll; msg_scroll = 0; // truncate msg when // needed msg_no_more = TRUE; // write message same highlighting as for // wait_return smsg_attr(HL_ATTR(HLF_R), _("replace with %s (y/n/a/q/l/^E/^Y)?"), sub); msg_no_more = FALSE; msg_scroll = i; showruler(TRUE); windgoto(msg_row, msg_col); RedrawingDisabled = temp; #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif ++no_mapping; // don't map this key ++allow_keys; // allow special keys typed = plain_vgetc(); --allow_keys; --no_mapping; // clear the question msg_didout = FALSE; // don't scroll up msg_col = 0; gotocmdline(TRUE); p_lz = save_p_lz; // restore the line if (orig_line != NULL) ml_replace(lnum, orig_line, FALSE); } need_wait_return = FALSE; // no hit-return prompt if (typed == 'q' || typed == ESC || typed == Ctrl_C #ifdef UNIX || typed == intr_char #endif ) { got_quit = TRUE; break; } if (typed == 'n') break; if (typed == 'y') break; if (typed == 'l') { // last: replace and then stop subflags.do_all = FALSE; line2 = lnum; break; } if (typed == 'a') { subflags.do_ask = FALSE; break; } if (typed == Ctrl_E) scrollup_clamp(); else if (typed == Ctrl_Y) scrolldown_clamp(); } State = save_State; setmouse(); if (vim_strchr(p_cpo, CPO_UNDO) != NULL) --no_u_sync; if (typed == 'n') { // For a multi-line match, put matchcol at the NUL at // the end of the line and set nmatch to one, so that // we continue looking for a match on the next line. // Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc" // get stuck when pressing 'n'. if (nmatch > 1) { matchcol = (colnr_T)STRLEN(sub_firstline); skip_match = TRUE; } goto skip; } if (got_quit) goto skip; } // Move the cursor to the start of the match, so that we can // use "\=col("."). curwin->w_cursor.col = regmatch.startpos[0].col; /* * 3. substitute the string. */ #ifdef FEAT_EVAL save_ma = curbuf->b_p_ma; if (subflags.do_count) { // prevent accidentally changing the buffer by a function curbuf->b_p_ma = FALSE; sandbox++; } // Save flags for recursion. They can change for e.g. // :s/^/\=execute("s#^##gn") subflags_save = subflags; #endif // get length of substitution part sublen = vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, sub_firstline, FALSE, magic_isset(), TRUE); #ifdef FEAT_EVAL // If getting the substitute string caused an error, don't do // the replacement. // Don't keep flags set by a recursive call. subflags = subflags_save; if (aborting() || subflags.do_count) { curbuf->b_p_ma = save_ma; if (sandbox > 0) sandbox--; goto skip; } #endif // When the match included the "$" of the last line it may // go beyond the last line of the buffer. if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1) { nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1; skip_match = TRUE; } // Need room for: // - result so far in new_start (not for first sub in line) // - original text up to match // - length of substituted part // - original text after match // Adjust text properties here, since we have all information // needed. if (nmatch == 1) { p1 = sub_firstline; #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { int bytes_added = sublen - 1 - (regmatch.endpos[0].col - regmatch.startpos[0].col); // When text properties are changed, need to save for // undo first, unless done already. if (adjust_prop_columns(lnum, total_added + regmatch.startpos[0].col, bytes_added, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; // Offset for column byte number of the text property // in the resulting buffer afterwards. total_added += bytes_added; } #endif } else { p1 = ml_get(sub_firstlnum + nmatch - 1); nmatch_tl += nmatch - 1; } copy_len = regmatch.startpos[0].col - copycol; needed_len = copy_len + ((unsigned)STRLEN(p1) - regmatch.endpos[0].col) + sublen + 1; if (new_start == NULL) { /* * Get some space for a temporary buffer to do the * substitution into (and some extra space to avoid * too many calls to alloc()/free()). */ new_start_len = needed_len + 50; if ((new_start = alloc(new_start_len)) == NULL) goto outofmem; *new_start = NUL; new_end = new_start; } else { /* * Check if the temporary buffer is long enough to do the * substitution into. If not, make it larger (with a bit * extra to avoid too many calls to alloc()/free()). */ len = (unsigned)STRLEN(new_start); needed_len += len; if (needed_len > (int)new_start_len) { new_start_len = needed_len + 50; if ((p1 = alloc(new_start_len)) == NULL) { vim_free(new_start); goto outofmem; } mch_memmove(p1, new_start, (size_t)(len + 1)); vim_free(new_start); new_start = p1; } new_end = new_start + len; } /* * copy the text up to the part that matched */ mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len); new_end += copy_len; (void)vim_regsub_multi(&regmatch, sub_firstlnum - regmatch.startpos[0].lnum, sub, new_end, TRUE, magic_isset(), TRUE); sub_nsubs++; did_sub = TRUE; // Move the cursor to the start of the line, to avoid that it // is beyond the end of the line after the substitution. curwin->w_cursor.col = 0; // For a multi-line match, make a copy of the last matched // line and continue in that one. if (nmatch > 1) { sub_firstlnum += nmatch - 1; vim_free(sub_firstline); sub_firstline = vim_strsave(ml_get(sub_firstlnum)); // When going beyond the last line, stop substituting. if (sub_firstlnum <= line2) do_again = TRUE; else subflags.do_all = FALSE; } // Remember next character to be copied. copycol = regmatch.endpos[0].col; if (skip_match) { // Already hit end of the buffer, sub_firstlnum is one // less than what it ought to be. vim_free(sub_firstline); sub_firstline = vim_strsave((char_u *)""); copycol = 0; } /* * Now the trick is to replace CTRL-M chars with a real line * break. This would make it impossible to insert a CTRL-M in * the text. The line break can be avoided by preceding the * CTRL-M with a backslash. To be able to insert a backslash, * they must be doubled in the string and are halved here. * That is Vi compatible. */ for (p1 = new_end; *p1; ++p1) { if (p1[0] == '\\' && p1[1] != NUL) // remove backslash { STRMOVE(p1, p1 + 1); #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop) { // When text properties are changed, need to save // for undo first, unless done already. if (adjust_prop_columns(lnum, (colnr_T)(p1 - new_start), -1, apc_flags)) apc_flags &= ~APC_SAVE_FOR_UNDO; } #endif } else if (*p1 == CAR) { if (u_inssub(lnum) == OK) // prepare for undo { colnr_T plen = (colnr_T)(p1 - new_start + 1); *p1 = NUL; // truncate up to the CR ml_append(lnum - 1, new_start, plen, FALSE); mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L); if (subflags.do_ask) appended_lines(lnum - 1, 1L); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } #ifdef FEAT_PROP_POPUP adjust_props_for_split(lnum + 1, lnum, plen, 1); #endif // all line numbers increase ++sub_firstlnum; ++lnum; ++line2; // move the cursor to the new line, like Vi ++curwin->w_cursor.lnum; // copy the rest STRMOVE(new_start, p1 + 1); p1 = new_start - 1; } } else if (has_mbyte) p1 += (*mb_ptr2len)(p1) - 1; } /* * 4. If do_all is set, find next match. * Prevent endless loop with patterns that match empty * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g. * But ":s/\n/#/" is OK. */ skip: // We already know that we did the last subst when we are at // the end of the line, except that a pattern like // "bar\|\nfoo" may match at the NUL. "lnum" can be below // "line2" when there is a \zs in the pattern after a line // break. lastone = (skip_match || got_int || got_quit || lnum > line2 || !(subflags.do_all || do_again) || (sub_firstline[matchcol] == NUL && nmatch <= 1 && !re_multiline(regmatch.regprog))); nmatch = -1; /* * Replace the line in the buffer when needed. This is * skipped when there are more matches. * The check for nmatch_tl is needed for when multi-line * matching must replace the lines before trying to do another * match, otherwise "\@<=" won't work. * When the match starts below where we start searching also * need to replace the line first (using \zs after \n). */ if (lastone || nmatch_tl > 0 || (nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL)) == 0 || regmatch.startpos[0].lnum > 0) { if (new_start != NULL) { /* * Copy the rest of the line, that didn't match. * "matchcol" has to be adjusted, we use the end of * the line as reference, because the substitute may * have changed the number of characters. Same for * "prev_matchcol". */ STRCAT(new_start, sub_firstline + copycol); matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; if (u_savesub(lnum) != OK) break; ml_replace(lnum, new_start, TRUE); if (nmatch_tl > 0) { /* * Matched lines have now been substituted and are * useless, delete them. The part after the match * has been appended to new_start, we don't need * it in the buffer. */ ++lnum; if (u_savedel(lnum, nmatch_tl) != OK) break; for (i = 0; i < nmatch_tl; ++i) ml_delete(lnum); mark_adjust(lnum, lnum + nmatch_tl - 1, (long)MAXLNUM, -nmatch_tl); if (subflags.do_ask) deleted_lines(lnum, nmatch_tl); --lnum; line2 -= nmatch_tl; // nr of lines decreases nmatch_tl = 0; } // When asking, undo is saved each time, must also set // changed flag each time. if (subflags.do_ask) changed_bytes(lnum, 0); else { if (first_line == 0) first_line = lnum; last_line = lnum + 1; } sub_firstlnum = lnum; vim_free(sub_firstline); // free the temp buffer sub_firstline = new_start; new_start = NULL; matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) - prev_matchcol; copycol = 0; } if (nmatch == -1 && !lastone) nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL); /* * 5. break if there isn't another match in this line */ if (nmatch <= 0) { // If the match found didn't start where we were // searching, do the next search in the line where we // found the match. if (nmatch == -1) lnum -= regmatch.startpos[0].lnum; break; } } line_breakcheck(); } if (did_sub) ++sub_nlines; vim_free(new_start); // for when substitute was cancelled VIM_CLEAR(sub_firstline); // free the copy of the original line } line_breakcheck(); } if (first_line != 0) { // Need to subtract the number of added lines from "last_line" to get // the line number before the change (same as adding the number of // deleted lines). i = curbuf->b_ml.ml_line_count - old_line_count; changed_lines(first_line, 0, last_line - i, i); } outofmem: vim_free(sub_firstline); // may have to free allocated copy of the line // ":s/pat//n" doesn't move the cursor if (subflags.do_count) curwin->w_cursor = old_cursor; if (sub_nsubs > start_nsubs) { if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '[ and '] marks. curbuf->b_op_start.lnum = eap->line1; curbuf->b_op_end.lnum = line2; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } if (!global_busy) { // when interactive leave cursor on the match if (!subflags.do_ask) { if (endcolumn) coladvance((colnr_T)MAXCOL); else beginline(BL_WHITE | BL_FIX); } if (!do_sub_msg(subflags.do_count) && subflags.do_ask) msg(""); } else global_need_beginline = TRUE; if (subflags.do_print) print_line(curwin->w_cursor.lnum, subflags.do_number, subflags.do_list); } else if (!global_busy) { if (got_int) // interrupted emsg(_(e_interrupted)); else if (got_match) // did find something but nothing substituted msg(""); else if (subflags.do_error) // nothing found semsg(_(e_pattern_not_found_str), get_search_pat()); } #ifdef FEAT_FOLDING if (subflags.do_ask && hasAnyFolding(curwin)) // Cursor position may require updating changed_window_setting(); #endif vim_regfree(regmatch.regprog); // Restore the flag values, they can be used for ":&&". subflags.do_all = save_do_all; subflags.do_ask = save_do_ask; }
1
248,273
DLLIMPORT cfg_t *cfg_gettsec(cfg_t *cfg, const char *name, const char *title) { return cfg_opt_gettsec(cfg_getopt(cfg, name), title); }
0
226,132
void npck_box_del(GF_Box *s) { gf_free((GF_NPCKBox *)s); }
0
214,160
composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) { struct usb_composite_dev *cdev = get_gadget_data(gadget); struct usb_request *req = cdev->req; int value = -EOPNOTSUPP; int status = 0; u16 w_index = le16_to_cpu(ctrl->wIndex); u8 intf = w_index & 0xFF; u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); struct usb_function *f = NULL; u8 endp; if (w_length > USB_COMP_EP0_BUFSIZ) { if (ctrl->bRequestType & USB_DIR_IN) { /* Cast away the const, we are going to overwrite on purpose. */ __le16 *temp = (__le16 *)&ctrl->wLength; *temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ); w_length = USB_COMP_EP0_BUFSIZ; } else { goto done; } } /* partial re-init of the response message; the function or the * gadget might need to intercept e.g. a control-OUT completion * when we delegate to it. */ req->zero = 0; req->context = cdev; req->complete = composite_setup_complete; req->length = 0; gadget->ep0->driver_data = cdev; /* * Don't let non-standard requests match any of the cases below * by accident. */ if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD) goto unknown; switch (ctrl->bRequest) { /* we handle all standard USB descriptors */ case USB_REQ_GET_DESCRIPTOR: if (ctrl->bRequestType != USB_DIR_IN) goto unknown; switch (w_value >> 8) { case USB_DT_DEVICE: cdev->desc.bNumConfigurations = count_configs(cdev, USB_DT_DEVICE); cdev->desc.bMaxPacketSize0 = cdev->gadget->ep0->maxpacket; if (gadget_is_superspeed(gadget)) { if (gadget->speed >= USB_SPEED_SUPER) { cdev->desc.bcdUSB = cpu_to_le16(0x0320); cdev->desc.bMaxPacketSize0 = 9; } else { cdev->desc.bcdUSB = cpu_to_le16(0x0210); } } else { if (gadget->lpm_capable) cdev->desc.bcdUSB = cpu_to_le16(0x0201); else cdev->desc.bcdUSB = cpu_to_le16(0x0200); } value = min(w_length, (u16) sizeof cdev->desc); memcpy(req->buf, &cdev->desc, value); break; case USB_DT_DEVICE_QUALIFIER: if (!gadget_is_dualspeed(gadget) || gadget->speed >= USB_SPEED_SUPER) break; device_qual(cdev); value = min_t(int, w_length, sizeof(struct usb_qualifier_descriptor)); break; case USB_DT_OTHER_SPEED_CONFIG: if (!gadget_is_dualspeed(gadget) || gadget->speed >= USB_SPEED_SUPER) break; fallthrough; case USB_DT_CONFIG: value = config_desc(cdev, w_value); if (value >= 0) value = min(w_length, (u16) value); break; case USB_DT_STRING: value = get_string(cdev, req->buf, w_index, w_value & 0xff); if (value >= 0) value = min(w_length, (u16) value); break; case USB_DT_BOS: if (gadget_is_superspeed(gadget) || gadget->lpm_capable) { value = bos_desc(cdev); value = min(w_length, (u16) value); } break; case USB_DT_OTG: if (gadget_is_otg(gadget)) { struct usb_configuration *config; int otg_desc_len = 0; if (cdev->config) config = cdev->config; else config = list_first_entry( &cdev->configs, struct usb_configuration, list); if (!config) goto done; if (gadget->otg_caps && (gadget->otg_caps->otg_rev >= 0x0200)) otg_desc_len += sizeof( struct usb_otg20_descriptor); else otg_desc_len += sizeof( struct usb_otg_descriptor); value = min_t(int, w_length, otg_desc_len); memcpy(req->buf, config->descriptors[0], value); } break; } break; /* any number of configs can work */ case USB_REQ_SET_CONFIGURATION: if (ctrl->bRequestType != 0) goto unknown; if (gadget_is_otg(gadget)) { if (gadget->a_hnp_support) DBG(cdev, "HNP available\n"); else if (gadget->a_alt_hnp_support) DBG(cdev, "HNP on another port\n"); else VDBG(cdev, "HNP inactive\n"); } spin_lock(&cdev->lock); value = set_config(cdev, ctrl, w_value); spin_unlock(&cdev->lock); break; case USB_REQ_GET_CONFIGURATION: if (ctrl->bRequestType != USB_DIR_IN) goto unknown; if (cdev->config) *(u8 *)req->buf = cdev->config->bConfigurationValue; else *(u8 *)req->buf = 0; value = min(w_length, (u16) 1); break; /* function drivers must handle get/set altsetting */ case USB_REQ_SET_INTERFACE: if (ctrl->bRequestType != USB_RECIP_INTERFACE) goto unknown; if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; /* * If there's no get_alt() method, we know only altsetting zero * works. There is no need to check if set_alt() is not NULL * as we check this in usb_add_function(). */ if (w_value && !f->get_alt) break; spin_lock(&cdev->lock); value = f->set_alt(f, w_index, w_value); if (value == USB_GADGET_DELAYED_STATUS) { DBG(cdev, "%s: interface %d (%s) requested delayed status\n", __func__, intf, f->name); cdev->delayed_status++; DBG(cdev, "delayed_status count %d\n", cdev->delayed_status); } spin_unlock(&cdev->lock); break; case USB_REQ_GET_INTERFACE: if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)) goto unknown; if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; /* lots of interfaces only need altsetting zero... */ value = f->get_alt ? f->get_alt(f, w_index) : 0; if (value < 0) break; *((u8 *)req->buf) = value; value = min(w_length, (u16) 1); break; case USB_REQ_GET_STATUS: if (gadget_is_otg(gadget) && gadget->hnp_polling_support && (w_index == OTG_STS_SELECTOR)) { if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_DEVICE)) goto unknown; *((u8 *)req->buf) = gadget->host_request_flag; value = 1; break; } /* * USB 3.0 additions: * Function driver should handle get_status request. If such cb * wasn't supplied we respond with default value = 0 * Note: function driver should supply such cb only for the * first interface of the function */ if (!gadget_is_superspeed(gadget)) goto unknown; if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE)) goto unknown; value = 2; /* This is the length of the get_status reply */ put_unaligned_le16(0, req->buf); if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; status = f->get_status ? f->get_status(f) : 0; if (status < 0) break; put_unaligned_le16(status & 0x0000ffff, req->buf); break; /* * Function drivers should handle SetFeature/ClearFeature * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied * only for the first interface of the function */ case USB_REQ_CLEAR_FEATURE: case USB_REQ_SET_FEATURE: if (!gadget_is_superspeed(gadget)) goto unknown; if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE)) goto unknown; switch (w_value) { case USB_INTRF_FUNC_SUSPEND: if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; if (!f) break; value = 0; if (f->func_suspend) value = f->func_suspend(f, w_index >> 8); if (value < 0) { ERROR(cdev, "func_suspend() returned error %d\n", value); value = 0; } break; } break; default: unknown: /* * OS descriptors handling */ if (cdev->use_os_string && cdev->os_desc_config && (ctrl->bRequestType & USB_TYPE_VENDOR) && ctrl->bRequest == cdev->b_vendor_code) { struct usb_configuration *os_desc_cfg; u8 *buf; int interface; int count = 0; req = cdev->os_desc_req; req->context = cdev; req->complete = composite_setup_complete; buf = req->buf; os_desc_cfg = cdev->os_desc_config; w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ); memset(buf, 0, w_length); buf[5] = 0x01; switch (ctrl->bRequestType & USB_RECIP_MASK) { case USB_RECIP_DEVICE: if (w_index != 0x4 || (w_value >> 8)) break; buf[6] = w_index; /* Number of ext compat interfaces */ count = count_ext_compat(os_desc_cfg); buf[8] = count; count *= 24; /* 24 B/ext compat desc */ count += 16; /* header */ put_unaligned_le32(count, buf); value = w_length; if (w_length > 0x10) { value = fill_ext_compat(os_desc_cfg, buf); value = min_t(u16, w_length, value); } break; case USB_RECIP_INTERFACE: if (w_index != 0x5 || (w_value >> 8)) break; interface = w_value & 0xFF; buf[6] = w_index; count = count_ext_prop(os_desc_cfg, interface); put_unaligned_le16(count, buf + 8); count = len_ext_prop(os_desc_cfg, interface); put_unaligned_le32(count, buf); value = w_length; if (w_length > 0x0A) { value = fill_ext_prop(os_desc_cfg, interface, buf); if (value >= 0) value = min_t(u16, w_length, value); } break; } goto check_value; } VDBG(cdev, "non-core control req%02x.%02x v%04x i%04x l%d\n", ctrl->bRequestType, ctrl->bRequest, w_value, w_index, w_length); /* functions always handle their interfaces and endpoints... * punt other recipients (other, WUSB, ...) to the current * configuration code. */ if (cdev->config) { list_for_each_entry(f, &cdev->config->functions, list) if (f->req_match && f->req_match(f, ctrl, false)) goto try_fun_setup; } else { struct usb_configuration *c; list_for_each_entry(c, &cdev->configs, list) list_for_each_entry(f, &c->functions, list) if (f->req_match && f->req_match(f, ctrl, true)) goto try_fun_setup; } f = NULL; switch (ctrl->bRequestType & USB_RECIP_MASK) { case USB_RECIP_INTERFACE: if (!cdev->config || intf >= MAX_CONFIG_INTERFACES) break; f = cdev->config->interface[intf]; break; case USB_RECIP_ENDPOINT: if (!cdev->config) break; endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f); list_for_each_entry(f, &cdev->config->functions, list) { if (test_bit(endp, f->endpoints)) break; } if (&f->list == &cdev->config->functions) f = NULL; break; } try_fun_setup: if (f && f->setup) value = f->setup(f, ctrl); else { struct usb_configuration *c; c = cdev->config; if (!c) goto done; /* try current config's setup */ if (c->setup) { value = c->setup(c, ctrl); goto done; } /* try the only function in the current config */ if (!list_is_singular(&c->functions)) goto done; f = list_first_entry(&c->functions, struct usb_function, list); if (f->setup) value = f->setup(f, ctrl); } goto done; } check_value: /* respond with data transfer before status phase? */ if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) { req->length = value; req->context = cdev; req->zero = value < w_length; value = composite_ep0_queue(cdev, req, GFP_ATOMIC); if (value < 0) { DBG(cdev, "ep_queue --> %d\n", value); req->status = 0; composite_setup_complete(gadget->ep0, req); } } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) { WARN(cdev, "%s: Delayed status not supported for w_length != 0", __func__); } done: /* device either stalls (value < 0) or reports success */ return value; }
1
474,006
big5_hkscs_mbc_enc_len(const UChar* p, const UChar* e, OnigEncoding enc ARG_UNUSED) { return big5_mbc_enc_len0(p, e, 2, EncLen_BIG5_HKSCS); }
0
264,647
GF_Err BM_ParseCommand(GF_BifsDecoder *codec, GF_BitStream *bs, GF_List *com_list) { u8 go, type; GF_Err e; go = 1; e = GF_OK; GF_SceneGraph *cur_graph = codec->current_graph; GF_Proto *cur_proto = codec->pCurrentProto; codec->LastError = GF_OK; while (go) { type = gf_bs_read_int(bs, 2); switch (type) { case 0: e = BM_ParseInsert(codec, bs, com_list); break; case 1: e = BM_ParseDelete(codec, bs, com_list); break; case 2: e = BM_ParseReplace(codec, bs, com_list); break; case 3: e = BM_SceneReplace(codec, bs, com_list); break; } if (e) break; go = gf_bs_read_int(bs, 1); } while (gf_list_count(codec->QPs)) { gf_bifs_dec_qp_remove(codec, GF_TRUE); } codec->current_graph = cur_graph; codec->pCurrentProto = cur_proto; return e; }
0
361,755
static int em28xx_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev; struct em28xx *dev = NULL; int retval; bool has_vendor_audio = false, has_video = false, has_dvb = false; int i, nr, try_bulk; const int ifnum = intf->altsetting[0].desc.bInterfaceNumber; char *speed; udev = usb_get_dev(interface_to_usbdev(intf)); /* Check to see next free device and mark as used */ do { nr = find_first_zero_bit(em28xx_devused, EM28XX_MAXBOARDS); if (nr >= EM28XX_MAXBOARDS) { /* No free device slots */ dev_err(&intf->dev, "Driver supports up to %i em28xx boards.\n", EM28XX_MAXBOARDS); retval = -ENOMEM; goto err_no_slot; } } while (test_and_set_bit(nr, em28xx_devused)); /* Don't register audio interfaces */ if (intf->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) { dev_info(&intf->dev, "audio device (%04x:%04x): interface %i, class %i\n", le16_to_cpu(udev->descriptor.idVendor), le16_to_cpu(udev->descriptor.idProduct), ifnum, intf->altsetting[0].desc.bInterfaceClass); retval = -ENODEV; goto err; } /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) { retval = -ENOMEM; goto err; } /* compute alternate max packet sizes */ dev->alt_max_pkt_size_isoc = kcalloc(intf->num_altsetting, sizeof(dev->alt_max_pkt_size_isoc[0]), GFP_KERNEL); if (!dev->alt_max_pkt_size_isoc) { kfree(dev); retval = -ENOMEM; goto err; } /* Get endpoints */ for (i = 0; i < intf->num_altsetting; i++) { int ep; for (ep = 0; ep < intf->altsetting[i].desc.bNumEndpoints; ep++) em28xx_check_usb_descriptor(dev, udev, intf, i, ep, &has_vendor_audio, &has_video, &has_dvb); } if (!(has_vendor_audio || has_video || has_dvb)) { retval = -ENODEV; goto err_free; } switch (udev->speed) { case USB_SPEED_LOW: speed = "1.5"; break; case USB_SPEED_UNKNOWN: case USB_SPEED_FULL: speed = "12"; break; case USB_SPEED_HIGH: speed = "480"; break; default: speed = "unknown"; } dev_info(&intf->dev, "New device %s %s @ %s Mbps (%04x:%04x, interface %d, class %d)\n", udev->manufacturer ? udev->manufacturer : "", udev->product ? udev->product : "", speed, le16_to_cpu(udev->descriptor.idVendor), le16_to_cpu(udev->descriptor.idProduct), ifnum, intf->altsetting->desc.bInterfaceNumber); /* * Make sure we have 480 Mbps of bandwidth, otherwise things like * video stream wouldn't likely work, since 12 Mbps is generally * not enough even for most Digital TV streams. */ if (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) { dev_err(&intf->dev, "Device initialization failed.\n"); dev_err(&intf->dev, "Device must be connected to a high-speed USB 2.0 port.\n"); retval = -ENODEV; goto err_free; } kref_init(&dev->ref); dev->devno = nr; dev->model = id->driver_info; dev->alt = -1; dev->is_audio_only = has_vendor_audio && !(has_video || has_dvb); dev->has_video = has_video; dev->ifnum = ifnum; dev->ts = PRIMARY_TS; snprintf(dev->name, 28, "em28xx"); dev->dev_next = NULL; if (has_vendor_audio) { dev_info(&intf->dev, "Audio interface %i found (Vendor Class)\n", ifnum); dev->usb_audio_type = EM28XX_USB_AUDIO_VENDOR; } /* Checks if audio is provided by a USB Audio Class intf */ for (i = 0; i < udev->config->desc.bNumInterfaces; i++) { struct usb_interface *uif = udev->config->interface[i]; if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) { if (has_vendor_audio) dev_err(&intf->dev, "em28xx: device seems to have vendor AND usb audio class interfaces !\n" "\t\tThe vendor interface will be ignored. Please contact the developers <linux-media@vger.kernel.org>\n"); dev->usb_audio_type = EM28XX_USB_AUDIO_CLASS; break; } } if (has_video) dev_info(&intf->dev, "Video interface %i found:%s%s\n", ifnum, dev->analog_ep_bulk ? " bulk" : "", dev->analog_ep_isoc ? " isoc" : ""); if (has_dvb) dev_info(&intf->dev, "DVB interface %i found:%s%s\n", ifnum, dev->dvb_ep_bulk ? " bulk" : "", dev->dvb_ep_isoc ? " isoc" : ""); dev->num_alt = intf->num_altsetting; if ((unsigned int)card[nr] < em28xx_bcount) dev->model = card[nr]; /* save our data pointer in this intf device */ usb_set_intfdata(intf, dev); /* allocate device struct and check if the device is a webcam */ mutex_init(&dev->lock); retval = em28xx_init_dev(dev, udev, intf, nr); if (retval) goto err_free; if (usb_xfer_mode < 0) { if (dev->is_webcam) try_bulk = 1; else try_bulk = 0; } else { try_bulk = usb_xfer_mode > 0; } /* Disable V4L2 if the device doesn't have a decoder or image sensor */ if (has_video && dev->board.decoder == EM28XX_NODECODER && dev->em28xx_sensor == EM28XX_NOSENSOR) { dev_err(&intf->dev, "Currently, V4L2 is not supported on this model\n"); has_video = false; dev->has_video = false; } if (dev->board.has_dual_ts && (dev->tuner_type != TUNER_ABSENT || INPUT(0)->type)) { /* * The logic with sets alternate is not ready for dual-tuners * which analog modes. */ dev_err(&intf->dev, "We currently don't support analog TV or stream capture on dual tuners.\n"); has_video = false; } /* Select USB transfer types to use */ if (has_video) { if (!dev->analog_ep_isoc || (try_bulk && dev->analog_ep_bulk)) dev->analog_xfer_bulk = 1; dev_info(&intf->dev, "analog set to %s mode.\n", dev->analog_xfer_bulk ? "bulk" : "isoc"); } if (has_dvb) { if (!dev->dvb_ep_isoc || (try_bulk && dev->dvb_ep_bulk)) dev->dvb_xfer_bulk = 1; dev_info(&intf->dev, "dvb set to %s mode.\n", dev->dvb_xfer_bulk ? "bulk" : "isoc"); } if (dev->board.has_dual_ts && em28xx_duplicate_dev(dev) == 0) { kref_init(&dev->dev_next->ref); dev->dev_next->ts = SECONDARY_TS; dev->dev_next->alt = -1; dev->dev_next->is_audio_only = has_vendor_audio && !(has_video || has_dvb); dev->dev_next->has_video = false; dev->dev_next->ifnum = ifnum; dev->dev_next->model = id->driver_info; mutex_init(&dev->dev_next->lock); retval = em28xx_init_dev(dev->dev_next, udev, intf, dev->dev_next->devno); if (retval) goto err_free; dev->dev_next->board.ir_codes = NULL; /* No IR for 2nd tuner */ dev->dev_next->board.has_ir_i2c = 0; /* No IR for 2nd tuner */ if (usb_xfer_mode < 0) { if (dev->dev_next->is_webcam) try_bulk = 1; else try_bulk = 0; } else { try_bulk = usb_xfer_mode > 0; } /* Select USB transfer types to use */ if (has_dvb) { if (!dev->dvb_ep_isoc_ts2 || (try_bulk && dev->dvb_ep_bulk_ts2)) dev->dev_next->dvb_xfer_bulk = 1; dev_info(&dev->intf->dev, "dvb ts2 set to %s mode.\n", dev->dev_next->dvb_xfer_bulk ? "bulk" : "isoc"); } dev->dev_next->dvb_ep_isoc = dev->dvb_ep_isoc_ts2; dev->dev_next->dvb_ep_bulk = dev->dvb_ep_bulk_ts2; dev->dev_next->dvb_max_pkt_size_isoc = dev->dvb_max_pkt_size_isoc_ts2; dev->dev_next->dvb_alt_isoc = dev->dvb_alt_isoc; /* Configure hardware to support TS2*/ if (dev->dvb_xfer_bulk) { /* The ep4 and ep5 are configured for BULK */ em28xx_write_reg(dev, 0x0b, 0x96); mdelay(100); em28xx_write_reg(dev, 0x0b, 0x80); mdelay(100); } else { /* The ep4 and ep5 are configured for ISO */ em28xx_write_reg(dev, 0x0b, 0x96); mdelay(100); em28xx_write_reg(dev, 0x0b, 0x82); mdelay(100); } } request_modules(dev); /* * Do it at the end, to reduce dynamic configuration changes during * the device init. Yet, as request_modules() can be async, the * topology will likely change after the load of the em28xx subdrivers. */ #ifdef CONFIG_MEDIA_CONTROLLER retval = media_device_register(dev->media_dev); #endif return 0; err_free: kfree(dev->alt_max_pkt_size_isoc); kfree(dev); err: clear_bit(nr, em28xx_devused); err_no_slot: usb_put_dev(udev); return retval; }
0
263,494
static int sco_sock_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sco_pinfo *pi = sco_pi(sk); lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { sco_conn_defer_accept(pi->conn->hcon, pi->setting); sk->sk_state = BT_CONFIG; release_sock(sk); return 0; } release_sock(sk); return bt_sock_recvmsg(sock, msg, len, flags); }
0
254,741
njs_typed_array_prototype_index_of(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, njs_index_t type) { double v; int64_t i, i64, from, to, index, increment, offset, length; njs_int_t ret, integer; njs_value_t *this; const float *f32; const double *f64; const uint8_t *u8; const uint16_t *u16; const uint32_t *u32; njs_typed_array_t *array; njs_array_buffer_t *buffer; this = njs_argument(args, 0); if (njs_slow_path(!njs_is_typed_array(this))) { njs_type_error(vm, "this is not a typed array"); return NJS_ERROR; } index = -1; array = njs_typed_array(this); length = njs_typed_array_length(array); if (!njs_is_number(njs_arg(args, nargs, 1)) || length == 0) { goto done; } if (type & 2) { /* lastIndexOf(). */ if (nargs > 2) { ret = njs_value_to_integer(vm, njs_arg(args, nargs, 2), &from); if (njs_slow_path(ret != NJS_OK)) { return ret; } } else { from = length - 1; } if (from >= 0) { from = njs_min(from, length - 1); } else if (from < 0) { from += length; } to = -1; increment = -1; if (from <= to) { goto done; } } else { /* indexOf(), includes(). */ ret = njs_value_to_integer(vm, njs_arg(args, nargs, 2), &from); if (njs_slow_path(ret != NJS_OK)) { return ret; } if (from < 0) { from += length; if (from < 0) { from = 0; } } to = length; increment = 1; if (from >= to) { goto done; } } if (njs_slow_path(njs_is_detached_buffer(array->buffer))) { njs_type_error(vm, "detached buffer"); return NJS_ERROR; } v = njs_number(njs_argument(args, 1)); i64 = v; integer = (v == i64); buffer = array->buffer; offset = array->offset; switch (array->type) { case NJS_OBJ_TYPE_INT8_ARRAY: if (integer && ((int8_t) i64 == i64)) { goto search8; } break; case NJS_OBJ_TYPE_UINT8_CLAMPED_ARRAY: case NJS_OBJ_TYPE_UINT8_ARRAY: if (integer && ((uint8_t) i64 == i64)) { search8: u8 = &buffer->u.u8[0]; for (i = from; i != to; i += increment) { if (u8[offset + i] == (uint8_t) i64) { index = i; break; } } } break; case NJS_OBJ_TYPE_INT16_ARRAY: if (integer && ((int16_t) i64 == i64)) { goto search16; } break; case NJS_OBJ_TYPE_UINT16_ARRAY: if (integer && ((uint16_t) i64 == i64)) { search16: u16 = &buffer->u.u16[0]; for (i = from; i != to; i += increment) { if (u16[offset + i] == (uint16_t) i64) { index = i; break; } } } break; case NJS_OBJ_TYPE_INT32_ARRAY: if (integer && ((int32_t) i64 == i64)) { goto search32; } break; case NJS_OBJ_TYPE_UINT32_ARRAY: if (integer && ((uint32_t) i64 == i64)) { search32: u32 = &buffer->u.u32[0]; for (i = from; i != to; i += increment) { if (u32[offset + i] == (uint32_t) i64) { index = i; break; } } } break; case NJS_OBJ_TYPE_FLOAT32_ARRAY: f32 = &buffer->u.f32[0]; if (((float) v == v)) { for (i = from; i != to; i += increment) { if (f32[offset + i] == (float) v) { index = i; break; } } } else if ((type & 1) && isnan(v)) { /* includes() handles NaN. */ for (i = from; i != to; i += increment) { if (isnan(f32[offset + i])) { index = i; break; } } } break; default: /* NJS_OBJ_TYPE_FLOAT64_ARRAY. */ f64 = &buffer->u.f64[0]; if ((type & 1) && isnan(v)) { /* includes() handles NaN. */ for (i = from; i != to; i += increment) { if (isnan(f64[offset + i])) { index = i; break; } } } else { for (i = from; i != to; i += increment) { if (f64[offset + i] == v) { index = i; break; } } } } done: /* Default values. */ if (type & 1) { njs_set_boolean(&vm->retval, index != -1); } else { njs_set_number(&vm->retval, index); } return NJS_OK; }
0
225,873
GF_Box *gnra_box_new() { ISOM_DECL_BOX_ALLOC(GF_GenericAudioSampleEntryBox, GF_ISOM_BOX_TYPE_GNRA); gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*) tmp); return (GF_Box *)tmp; }
0
313,534
int rose_add_loopback_node(const rose_address *address) { struct rose_node *rose_node; int err = 0; spin_lock_bh(&rose_node_list_lock); rose_node = rose_node_list; while (rose_node != NULL) { if ((rose_node->mask == 10) && (rosecmpm(address, &rose_node->address, 10) == 0) && rose_node->loopback) break; rose_node = rose_node->next; } if (rose_node != NULL) goto out; if ((rose_node = kmalloc(sizeof(*rose_node), GFP_ATOMIC)) == NULL) { err = -ENOMEM; goto out; } rose_node->address = *address; rose_node->mask = 10; rose_node->count = 1; rose_node->loopback = 1; rose_node->neighbour[0] = rose_loopback_neigh; /* Insert at the head of list. Address is always mask=10 */ rose_node->next = rose_node_list; rose_node_list = rose_node; rose_loopback_neigh->count++; out: spin_unlock_bh(&rose_node_list_lock); return err; }
0
328,944
R_API RBinJavaField *r_bin_java_read_next_method(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) { ut32 i, idx; const ut8 *f_buf = buf + offset; ut64 adv = 0; RBinJavaCPTypeObj *item = NULL; if (!bin || offset + 8 >= len) { return NULL; } RBinJavaField *method = (RBinJavaField *) R_NEW0 (RBinJavaField); if (!method) { eprintf ("Unable to allocate memory for method information\n"); return NULL; } method->metas = (RBinJavaMetaInfo *) R_NEW0 (RBinJavaMetaInfo); if (!method->metas) { eprintf ("Unable to allocate memory for meta information\n"); free (method); return NULL; } method->file_offset = offset; method->flags = R_BIN_JAVA_USHORT (f_buf, 0); method->flags_str = retrieve_method_access_string (method->flags); // need to subtract 1 for the idx method->name_idx = R_BIN_JAVA_USHORT (f_buf, 2); method->descriptor_idx = R_BIN_JAVA_USHORT (f_buf, 4); method->attr_count = R_BIN_JAVA_USHORT (f_buf, 6); method->attributes = r_list_newf (r_bin_java_attribute_free); method->type = R_BIN_JAVA_FIELD_TYPE_METHOD; method->metas->ord = bin->method_idx; adv += 8; idx = method->name_idx; item = r_bin_java_get_item_from_bin_cp_list (bin, idx); method->name = r_bin_java_get_utf8_from_bin_cp_list (bin, (ut32) (method->name_idx)); IFDBG eprintf ("Method name_idx: %d, which is: ord: %d, name: %s, value: %s\n", idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name, method->name); if (!method->name) { method->name = (char *) malloc (21); snprintf ((char *) method->name, 20, "sym.method_%08x", method->metas->ord); IFDBG eprintf ("r_bin_java_read_next_method: Unable to find the name for 0x%02x index.\n", method->name_idx); } idx = method->descriptor_idx; item = r_bin_java_get_item_from_bin_cp_list (bin, idx); method->descriptor = r_bin_java_get_utf8_from_bin_cp_list (bin, (ut32) method->descriptor_idx); IFDBG eprintf ("Method descriptor_idx: %d, which is: ord: %d, name: %s, value: %s\n", idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name, method->descriptor); if (!method->descriptor) { method->descriptor = r_str_dup (NULL, "NULL"); IFDBG eprintf ("r_bin_java_read_next_method: Unable to find the descriptor for 0x%02x index.\n", method->descriptor_idx); } IFDBG eprintf ("Looking for a NameAndType CP with name_idx: %d descriptor_idx: %d\n", method->name_idx, method->descriptor_idx); method->field_ref_cp_obj = r_bin_java_find_cp_ref_info_from_name_and_type (bin, method->name_idx, method->descriptor_idx); if (method->field_ref_cp_obj) { IFDBG eprintf ("Found the obj.\n"); item = r_bin_java_get_item_from_bin_cp_list (bin, method->field_ref_cp_obj->info.cp_method.class_idx); IFDBG eprintf ("Method class reference value: %d, which is: ord: %d, name: %s\n", method->field_ref_cp_obj->info.cp_method.class_idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name); method->class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, item); IFDBG eprintf ("Method requesting ref_cp_obj the following which is: ord: %d, name: %s\n", method->field_ref_cp_obj->metas->ord, ((RBinJavaCPTypeMetas *)method->field_ref_cp_obj->metas->type_info)->name); IFDBG eprintf ("MethodRef class name resolves to: %s\n", method->class_name); if (!method->class_name) { method->class_name = r_str_dup (NULL, "NULL"); } } else { // XXX - default to this class? method->field_ref_cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, bin->cf2.this_class); method->class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, method->field_ref_cp_obj); } IFDBG eprintf ("Parsing %s(%s)\n", method->name, method->descriptor); if (method->attr_count > 0) { method->attr_offset = adv + offset; RBinJavaAttrInfo *attr = NULL; for (i = 0; i < method->attr_count; i++) { attr = r_bin_java_read_next_attr (bin, adv + offset, buf, len); if (!attr) { eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Method Attribute: %d.\n", i); break; } if ((r_bin_java_get_attr_type_by_name (attr->name))->type == R_BIN_JAVA_ATTR_TYPE_CODE_ATTR) { // This is necessary for determing the appropriate number of bytes when readin // uoffset, ustack, ulocalvar values bin->cur_method_code_length = attr->info.code_attr.code_length; bin->offset_sz = 2;// (attr->info.code_attr.code_length > 65535) ? 4 : 2; bin->ustack_sz = 2;// (attr->info.code_attr.max_stack > 65535) ? 4 : 2; bin->ulocalvar_sz = 2;// (attr->info.code_attr.max_locals > 65535) ? 4 : 2; } IFDBG eprintf ("Parsing @ 0x%"PFMT64x " (%s) = 0x%"PFMT64x " bytes\n", attr->file_offset, attr->name, attr->size); r_list_append (method->attributes, attr); adv += attr->size; if (adv + offset >= len) { eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Method Attribute: %d.\n", i); break; } } } method->size = adv; // reset after parsing the method attributes IFDBG eprintf ("Parsing @ 0x%"PFMT64x " %s(%s) = 0x%"PFMT64x " bytes\n", method->file_offset, method->name, method->descriptor, method->size); return method; }
0
195,083
bool Tensor::FromProto(Allocator* a, const TensorProto& proto) { CHECK_NOTNULL(a); TensorBuffer* p = nullptr; if (!TensorShape::IsValid(proto.tensor_shape())) return false; if (proto.dtype() == DT_INVALID) return false; TensorShape shape(proto.tensor_shape()); const int64_t N = shape.num_elements(); if (N > 0 && proto.dtype()) { bool dtype_error = false; if (!proto.tensor_content().empty()) { const auto& content = proto.tensor_content(); CASES_WITH_DEFAULT(proto.dtype(), p = Helper<T>::Decode(a, content, N), dtype_error = true, dtype_error = true); } else { CASES_WITH_DEFAULT(proto.dtype(), p = FromProtoField<T>(a, proto, N), dtype_error = true, dtype_error = true); } if (dtype_error || p == nullptr) return false; } shape_ = shape; set_dtype(proto.dtype()); UnrefIfNonNull(buf_); buf_ = p; // TODO(misard) add tracking of which kernels and steps are calling // FromProto. if (MemoryLoggingEnabled() && buf_ != nullptr && buf_->data() != nullptr) { LogMemory::RecordTensorAllocation("Unknown (from Proto)", LogMemory::UNKNOWN_STEP_ID, *this); } return true; }
1
310,050
copy_input(FILE *source, const char *filename, char *alt_file) { char my_altfile[PATH_MAX]; FILE *result = 0; FILE *target = 0; int ch; if (alt_file == 0) alt_file = my_altfile; if (source == 0) { failed("copy_input (source)"); } else if ((target = open_tempfile(alt_file)) == 0) { failed("copy_input (target)"); } else { clearerr(source); for (;;) { ch = fgetc(source); if (feof(source)) { break; } else if (ferror(source)) { failed(filename); } else if (ch == 0) { /* don't loop in case someone wants to convert /dev/zero */ fprintf(stderr, "%s: %s is not a text-file\n", _nc_progname, filename); ExitProgram(EXIT_FAILURE); } fputc(ch, target); } fclose(source); /* * rewind() does not force the target file's data to disk (not does * fflush()...). So open a second stream on the data and then close * the one that we were writing on before starting to read from the * second stream. */ result = fopen(alt_file, "r+"); fclose(target); to_remove = strdup(alt_file); } return result; }
0
222,674
static void setup_locale(void) { const char *s; if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL) { if (setlocale(LC_CTYPE, "") == NULL) tmate_fatal("invalid LC_ALL, LC_CTYPE or LANG"); s = nl_langinfo(CODESET); if (strcasecmp(s, "UTF-8") != 0 && strcasecmp(s, "UTF8") != 0) tmate_fatal("need UTF-8 locale (LC_CTYPE) but have %s", s); } setlocale(LC_TIME, ""); tzset(); }
0
353,151
SplashFunctionPattern::SplashFunctionPattern(SplashColorMode colorModeA, GfxState *stateA, GfxFunctionShading *shadingA) { Matrix ctm; SplashColor defaultColor; GfxColor srcColor; const double *matrix = shadingA->getMatrix(); shading = shadingA; state = stateA; colorMode = colorModeA; state->getCTM(&ctm); double a1 = ctm.m[0]; double b1 = ctm.m[1]; double c1 = ctm.m[2]; double d1 = ctm.m[3]; ctm.m[0] = matrix[0] * a1 + matrix[1] * c1; ctm.m[1] = matrix[0] * b1 + matrix[1] * d1; ctm.m[2] = matrix[2] * a1 + matrix[3] * c1; ctm.m[3] = matrix[2] * b1 + matrix[3] * d1; ctm.m[4] = matrix[4] * a1 + matrix[5] * c1 + ctm.m[4]; ctm.m[5] = matrix[4] * b1 + matrix[5] * d1 + ctm.m[5]; ctm.invertTo(&ictm); gfxMode = shadingA->getColorSpace()->getMode(); shadingA->getColorSpace()->getDefaultColor(&srcColor); shadingA->getDomain(&xMin, &yMin, &xMax, &yMax); convertGfxColor(defaultColor, colorModeA, shadingA->getColorSpace(), &srcColor); }
0
500,654
char *sftp_readlink(sftp_session sftp, const char *path) { sftp_status_message status = NULL; sftp_message msg = NULL; ssh_string path_s = NULL; ssh_string link_s = NULL; ssh_buffer buffer; char *lnk; uint32_t ignored; uint32_t id; if (sftp == NULL) return NULL; if (path == NULL) { ssh_set_error_invalid(sftp, __FUNCTION__); return NULL; } if (sftp->version < 3){ ssh_set_error(sftp,SSH_REQUEST_DENIED,"sftp version %d does not support sftp_readlink",sftp->version); return NULL; } buffer = ssh_buffer_new(); if (buffer == NULL) { ssh_set_error_oom(sftp->session); return NULL; } path_s = ssh_string_from_char(path); if (path_s == NULL) { ssh_set_error_oom(sftp->session); ssh_buffer_free(buffer); return NULL; } id = sftp_get_new_id(sftp); if (buffer_add_u32(buffer, id) < 0 || buffer_add_ssh_string(buffer, path_s) < 0) { ssh_set_error_oom(sftp->session); ssh_buffer_free(buffer); ssh_string_free(path_s); return NULL; } if (sftp_packet_write(sftp, SSH_FXP_READLINK, buffer) < 0) { ssh_buffer_free(buffer); ssh_string_free(path_s); return NULL; } ssh_buffer_free(buffer); ssh_string_free(path_s); while (msg == NULL) { if (sftp_read_and_dispatch(sftp) < 0) { return NULL; } msg = sftp_dequeue(sftp, id); } if (msg->packet_type == SSH_FXP_NAME) { /* we don't care about "count" */ buffer_get_u32(msg->payload, &ignored); /* we only care about the file name string */ link_s = buffer_get_ssh_string(msg->payload); sftp_message_free(msg); if (link_s == NULL) { /* TODO: what error to set here? */ return NULL; } lnk = ssh_string_to_char(link_s); ssh_string_free(link_s); return lnk; } else if (msg->packet_type == SSH_FXP_STATUS) { /* bad response (error) */ status = parse_status_msg(msg); sftp_message_free(msg); if (status == NULL) { return NULL; } ssh_set_error(sftp->session, SSH_REQUEST_DENIED, "SFTP server: %s", status->errormsg); status_msg_free(status); } else { /* this shouldn't happen */ ssh_set_error(sftp->session, SSH_FATAL, "Received message %d when attempting to set stats", msg->packet_type); sftp_message_free(msg); } return NULL; }
0
282,864
int rsi_send_ps_request(struct rsi_hw *adapter, bool enable, struct ieee80211_vif *vif) { struct rsi_common *common = adapter->priv; struct ieee80211_bss_conf *bss = &vif->bss_conf; struct rsi_request_ps *ps; struct rsi_ps_info *ps_info; struct sk_buff *skb; int frame_len = sizeof(*ps); skb = dev_alloc_skb(frame_len); if (!skb) return -ENOMEM; memset(skb->data, 0, frame_len); ps = (struct rsi_request_ps *)skb->data; ps_info = &adapter->ps_info; rsi_set_len_qno(&ps->desc.desc_dword0.len_qno, (frame_len - FRAME_DESC_SZ), RSI_WIFI_MGMT_Q); ps->desc.desc_dword0.frame_type = WAKEUP_SLEEP_REQUEST; if (enable) { ps->ps_sleep.enable = RSI_PS_ENABLE; ps->desc.desc_dword3.token = cpu_to_le16(RSI_SLEEP_REQUEST); } else { ps->ps_sleep.enable = RSI_PS_DISABLE; ps->desc.desc_dword0.len_qno |= cpu_to_le16(RSI_PS_DISABLE_IND); ps->desc.desc_dword3.token = cpu_to_le16(RSI_WAKEUP_REQUEST); } ps->ps_uapsd_acs = common->uapsd_bitmap; ps->ps_sleep.sleep_type = ps_info->sleep_type; ps->ps_sleep.num_bcns_per_lis_int = cpu_to_le16(ps_info->num_bcns_per_lis_int); ps->ps_sleep.sleep_duration = cpu_to_le32(ps_info->deep_sleep_wakeup_period); if (bss->assoc) ps->ps_sleep.connected_sleep = RSI_CONNECTED_SLEEP; else ps->ps_sleep.connected_sleep = RSI_DEEP_SLEEP; ps->ps_listen_interval = cpu_to_le32(ps_info->listen_interval); ps->ps_dtim_interval_duration = cpu_to_le32(ps_info->dtim_interval_duration); if (ps_info->listen_interval > ps_info->dtim_interval_duration) ps->ps_listen_interval = cpu_to_le32(RSI_PS_DISABLE); ps->ps_num_dtim_intervals = cpu_to_le16(ps_info->num_dtims_per_sleep); skb_put(skb, frame_len); return rsi_send_internal_mgmt_frame(common, skb); }
0
483,488
int efi_mem_type(unsigned long phys_addr) { const efi_memory_desc_t *md; if (!efi_enabled(EFI_MEMMAP)) return -ENOTSUPP; for_each_efi_memory_desc(md) { if ((md->phys_addr <= phys_addr) && (phys_addr < (md->phys_addr + (md->num_pages << EFI_PAGE_SHIFT)))) return md->type; } return -EINVAL; }
0
238,764
fuzzy_match_func_compare(const void *s1, const void *s2) { int v1 = ((fuzmatch_str_T *)s1)->score; int v2 = ((fuzmatch_str_T *)s2)->score; int idx1 = ((fuzmatch_str_T *)s1)->idx; int idx2 = ((fuzmatch_str_T *)s2)->idx; char_u *str1 = ((fuzmatch_str_T *)s1)->str; char_u *str2 = ((fuzmatch_str_T *)s2)->str; if (*str1 != '<' && *str2 == '<') return -1; if (*str1 == '<' && *str2 != '<') return 1; return v1 == v2 ? (idx1 - idx2) : v1 > v2 ? -1 : 1; }
0
220,844
inline Integer FloorLog2(Integer n) { static_assert(std::is_integral<Integer>::value, ""); static_assert(std::is_signed<Integer>::value, ""); static_assert(sizeof(Integer) == 4 || sizeof(Integer) == 8, ""); TFLITE_CHECK_GT(n, 0); if (sizeof(Integer) == 4) { return 30 - CountLeadingSignBits(n); } else { return 62 - CountLeadingSignBits(n); } }
0
233,868
*/ void php_wddx_serialize_var(wddx_packet *packet, zval *var, zend_string *name) { HashTable *ht; if (name) { char *tmp_buf; zend_string *name_esc = php_escape_html_entities((unsigned char *) ZSTR_VAL(name), ZSTR_LEN(name), 0, ENT_QUOTES, NULL); tmp_buf = emalloc(ZSTR_LEN(name_esc) + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, ZSTR_LEN(name_esc) + sizeof(WDDX_VAR_S), WDDX_VAR_S, ZSTR_VAL(name_esc)); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); zend_string_release(name_esc); } if (Z_TYPE_P(var) == IS_INDIRECT) { var = Z_INDIRECT_P(var); } ZVAL_DEREF(var); switch (Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_TRUE: case IS_FALSE: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->u.v.nApplyCount > 1) { php_error_docref(NULL, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } if (ZEND_HASH_APPLY_PROTECTION(ht)) { ht->u.v.nApplyCount++; } php_wddx_serialize_array(packet, var); if (ZEND_HASH_APPLY_PROTECTION(ht)) { ht->u.v.nApplyCount--; } break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->u.v.nApplyCount > 1) { php_error_docref(NULL, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->u.v.nApplyCount++; php_wddx_serialize_object(packet, var); ht->u.v.nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); }
0
369,428
SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit, u32, min_complete, u32, flags, const void __user *, argp, size_t, argsz) { struct io_ring_ctx *ctx; int submitted = 0; struct fd f; long ret; io_run_task_work(); if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP | IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG | IORING_ENTER_REGISTERED_RING))) return -EINVAL; /* * Ring fd has been registered via IORING_REGISTER_RING_FDS, we * need only dereference our task private array to find it. */ if (flags & IORING_ENTER_REGISTERED_RING) { struct io_uring_task *tctx = current->io_uring; if (!tctx || fd >= IO_RINGFD_REG_MAX) return -EINVAL; fd = array_index_nospec(fd, IO_RINGFD_REG_MAX); f.file = tctx->registered_rings[fd]; if (unlikely(!f.file)) return -EBADF; } else { f = fdget(fd); if (unlikely(!f.file)) return -EBADF; } ret = -EOPNOTSUPP; if (unlikely(f.file->f_op != &io_uring_fops)) goto out_fput; ret = -ENXIO; ctx = f.file->private_data; if (unlikely(!percpu_ref_tryget(&ctx->refs))) goto out_fput; ret = -EBADFD; if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED)) goto out; /* * For SQ polling, the thread will do all submissions and completions. * Just return the requested submit count, and wake the thread if * we were asked to. */ ret = 0; if (ctx->flags & IORING_SETUP_SQPOLL) { io_cqring_overflow_flush(ctx); if (unlikely(ctx->sq_data->thread == NULL)) { ret = -EOWNERDEAD; goto out; } if (flags & IORING_ENTER_SQ_WAKEUP) wake_up(&ctx->sq_data->wait); if (flags & IORING_ENTER_SQ_WAIT) { ret = io_sqpoll_wait_sq(ctx); if (ret) goto out; } submitted = to_submit; } else if (to_submit) { ret = io_uring_add_tctx_node(ctx); if (unlikely(ret)) goto out; mutex_lock(&ctx->uring_lock); submitted = io_submit_sqes(ctx, to_submit); mutex_unlock(&ctx->uring_lock); if (submitted != to_submit) goto out; } if (flags & IORING_ENTER_GETEVENTS) { const sigset_t __user *sig; struct __kernel_timespec __user *ts; ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig); if (unlikely(ret)) goto out; min_complete = min(min_complete, ctx->cq_entries); /* * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user * space applications don't need to do io completion events * polling again, they can rely on io_sq_thread to do polling * work, which can reduce cpu usage and uring_lock contention. */ if (ctx->flags & IORING_SETUP_IOPOLL && !(ctx->flags & IORING_SETUP_SQPOLL)) { ret = io_iopoll_check(ctx, min_complete); } else { ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts); } } out: percpu_ref_put(&ctx->refs); out_fput: if (!(flags & IORING_ENTER_REGISTERED_RING)) fdput(f); return submitted ? submitted : ret;
0
343,162
static void esp_output_restore_header(struct sk_buff *skb) { void *tmp = ESP_SKB_CB(skb)->tmp; struct esp_output_extra *extra = esp_tmp_extra(tmp); esp_restore_header(skb, skb_transport_offset(skb) + extra->esphoff - sizeof(__be32)); }
0
226,097
GF_Err hdlr_box_write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_HandlerBox *ptr = (GF_HandlerBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->reserved1); gf_bs_write_u32(bs, ptr->handlerType); gf_bs_write_data(bs, (char*)ptr->reserved2, 12); if (ptr->nameUTF8) { u32 len = (u32)strlen(ptr->nameUTF8); if (ptr->store_counted_string) { gf_bs_write_u8(bs, len); gf_bs_write_data(bs, ptr->nameUTF8, len); } else { gf_bs_write_data(bs, ptr->nameUTF8, len); gf_bs_write_u8(bs, 0); } } else { gf_bs_write_u8(bs, 0); } return GF_OK; }
0
101,698
void WebProcessProxy::sendDidGetPlugins(uint64_t requestID, PassOwnPtr<Vector<PluginInfo> > pluginInfos) { ASSERT(isMainThread()); OwnPtr<Vector<PluginInfo> > plugins(pluginInfos); #if PLATFORM(MAC) if (!m_context->omitPDFSupport()) { #if ENABLE(PDFKIT_PLUGIN) plugins->append(PDFPlugin::pluginInfo()); #endif plugins->append(SimplePDFPlugin::pluginInfo()); } #endif send(Messages::WebProcess::DidGetPlugins(requestID, *plugins), 0); }
0
331,762
void QPaintEngineEx::drawEllipse(const QRectF &r) { qreal pts[26]; // QPointF[13] without constructors... union { qreal *ptr; QPointF *points; } x; x.ptr = pts; int point_count = 0; x.points[0] = qt_curves_for_arc(r, 0, -360, x.points + 1, &point_count); if (point_count == 0) return; QVectorPath vp((qreal *) pts, point_count + 1, qpaintengineex_ellipse_types, QVectorPath::EllipseHint); draw(vp); }
0
512,973
bool Item_func_coalesce::native_op(THD *thd, Native *to) { DBUG_ASSERT(fixed == 1); for (uint i= 0; i < arg_count; i++) { if (!val_native_with_conversion_from_item(thd, args[i], to, type_handler())) return false; } return (null_value= true); }
0
437,330
recursive_call_check_trav(Node* node, ScanEnv* env, int state) { int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: { int ret; do { ret = recursive_call_check_trav(NODE_CAR(node), env, state); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; else if (ret < 0) return ret; } while (IS_NOT_NULL(node = NODE_CDR(node))); } break; case NODE_QUANT: r = recursive_call_check_trav(NODE_BODY(node), env, state); if (QUANT_(node)->upper == 0) { if (r == FOUND_CALLED_NODE) QUANT_(node)->is_refered = 1; } break; case NODE_ANCHOR: { AnchorNode* an = ANCHOR_(node); if (ANCHOR_HAS_BODY(an)) r = recursive_call_check_trav(NODE_ANCHOR_BODY(an), env, state); } break; case NODE_ENCLOSURE: { int ret; int state1; EnclosureNode* en = ENCLOSURE_(node); if (en->type == ENCLOSURE_MEMORY) { if (NODE_IS_CALLED(node) || (state & IN_RECURSION) != 0) { if (! NODE_IS_RECURSION(node)) { NODE_STATUS_ADD(node, MARK1); r = recursive_call_check(NODE_BODY(node)); if (r != 0) NODE_STATUS_ADD(node, RECURSION); NODE_STATUS_REMOVE(node, MARK1); } if (NODE_IS_CALLED(node)) r = FOUND_CALLED_NODE; } } state1 = state; if (NODE_IS_RECURSION(node)) state1 |= IN_RECURSION; ret = recursive_call_check_trav(NODE_BODY(node), env, state1); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; if (en->type == ENCLOSURE_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { ret = recursive_call_check_trav(en->te.Then, env, state1); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; } if (IS_NOT_NULL(en->te.Else)) { ret = recursive_call_check_trav(en->te.Else, env, state1); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; } } } break; default: break; } return r; }
0
225,427
static int vidioc_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *fmt) { struct v4l2_loopback_device *dev; char buf[5]; dev = v4l2loopback_getdevice(file); if (0 == dev->ready_for_capture) { dprintk("setting fmt_cap not possible yet\n"); return -EBUSY; } if (fmt->fmt.pix.pixelformat != dev->pix_format.pixelformat) return -EINVAL; fmt->fmt.pix = dev->pix_format; buf[4] = 0; dprintk("capFOURCC=%s\n", fourcc2str(dev->pix_format.pixelformat, buf)); return 0; }
0
289,259
static int snd_pcm_oss_register_minor(struct snd_pcm *pcm) { pcm->oss.reg = 0; if (dsp_map[pcm->card->number] == (int)pcm->device) { char name[128]; int duplex; register_oss_dsp(pcm, 0); duplex = (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream_count > 0 && pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream_count && !(pcm->info_flags & SNDRV_PCM_INFO_HALF_DUPLEX)); sprintf(name, "%s%s", pcm->name, duplex ? " (DUPLEX)" : ""); #ifdef SNDRV_OSS_INFO_DEV_AUDIO snd_oss_info_register(SNDRV_OSS_INFO_DEV_AUDIO, pcm->card->number, name); #endif pcm->oss.reg++; pcm->oss.reg_mask |= 1; } if (adsp_map[pcm->card->number] == (int)pcm->device) { register_oss_dsp(pcm, 1); pcm->oss.reg++; pcm->oss.reg_mask |= 2; } if (pcm->oss.reg) snd_pcm_oss_proc_init(pcm); return 0; }
0
238,318
static int digest_update_interruptible(struct digest *d, const void *data, unsigned long len) { if (ctrlc()) return -EINTR; return digest_update(d, data, len); }
0
215,399
int hfsplus_find_cat(struct super_block *sb, u32 cnid, struct hfs_find_data *fd) { hfsplus_cat_entry tmp; int err; u16 type; hfsplus_cat_build_key(sb, fd->search_key, cnid, NULL); err = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry)); if (err) return err; type = be16_to_cpu(tmp.type); if (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) { printk(KERN_ERR "hfs: found bad thread record in catalog\n"); return -EIO; } hfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID), &tmp.thread.nodeName); return hfs_brec_find(fd); }
1
313,831
push_showcmd(void) { if (p_sc) STRCPY(old_showcmd_buf, showcmd_buf); }
0
301,399
static char *vfswrap_realpath(vfs_handle_struct *handle, const char *path) { char *result; START_PROFILE(syscall_realpath); #ifdef REALPATH_TAKES_NULL result = realpath(path, NULL); #else result = SMB_MALLOC_ARRAY(char, PATH_MAX+1); if (result) { char *resolved_path = realpath(path, result); if (!resolved_path) { SAFE_FREE(result); } else { /* SMB_ASSERT(result == resolved_path) ? */ result = resolved_path; } } #endif END_PROFILE(syscall_realpath); return result; }
0
230,308
njs_array_handler_find_index(njs_vm_t *vm, njs_iterator_args_t *args, njs_value_t *entry, int64_t n) { njs_int_t ret; njs_value_t copy; if (njs_is_valid(entry)) { copy = *entry; } else { njs_set_undefined(&copy); } ret = njs_array_iterator_call(vm, args, &copy, n); if (njs_slow_path(ret != NJS_OK)) { return ret; } if (njs_is_true(&vm->retval)) { njs_set_number(&vm->retval, n); return NJS_DONE; } return NJS_OK; }
0
310,007
_nc_retrace_int(int code) { T((T_RETURN("%d"), code)); return code; }
0
328,849
R_API void r_bin_java_print_method_summary(RBinJavaField *field) { RBinJavaAttrInfo *attr; RListIter *iter, *iter_tmp; if (field == NULL) { eprintf ("Attempting to print an invalid RBinJavaField* Method.\n"); return; } printf ("Method Summary Information:\n"); printf (" File Offset: 0x%08"PFMT64x "\n", field->file_offset); printf (" Name Index: %d (%s)\n", field->name_idx, field->name); printf (" Descriptor Index: %d (%s)\n", field->descriptor_idx, field->descriptor); printf (" Access Flags: 0x%02x (%s)\n", field->flags, field->flags_str); printf (" Method Attributes Count: %d\n", field->attr_count); printf (" Method Attributes:\n"); r_list_foreach_safe (field->attributes, iter, iter_tmp, attr) { r_bin_java_print_attr_summary (attr); } }
0
359,390
DEFUN (no_bgp_cluster_id, no_bgp_cluster_id_cmd, "no bgp cluster-id", NO_STR BGP_STR "Configure Route-Reflector Cluster-id\n") { int ret; struct bgp *bgp; struct in_addr cluster; bgp = vty->index; if (argc == 1) { ret = inet_aton (argv[0], &cluster); if (! ret) { vty_out (vty, "%% Malformed bgp cluster identifier%s", VTY_NEWLINE); return CMD_WARNING; } } bgp_cluster_id_unset (bgp); return CMD_SUCCESS; }
0
220,178
Status Node::input_edge(int idx, const Edge** e) const { if (idx < 0 || idx >= num_inputs()) { return errors::InvalidArgument("Invalid input_edge index: ", idx, ", Node ", name(), " only has ", num_inputs(), " inputs."); } // This does a linear search over the edges. In the common case, // the number of elements is small enough that this search isn't // expensive. Should it become a bottleneck, one can make an // optimization where, if the number of edges is small, we use // linear iteration, and if the number of edges is large, we perform // an indexing step during construction that keeps an array of Edges // indexed by pointer. This would keep the size of each Node small // in the common case but make this function faster when the number // of edges is large. for (const Edge* edge : in_edges()) { if (edge->dst_input() == idx) { *e = edge; return Status::OK(); } } return errors::NotFound("Could not find input edge ", idx, " for ", name()); }
0
247,350
int pgpPubkeyFingerprint(const uint8_t *h, size_t hlen, uint8_t **fp, size_t *fplen) { int rc = -1; /* assume failure */ const uint8_t *se; const uint8_t *pend = h + hlen; uint8_t version = 0; if (pgpVersion(h, hlen, &version)) return rc; /* We only permit V4 keys, V3 keys are long long since deprecated */ switch (version) { case 4: { pgpPktKeyV4 v = (pgpPktKeyV4) (h); int mpis = -1; /* Packet must be larger than v to have room for the required MPIs */ if (hlen > sizeof(*v)) { switch (v->pubkey_algo) { case PGPPUBKEYALGO_RSA: mpis = 2; break; case PGPPUBKEYALGO_DSA: mpis = 4; break; case PGPPUBKEYALGO_EDDSA: mpis = 1; break; } } se = (uint8_t *)(v + 1); /* EdDSA has a curve id before the MPIs */ if (v->pubkey_algo == PGPPUBKEYALGO_EDDSA) { if (se < pend && se[0] != 0x00 && se[0] != 0xff) se += 1 + se[0]; else se = pend; /* error out when reading the MPI */ } while (se < pend && mpis-- > 0) se += pgpMpiLen(se); /* Does the size and number of MPI's match our expectations? */ if (se == pend && mpis == 0) { DIGEST_CTX ctx = rpmDigestInit(PGPHASHALGO_SHA1, RPMDIGEST_NONE); uint8_t *d = NULL; size_t dlen = 0; int i = se - h; uint8_t in[3] = { 0x99, (i >> 8), i }; (void) rpmDigestUpdate(ctx, in, 3); (void) rpmDigestUpdate(ctx, h, i); (void) rpmDigestFinal(ctx, (void **)&d, &dlen, 0); if (dlen == 20) { rc = 0; *fp = d; *fplen = dlen; } else { free(d); } } } break; default: rpmlog(RPMLOG_WARNING, _("Unsupported version of key: V%d\n"), version); } return rc; }
0
259,303
static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; unsigned mov_field_order; enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 2) return AVERROR_INVALIDDATA; mov_field_order = avio_rb16(pb); if ((mov_field_order & 0xFF00) == 0x0100) decoded_field_order = AV_FIELD_PROGRESSIVE; else if ((mov_field_order & 0xFF00) == 0x0200) { switch (mov_field_order & 0xFF) { case 0x01: decoded_field_order = AV_FIELD_TT; break; case 0x06: decoded_field_order = AV_FIELD_BB; break; case 0x09: decoded_field_order = AV_FIELD_TB; break; case 0x0E: decoded_field_order = AV_FIELD_BT; break; } } if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) { av_log(c->fc, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order); } st->codecpar->field_order = decoded_field_order; return 0; }
0
198,588
get_lisp_indent(void) { pos_T *pos, realpos, paren; int amount; char_u *that; colnr_T col; colnr_T firsttry; int parencount, quotecount; int vi_lisp; // Set vi_lisp to use the vi-compatible method vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL); realpos = curwin->w_cursor; curwin->w_cursor.col = 0; if ((pos = findmatch(NULL, '(')) == NULL) pos = findmatch(NULL, '['); else { paren = *pos; pos = findmatch(NULL, '['); if (pos == NULL || LT_POSP(pos, &paren)) pos = &paren; } if (pos != NULL) { // Extra trick: Take the indent of the first previous non-white // line that is at the same () level. amount = -1; parencount = 0; while (--curwin->w_cursor.lnum >= pos->lnum) { if (linewhite(curwin->w_cursor.lnum)) continue; for (that = ml_get_curline(); *that != NUL; ++that) { if (*that == ';') { while (*(that + 1) != NUL) ++that; continue; } if (*that == '\\') { if (*(that + 1) != NUL) ++that; continue; } if (*that == '"' && *(that + 1) != NUL) { while (*++that && *that != '"') { // skipping escaped characters in the string if (*that == '\\') { if (*++that == NUL) break; if (that[1] == NUL) { ++that; break; } } } } if (*that == '(' || *that == '[') ++parencount; else if (*that == ')' || *that == ']') --parencount; } if (parencount == 0) { amount = get_indent(); break; } } if (amount == -1) { curwin->w_cursor.lnum = pos->lnum; curwin->w_cursor.col = pos->col; col = pos->col; that = ml_get_curline(); if (vi_lisp && get_indent() == 0) amount = 2; else { char_u *line = that; amount = 0; while (*that && col) { amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount); col--; } // Some keywords require "body" indenting rules (the // non-standard-lisp ones are Scheme special forms): // // (let ((a 1)) instead (let ((a 1)) // (...)) of (...)) if (!vi_lisp && (*that == '(' || *that == '[') && lisp_match(that + 1)) amount += 2; else { that++; amount++; firsttry = amount; while (VIM_ISWHITE(*that)) { amount += lbr_chartabsize(line, that, (colnr_T)amount); ++that; } if (*that && *that != ';') // not a comment line { // test *that != '(' to accommodate first let/do // argument if it is more than one line if (!vi_lisp && *that != '(' && *that != '[') firsttry++; parencount = 0; quotecount = 0; if (vi_lisp || (*that != '"' && *that != '\'' && *that != '#' && (*that < '0' || *that > '9'))) { while (*that && (!VIM_ISWHITE(*that) || quotecount || parencount) && (!((*that == '(' || *that == '[') && !quotecount && !parencount && vi_lisp))) { if (*that == '"') quotecount = !quotecount; if ((*that == '(' || *that == '[') && !quotecount) ++parencount; if ((*that == ')' || *that == ']') && !quotecount) --parencount; if (*that == '\\' && *(that+1) != NUL) amount += lbr_chartabsize_adv( line, &that, (colnr_T)amount); amount += lbr_chartabsize_adv( line, &that, (colnr_T)amount); } } while (VIM_ISWHITE(*that)) { amount += lbr_chartabsize( line, that, (colnr_T)amount); that++; } if (!*that || *that == ';') amount = firsttry; } } } } } else amount = 0; // no matching '(' or '[' found, use zero indent curwin->w_cursor = realpos; return amount; }
1
281,125
static int xfrm_policy_migrate(struct xfrm_policy *pol, struct xfrm_migrate *m, int num_migrate) { struct xfrm_migrate *mp; int i, j, n = 0; write_lock_bh(&pol->lock); if (unlikely(pol->walk.dead)) { /* target policy has been deleted */ write_unlock_bh(&pol->lock); return -ENOENT; } for (i = 0; i < pol->xfrm_nr; i++) { for (j = 0, mp = m; j < num_migrate; j++, mp++) { if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i])) continue; n++; if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL && pol->xfrm_vec[i].mode != XFRM_MODE_BEET) continue; /* update endpoints */ memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr, sizeof(pol->xfrm_vec[i].id.daddr)); memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr, sizeof(pol->xfrm_vec[i].saddr)); pol->xfrm_vec[i].encap_family = mp->new_family; /* flush bundles */ atomic_inc(&pol->genid); } } write_unlock_bh(&pol->lock); if (!n) return -ENODATA; return 0; }
0
225,439
static void check_timers(struct v4l2_loopback_device *dev) { if (!dev->ready_for_capture) return; if (dev->timeout_jiffies > 0 && !timer_pending(&dev->timeout_timer)) mod_timer(&dev->timeout_timer, jiffies + dev->timeout_jiffies); if (dev->sustain_framerate && !timer_pending(&dev->sustain_timer)) mod_timer(&dev->sustain_timer, jiffies + dev->frame_jiffies * 3 / 2); }
0
90,746
void CallCallbacksAndClear( CallbackList* callbacks, QuotaStatusCode status, int64 usage, int64 quota) { for (CallbackList::iterator iter = callbacks->begin(); iter != callbacks->end(); ++iter) { (*iter)->Run(status, usage, quota); delete *iter; } callbacks->clear(); }
0
231,017
QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t * pxStaticQueue ) { QueueHandle_t xHandle; configASSERT( uxMaxCount != 0 ); configASSERT( uxInitialCount <= uxMaxCount ); xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); if( xHandle != NULL ) { ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; traceCREATE_COUNTING_SEMAPHORE(); } else { traceCREATE_COUNTING_SEMAPHORE_FAILED(); } return xHandle; }
0
231,734
TEST_P( QuicServerTransportAllowMigrationTest, ReceiveProbingPacketFromChangedPeerAddress) { auto qLogger = std::make_shared<FileQLogger>(VantagePoint::Server); server->getNonConstConn().qLogger = qLogger; server->getNonConstConn().transportSettings.disableMigration = false; // Add additional peer id so PathResponse completes. server->getNonConstConn().peerConnectionIds.emplace_back( ConnectionId({1, 2, 3, 4}), 1); ShortHeader header( ProtectionType::KeyPhaseZero, *server->getConn().serverConnectionId, clientNextAppDataPacketNum++); RegularQuicPacketBuilder builder( server->getConn().udpSendPacketLen, std::move(header), 0 /* largestAcked */); builder.encodePacketHeader(); ASSERT_TRUE(builder.canBuildPacket()); writeSimpleFrame(PathChallengeFrame(123), builder); auto packet = std::move(builder).buildPacket(); auto packetData = packetToBuf(packet); folly::SocketAddress newPeer("100.101.102.103", 23456); try { deliverData(std::move(packetData), true, &newPeer); FAIL(); } catch (const std::runtime_error& ex) { EXPECT_EQ(std::string(ex.what()), "Invalid migration"); } EXPECT_TRUE(server->getConn().localConnectionError); EXPECT_EQ( server->getConn().localConnectionError->second, "Probing not supported yet"); std::vector<int> indices = getQLogEventIndices(QLogEventType::PacketDrop, qLogger); EXPECT_EQ(indices.size(), 1); auto tmp = std::move(qLogger->logs[indices[0]]); auto event = dynamic_cast<QLogPacketDropEvent*>(tmp.get()); EXPECT_EQ(event->packetSize, 29); EXPECT_EQ( event->dropReason, QuicTransportStatsCallback::toString( PacketDropReason::PEER_ADDRESS_CHANGE)); }
0
242,991
static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen > 0 ) return( 1 ); return( 0 ); }
0
387,794
klassItable InstanceKlass::itable() const { return klassItable(const_cast<InstanceKlass*>(this)); }
0
225,926
GF_Box *hnti_box_new() { ISOM_DECL_BOX_ALLOC(GF_HintTrackInfoBox, GF_ISOM_BOX_TYPE_HNTI); return (GF_Box *)tmp; }
0
244,015
void jp2h_box_del(GF_Box *s) { gf_free(s); }
0
521,484
static MemoryBlock createZipMemoryBlock (const StringArray& entryNames) { ZipFile::Builder builder; HashMap<String, MemoryBlock> blocks; for (auto& entryName : entryNames) { auto& block = blocks.getReference (entryName); MemoryOutputStream mo (block, false); mo << entryName; mo.flush(); builder.addEntry (new MemoryInputStream (block, false), 9, entryName, Time::getCurrentTime()); } MemoryBlock data; MemoryOutputStream mo (data, false); builder.writeToStream (mo, nullptr); return data; }
0
229,244
sstring to_string(const event::schema_change::change_type t) { switch (t) { case event::schema_change::change_type::CREATED: return "CREATED"; case event::schema_change::change_type::UPDATED: return "UPDATED"; case event::schema_change::change_type::DROPPED: return "DROPPED"; } assert(false && "unreachable"); }
0
90,841
void DidGetGlobalUsage(StorageType type, int64 usage, int64 unlimited_usage) { type_ = type; usage_ = usage; unlimited_usage_ = unlimited_usage; }
0
384,194
static int nf_tables_dump_rules(struct sk_buff *skb, struct netlink_callback *cb) { const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh); const struct nft_rule_dump_ctx *ctx = cb->data; struct nft_table *table; const struct nft_chain *chain; unsigned int idx = 0; struct net *net = sock_net(skb->sk); int family = nfmsg->nfgen_family; struct nftables_pernet *nft_net; rcu_read_lock(); nft_net = nft_pernet(net); cb->seq = READ_ONCE(nft_net->base_seq); list_for_each_entry_rcu(table, &nft_net->tables, list) { if (family != NFPROTO_UNSPEC && family != table->family) continue; if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0) continue; if (ctx && ctx->table && ctx->chain) { struct rhlist_head *list, *tmp; list = rhltable_lookup(&table->chains_ht, ctx->chain, nft_chain_ht_params); if (!list) goto done; rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) { if (!nft_is_active(net, chain)) continue; __nf_tables_dump_rules(skb, &idx, cb, table, chain); break; } goto done; } list_for_each_entry_rcu(chain, &table->chains, list) { if (__nf_tables_dump_rules(skb, &idx, cb, table, chain)) goto done; } if (ctx && ctx->table) break; } done: rcu_read_unlock(); cb->args[0] = idx; return skb->len; }
0
224,179
void Compute(OpKernelContext* ctx) override { StagingMap<Ordered>* map = nullptr; OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map)); core::ScopedUnref scope(map); // Pop a random (key, value) off the map typename StagingMap<Ordered>::KeyType key; typename StagingMap<Ordered>::Tuple tuple; const Tensor* indices_tensor; OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor)); OP_REQUIRES_OK(ctx, map->popitem(&key, indices_tensor, &tuple)); // Allocate a key tensor and assign the key as the first output ctx->set_output(0, key); // Set the rest of the outputs to the tuple Tensors OP_REQUIRES( ctx, tuple.size() == indices_tensor->NumElements(), errors::InvalidArgument("output/indices size mismatch: ", tuple.size(), " vs. ", indices_tensor->NumElements())); for (std::size_t i = 0; i < tuple.size(); ++i) { ctx->set_output(i + 1, tuple[i]); } }
0
476,122
next_desc(struct usb_descriptor_header **t, u8 desc_type) { for (; *t; t++) { if ((*t)->bDescriptorType == desc_type) return t; } return NULL; }
0
359,373
DEFUN (clear_ip_bgp_all_soft_in, clear_ip_bgp_all_soft_in_cmd, "clear ip bgp * soft in", CLEAR_STR IP_STR BGP_STR "Clear all peers\n" "Soft reconfig\n" "Soft reconfig inbound update\n") { if (argc == 1) return bgp_clear_vty (vty, argv[0], AFI_IP, SAFI_UNICAST, clear_all, BGP_CLEAR_SOFT_IN, NULL); return bgp_clear_vty (vty, NULL, AFI_IP, SAFI_UNICAST, clear_all, BGP_CLEAR_SOFT_IN, NULL); }
0
225,594
GF_Box *trpy_box_new() { ISOM_DECL_BOX_ALLOC(GF_TRPYBox, GF_ISOM_BOX_TYPE_TRPY); return (GF_Box *)tmp; }
0
261,749
void RtmpProtocol::sendAcknowledgementSize(uint32_t size) { size = htonl(size); std::string set_windowSize((char *) &size, 4); sendRequest(MSG_WIN_SIZE, set_windowSize); }
0
338,193
void WasmBinaryWriter::writeLateUserSections() { for (auto& section : wasm->userSections) { if (section.name != BinaryConsts::UserSections::Dylink) { writeUserSection(section); } } }
0
427,202
LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Dyndata *dyd, const char *name, int firstchar) { LexState lexstate; FuncState funcstate; LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ setclLvalue2s(L, L->top, cl); /* anchor it (to avoid being collected) */ luaD_inctop(L); lexstate.h = luaH_new(L); /* create table for scanner */ sethvalue2s(L, L->top, lexstate.h); /* anchor it */ luaD_inctop(L); funcstate.f = cl->p = luaF_newproto(L); luaC_objbarrier(L, cl, cl->p); funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ luaC_objbarrier(L, funcstate.f, funcstate.f->source); lexstate.buff = buff; lexstate.dyd = dyd; dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); mainfunc(&lexstate, &funcstate); lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); /* all scopes should be correctly finished */ lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); L->top--; /* remove scanner's table */ return cl; /* closure is on the stack, too */ }
0
318,092
static int rsi_find_bulk_in_and_out_endpoints(struct usb_interface *interface, struct rsi_hw *adapter) { struct rsi_91x_usbdev *dev = (struct rsi_91x_usbdev *)adapter->rsi_dev; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; __le16 buffer_size; int ii, bin_found = 0, bout_found = 0; iface_desc = &(interface->altsetting[0]); for (ii = 0; ii < iface_desc->desc.bNumEndpoints; ++ii) { endpoint = &(iface_desc->endpoint[ii].desc); if (!dev->bulkin_endpoint_addr[bin_found] && (endpoint->bEndpointAddress & USB_DIR_IN) && ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)) { buffer_size = endpoint->wMaxPacketSize; dev->bulkin_size[bin_found] = buffer_size; dev->bulkin_endpoint_addr[bin_found] = endpoint->bEndpointAddress; bin_found++; } if (!dev->bulkout_endpoint_addr[bout_found] && !(endpoint->bEndpointAddress & USB_DIR_IN) && ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)) { buffer_size = endpoint->wMaxPacketSize; dev->bulkout_endpoint_addr[bout_found] = endpoint->bEndpointAddress; dev->bulkout_size[bout_found] = buffer_size; bout_found++; } if (bin_found >= MAX_BULK_EP || bout_found >= MAX_BULK_EP) break; } if (!(dev->bulkin_endpoint_addr[0]) && dev->bulkout_endpoint_addr[0]) return -EINVAL; return 0; }
0
405,373
static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst, const void *daddr) { while (dst->xfrm) { const struct xfrm_state *xfrm = dst->xfrm; dst = xfrm_dst_child(dst); if (xfrm->props.mode == XFRM_MODE_TRANSPORT) continue; if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR) daddr = xfrm->coaddr; else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR)) daddr = &xfrm->id.daddr; } return daddr; }
0
430,339
struct hlist_node *seq_hlist_next_rcu(void *v, struct hlist_head *head, loff_t *ppos) { struct hlist_node *node = v; ++*ppos; if (v == SEQ_START_TOKEN) return rcu_dereference(head->first); else return rcu_dereference(node->next); }
0
281,141
int xfrm_policy_delete(struct xfrm_policy *pol, int dir) { struct net *net = xp_net(pol); spin_lock_bh(&net->xfrm.xfrm_policy_lock); pol = __xfrm_policy_unlink(pol, dir); spin_unlock_bh(&net->xfrm.xfrm_policy_lock); if (pol) { xfrm_policy_kill(pol); return 0; } return -ENOENT; }
0
450,834
static u8 st21nfca_se_get_bwi(struct nfc_hci_dev *hdev) { int i; u8 td; struct st21nfca_hci_info *info = nfc_hci_get_clientdata(hdev); /* Bits 8 to 5 of the first TB for T=1 encode BWI from zero to nine */ for (i = 1; i < ST21NFCA_ESE_MAX_LENGTH; i++) { td = ST21NFCA_ATR_GET_Y_FROM_TD(info->se_info.atr[i]); if (ST21NFCA_ATR_TA_PRESENT(td)) i++; if (ST21NFCA_ATR_TB_PRESENT(td)) { i++; return info->se_info.atr[i] >> 4; } } return ST21NFCA_ATR_DEFAULT_BWI; }
0
195,220
int main(int argc, char **argv, char **envp) { int opt; while ((opt = getopt(argc, argv, "b:h:k:p:q:w:z:xv")) != -1) { switch (opt) { case 'b': tmate_settings->bind_addr = xstrdup(optarg); break; case 'h': tmate_settings->tmate_host = xstrdup(optarg); break; case 'k': tmate_settings->keys_dir = xstrdup(optarg); break; case 'p': tmate_settings->ssh_port = atoi(optarg); break; case 'q': tmate_settings->ssh_port_advertized = atoi(optarg); break; case 'w': tmate_settings->websocket_hostname = xstrdup(optarg); break; case 'z': tmate_settings->websocket_port = atoi(optarg); break; case 'x': tmate_settings->use_proxy_protocol = true; break; case 'v': tmate_settings->log_level++; break; default: usage(); return 1; } } init_logging(tmate_settings->log_level); setup_locale(); if (!tmate_settings->tmate_host) tmate_settings->tmate_host = get_full_hostname(); cmdline = *argv; cmdline_end = *envp; tmate_preload_trace_lib(); tmate_catch_sigsegv(); tmate_init_rand(); if ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) || (mkdir(TMATE_WORKDIR "/sessions", 0703) < 0 && errno != EEXIST) || (mkdir(TMATE_WORKDIR "/jail", 0700) < 0 && errno != EEXIST)) tmate_fatal("Cannot prepare session in " TMATE_WORKDIR); /* The websocket server needs to access the /session dir to rename sockets */ if ((chmod(TMATE_WORKDIR, 0701) < 0) || (chmod(TMATE_WORKDIR "/sessions", 0703) < 0) || (chmod(TMATE_WORKDIR "/jail", 0700) < 0)) tmate_fatal("Cannot prepare session in " TMATE_WORKDIR); tmate_ssh_server_main(tmate_session, tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port); return 0; }
1
234,750
static int decide_stripe_size(struct btrfs_fs_devices *fs_devices, struct alloc_chunk_ctl *ctl, struct btrfs_device_info *devices_info) { struct btrfs_fs_info *info = fs_devices->fs_info; /* * Round down to number of usable stripes, devs_increment can be any * number so we can't use round_down() that requires power of 2, while * rounddown is safe. */ ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment); if (ctl->ndevs < ctl->devs_min) { if (btrfs_test_opt(info, ENOSPC_DEBUG)) { btrfs_debug(info, "%s: not enough devices with free space: have=%d minimum required=%d", __func__, ctl->ndevs, ctl->devs_min); } return -ENOSPC; } ctl->ndevs = min(ctl->ndevs, ctl->devs_max); switch (fs_devices->chunk_alloc_policy) { case BTRFS_CHUNK_ALLOC_REGULAR: return decide_stripe_size_regular(ctl, devices_info); case BTRFS_CHUNK_ALLOC_ZONED: return decide_stripe_size_zoned(ctl, devices_info); default: BUG(); } }
0
224,188
explicit MapIncompleteSizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
0
261,252
int wm_SemLock(wm_Sem *s) { WaitForSingleObject(*s, 0); return 0; }
0
225,557
void TfLiteQuantizationFree(TfLiteQuantization* quantization) { if (quantization->type == kTfLiteAffineQuantization) { TfLiteAffineQuantization* q_params = (TfLiteAffineQuantization*)(quantization->params); if (q_params->scale) { TfLiteFloatArrayFree(q_params->scale); q_params->scale = NULL; } if (q_params->zero_point) { TfLiteIntArrayFree(q_params->zero_point); q_params->zero_point = NULL; } free(q_params); } quantization->params = NULL; quantization->type = kTfLiteNoQuantization; }
0
489,171
sctp_disposition_t sctp_sf_backbeat_8_3(const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; union sctp_addr from_addr; struct sctp_transport *link; sctp_sender_hb_info_t *hbinfo; unsigned long max_interval; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(ep, asoc, type, arg, commands); /* Make sure that the HEARTBEAT-ACK chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_heartbeat_chunk_t))) return sctp_sf_violation_chunklen(ep, asoc, type, arg, commands); hbinfo = (sctp_sender_hb_info_t *) chunk->skb->data; /* Make sure that the length of the parameter is what we expect */ if (ntohs(hbinfo->param_hdr.length) != sizeof(sctp_sender_hb_info_t)) { return SCTP_DISPOSITION_DISCARD; } from_addr = hbinfo->daddr; link = sctp_assoc_lookup_paddr(asoc, &from_addr); /* This should never happen, but lets log it if so. */ if (unlikely(!link)) { if (from_addr.sa.sa_family == AF_INET6) { if (net_ratelimit()) printk(KERN_WARNING "%s association %p could not find address " NIP6_FMT "\n", __func__, asoc, NIP6(from_addr.v6.sin6_addr)); } else { if (net_ratelimit()) printk(KERN_WARNING "%s association %p could not find address " NIPQUAD_FMT "\n", __func__, asoc, NIPQUAD(from_addr.v4.sin_addr.s_addr)); } return SCTP_DISPOSITION_DISCARD; } /* Validate the 64-bit random nonce. */ if (hbinfo->hb_nonce != link->hb_nonce) return SCTP_DISPOSITION_DISCARD; max_interval = link->hbinterval + link->rto; /* Check if the timestamp looks valid. */ if (time_after(hbinfo->sent_at, jiffies) || time_after(jiffies, hbinfo->sent_at + max_interval)) { SCTP_DEBUG_PRINTK("%s: HEARTBEAT ACK with invalid timestamp " "received for transport: %p\n", __func__, link); return SCTP_DISPOSITION_DISCARD; } /* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of * the HEARTBEAT should clear the error counter of the * destination transport address to which the HEARTBEAT was * sent and mark the destination transport address as active if * it is not so marked. */ sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_ON, SCTP_TRANSPORT(link)); return SCTP_DISPOSITION_CONSUME; }
0
231,028
BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void * pvBuffer, BaseType_t * pxCoRoutineWoken ) { BaseType_t xReturn; Queue_t * const pxQueue = xQueue; /* We cannot block from an ISR, so check there is data available. If * not then just leave without doing anything. */ if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) { /* Copy the data from the queue. */ pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) { pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; } else { mtCOVERAGE_TEST_MARKER(); } --( pxQueue->uxMessagesWaiting ); ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); if( ( *pxCoRoutineWoken ) == pdFALSE ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { *pxCoRoutineWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } xReturn = pdPASS; } else { xReturn = pdFAIL; } return xReturn; }
0
224,739
GF_Box *iloc_box_new() { ISOM_DECL_BOX_ALLOC(GF_ItemLocationBox, GF_ISOM_BOX_TYPE_ILOC); tmp->location_entries = gf_list_new(); return (GF_Box *)tmp; }
0
318,768
const char *drill_g_code_name(drill_g_code_t g_code) { switch (g_code) { case DRILL_G_ROUT: return N_("rout mode"); case DRILL_G_LINEARMOVE: return N_("linear mode"); case DRILL_G_CWMOVE: return N_("circular CW mode"); case DRILL_G_CCWMOVE: return N_("circular CCW mode"); case DRILL_G_VARIABLEDWELL: return N_("variable dwell"); case DRILL_G_DRILL: return N_("drill mode"); case DRILL_G_OVERRIDETOOLSPEED: return N_("override tool feed or speed"); case DRILL_G_ROUTCIRCLE: return N_("routed CW circle"); case DRILL_G_ROUTCIRCLECCW: return N_("routed CCW circle"); case DRILL_G_VISTOOL: return N_("select vision tool"); case DRILL_G_VISSINGLEPOINTOFFSET: return N_("single point vision offset"); case DRILL_G_VISMULTIPOINTTRANS: return N_("multipoint vision translation"); case DRILL_G_VISCANCEL: return N_("cancel vision translation or offset"); case DRILL_G_VISCORRHOLEDRILL: return N_("vision corrected single hole drilling"); case DRILL_G_VISAUTOCALIBRATION: return N_("vision system autocalibration"); case DRILL_G_CUTTERCOMPOFF: return N_("cutter compensation off"); case DRILL_G_CUTTERCOMPLEFT: return N_("cutter compensation left"); case DRILL_G_CUTTERCOMPRIGHT: return N_("cutter compensation right"); case DRILL_G_VISSINGLEPOINTOFFSETREL: return N_("single point vision relative offset"); case DRILL_G_VISMULTIPOINTTRANSREL: return N_("multipoint vision relative translation"); case DRILL_G_VISCANCELREL: return N_("cancel vision relative translation or offset"); case DRILL_G_VISCORRHOLEDRILLREL: return N_("vision corrected single hole relative drilling"); case DRILL_G_PACKDIP2: return N_("dual in line package"); case DRILL_G_PACKDIP: return N_("dual in line package"); case DRILL_G_PACK8PINL: return N_("eight pin L package"); case DRILL_G_CIRLE: return N_("canned circle"); case DRILL_G_SLOT: return N_("canned slot"); case DRILL_G_ROUTSLOT: return N_("routed step slot"); case DRILL_G_ABSOLUTE: return N_("absolute input mode"); case DRILL_G_INCREMENTAL: return N_("incremental input mode"); case DRILL_G_ZEROSET: return N_("zero set"); case DRILL_G_UNKNOWN: default: return N_("unknown G-code"); } } /* drill_g_code_name() */
0
445,870
fr_window_finalize (GObject *object) { FrWindow *window = FR_WINDOW (object); fr_window_free_open_files (window); if (window->archive != NULL) { g_object_unref (window->archive); window->archive = NULL; } if (window->priv != NULL) { fr_window_free_private_data (window); g_free (window->priv); window->priv = NULL; } G_OBJECT_CLASS (fr_window_parent_class)->finalize (object); }
0
427,156
static int reglevel (FuncState *fs, int nvar) { while (nvar-- > 0) { Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */ if (vd->vd.kind != RDKCTC) /* is in a register? */ return vd->vd.ridx + 1; } return 0; /* no variables in registers */ }
0
274,736
callbacks_about_activate (GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *aboutdialog1; /* TRANSLATORS: Replace this string with your names, one name per line. */ gchar *translators = _("translator-credits"); gchar *string = g_strdup_printf(_( "Gerbv — a Gerber (RS-274/X) viewer\n" "\n" "Version %s\n" "Compiled on %s at %s\n" "\n" "Gerbv was originally developed as part of the gEDA Project " "but is now separately maintained.\n" "\n" "For more information see:\n" " gerbv homepage: https://gerbv.github.io/\n" " gerbv repository: https://github.com/gerbv/gerbv"), VERSION, __DATE__, __TIME__); #if GTK_CHECK_VERSION(2,6,0) gchar *license = g_strdup_printf(_( "Gerbv — a Gerber (RS-274/X) viewer\n" "\n" "Copyright (C) 2000—2007 Stefan Petersen\n" "\n" "This program is free software: you can redistribute it and/or modify\n" "it under the terms of the GNU General Public License as published by\n" "the Free Software Foundation, either version 2 of the License, or\n" "(at your option) any later version.\n" "\n" "This program is distributed in the hope that it will be useful,\n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" "GNU General Public License for more details.\n\n" "You should have received a copy of the GNU General Public License\n" "along with this program. If not, see <http://www.gnu.org/licenses/>.")); #include "authors.c" int a_size, i; gchar **a; aboutdialog1 = gtk_about_dialog_new (); gtk_container_set_border_width (GTK_CONTAINER (aboutdialog1), 5); gtk_about_dialog_set_version (GTK_ABOUT_DIALOG (aboutdialog1), VERSION); gtk_about_dialog_set_name (GTK_ABOUT_DIALOG (aboutdialog1), _("Gerbv")); gtk_about_dialog_set_translator_credits (GTK_ABOUT_DIALOG (aboutdialog1), translators); gtk_about_dialog_set_comments (GTK_ABOUT_DIALOG (aboutdialog1), string); gtk_about_dialog_set_license(GTK_ABOUT_DIALOG (aboutdialog1), license); /* The authors.c file is autogenerated at build time */ a_size = sizeof(authors_string_array)/sizeof(authors_string_array[0]); a = g_new(gchar *, a_size); for (i = 0; i < a_size; i++) a[i] = _(authors_string_array[i]); gtk_about_dialog_set_authors(GTK_ABOUT_DIALOG (aboutdialog1), (const gchar **)a); gtk_about_dialog_set_website(GTK_ABOUT_DIALOG (aboutdialog1), "https://gerbv.github.io/"); g_free(a); g_signal_connect (G_OBJECT(aboutdialog1),"response", G_CALLBACK (gtk_widget_destroy), GTK_WIDGET(aboutdialog1)); g_free (string); g_free (license); #else aboutdialog1 = gtk_message_dialog_new ( GTK_WINDOW (screen.win.topLevelWindow), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, string ); gtk_window_set_title ( GTK_WINDOW (aboutdialog1), _("About Gerbv")); /* Destroy the dialog when the user responds to it (e.g. clicks a button) */ g_signal_connect_swapped (aboutdialog1, "response", G_CALLBACK (gtk_widget_destroy), aboutdialog1); g_free (string); #endif gtk_widget_show_all(GTK_WIDGET(aboutdialog1)); }
0
345,206
void con_free_unimap(struct vc_data *vc) { struct uni_pagedir *p; p = *vc->vc_uni_pagedir_loc; if (!p) return; *vc->vc_uni_pagedir_loc = NULL; if (--p->refcount) return; con_release_unimap(p); kfree(p); }
0
310,038
usage(void) { static const char *msg[] = { "Usage: test_tparm [options] [capability] [value1 [value2 [...]]]", "", "Print all distinct combinations of given capability.", "", "Options:", " -T TERM override $TERM; this may be a comma-separated list or \"-\"", " to read a list from standard-input", " -a if capability is given, test all combinations of values", " -r NUM repeat tests NUM times", " -v show values and results", }; unsigned n; for (n = 0; n < SIZEOF(msg); ++n) { fprintf(stderr, "%s\n", msg[n]); } ExitProgram(EXIT_FAILURE); }
0
437,700
static int cx23888_ir_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; unsigned long flags; u32 cntrl = cx23888_ir_read4(dev, CX23888_IR_CNTRL_REG); u32 irqen = cx23888_ir_read4(dev, CX23888_IR_IRQEN_REG); u32 stats = cx23888_ir_read4(dev, CX23888_IR_STATS_REG); union cx23888_ir_fifo_rec rx_data[FIFO_RX_DEPTH]; unsigned int i, j, k; u32 events, v; int tsr, rsr, rto, ror, tse, rse, rte, roe, kror; tsr = stats & STATS_TSR; /* Tx FIFO Service Request */ rsr = stats & STATS_RSR; /* Rx FIFO Service Request */ rto = stats & STATS_RTO; /* Rx Pulse Width Timer Time Out */ ror = stats & STATS_ROR; /* Rx FIFO Over Run */ tse = irqen & IRQEN_TSE; /* Tx FIFO Service Request IRQ Enable */ rse = irqen & IRQEN_RSE; /* Rx FIFO Service Request IRQ Enable */ rte = irqen & IRQEN_RTE; /* Rx Pulse Width Timer Time Out IRQ Enable */ roe = irqen & IRQEN_ROE; /* Rx FIFO Over Run IRQ Enable */ *handled = false; v4l2_dbg(2, ir_888_debug, sd, "IRQ Status: %s %s %s %s %s %s\n", tsr ? "tsr" : " ", rsr ? "rsr" : " ", rto ? "rto" : " ", ror ? "ror" : " ", stats & STATS_TBY ? "tby" : " ", stats & STATS_RBY ? "rby" : " "); v4l2_dbg(2, ir_888_debug, sd, "IRQ Enables: %s %s %s %s\n", tse ? "tse" : " ", rse ? "rse" : " ", rte ? "rte" : " ", roe ? "roe" : " "); /* * Transmitter interrupt service */ if (tse && tsr) { /* * TODO: * Check the watermark threshold setting * Pull FIFO_TX_DEPTH or FIFO_TX_DEPTH/2 entries from tx_kfifo * Push the data to the hardware FIFO. * If there was nothing more to send in the tx_kfifo, disable * the TSR IRQ and notify the v4l2_device. * If there was something in the tx_kfifo, check the tx_kfifo * level and notify the v4l2_device, if it is low. */ /* For now, inhibit TSR interrupt until Tx is implemented */ irqenable_tx(dev, 0); events = V4L2_SUBDEV_IR_TX_FIFO_SERVICE_REQ; v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_TX_NOTIFY, &events); *handled = true; } /* * Receiver interrupt service */ kror = 0; if ((rse && rsr) || (rte && rto)) { /* * Receive data on RSR to clear the STATS_RSR. * Receive data on RTO, since we may not have yet hit the RSR * watermark when we receive the RTO. */ for (i = 0, v = FIFO_RX_NDV; (v & FIFO_RX_NDV) && !kror; i = 0) { for (j = 0; (v & FIFO_RX_NDV) && j < FIFO_RX_DEPTH; j++) { v = cx23888_ir_read4(dev, CX23888_IR_FIFO_REG); rx_data[i].hw_fifo_data = v & ~FIFO_RX_NDV; i++; } if (i == 0) break; j = i * sizeof(union cx23888_ir_fifo_rec); k = kfifo_in_locked(&state->rx_kfifo, (unsigned char *) rx_data, j, &state->rx_kfifo_lock); if (k != j) kror++; /* rx_kfifo over run */ } *handled = true; } events = 0; v = 0; if (kror) { events |= V4L2_SUBDEV_IR_RX_SW_FIFO_OVERRUN; v4l2_err(sd, "IR receiver software FIFO overrun\n"); } if (roe && ror) { /* * The RX FIFO Enable (CNTRL_RFE) must be toggled to clear * the Rx FIFO Over Run status (STATS_ROR) */ v |= CNTRL_RFE; events |= V4L2_SUBDEV_IR_RX_HW_FIFO_OVERRUN; v4l2_err(sd, "IR receiver hardware FIFO overrun\n"); } if (rte && rto) { /* * The IR Receiver Enable (CNTRL_RXE) must be toggled to clear * the Rx Pulse Width Timer Time Out (STATS_RTO) */ v |= CNTRL_RXE; events |= V4L2_SUBDEV_IR_RX_END_OF_RX_DETECTED; } if (v) { /* Clear STATS_ROR & STATS_RTO as needed by resetting hardware */ cx23888_ir_write4(dev, CX23888_IR_CNTRL_REG, cntrl & ~v); cx23888_ir_write4(dev, CX23888_IR_CNTRL_REG, cntrl); *handled = true; } spin_lock_irqsave(&state->rx_kfifo_lock, flags); if (kfifo_len(&state->rx_kfifo) >= CX23888_IR_RX_KFIFO_SIZE / 2) events |= V4L2_SUBDEV_IR_RX_FIFO_SERVICE_REQ; spin_unlock_irqrestore(&state->rx_kfifo_lock, flags); if (events) v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_RX_NOTIFY, &events); return 0; }
0
437,707
static inline void control_tx_enable(struct cx23885_dev *dev, bool enable) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~(CNTRL_TXE | CNTRL_TFE), enable ? (CNTRL_TXE | CNTRL_TFE) : 0); }
0
393,525
static SQInteger closure_getinfos(HSQUIRRELVM v) { SQObject o = stack_get(v,1); SQTable *res = SQTable::Create(_ss(v),4); if(sq_type(o) == OT_CLOSURE) { SQFunctionProto *f = _closure(o)->_function; SQInteger nparams = f->_nparameters + (f->_varparams?1:0); SQObjectPtr params = SQArray::Create(_ss(v),nparams); SQObjectPtr defparams = SQArray::Create(_ss(v),f->_ndefaultparams); for(SQInteger n = 0; n<f->_nparameters; n++) { _array(params)->Set((SQInteger)n,f->_parameters[n]); } for(SQInteger j = 0; j<f->_ndefaultparams; j++) { _array(defparams)->Set((SQInteger)j,_closure(o)->_defaultparams[j]); } if(f->_varparams) { _array(params)->Set(nparams-1,SQString::Create(_ss(v),_SC("..."),-1)); } res->NewSlot(SQString::Create(_ss(v),_SC("native"),-1),false); res->NewSlot(SQString::Create(_ss(v),_SC("name"),-1),f->_name); res->NewSlot(SQString::Create(_ss(v),_SC("src"),-1),f->_sourcename); res->NewSlot(SQString::Create(_ss(v),_SC("parameters"),-1),params); res->NewSlot(SQString::Create(_ss(v),_SC("varargs"),-1),f->_varparams); res->NewSlot(SQString::Create(_ss(v),_SC("defparams"),-1),defparams); } else { //OT_NATIVECLOSURE SQNativeClosure *nc = _nativeclosure(o); res->NewSlot(SQString::Create(_ss(v),_SC("native"),-1),true); res->NewSlot(SQString::Create(_ss(v),_SC("name"),-1),nc->_name); res->NewSlot(SQString::Create(_ss(v),_SC("paramscheck"),-1),nc->_nparamscheck); SQObjectPtr typecheck; if(nc->_typecheck.size() > 0) { typecheck = SQArray::Create(_ss(v), nc->_typecheck.size()); for(SQUnsignedInteger n = 0; n<nc->_typecheck.size(); n++) { _array(typecheck)->Set((SQInteger)n,nc->_typecheck[n]); } } res->NewSlot(SQString::Create(_ss(v),_SC("typecheck"),-1),typecheck); } v->Push(res); return 1; }
0