idx
int64
func
string
target
int64
221,464
start_dbus_proxy (FlatpakBwrap *app_bwrap, FlatpakBwrap *proxy_arg_bwrap, const char *app_info_path, GError **error) { char x = 'x'; const char *proxy; g_autofree char *commandline = NULL; g_autoptr(FlatpakBwrap) proxy_bwrap = NULL; int sync_fds[2] = {-1, -1}; int proxy_start_index; proxy_bwrap = flatpak_bwrap_new (NULL); if (!add_bwrap_wrapper (proxy_bwrap, app_info_path, error)) return FALSE; proxy = g_getenv ("FLATPAK_DBUSPROXY"); if (proxy == NULL) proxy = DBUSPROXY; flatpak_bwrap_add_arg (proxy_bwrap, proxy); proxy_start_index = proxy_bwrap->argv->len; if (pipe2 (sync_fds, O_CLOEXEC) < 0) { g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno), _("Unable to create sync pipe")); return FALSE; } /* read end goes to app */ flatpak_bwrap_add_args_data_fd (app_bwrap, "--sync-fd", sync_fds[0], NULL); /* write end goes to proxy */ flatpak_bwrap_add_fd (proxy_bwrap, sync_fds[1]); flatpak_bwrap_add_arg_printf (proxy_bwrap, "--fd=%d", sync_fds[1]); /* Note: This steals the fds from proxy_arg_bwrap */ flatpak_bwrap_append_bwrap (proxy_bwrap, proxy_arg_bwrap); if (!flatpak_bwrap_bundle_args (proxy_bwrap, proxy_start_index, -1, TRUE, error)) return FALSE; flatpak_bwrap_finish (proxy_bwrap); commandline = flatpak_quote_argv ((const char **) proxy_bwrap->argv->pdata, -1); g_debug ("Running '%s'", commandline); /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */ if (!g_spawn_async (NULL, (char **) proxy_bwrap->argv->pdata, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN, flatpak_bwrap_child_setup_cb, proxy_bwrap->fds, NULL, error)) return FALSE; /* The write end can be closed now, otherwise the read below will hang of xdg-dbus-proxy fails to start. */ g_clear_pointer (&proxy_bwrap, flatpak_bwrap_free); /* Sync with proxy, i.e. wait until its listening on the sockets */ if (read (sync_fds[0], &x, 1) != 1) { g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno), _("Failed to sync with dbus proxy")); return FALSE; } return TRUE; }
0
512,889
uchar *in_timestamp::get_value(Item *item) { Timestamp_or_zero_datetime_native_null native(current_thd, item, true); if (native.is_null()) return 0; tmp= Timestamp_or_zero_datetime(native); return (uchar*) &tmp; }
0
248,233
DLLIMPORT int cfg_setlist(cfg_t *cfg, const char *name, unsigned int nvalues, ...) { va_list ap; cfg_opt_t *opt = cfg_getopt(cfg, name); if (!opt || !is_set(CFGF_LIST, opt->flags)) { errno = EINVAL; return CFG_FAIL; } cfg_free_value(opt); va_start(ap, nvalues); cfg_addlist_internal(opt, nvalues, ap); va_end(ap); return CFG_SUCCESS; }
0
462,565
void controller::update_flags(std::shared_ptr<rss_item> item) { if (api) { api->update_article_flags(item->oldflags(), item->flags(), item->guid()); } item->update_flags(); }
0
317,303
static unsigned int selinux_ip_forward(struct sk_buff *skb, const struct net_device *indev, u16 family) { int err; char *addrp; u32 peer_sid; struct common_audit_data ad; struct lsm_network_audit net = {0,}; u8 secmark_active; u8 netlbl_active; u8 peerlbl_active; if (!selinux_policycap_netpeer()) return NF_ACCEPT; secmark_active = selinux_secmark_enabled(); netlbl_active = netlbl_enabled(); peerlbl_active = selinux_peerlbl_enabled(); if (!secmark_active && !peerlbl_active) return NF_ACCEPT; if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0) return NF_DROP; ad.type = LSM_AUDIT_DATA_NET; ad.u.net = &net; ad.u.net->netif = indev->ifindex; ad.u.net->family = family; if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0) return NF_DROP; if (peerlbl_active) { err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex, addrp, family, peer_sid, &ad); if (err) { selinux_netlbl_err(skb, family, err, 1); return NF_DROP; } } if (secmark_active) if (avc_has_perm(&selinux_state, peer_sid, skb->secmark, SECCLASS_PACKET, PACKET__FORWARD_IN, &ad)) return NF_DROP; if (netlbl_active) /* we do this in the FORWARD path and not the POST_ROUTING * path because we want to make sure we apply the necessary * labeling before IPsec is applied so we can leverage AH * protection */ if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0) return NF_DROP; return NF_ACCEPT; }
0
417,078
virtual void mix(mp_sint32* buffer, mp_uint32 bufferSize) { const mp_sint32* buffer32 = buffer; for (mp_uint32 i = 0; i < bufferSize*MP_NUMCHANNELS; i++) { mp_sint32 b = *buffer32++; if (abs(b) > lastPeakValue) lastPeakValue = abs(b); } }
0
338,169
void WasmBinaryBuilder::readGlobals() { BYN_TRACE("== readGlobals\n"); size_t num = getU32LEB(); BYN_TRACE("num: " << num << std::endl); for (size_t i = 0; i < num; i++) { BYN_TRACE("read one\n"); auto type = getConcreteType(); auto mutable_ = getU32LEB(); if (mutable_ & ~1) { throwError("Global mutability must be 0 or 1"); } auto* init = readExpression(); globals.push_back( Builder::makeGlobal("global$" + std::to_string(i), type, init, mutable_ ? Builder::Mutable : Builder::Immutable)); } }
0
326,914
*vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args) { u32 priv_sz = sizeof(struct vidtv_s302m_ctx); struct vidtv_s302m_ctx *ctx; struct vidtv_encoder *e; e = kzalloc(sizeof(*e), GFP_KERNEL); if (!e) return NULL; e->id = S302M; if (args.name) e->name = kstrdup(args.name, GFP_KERNEL); e->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ); if (!e->encoder_buf) goto out_kfree_e; e->encoder_buf_sz = VIDTV_S302M_BUF_SZ; e->encoder_buf_offset = 0; e->sample_count = 0; e->src_buf = (args.src_buf) ? args.src_buf : NULL; e->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0; e->src_buf_offset = 0; e->is_video_encoder = false; ctx = kzalloc(priv_sz, GFP_KERNEL); if (!ctx) goto out_kfree_buf; e->ctx = ctx; ctx->last_duration = 0; e->encode = vidtv_s302m_encode; e->clear = vidtv_s302m_clear; e->es_pid = cpu_to_be16(args.es_pid); e->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1); e->sync = args.sync; e->sampling_rate_hz = S302M_SAMPLING_RATE_HZ; e->last_sample_cb = args.last_sample_cb; e->destroy = vidtv_s302m_encoder_destroy; if (args.head) { while (args.head->next) args.head = args.head->next; args.head->next = e; } e->next = NULL; return e; out_kfree_buf: kfree(e->encoder_buf); out_kfree_e: kfree(e->name); kfree(e); return NULL; }
0
218,803
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(pixels,0,row_size*sizeof(*pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) { status=MagickFalse; break; } status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); }
0
281,628
void CLASS sony_arw_load_raw() { ushort huff[32768]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, len, diff, sum=0; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[n++] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; len = getbithuff(15,huff); diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if ((sum += diff) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } }
0
231,777
TEST_F(QuicServerTransportTest, RecvStopSendingFrameAfterHalfCloseRemote) { server->getNonConstConn().ackStates.appDataAckState.nextPacketNum = 3; std::array<std::string, 4> words = { "Hey Bob, this is Alice, for real.", "What message did I send you last time?", "You don't sound like Alice", "You are a liar!", }; StreamId streamId = 0x00; auto stream = server->getNonConstConn().streamManager->getStream(streamId); stream->readBuffer.emplace_back(IOBuf::copyBuffer(words.at(0)), 0, false); stream->readBuffer.emplace_back( IOBuf::copyBuffer(words.at(1)), words.at(0).length(), false); stream->retransmissionBuffer.emplace( std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple(std::make_unique<StreamBuffer>( IOBuf::copyBuffer(words.at(2)), 0, false))); stream->writeBuffer.append(IOBuf::copyBuffer(words.at(3))); stream->currentWriteOffset = words.at(2).length() + words.at(3).length(); stream->currentReadOffset = words.at(0).length() + words.at(1).length(); server->getNonConstConn().ackStates.appDataAckState.nextPacketNum = 5; ShortHeader header( ProtectionType::KeyPhaseZero, *server->getConn().serverConnectionId, clientNextAppDataPacketNum++); RegularQuicPacketBuilder builder( server->getConn().udpSendPacketLen, std::move(header), 0 /* largestAcked */); builder.encodePacketHeader(); StopSendingFrame stopSendingFrame( streamId, GenericApplicationErrorCode::UNKNOWN); ASSERT_TRUE(builder.canBuildPacket()); auto dataLen = writeStreamFrameHeader( builder, 0x00, stream->currentReadOffset, 0, 10, true, folly::none /* skipLenHint */); ASSERT_TRUE(dataLen.has_value()); ASSERT_EQ(*dataLen, 0); writeFrame(QuicSimpleFrame(stopSendingFrame), builder); auto packet = std::move(builder).buildPacket(); EXPECT_CALL( connCallback, onStopSending(streamId, GenericApplicationErrorCode::UNKNOWN)); deliverData(packetToBuf(packet)); }
0
359,562
DEFUN (show_ip_extcommunity_list_arg, show_ip_extcommunity_list_arg_cmd, "show ip extcommunity-list (<1-500>|WORD)", SHOW_STR IP_STR "List extended-community list\n" "Extcommunity-list number\n" "Extcommunity-list name\n") { struct community_list *list; list = community_list_lookup (bgp_clist, argv[0], EXTCOMMUNITY_LIST_MASTER); if (! list) { vty_out (vty, "%% Can't find extcommunit-list%s", VTY_NEWLINE); return CMD_WARNING; } extcommunity_list_show (vty, list); return CMD_SUCCESS; }
0
200,976
get_visual_text( cmdarg_T *cap, char_u **pp, // return: start of selected text int *lenp) // return: length of selected text { if (VIsual_mode != 'V') unadjust_for_sel(); if (VIsual.lnum != curwin->w_cursor.lnum) { if (cap != NULL) clearopbeep(cap->oap); return FAIL; } if (VIsual_mode == 'V') { *pp = ml_get_curline(); *lenp = (int)STRLEN(*pp); } else { if (LT_POS(curwin->w_cursor, VIsual)) { *pp = ml_get_pos(&curwin->w_cursor); *lenp = VIsual.col - curwin->w_cursor.col + 1; } else { *pp = ml_get_pos(&VIsual); *lenp = curwin->w_cursor.col - VIsual.col + 1; } if (**pp == NUL) *lenp = 0; if (has_mbyte && *lenp > 0) // Correct the length to include all bytes of the last character. *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1; } reset_VIsual_and_resel(); return OK; }
1
379,323
do_one_cmd( char_u **cmdlinep, int flags, #ifdef FEAT_EVAL cstack_T *cstack, #endif char_u *(*fgetline)(int, void *, int, getline_opt_T), void *cookie) // argument for fgetline() { char_u *p; linenr_T lnum; long n; char *errormsg = NULL; // error message char_u *after_modifier = NULL; exarg_T ea; // Ex command arguments cmdmod_T save_cmdmod; int save_reg_executing = reg_executing; int save_pending_end_reg_executing = pending_end_reg_executing; int ni; // set when Not Implemented char_u *cmd; int starts_with_colon = FALSE; #ifdef FEAT_EVAL int may_have_range; int vim9script; int did_set_expr_line = FALSE; #endif int sourcing = flags & DOCMD_VERBOSE; int did_append_cmd = FALSE; CLEAR_FIELD(ea); ea.line1 = 1; ea.line2 = 1; #ifdef FEAT_EVAL ++ex_nesting_level; #endif // When the last file has not been edited :q has to be typed twice. if (quitmore #ifdef FEAT_EVAL // avoid that a function call in 'statusline' does this && !getline_equal(fgetline, cookie, get_func_line) #endif // avoid that an autocommand, e.g. QuitPre, does this && !getline_equal(fgetline, cookie, getnextac)) --quitmore; /* * Reset browse, confirm, etc.. They are restored when returning, for * recursive calls. */ save_cmdmod = cmdmod; // "#!anything" is handled like a comment. if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!') goto doend; /* * 1. Skip comment lines and leading white space and colons. * 2. Handle command modifiers. */ // The "ea" structure holds the arguments that can be used. ea.cmd = *cmdlinep; ea.cmdlinep = cmdlinep; ea.getline = fgetline; ea.cookie = cookie; #ifdef FEAT_EVAL ea.cstack = cstack; starts_with_colon = *skipwhite(ea.cmd) == ':'; #endif if (parse_command_modifiers(&ea, &errormsg, &cmdmod, FALSE) == FAIL) goto doend; apply_cmdmod(&cmdmod); #ifdef FEAT_EVAL vim9script = in_vim9script(); #endif after_modifier = ea.cmd; #ifdef FEAT_EVAL ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE)); #else ea.skip = (if_level > 0); #endif /* * 3. Skip over the range to find the command. Let "p" point to after it. * * We need the command to know what kind of range it uses. */ cmd = ea.cmd; #ifdef FEAT_EVAL // In Vim9 script a colon is required before the range. This may also be // after command modifiers. if (vim9script && (flags & DOCMD_RANGEOK) == 0) { may_have_range = FALSE; for (p = ea.cmd; p >= *cmdlinep; --p) { if (*p == ':') may_have_range = TRUE; if (p < ea.cmd && !VIM_ISWHITE(*p)) break; } } else may_have_range = TRUE; if (may_have_range) #endif ea.cmd = skip_range(ea.cmd, TRUE, NULL); #ifdef FEAT_EVAL if (vim9script && !may_have_range) { if (ea.cmd == cmd + 1 && *cmd == '$') // should be "$VAR = val" --ea.cmd; p = find_ex_command(&ea, NULL, lookup_scriptitem, NULL); if (ea.cmdidx == CMD_SIZE) { char_u *ar = skip_range(ea.cmd, TRUE, NULL); // If a ':' before the range is missing, give a clearer error // message. if (ar > ea.cmd && !ea.skip) { semsg(_(e_colon_required_before_range_str), ea.cmd); goto doend; } } } else #endif p = find_ex_command(&ea, NULL, NULL, NULL); #ifdef FEAT_EVAL # ifdef FEAT_PROFILE // Count this line for profiling if skip is TRUE. if (do_profiling == PROF_YES && (!ea.skip || cstack->cs_idx == 0 || (cstack->cs_idx > 0 && (cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)))) { int skip = did_emsg || got_int || did_throw; if (ea.cmdidx == CMD_catch) skip = !skip && !(cstack->cs_idx >= 0 && (cstack->cs_flags[cstack->cs_idx] & CSF_THROWN) && !(cstack->cs_flags[cstack->cs_idx] & CSF_CAUGHT)); else if (ea.cmdidx == CMD_else || ea.cmdidx == CMD_elseif) skip = skip || !(cstack->cs_idx >= 0 && !(cstack->cs_flags[cstack->cs_idx] & (CSF_ACTIVE | CSF_TRUE))); else if (ea.cmdidx == CMD_finally) skip = FALSE; else if (ea.cmdidx != CMD_endif && ea.cmdidx != CMD_endfor && ea.cmdidx != CMD_endtry && ea.cmdidx != CMD_endwhile) skip = ea.skip; if (!skip) { if (getline_equal(fgetline, cookie, get_func_line)) func_line_exec(getline_cookie(fgetline, cookie)); else if (getline_equal(fgetline, cookie, getsourceline)) script_line_exec(); } } # endif // May go to debug mode. If this happens and the ">quit" debug command is // used, throw an interrupt exception and skip the next command. dbg_check_breakpoint(&ea); if (!ea.skip && got_int) { ea.skip = TRUE; (void)do_intthrow(cstack); } #endif /* * 4. parse a range specifier of the form: addr [,addr] [;addr] .. * * where 'addr' is: * * % (entire file) * $ [+-NUM] * 'x [+-NUM] (where x denotes a currently defined mark) * . [+-NUM] * [+-NUM].. * NUM * * The ea.cmd pointer is updated to point to the first character following the * range spec. If an initial address is found, but no second, the upper bound * is equal to the lower. */ // ea.addr_type for user commands is set by find_ucmd if (!IS_USER_CMDIDX(ea.cmdidx)) { if (ea.cmdidx != CMD_SIZE) ea.addr_type = cmdnames[(int)ea.cmdidx].cmd_addr_type; else ea.addr_type = ADDR_LINES; // :wincmd range depends on the argument. if (ea.cmdidx == CMD_wincmd && p != NULL) get_wincmd_addr_type(skipwhite(p), &ea); #ifdef FEAT_QUICKFIX // :.cc in quickfix window uses line number if ((ea.cmdidx == CMD_cc || ea.cmdidx == CMD_ll) && bt_quickfix(curbuf)) ea.addr_type = ADDR_OTHER; #endif } ea.cmd = cmd; #ifdef FEAT_EVAL if (!may_have_range) ea.line1 = ea.line2 = default_address(&ea); else #endif if (parse_cmd_address(&ea, &errormsg, FALSE) == FAIL) goto doend; /* * 5. Parse the command. */ /* * Skip ':' and any white space */ ea.cmd = skipwhite(ea.cmd); while (*ea.cmd == ':') ea.cmd = skipwhite(ea.cmd + 1); /* * If we got a line, but no command, then go to the line. * If we find a '|' or '\n' we set ea.nextcmd. */ if (*ea.cmd == NUL || comment_start(ea.cmd, starts_with_colon) || (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL) { /* * strange vi behaviour: * ":3" jumps to line 3 * ":3|..." prints line 3 (not in Vim9 script) * ":|" prints current line (not in Vim9 script) */ if (ea.skip) // skip this if inside :if goto doend; errormsg = ex_range_without_command(&ea); goto doend; } // If this looks like an undefined user command and there are CmdUndefined // autocommands defined, trigger the matching autocommands. if (p != NULL && ea.cmdidx == CMD_SIZE && !ea.skip && ASCII_ISUPPER(*ea.cmd) && has_cmdundefined()) { int ret; p = ea.cmd; while (ASCII_ISALNUM(*p)) ++p; p = vim_strnsave(ea.cmd, p - ea.cmd); ret = apply_autocmds(EVENT_CMDUNDEFINED, p, p, TRUE, NULL); vim_free(p); // If the autocommands did something and didn't cause an error, try // finding the command again. p = (ret #ifdef FEAT_EVAL && !aborting() #endif ) ? find_ex_command(&ea, NULL, NULL, NULL) : ea.cmd; } if (p == NULL) { if (!ea.skip) errormsg = _(e_ambiguous_use_of_user_defined_command); goto doend; } // Check for wrong commands. if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78 && !IS_USER_CMDIDX(ea.cmdidx)) { errormsg = uc_fun_cmd(); goto doend; } if (ea.cmdidx == CMD_SIZE) { if (!ea.skip) { STRCPY(IObuff, _(e_not_an_editor_command)); if (!sourcing) { // If the modifier was parsed OK the error must be in the // following command if (after_modifier != NULL) append_command(after_modifier); else append_command(*cmdlinep); did_append_cmd = TRUE; } errormsg = (char *)IObuff; did_emsg_syntax = TRUE; } goto doend; } ni = (!IS_USER_CMDIDX(ea.cmdidx) && (cmdnames[ea.cmdidx].cmd_func == ex_ni #ifdef HAVE_EX_SCRIPT_NI || cmdnames[ea.cmdidx].cmd_func == ex_script_ni #endif )); #ifndef FEAT_EVAL /* * When the expression evaluation is disabled, recognize the ":if" and * ":endif" commands and ignore everything in between it. */ if (ea.cmdidx == CMD_if) ++if_level; if (if_level) { if (ea.cmdidx == CMD_endif) --if_level; goto doend; } #endif // forced commands if (*p == '!' && ea.cmdidx != CMD_substitute && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic) { ++p; ea.forceit = TRUE; } else ea.forceit = FALSE; /* * 6. Parse arguments. Then check for errors. */ if (!IS_USER_CMDIDX(ea.cmdidx)) ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt; if (!ea.skip) { #ifdef HAVE_SANDBOX if (sandbox != 0 && !(ea.argt & EX_SBOXOK)) { // Command not allowed in sandbox. errormsg = _(e_not_allowed_in_sandbox); goto doend; } #endif if (restricted != 0 && (ea.argt & EX_RESTRICT)) { errormsg = _(e_command_not_allowed_in_rvim); goto doend; } if (!curbuf->b_p_ma && (ea.argt & EX_MODIFY)) { // Command not allowed in non-'modifiable' buffer errormsg = _(e_cannot_make_changes_modifiable_is_off); goto doend; } if (!IS_USER_CMDIDX(ea.cmdidx)) { #ifdef FEAT_CMDWIN if (cmdwin_type != 0 && !(ea.argt & EX_CMDWIN)) { // Command not allowed in the command line window errormsg = _(e_invalid_in_cmdline_window); goto doend; } #endif if (text_locked() && !(ea.argt & EX_LOCK_OK)) { // Command not allowed when text is locked errormsg = _(get_text_locked_msg()); goto doend; } } // Disallow editing another buffer when "curbuf_lock" is set. // Do allow ":checktime" (it is postponed). // Do allow ":edit" (check for an argument later). // Do allow ":file" with no arguments (check for an argument later). if (!(ea.argt & (EX_CMDWIN | EX_LOCK_OK)) && ea.cmdidx != CMD_checktime && ea.cmdidx != CMD_edit && ea.cmdidx != CMD_file && !IS_USER_CMDIDX(ea.cmdidx) && curbuf_locked()) goto doend; if (!ni && !(ea.argt & EX_RANGE) && ea.addr_count > 0) { errormsg = _(e_no_range_allowed); goto doend; } } if (!ni && !(ea.argt & EX_BANG) && ea.forceit) { errormsg = _(e_no_bang_allowed); goto doend; } /* * Don't complain about the range if it is not used * (could happen if line_count is accidentally set to 0). */ if (!ea.skip && !ni && (ea.argt & EX_RANGE)) { /* * If the range is backwards, ask for confirmation and, if given, swap * ea.line1 & ea.line2 so it's forwards again. * When global command is busy, don't ask, will fail below. */ if (!global_busy && ea.line1 > ea.line2) { if (msg_silent == 0) { if (sourcing || exmode_active) { errormsg = _(e_backwards_range_given); goto doend; } if (ask_yesno((char_u *) _("Backwards range given, OK to swap"), FALSE) != 'y') goto doend; } lnum = ea.line1; ea.line1 = ea.line2; ea.line2 = lnum; } if ((errormsg = invalid_range(&ea)) != NULL) goto doend; } if ((ea.addr_type == ADDR_OTHER) && ea.addr_count == 0) // default is 1, not cursor ea.line2 = 1; correct_range(&ea); #ifdef FEAT_FOLDING if (((ea.argt & EX_WHOLEFOLD) || ea.addr_count >= 2) && !global_busy && ea.addr_type == ADDR_LINES) { // Put the first line at the start of a closed fold, put the last line // at the end of a closed fold. (void)hasFolding(ea.line1, &ea.line1, NULL); (void)hasFolding(ea.line2, NULL, &ea.line2); } #endif #ifdef FEAT_QUICKFIX /* * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg' * option here, so things like % get expanded. */ p = replace_makeprg(&ea, p, cmdlinep); if (p == NULL) goto doend; #endif /* * Skip to start of argument. * Don't do this for the ":!" command, because ":!! -l" needs the space. */ if (ea.cmdidx == CMD_bang) ea.arg = p; else ea.arg = skipwhite(p); // ":file" cannot be run with an argument when "curbuf_lock" is set if (ea.cmdidx == CMD_file && *ea.arg != NUL && curbuf_locked()) goto doend; /* * Check for "++opt=val" argument. * Must be first, allow ":w ++enc=utf8 !cmd" */ if (ea.argt & EX_ARGOPT) while (ea.arg[0] == '+' && ea.arg[1] == '+') if (getargopt(&ea) == FAIL && !ni) { errormsg = _(e_invalid_argument); goto doend; } if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { if (*ea.arg == '>') // append { if (*++ea.arg != '>') // typed wrong { errormsg = _(e_use_w_or_w_gt_gt); goto doend; } ea.arg = skipwhite(ea.arg + 1); ea.append = TRUE; } else if (*ea.arg == '!' && ea.cmdidx == CMD_write) // :w !filter { ++ea.arg; ea.usefilter = TRUE; } } if (ea.cmdidx == CMD_read) { if (ea.forceit) { ea.usefilter = TRUE; // :r! filter if ea.forceit ea.forceit = FALSE; } else if (*ea.arg == '!') // :r !filter { ++ea.arg; ea.usefilter = TRUE; } } if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { ea.amount = 1; while (*ea.arg == *ea.cmd) // count number of '>' or '<' { ++ea.arg; ++ea.amount; } ea.arg = skipwhite(ea.arg); } /* * Check for "+command" argument, before checking for next command. * Don't do this for ":read !cmd" and ":write !cmd". */ if ((ea.argt & EX_CMDARG) && !ea.usefilter) ea.do_ecmd_cmd = getargcmd(&ea.arg); /* * For commands that do not use '|' inside their argument: Check for '|' to * separate commands and '"' or '#' to start comments. * * Otherwise: Check for <newline> to end a shell command. * Also do this for ":read !cmd", ":write !cmd" and ":global". * Also do this inside a { - } block after :command and :autocmd. * Any others? */ if ((ea.argt & EX_TRLBAR) && !ea.usefilter) { separate_nextcmd(&ea, FALSE); } else if (ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal || ea.cmdidx == CMD_global || ea.cmdidx == CMD_vglobal || ea.usefilter #ifdef FEAT_EVAL || inside_block(&ea) #endif ) { for (p = ea.arg; *p; ++p) { // Remove one backslash before a newline, so that it's possible to // pass a newline to the shell and also a newline that is preceded // with a backslash. This makes it impossible to end a shell // command in a backslash, but that doesn't appear useful. // Halving the number of backslashes is incompatible with previous // versions. if (*p == '\\' && p[1] == '\n') STRMOVE(p, p + 1); else if (*p == '\n' && !(ea.argt & EX_EXPR_ARG)) { ea.nextcmd = p + 1; *p = NUL; break; } } } if ((ea.argt & EX_DFLALL) && ea.addr_count == 0) address_default_all(&ea); // accept numbered register only when no count allowed (:put) if ( (ea.argt & EX_REGSTR) && *ea.arg != NUL // Do not allow register = for user commands && (!IS_USER_CMDIDX(ea.cmdidx) || *ea.arg != '=') && !((ea.argt & EX_COUNT) && VIM_ISDIGIT(*ea.arg))) { #ifndef FEAT_CLIPBOARD // check these explicitly for a more specific error message if (*ea.arg == '*' || *ea.arg == '+') { errormsg = _(e_invalid_register_name); goto doend; } #endif if (valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put && !IS_USER_CMDIDX(ea.cmdidx)))) { ea.regname = *ea.arg++; #ifdef FEAT_EVAL // for '=' register: accept the rest of the line as an expression if (ea.arg[-1] == '=' && ea.arg[0] != NUL) { if (!ea.skip) { set_expr_line(vim_strsave(ea.arg), &ea); did_set_expr_line = TRUE; } ea.arg += STRLEN(ea.arg); } #endif ea.arg = skipwhite(ea.arg); } } /* * Check for a count. When accepting a EX_BUFNAME, don't use "123foo" as a * count, it's a buffer name. */ if ((ea.argt & EX_COUNT) && VIM_ISDIGIT(*ea.arg) && (!(ea.argt & EX_BUFNAME) || *(p = skipdigits(ea.arg + 1)) == NUL || VIM_ISWHITE(*p))) { n = getdigits_quoted(&ea.arg); ea.arg = skipwhite(ea.arg); if (n <= 0 && !ni && (ea.argt & EX_ZEROR) == 0) { errormsg = _(e_positive_count_required); goto doend; } if (ea.addr_type != ADDR_LINES) // e.g. :buffer 2, :sleep 3 { ea.line2 = n; if (ea.addr_count == 0) ea.addr_count = 1; } else { ea.line1 = ea.line2; if (ea.line2 >= LONG_MAX - (n - 1)) ea.line2 = LONG_MAX; // avoid overflow else ea.line2 += n - 1; ++ea.addr_count; /* * Be vi compatible: no error message for out of range. */ if (ea.line2 > curbuf->b_ml.ml_line_count) ea.line2 = curbuf->b_ml.ml_line_count; } } /* * Check for flags: 'l', 'p' and '#'. */ if (ea.argt & EX_FLAGS) get_flags(&ea); if (!ni && !(ea.argt & EX_EXTRA) && *ea.arg != NUL && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & EX_TRLBAR) == 0)) { // no arguments allowed but there is something errormsg = ex_errmsg(e_trailing_characters_str, ea.arg); goto doend; } if (!ni && (ea.argt & EX_NEEDARG) && *ea.arg == NUL) { errormsg = _(e_argument_required); goto doend; } #ifdef FEAT_EVAL /* * Skip the command when it's not going to be executed. * The commands like :if, :endif, etc. always need to be executed. * Also make an exception for commands that handle a trailing command * themselves. */ if (ea.skip) { switch (ea.cmdidx) { // commands that need evaluation case CMD_while: case CMD_endwhile: case CMD_for: case CMD_endfor: case CMD_if: case CMD_elseif: case CMD_else: case CMD_endif: case CMD_try: case CMD_catch: case CMD_finally: case CMD_endtry: case CMD_function: case CMD_def: break; // Commands that handle '|' themselves. Check: A command should // either have the EX_TRLBAR flag, appear in this list or appear in // the list at ":help :bar". case CMD_aboveleft: case CMD_and: case CMD_belowright: case CMD_botright: case CMD_browse: case CMD_call: case CMD_confirm: case CMD_const: case CMD_delfunction: case CMD_djump: case CMD_dlist: case CMD_dsearch: case CMD_dsplit: case CMD_echo: case CMD_echoerr: case CMD_echomsg: case CMD_echon: case CMD_eval: case CMD_execute: case CMD_filter: case CMD_final: case CMD_help: case CMD_hide: case CMD_ijump: case CMD_ilist: case CMD_isearch: case CMD_isplit: case CMD_keepalt: case CMD_keepjumps: case CMD_keepmarks: case CMD_keeppatterns: case CMD_leftabove: case CMD_let: case CMD_lockmarks: case CMD_lockvar: case CMD_lua: case CMD_match: case CMD_mzscheme: case CMD_noautocmd: case CMD_noswapfile: case CMD_perl: case CMD_psearch: case CMD_py3: case CMD_python3: case CMD_python: case CMD_return: case CMD_rightbelow: case CMD_ruby: case CMD_silent: case CMD_smagic: case CMD_snomagic: case CMD_substitute: case CMD_syntax: case CMD_tab: case CMD_tcl: case CMD_throw: case CMD_tilde: case CMD_topleft: case CMD_unlet: case CMD_unlockvar: case CMD_var: case CMD_verbose: case CMD_vertical: case CMD_wincmd: break; default: goto doend; } } #endif if (ea.argt & EX_XFILE) { if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL) goto doend; } /* * Accept buffer name. Cannot be used at the same time with a buffer * number. Don't do this for a user command. */ if ((ea.argt & EX_BUFNAME) && *ea.arg != NUL && ea.addr_count == 0 && !IS_USER_CMDIDX(ea.cmdidx)) { /* * :bdelete, :bwipeout and :bunload take several arguments, separated * by spaces: find next space (skipping over escaped characters). * The others take one argument: ignore trailing spaces. */ if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout || ea.cmdidx == CMD_bunload) p = skiptowhite_esc(ea.arg); else { p = ea.arg + STRLEN(ea.arg); while (p > ea.arg && VIM_ISWHITE(p[-1])) --p; } ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & EX_BUFUNL) != 0, FALSE, FALSE); if (ea.line2 < 0) // failed goto doend; ea.addr_count = 1; ea.arg = skipwhite(p); } // The :try command saves the emsg_silent flag, reset it here when // ":silent! try" was used, it should only apply to :try itself. if (ea.cmdidx == CMD_try && cmdmod.cmod_did_esilent > 0) { emsg_silent -= cmdmod.cmod_did_esilent; if (emsg_silent < 0) emsg_silent = 0; cmdmod.cmod_did_esilent = 0; } /* * 7. Execute the command. */ if (IS_USER_CMDIDX(ea.cmdidx)) { /* * Execute a user-defined command. */ do_ucmd(&ea); } else { /* * Call the function to execute the builtin command. */ ea.errmsg = NULL; (cmdnames[ea.cmdidx].cmd_func)(&ea); if (ea.errmsg != NULL) errormsg = ea.errmsg; } #ifdef FEAT_EVAL // Set flag that any command was executed, used by ex_vim9script(). // Not if this was a command that wasn't executed or :endif. if (sourcing_a_script(&ea) && current_sctx.sc_sid > 0 && ea.cmdidx != CMD_endif && (cstack->cs_idx < 0 || (cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE))) SCRIPT_ITEM(current_sctx.sc_sid)->sn_state = SN_STATE_HAD_COMMAND; /* * If the command just executed called do_cmdline(), any throw or ":return" * or ":finish" encountered there must also check the cstack of the still * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught * exception, or reanimate a returned function or finished script file and * return or finish it again. */ if (need_rethrow) do_throw(cstack); else if (check_cstack) { if (source_finished(fgetline, cookie)) do_finish(&ea, TRUE); else if (getline_equal(fgetline, cookie, get_func_line) && current_func_returned()) do_return(&ea, TRUE, FALSE, NULL); } need_rethrow = check_cstack = FALSE; #endif doend: if (curwin->w_cursor.lnum == 0) // can happen with zero line number { curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; } if (errormsg != NULL && *errormsg != NUL && !did_emsg) { if ((sourcing || !KeyTyped) && !did_append_cmd) { if (errormsg != (char *)IObuff) { STRCPY(IObuff, errormsg); errormsg = (char *)IObuff; } append_command(*cmdlinep); } emsg(errormsg); } #ifdef FEAT_EVAL do_errthrow(cstack, (ea.cmdidx != CMD_SIZE && !IS_USER_CMDIDX(ea.cmdidx)) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL); if (did_set_expr_line) set_expr_line(NULL, NULL); #endif undo_cmdmod(&cmdmod); cmdmod = save_cmdmod; reg_executing = save_reg_executing; pending_end_reg_executing = save_pending_end_reg_executing; if (ea.nextcmd && *ea.nextcmd == NUL) // not really a next command ea.nextcmd = NULL; #ifdef FEAT_EVAL --ex_nesting_level; vim_free(ea.cmdline_tofree); #endif return ea.nextcmd; }
0
195,261
Node* Graph::AddNode(NodeDef node_def, Status* status) { const OpRegistrationData* op_reg_data; status->Update(ops_.LookUp(node_def.op(), &op_reg_data)); if (!status->ok()) return nullptr; DataTypeVector inputs; DataTypeVector outputs; status->Update( InOutTypesForNode(node_def, op_reg_data->op_def, &inputs, &outputs)); if (!status->ok()) { *status = AttachDef(*status, node_def); return nullptr; } Node::NodeClass node_class = op_reg_data->is_function_op ? Node::NC_FUNCTION_OP : Node::GetNodeClassForOp(node_def.op()); if (op_reg_data->type_ctor != nullptr) { VLOG(3) << "AddNode: found type constructor for " << node_def.name(); const auto ctor_type = full_type::SpecializeType(AttrSlice(node_def), op_reg_data->op_def); const FullTypeDef ctor_typedef = ctor_type.ValueOrDie(); if (ctor_typedef.type_id() != TFT_UNSET) { *(node_def.mutable_experimental_type()) = ctor_typedef; } } else { VLOG(3) << "AddNode: no type constructor for " << node_def.name(); } Node* node = AllocateNode(std::make_shared<NodeProperties>( &op_reg_data->op_def, std::move(node_def), inputs, outputs, op_reg_data->fwd_type_fn), nullptr, node_class); return node; }
1
508,916
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num) { if (!((options & SELECT_DISTINCT) && !group_list.elements)) hidden_bit_fields= 0; // find_order_in_list() may need some extra space, so multiply by two. order_group_num*= 2; /* We have to create array in prepared statement memory if it is a prepared statement */ Query_arena *arena= thd->stmt_arena; const size_t n_elems= (n_sum_items + n_child_sum_items + item_list.elements + select_n_reserved + select_n_having_items + select_n_where_fields + order_group_num + hidden_bit_fields + fields_in_window_functions) * (size_t) 5; DBUG_ASSERT(n_elems % 5 == 0); if (!ref_pointer_array.is_null()) { /* We need to take 'n_sum_items' into account when allocating the array, and this may actually increase during the optimization phase due to MIN/MAX rewrite in Item_in_subselect::single_value_transformer. In the usual case we can reuse the array from the prepare phase. If we need a bigger array, we must allocate a new one. */ if (ref_pointer_array.size() >= n_elems) return false; } Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems)); if (array != NULL) ref_pointer_array= Ref_ptr_array(array, n_elems); return array == NULL; }
0
274,879
TEST(ComparisonsTest, LessInt) { ComparisonOpModel model({1, 1, 1, 4}, {1, 1, 1, 4}, TensorType_INT32, BuiltinOperator_LESS); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3}); model.PopulateTensor<int>(model.input2(), {1, 2, 6, 5}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAre(true, false, false, true)); EXPECT_THAT(model.GetOutputShape(), ElementsAre(1, 1, 1, 4)); }
0
474,018
utf16be_mbc_enc_len(const UChar* p, const OnigUChar* e ARG_UNUSED, OnigEncoding enc ARG_UNUSED) { int byte = p[0]; if (!UTF16_IS_SURROGATE(byte)) { if (2 <= e-p) return ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(2); else return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1); } if (UTF16_IS_SURROGATE_FIRST(byte)) { switch (e-p) { case 1: return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(3); case 2: return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(2); case 3: if (UTF16_IS_SURROGATE_SECOND(p[2])) return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1); break; default: if (UTF16_IS_SURROGATE_SECOND(p[2])) return ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(4); break; } } return ONIGENC_CONSTRUCT_MBCLEN_INVALID(); }
0
346,469
add_pack_plugin(char_u *fname, void *cookie) { if (cookie != &APP_LOAD) { char_u *buf = alloc(MAXPATHL); char_u *p; int found = FALSE; if (buf == NULL) return; p = p_rtp; while (*p != NUL) { copy_option_part(&p, buf, MAXPATHL, ","); if (pathcmp((char *)buf, (char *)fname, -1) == 0) { found = TRUE; break; } } vim_free(buf); if (!found) // directory is not yet in 'runtimepath', add it if (add_pack_dir_to_rtp(fname) == FAIL) return; } if (cookie != &APP_ADD_DIR) load_pack_plugin(fname); }
0
488,425
static unsigned long __init find_function64(struct lib64_elfinfo *lib, const char *symname) { Elf64_Sym *sym = find_symbol64(lib, symname); if (sym == NULL) { printk(KERN_WARNING "vDSO64: function %s not found !\n", symname); return 0; } #ifdef VDS64_HAS_DESCRIPTORS return *((u64 *)(vdso64_kbase + sym->st_value - VDSO64_LBASE)) - VDSO64_LBASE; #else return sym->st_value - VDSO64_LBASE; #endif }
0
90,891
void ClientUsageTracker::GatherHostUsageComplete(const std::string& host) { DCHECK(host_usage_tasks_.find(host) != host_usage_tasks_.end()); host_usage_tasks_.erase(host); host_usage_callbacks_.Run(host, host, type_, GetCachedHostUsage(host)); }
0
512,299
Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d) { arg_count= 0; if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 4)))) { arg_count= 4; args[0]= a; args[1]= b; args[2]= c; args[3]= d; } }
0
328,903
R_API void r_bin_java_reset_bin_info(RBinJavaObj *bin) { free (bin->cf2.flags_str); free (bin->cf2.this_class_name); r_list_free (bin->imports_list); r_list_free (bin->methods_list); r_list_free (bin->fields_list); r_list_free (bin->attrs_list); r_list_free (bin->cp_list); r_list_free (bin->interfaces_list); r_str_constpool_fini (&bin->constpool); r_str_constpool_init (&bin->constpool); bin->cf2.flags_str = strdup ("unknown"); bin->cf2.this_class_name = strdup ("unknown"); bin->imports_list = r_list_newf (free); bin->methods_list = r_list_newf (r_bin_java_fmtype_free); bin->fields_list = r_list_newf (r_bin_java_fmtype_free); bin->attrs_list = r_list_newf (r_bin_java_attribute_free); bin->cp_list = r_list_newf (r_bin_java_constant_pool); bin->interfaces_list = r_list_newf (r_bin_java_interface_free); }
0
513,249
static int test_if_order_by_key(JOIN *join, ORDER *order, TABLE *table, uint idx, uint *used_key_parts= NULL) { KEY_PART_INFO *key_part,*key_part_end; key_part=table->key_info[idx].key_part; key_part_end=key_part + table->key_info[idx].ext_key_parts; key_part_map const_key_parts=table->const_key_parts[idx]; uint user_defined_kp= table->key_info[idx].user_defined_key_parts; int reverse=0; uint key_parts; bool have_pk_suffix= false; uint pk= table->s->primary_key; DBUG_ENTER("test_if_order_by_key"); if ((table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) && table->key_info[idx].ext_key_part_map && pk != MAX_KEY && pk != idx) { have_pk_suffix= true; } for (; order ; order=order->next, const_key_parts>>=1) { Item_field *item_field= ((Item_field*) (*order->item)->real_item()); Field *field= item_field->field; int flag; /* Skip key parts that are constants in the WHERE clause. These are already skipped in the ORDER BY by const_expression_in_where() */ for (; const_key_parts & 1 ; const_key_parts>>= 1) key_part++; /* This check was in this function historically (although I think it's better to check it outside of this function): "Test if the primary key parts were all const (i.e. there's one row). The sorting doesn't matter" So, we're checking that (1) this is an extended key (2) we've reached its end */ key_parts= (uint)(key_part - table->key_info[idx].key_part); if (have_pk_suffix && reverse == 0 && // all were =const so far key_parts == table->key_info[idx].ext_key_parts && table->const_key_parts[pk] == PREV_BITS(uint, table->key_info[pk]. user_defined_key_parts)) { key_parts= 0; reverse= 1; // Key is ok to use goto ok; } if (key_part == key_part_end) { /* There are some items left in ORDER BY that we don't */ DBUG_RETURN(0); } if (key_part->field != field) { /* Check if there is a multiple equality that allows to infer that field and key_part->field are equal (see also: compute_part_of_sort_key_for_equals) */ if (item_field->item_equal && item_field->item_equal->contains(key_part->field)) field= key_part->field; } if (key_part->field != field || !field->part_of_sortkey.is_set(idx)) DBUG_RETURN(0); const ORDER::enum_order keypart_order= (key_part->key_part_flag & HA_REVERSE_SORT) ? ORDER::ORDER_DESC : ORDER::ORDER_ASC; /* set flag to 1 if we can use read-next on key, else to -1 */ flag= (order->direction == keypart_order) ? 1 : -1; if (reverse && flag != reverse) DBUG_RETURN(0); reverse=flag; // Remember if reverse if (key_part < key_part_end) key_part++; } key_parts= (uint) (key_part - table->key_info[idx].key_part); if (reverse == -1 && !(table->file->index_flags(idx, user_defined_kp-1, 1) & HA_READ_PREV)) reverse= 0; // Index can't be used if (have_pk_suffix && reverse == -1) { uint pk_parts= table->key_info[pk].user_defined_key_parts; if (!(table->file->index_flags(pk, pk_parts, 1) & HA_READ_PREV)) reverse= 0; // Index can't be used } ok: if (used_key_parts != NULL) *used_key_parts= key_parts; DBUG_RETURN(reverse); }
0
374,048
static const char *subtypeString(int n) { if (n == 9) { // CPU_SUBTYPE_ARM_V7) { return "armv7"; } return "?"; }
0
317,215
static int selinux_is_genfs_special_handling(struct super_block *sb) { /* Special handling. Genfs but also in-core setxattr handler */ return !strcmp(sb->s_type->name, "sysfs") || !strcmp(sb->s_type->name, "pstore") || !strcmp(sb->s_type->name, "debugfs") || !strcmp(sb->s_type->name, "tracefs") || !strcmp(sb->s_type->name, "rootfs") || (selinux_policycap_cgroupseclabel() && (!strcmp(sb->s_type->name, "cgroup") || !strcmp(sb->s_type->name, "cgroup2"))); }
0
139,238
void OverlayWindowViews::OnNativeWidgetWorkspaceChanged() { }
0
512,324
double val_real() { return (double) value; }
0
195,388
PQconnectPoll(PGconn *conn) { bool reset_connection_state_machine = false; bool need_new_connection = false; PGresult *res; char sebuf[PG_STRERROR_R_BUFLEN]; int optval; if (conn == NULL) return PGRES_POLLING_FAILED; /* Get the new data */ switch (conn->status) { /* * We really shouldn't have been polled in these two cases, but we * can handle it. */ case CONNECTION_BAD: return PGRES_POLLING_FAILED; case CONNECTION_OK: return PGRES_POLLING_OK; /* These are reading states */ case CONNECTION_AWAITING_RESPONSE: case CONNECTION_AUTH_OK: case CONNECTION_CHECK_WRITABLE: case CONNECTION_CONSUME: case CONNECTION_CHECK_STANDBY: { /* Load waiting data */ int n = pqReadData(conn); if (n < 0) goto error_return; if (n == 0) return PGRES_POLLING_READING; break; } /* These are writing states, so we just proceed. */ case CONNECTION_STARTED: case CONNECTION_MADE: break; /* Special cases: proceed without waiting. */ case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: case CONNECTION_GSS_STARTUP: case CONNECTION_CHECK_TARGET: break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("invalid connection state, probably indicative of memory corruption\n")); goto error_return; } keep_going: /* We will come back to here until there is * nothing left to do. */ /* Time to advance to next address, or next host if no more addresses? */ if (conn->try_next_addr) { if (conn->addr_cur && conn->addr_cur->ai_next) { conn->addr_cur = conn->addr_cur->ai_next; reset_connection_state_machine = true; } else conn->try_next_host = true; conn->try_next_addr = false; } /* Time to advance to next connhost[] entry? */ if (conn->try_next_host) { pg_conn_host *ch; struct addrinfo hint; int thisport; int ret; char portstr[MAXPGPATH]; if (conn->whichhost + 1 < conn->nconnhost) conn->whichhost++; else { /* * Oops, no more hosts. * * If we are trying to connect in "prefer-standby" mode, then drop * the standby requirement and start over. * * Otherwise, an appropriate error message is already set up, so * we just need to set the right status. */ if (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY && conn->nconnhost > 0) { conn->target_server_type = SERVER_TYPE_PREFER_STANDBY_PASS2; conn->whichhost = 0; } else goto error_return; } /* Drop any address info for previous host */ release_conn_addrinfo(conn); /* * Look up info for the new host. On failure, log the problem in * conn->errorMessage, then loop around to try the next host. (Note * we don't clear try_next_host until we've succeeded.) */ ch = &conn->connhost[conn->whichhost]; /* Initialize hint structure */ MemSet(&hint, 0, sizeof(hint)); hint.ai_socktype = SOCK_STREAM; conn->addrlist_family = hint.ai_family = AF_UNSPEC; /* Figure out the port number we're going to use. */ if (ch->port == NULL || ch->port[0] == '\0') thisport = DEF_PGPORT; else { if (!parse_int_param(ch->port, &thisport, conn, "port")) goto error_return; if (thisport < 1 || thisport > 65535) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid port number: \"%s\"\n"), ch->port); goto keep_going; } } snprintf(portstr, sizeof(portstr), "%d", thisport); /* Use pg_getaddrinfo_all() to resolve the address */ switch (ch->type) { case CHT_HOST_NAME: ret = pg_getaddrinfo_all(ch->host, portstr, &hint, &conn->addrlist); if (ret || !conn->addrlist) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not translate host name \"%s\" to address: %s\n"), ch->host, gai_strerror(ret)); goto keep_going; } break; case CHT_HOST_ADDRESS: hint.ai_flags = AI_NUMERICHOST; ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint, &conn->addrlist); if (ret || !conn->addrlist) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not parse network address \"%s\": %s\n"), ch->hostaddr, gai_strerror(ret)); goto keep_going; } break; case CHT_UNIX_SOCKET: #ifdef HAVE_UNIX_SOCKETS conn->addrlist_family = hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, thisport, ch->host); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); goto keep_going; } /* * NULL hostname tells pg_getaddrinfo_all to parse the service * name as a Unix-domain socket path. */ ret = pg_getaddrinfo_all(NULL, portstr, &hint, &conn->addrlist); if (ret || !conn->addrlist) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), portstr, gai_strerror(ret)); goto keep_going; } #else Assert(false); #endif break; } /* OK, scan this addrlist for a working server address */ conn->addr_cur = conn->addrlist; reset_connection_state_machine = true; conn->try_next_host = false; } /* Reset connection state machine? */ if (reset_connection_state_machine) { /* * (Re) initialize our connection control variables for a set of * connection attempts to a single server address. These variables * must persist across individual connection attempts, but we must * reset them when we start to consider a new server. */ conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; #ifdef USE_SSL /* initialize these values based on SSL mode */ conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */ conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */ #endif #ifdef ENABLE_GSS conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */ #endif reset_connection_state_machine = false; need_new_connection = true; } /* Force a new connection (perhaps to the same server as before)? */ if (need_new_connection) { /* Drop any existing connection */ pqDropConnection(conn, true); /* Reset all state obtained from old server */ pqDropServerData(conn); /* Drop any PGresult we might have, too */ conn->asyncStatus = PGASYNC_IDLE; conn->xactStatus = PQTRANS_IDLE; conn->pipelineStatus = PQ_PIPELINE_OFF; pqClearAsyncResult(conn); /* Reset conn->status to put the state machine in the right state */ conn->status = CONNECTION_NEEDED; need_new_connection = false; } /* Now try to advance the state machine for this connection */ switch (conn->status) { case CONNECTION_NEEDED: { /* * Try to initiate a connection to one of the addresses * returned by pg_getaddrinfo_all(). conn->addr_cur is the * next one to try. * * The extra level of braces here is historical. It's not * worth reindenting this whole switch case to remove 'em. */ { struct addrinfo *addr_cur = conn->addr_cur; char host_addr[NI_MAXHOST]; /* * Advance to next possible host, if we've tried all of * the addresses for the current host. */ if (addr_cur == NULL) { conn->try_next_host = true; goto keep_going; } /* Remember current address for possible use later */ memcpy(&conn->raddr.addr, addr_cur->ai_addr, addr_cur->ai_addrlen); conn->raddr.salen = addr_cur->ai_addrlen; /* * Set connip, too. Note we purposely ignore strdup * failure; not a big problem if it fails. */ if (conn->connip != NULL) { free(conn->connip); conn->connip = NULL; } getHostaddr(conn, host_addr, NI_MAXHOST); if (host_addr[0]) conn->connip = strdup(host_addr); /* Try to create the socket */ conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0); if (conn->sock == PGINVALID_SOCKET) { int errorno = SOCK_ERRNO; /* * Silently ignore socket() failure if we have more * addresses to try; this reduces useless chatter in * cases where the address list includes both IPv4 and * IPv6 but kernel only accepts one family. */ if (addr_cur->ai_next != NULL || conn->whichhost + 1 < conn->nconnhost) { conn->try_next_addr = true; goto keep_going; } emitHostIdentityInfo(conn, host_addr); appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not create socket: %s\n"), SOCK_STRERROR(errorno, sebuf, sizeof(sebuf))); goto error_return; } /* * Once we've identified a target address, all errors * except the preceding socket()-failure case should be * prefixed with host-identity information. (If the * connection succeeds, the contents of conn->errorMessage * won't matter, so this is harmless.) */ emitHostIdentityInfo(conn, host_addr); /* * Select socket options: no delay of outgoing data for * TCP sockets, nonblock mode, close-on-exec. Try the * next address if any of this fails. */ if (!IS_AF_UNIX(addr_cur->ai_family)) { if (!connectNoDelay(conn)) { /* error message already created */ conn->try_next_addr = true; goto keep_going; } } if (!pg_set_noblock(conn->sock)) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); conn->try_next_addr = true; goto keep_going; } #ifdef F_SETFD if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); conn->try_next_addr = true; goto keep_going; } #endif /* F_SETFD */ if (!IS_AF_UNIX(addr_cur->ai_family)) { #ifndef WIN32 int on = 1; #endif int usekeepalives = useKeepalives(conn); int err = 0; if (usekeepalives < 0) { appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("keepalives parameter must be an integer\n")); err = 1; } else if (usekeepalives == 0) { /* Do nothing */ } #ifndef WIN32 else if (setsockopt(conn->sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) < 0) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("%s(%s) failed: %s\n"), "setsockopt", "SO_KEEPALIVE", SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); err = 1; } else if (!setKeepalivesIdle(conn) || !setKeepalivesInterval(conn) || !setKeepalivesCount(conn)) err = 1; #else /* WIN32 */ #ifdef SIO_KEEPALIVE_VALS else if (!setKeepalivesWin32(conn)) err = 1; #endif /* SIO_KEEPALIVE_VALS */ #endif /* WIN32 */ else if (!setTCPUserTimeout(conn)) err = 1; if (err) { conn->try_next_addr = true; goto keep_going; } } /*---------- * We have three methods of blocking SIGPIPE during * send() calls to this socket: * * - setsockopt(sock, SO_NOSIGPIPE) * - send(sock, ..., MSG_NOSIGNAL) * - setting the signal mask to SIG_IGN during send() * * The third method requires three syscalls per send, * so we prefer either of the first two, but they are * less portable. The state is tracked in the following * members of PGconn: * * conn->sigpipe_so - we have set up SO_NOSIGPIPE * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL * * If we can use SO_NOSIGPIPE, then set sigpipe_so here * and we're done. Otherwise, set sigpipe_flag so that * we will try MSG_NOSIGNAL on sends. If we get an error * with MSG_NOSIGNAL, we'll clear that flag and revert to * signal masking. *---------- */ conn->sigpipe_so = false; #ifdef MSG_NOSIGNAL conn->sigpipe_flag = true; #else conn->sigpipe_flag = false; #endif /* MSG_NOSIGNAL */ #ifdef SO_NOSIGPIPE optval = 1; if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE, (char *) &optval, sizeof(optval)) == 0) { conn->sigpipe_so = true; conn->sigpipe_flag = false; } #endif /* SO_NOSIGPIPE */ /* * Start/make connection. This should not block, since we * are in nonblock mode. If it does, well, too bad. */ if (connect(conn->sock, addr_cur->ai_addr, addr_cur->ai_addrlen) < 0) { if (SOCK_ERRNO == EINPROGRESS || #ifdef WIN32 SOCK_ERRNO == EWOULDBLOCK || #endif SOCK_ERRNO == EINTR) { /* * This is fine - we're in non-blocking mode, and * the connection is in progress. Tell caller to * wait for write-ready on socket. */ conn->status = CONNECTION_STARTED; return PGRES_POLLING_WRITING; } /* otherwise, trouble */ } else { /* * Hm, we're connected already --- seems the "nonblock * connection" wasn't. Advance the state machine and * go do the next stuff. */ conn->status = CONNECTION_STARTED; goto keep_going; } /* * This connection failed. Add the error report to * conn->errorMessage, then try the next address if any. */ connectFailureMessage(conn, SOCK_ERRNO); conn->try_next_addr = true; goto keep_going; } } case CONNECTION_STARTED: { ACCEPT_TYPE_ARG3 optlen = sizeof(optval); /* * Write ready, since we've made it here, so the connection * has been made ... or has failed. */ /* * Now check (using getsockopt) that there is not an error * state waiting for us on the socket. */ if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &optval, &optlen) == -1) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not get socket error status: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); goto error_return; } else if (optval != 0) { /* * When using a nonblocking connect, we will typically see * connect failures at this point, so provide a friendly * error message. */ connectFailureMessage(conn, optval); /* * Try the next address if any, just as in the case where * connect() returned failure immediately. */ conn->try_next_addr = true; goto keep_going; } /* Fill in the client address */ conn->laddr.salen = sizeof(conn->laddr.addr); if (getsockname(conn->sock, (struct sockaddr *) &conn->laddr.addr, &conn->laddr.salen) < 0) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not get client address from socket: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); goto error_return; } /* * Make sure we can write before advancing to next step. */ conn->status = CONNECTION_MADE; return PGRES_POLLING_WRITING; } case CONNECTION_MADE: { char *startpacket; int packetlen; /* * Implement requirepeer check, if requested and it's a * Unix-domain socket. */ if (conn->requirepeer && conn->requirepeer[0] && IS_AF_UNIX(conn->raddr.addr.ss_family)) { #ifndef WIN32 char pwdbuf[BUFSIZ]; struct passwd pass_buf; struct passwd *pass; int passerr; #endif uid_t uid; gid_t gid; errno = 0; if (getpeereid(conn->sock, &uid, &gid) != 0) { /* * Provide special error message if getpeereid is a * stub */ if (errno == ENOSYS) appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("requirepeer parameter is not supported on this platform\n")); else appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not get peer credentials: %s\n"), strerror_r(errno, sebuf, sizeof(sebuf))); goto error_return; } #ifndef WIN32 passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass); if (pass == NULL) { if (passerr != 0) appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not look up local user ID %d: %s\n"), (int) uid, strerror_r(passerr, sebuf, sizeof(sebuf))); else appendPQExpBuffer(&conn->errorMessage, libpq_gettext("local user with ID %d does not exist\n"), (int) uid); goto error_return; } if (strcmp(pass->pw_name, conn->requirepeer) != 0) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"), conn->requirepeer, pass->pw_name); goto error_return; } #else /* WIN32 */ /* should have failed with ENOSYS above */ Assert(false); #endif /* WIN32 */ } if (IS_AF_UNIX(conn->raddr.addr.ss_family)) { /* Don't request SSL or GSSAPI over Unix sockets */ #ifdef USE_SSL conn->allow_ssl_try = false; #endif #ifdef ENABLE_GSS conn->try_gss = false; #endif } #ifdef ENABLE_GSS /* * If GSSAPI encryption is enabled, then call * pg_GSS_have_cred_cache() which will return true if we can * acquire credentials (and give us a handle to use in * conn->gcred), and then send a packet to the server asking * for GSSAPI Encryption (and skip past SSL negotiation and * regular startup below). */ if (conn->try_gss && !conn->gctx) conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred); if (conn->try_gss && !conn->gctx) { ProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE); if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not send GSSAPI negotiation packet: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); goto error_return; } /* Ok, wait for response */ conn->status = CONNECTION_GSS_STARTUP; return PGRES_POLLING_READING; } else if (!conn->gctx && conn->gssencmode[0] == 'r') { appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\n")); goto error_return; } #endif #ifdef USE_SSL /* * Enable the libcrypto callbacks before checking if SSL needs * to be done. This is done before sending the startup packet * as depending on the type of authentication done, like MD5 * or SCRAM that use cryptohashes, the callbacks would be * required even without a SSL connection */ if (pqsecure_initialize(conn, false, true) < 0) goto error_return; /* * If SSL is enabled and we haven't already got encryption of * some sort running, request SSL instead of sending the * startup message. */ if (conn->allow_ssl_try && !conn->wait_ssl_try && !conn->ssl_in_use #ifdef ENABLE_GSS && !conn->gssenc #endif ) { ProtocolVersion pv; /* * Send the SSL request packet. * * Theoretically, this could block, but it really * shouldn't since we only got here if the socket is * write-ready. */ pv = pg_hton32(NEGOTIATE_SSL_CODE); if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not send SSL negotiation packet: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); goto error_return; } /* Ok, wait for response */ conn->status = CONNECTION_SSL_STARTUP; return PGRES_POLLING_READING; } #endif /* USE_SSL */ /* * Build the startup packet. */ startpacket = pqBuildStartupPacket3(conn, &packetlen, EnvironmentOptions); if (!startpacket) { appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("out of memory\n")); goto error_return; } /* * Send the startup packet. * * Theoretically, this could block, but it really shouldn't * since we only got here if the socket is write-ready. */ if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not send startup packet: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); free(startpacket); goto error_return; } free(startpacket); conn->status = CONNECTION_AWAITING_RESPONSE; return PGRES_POLLING_READING; } /* * Handle SSL negotiation: wait for postmaster messages and * respond as necessary. */ case CONNECTION_SSL_STARTUP: { #ifdef USE_SSL PostgresPollingStatusType pollres; /* * On first time through, get the postmaster's response to our * SSL negotiation packet. */ if (!conn->ssl_in_use) { /* * We use pqReadData here since it has the logic to * distinguish no-data-yet from connection closure. Since * conn->ssl isn't set, a plain recv() will occur. */ char SSLok; int rdresult; rdresult = pqReadData(conn); if (rdresult < 0) { /* errorMessage is already filled in */ goto error_return; } if (rdresult == 0) { /* caller failed to wait for data */ return PGRES_POLLING_READING; } if (pqGetc(&SSLok, conn) < 0) { /* should not happen really */ return PGRES_POLLING_READING; } if (SSLok == 'S') { /* mark byte consumed */ conn->inStart = conn->inCursor; /* * Set up global SSL state if required. The crypto * state has already been set if libpq took care of * doing that, so there is no need to make that happen * again. */ if (pqsecure_initialize(conn, true, false) != 0) goto error_return; } else if (SSLok == 'N') { /* mark byte consumed */ conn->inStart = conn->inCursor; /* OK to do without SSL? */ if (conn->sslmode[0] == 'r' || /* "require" */ conn->sslmode[0] == 'v') /* "verify-ca" or * "verify-full" */ { /* Require SSL, but server does not want it */ appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("server does not support SSL, but SSL was required\n")); goto error_return; } /* Otherwise, proceed with normal startup */ conn->allow_ssl_try = false; /* We can proceed using this connection */ conn->status = CONNECTION_MADE; return PGRES_POLLING_WRITING; } else if (SSLok == 'E') { /* * Server failure of some sort, such as failure to * fork a backend process. We need to process and * report the error message, which might be formatted * according to either protocol 2 or protocol 3. * Rather than duplicate the code for that, we flip * into AWAITING_RESPONSE state and let the code there * deal with it. Note we have *not* consumed the "E" * byte here. */ conn->status = CONNECTION_AWAITING_RESPONSE; goto keep_going; } else { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("received invalid response to SSL negotiation: %c\n"), SSLok); goto error_return; } } /* * Begin or continue the SSL negotiation process. */ pollres = pqsecure_open_client(conn); if (pollres == PGRES_POLLING_OK) { /* SSL handshake done, ready to send startup packet */ conn->status = CONNECTION_MADE; return PGRES_POLLING_WRITING; } if (pollres == PGRES_POLLING_FAILED) { /* * Failed ... if sslmode is "prefer" then do a non-SSL * retry */ if (conn->sslmode[0] == 'p' /* "prefer" */ && conn->allow_ssl_try /* redundant? */ && !conn->wait_ssl_try) /* redundant? */ { /* only retry once */ conn->allow_ssl_try = false; need_new_connection = true; goto keep_going; } /* Else it's a hard failure */ goto error_return; } /* Else, return POLLING_READING or POLLING_WRITING status */ return pollres; #else /* !USE_SSL */ /* can't get here */ goto error_return; #endif /* USE_SSL */ } case CONNECTION_GSS_STARTUP: { #ifdef ENABLE_GSS PostgresPollingStatusType pollres; /* * If we haven't yet, get the postmaster's response to our * negotiation packet */ if (conn->try_gss && !conn->gctx) { char gss_ok; int rdresult = pqReadData(conn); if (rdresult < 0) /* pqReadData fills in error message */ goto error_return; else if (rdresult == 0) /* caller failed to wait for data */ return PGRES_POLLING_READING; if (pqGetc(&gss_ok, conn) < 0) /* shouldn't happen... */ return PGRES_POLLING_READING; if (gss_ok == 'E') { /* * Server failure of some sort. Assume it's a * protocol version support failure, and let's see if * we can't recover (if it's not, we'll get a better * error message on retry). Server gets fussy if we * don't hang up the socket, though. */ conn->try_gss = false; need_new_connection = true; goto keep_going; } /* mark byte consumed */ conn->inStart = conn->inCursor; if (gss_ok == 'N') { /* Server doesn't want GSSAPI; fall back if we can */ if (conn->gssencmode[0] == 'r') { appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("server doesn't support GSSAPI encryption, but it was required\n")); goto error_return; } conn->try_gss = false; /* We can proceed using this connection */ conn->status = CONNECTION_MADE; return PGRES_POLLING_WRITING; } else if (gss_ok != 'G') { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("received invalid response to GSSAPI negotiation: %c\n"), gss_ok); goto error_return; } } /* Begin or continue GSSAPI negotiation */ pollres = pqsecure_open_gss(conn); if (pollres == PGRES_POLLING_OK) { /* All set for startup packet */ conn->status = CONNECTION_MADE; return PGRES_POLLING_WRITING; } else if (pollres == PGRES_POLLING_FAILED && conn->gssencmode[0] == 'p') { /* * We failed, but we can retry on "prefer". Have to drop * the current connection to do so, though. */ conn->try_gss = false; need_new_connection = true; goto keep_going; } return pollres; #else /* !ENABLE_GSS */ /* unreachable */ goto error_return; #endif /* ENABLE_GSS */ } /* * Handle authentication exchange: wait for postmaster messages * and respond as necessary. */ case CONNECTION_AWAITING_RESPONSE: { char beresp; int msgLength; int avail; AuthRequest areq; int res; /* * Scan the message from current point (note that if we find * the message is incomplete, we will return without advancing * inStart, and resume here next time). */ conn->inCursor = conn->inStart; /* Read type byte */ if (pqGetc(&beresp, conn)) { /* We'll come back when there is more data */ return PGRES_POLLING_READING; } /* * Validate message type: we expect only an authentication * request or an error here. Anything else probably means * it's not Postgres on the other end at all. */ if (!(beresp == 'R' || beresp == 'E')) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("expected authentication request from server, but received %c\n"), beresp); goto error_return; } /* Read message length word */ if (pqGetInt(&msgLength, 4, conn)) { /* We'll come back when there is more data */ return PGRES_POLLING_READING; } /* * Try to validate message length before using it. * Authentication requests can't be very large, although GSS * auth requests may not be that small. Errors can be a * little larger, but not huge. If we see a large apparent * length in an error, it means we're really talking to a * pre-3.0-protocol server; cope. (Before version 14, the * server also used the old protocol for errors that happened * before processing the startup packet.) */ if (beresp == 'R' && (msgLength < 8 || msgLength > 2000)) { appendPQExpBuffer(&conn->errorMessage, libpq_gettext("expected authentication request from server, but received %c\n"), beresp); goto error_return; } if (beresp == 'E' && (msgLength < 8 || msgLength > 30000)) { /* Handle error from a pre-3.0 server */ conn->inCursor = conn->inStart + 1; /* reread data */ if (pqGets_append(&conn->errorMessage, conn)) { /* We'll come back when there is more data */ return PGRES_POLLING_READING; } /* OK, we read the message; mark data consumed */ conn->inStart = conn->inCursor; /* * Before 7.2, the postmaster didn't always end its * messages with a newline, so add one if needed to * conform to libpq conventions. */ if (conn->errorMessage.len == 0 || conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') { appendPQExpBufferChar(&conn->errorMessage, '\n'); } goto error_return; } /* * Can't process if message body isn't all here yet. */ msgLength -= 4; avail = conn->inEnd - conn->inCursor; if (avail < msgLength) { /* * Before returning, try to enlarge the input buffer if * needed to hold the whole message; see notes in * pqParseInput3. */ if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength, conn)) goto error_return; /* We'll come back when there is more data */ return PGRES_POLLING_READING; } /* Handle errors. */ if (beresp == 'E') { if (pqGetErrorNotice3(conn, true)) { /* We'll come back when there is more data */ return PGRES_POLLING_READING; } /* OK, we read the message; mark data consumed */ conn->inStart = conn->inCursor; /* * If error is "cannot connect now", try the next host if * any (but we don't want to consider additional addresses * for this host, nor is there much point in changing SSL * or GSS mode). This is helpful when dealing with * standby servers that might not be in hot-standby state. */ if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0) { conn->try_next_host = true; goto keep_going; } /* Check to see if we should mention pgpassfile */ pgpassfileWarning(conn); #ifdef ENABLE_GSS /* * If gssencmode is "prefer" and we're using GSSAPI, retry * without it. */ if (conn->gssenc && conn->gssencmode[0] == 'p') { /* only retry once */ conn->try_gss = false; need_new_connection = true; goto keep_going; } #endif #ifdef USE_SSL /* * if sslmode is "allow" and we haven't tried an SSL * connection already, then retry with an SSL connection */ if (conn->sslmode[0] == 'a' /* "allow" */ && !conn->ssl_in_use && conn->allow_ssl_try && conn->wait_ssl_try) { /* only retry once */ conn->wait_ssl_try = false; need_new_connection = true; goto keep_going; } /* * if sslmode is "prefer" and we're in an SSL connection, * then do a non-SSL retry */ if (conn->sslmode[0] == 'p' /* "prefer" */ && conn->ssl_in_use && conn->allow_ssl_try /* redundant? */ && !conn->wait_ssl_try) /* redundant? */ { /* only retry once */ conn->allow_ssl_try = false; need_new_connection = true; goto keep_going; } #endif goto error_return; } /* It is an authentication request. */ conn->auth_req_received = true; /* Get the type of request. */ if (pqGetInt((int *) &areq, 4, conn)) { /* We'll come back when there are more data */ return PGRES_POLLING_READING; } msgLength -= 4; /* * Process the rest of the authentication request message, and * respond to it if necessary. * * Note that conn->pghost must be non-NULL if we are going to * avoid the Kerberos code doing a hostname look-up. */ res = pg_fe_sendauth(areq, msgLength, conn); /* OK, we have processed the message; mark data consumed */ conn->inStart = conn->inCursor; if (res != STATUS_OK) goto error_return; /* * Just make sure that any data sent by pg_fe_sendauth is * flushed out. Although this theoretically could block, it * really shouldn't since we don't send large auth responses. */ if (pqFlush(conn)) goto error_return; if (areq == AUTH_REQ_OK) { /* We are done with authentication exchange */ conn->status = CONNECTION_AUTH_OK; /* * Set asyncStatus so that PQgetResult will think that * what comes back next is the result of a query. See * below. */ conn->asyncStatus = PGASYNC_BUSY; } /* Look to see if we have more data yet. */ goto keep_going; } case CONNECTION_AUTH_OK: { /* * Now we expect to hear from the backend. A ReadyForQuery * message indicates that startup is successful, but we might * also get an Error message indicating failure. (Notice * messages indicating nonfatal warnings are also allowed by * the protocol, as are ParameterStatus and BackendKeyData * messages.) Easiest way to handle this is to let * PQgetResult() read the messages. We just have to fake it * out about the state of the connection, by setting * asyncStatus = PGASYNC_BUSY (done above). */ if (PQisBusy(conn)) return PGRES_POLLING_READING; res = PQgetResult(conn); /* * NULL return indicating we have gone to IDLE state is * expected */ if (res) { if (res->resultStatus != PGRES_FATAL_ERROR) appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("unexpected message from server during startup\n")); else if (conn->send_appname && (conn->appname || conn->fbappname)) { /* * If we tried to send application_name, check to see * if the error is about that --- pre-9.0 servers will * reject it at this stage of the process. If so, * close the connection and retry without sending * application_name. We could possibly get a false * SQLSTATE match here and retry uselessly, but there * seems no great harm in that; we'll just get the * same error again if it's unrelated. */ const char *sqlstate; sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE); if (sqlstate && strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0) { PQclear(res); conn->send_appname = false; need_new_connection = true; goto keep_going; } } /* * if the resultStatus is FATAL, then conn->errorMessage * already has a copy of the error; needn't copy it back. * But add a newline if it's not there already, since * postmaster error messages may not have one. */ if (conn->errorMessage.len <= 0 || conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); goto error_return; } /* Almost there now ... */ conn->status = CONNECTION_CHECK_TARGET; goto keep_going; } case CONNECTION_CHECK_TARGET: { /* * If a read-write, read-only, primary, or standby connection * is required, see if we have one. */ if (conn->target_server_type == SERVER_TYPE_READ_WRITE || conn->target_server_type == SERVER_TYPE_READ_ONLY) { bool read_only_server; /* * If the server didn't report * "default_transaction_read_only" or "in_hot_standby" at * startup, we must determine its state by sending the * query "SHOW transaction_read_only". This GUC exists in * all server versions that support 3.0 protocol. */ if (conn->default_transaction_read_only == PG_BOOL_UNKNOWN || conn->in_hot_standby == PG_BOOL_UNKNOWN) { /* * We use PQsendQueryContinue so that * conn->errorMessage does not get cleared. We need * to preserve any error messages related to previous * hosts we have tried and failed to connect to. */ conn->status = CONNECTION_OK; if (!PQsendQueryContinue(conn, "SHOW transaction_read_only")) goto error_return; /* We'll return to this state when we have the answer */ conn->status = CONNECTION_CHECK_WRITABLE; return PGRES_POLLING_READING; } /* OK, we can make the test */ read_only_server = (conn->default_transaction_read_only == PG_BOOL_YES || conn->in_hot_standby == PG_BOOL_YES); if ((conn->target_server_type == SERVER_TYPE_READ_WRITE) ? read_only_server : !read_only_server) { /* Wrong server state, reject and try the next host */ if (conn->target_server_type == SERVER_TYPE_READ_WRITE) appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("session is read-only\n")); else appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("session is not read-only\n")); /* Close connection politely. */ conn->status = CONNECTION_OK; sendTerminateConn(conn); /* * Try next host if any, but we don't want to consider * additional addresses for this host. */ conn->try_next_host = true; goto keep_going; } } else if (conn->target_server_type == SERVER_TYPE_PRIMARY || conn->target_server_type == SERVER_TYPE_STANDBY || conn->target_server_type == SERVER_TYPE_PREFER_STANDBY) { /* * If the server didn't report "in_hot_standby" at * startup, we must determine its state by sending the * query "SELECT pg_catalog.pg_is_in_recovery()". Servers * before 9.0 don't have that function, but by the same * token they don't have any standby mode, so we may just * assume the result. */ if (conn->sversion < 90000) conn->in_hot_standby = PG_BOOL_NO; if (conn->in_hot_standby == PG_BOOL_UNKNOWN) { /* * We use PQsendQueryContinue so that * conn->errorMessage does not get cleared. We need * to preserve any error messages related to previous * hosts we have tried and failed to connect to. */ conn->status = CONNECTION_OK; if (!PQsendQueryContinue(conn, "SELECT pg_catalog.pg_is_in_recovery()")) goto error_return; /* We'll return to this state when we have the answer */ conn->status = CONNECTION_CHECK_STANDBY; return PGRES_POLLING_READING; } /* OK, we can make the test */ if ((conn->target_server_type == SERVER_TYPE_PRIMARY) ? (conn->in_hot_standby == PG_BOOL_YES) : (conn->in_hot_standby == PG_BOOL_NO)) { /* Wrong server state, reject and try the next host */ if (conn->target_server_type == SERVER_TYPE_PRIMARY) appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("server is in hot standby mode\n")); else appendPQExpBufferStr(&conn->errorMessage, libpq_gettext("server is not in hot standby mode\n")); /* Close connection politely. */ conn->status = CONNECTION_OK; sendTerminateConn(conn); /* * Try next host if any, but we don't want to consider * additional addresses for this host. */ conn->try_next_host = true; goto keep_going; } } /* We can release the address list now. */ release_conn_addrinfo(conn); /* * Contents of conn->errorMessage are no longer interesting * (and it seems some clients expect it to be empty after a * successful connection). */ resetPQExpBuffer(&conn->errorMessage); /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; } case CONNECTION_CONSUME: { /* * This state just makes sure the connection is idle after * we've obtained the result of a SHOW or SELECT query. Once * we're clear, return to CONNECTION_CHECK_TARGET state to * decide what to do next. We must transiently set status = * CONNECTION_OK in order to use the result-consuming * subroutines. */ conn->status = CONNECTION_OK; if (!PQconsumeInput(conn)) goto error_return; if (PQisBusy(conn)) { conn->status = CONNECTION_CONSUME; return PGRES_POLLING_READING; } /* Call PQgetResult() again until we get a NULL result */ res = PQgetResult(conn); if (res != NULL) { PQclear(res); conn->status = CONNECTION_CONSUME; return PGRES_POLLING_READING; } conn->status = CONNECTION_CHECK_TARGET; goto keep_going; } case CONNECTION_CHECK_WRITABLE: { /* * Waiting for result of "SHOW transaction_read_only". We * must transiently set status = CONNECTION_OK in order to use * the result-consuming subroutines. */ conn->status = CONNECTION_OK; if (!PQconsumeInput(conn)) goto error_return; if (PQisBusy(conn)) { conn->status = CONNECTION_CHECK_WRITABLE; return PGRES_POLLING_READING; } res = PQgetResult(conn); if (res && PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1) { char *val = PQgetvalue(res, 0, 0); /* * "transaction_read_only = on" proves that at least one * of default_transaction_read_only and in_hot_standby is * on, but we don't actually know which. We don't care * though for the purpose of identifying a read-only * session, so satisfy the CONNECTION_CHECK_TARGET code by * claiming they are both on. On the other hand, if it's * a read-write session, they are certainly both off. */ if (strncmp(val, "on", 2) == 0) { conn->default_transaction_read_only = PG_BOOL_YES; conn->in_hot_standby = PG_BOOL_YES; } else { conn->default_transaction_read_only = PG_BOOL_NO; conn->in_hot_standby = PG_BOOL_NO; } PQclear(res); /* Finish reading messages before continuing */ conn->status = CONNECTION_CONSUME; goto keep_going; } /* Something went wrong with "SHOW transaction_read_only". */ if (res) PQclear(res); /* Append error report to conn->errorMessage. */ appendPQExpBuffer(&conn->errorMessage, libpq_gettext("\"%s\" failed\n"), "SHOW transaction_read_only"); /* Close connection politely. */ conn->status = CONNECTION_OK; sendTerminateConn(conn); /* Try next host. */ conn->try_next_host = true; goto keep_going; } case CONNECTION_CHECK_STANDBY: { /* * Waiting for result of "SELECT pg_is_in_recovery()". We * must transiently set status = CONNECTION_OK in order to use * the result-consuming subroutines. */ conn->status = CONNECTION_OK; if (!PQconsumeInput(conn)) goto error_return; if (PQisBusy(conn)) { conn->status = CONNECTION_CHECK_STANDBY; return PGRES_POLLING_READING; } res = PQgetResult(conn); if (res && PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1) { char *val = PQgetvalue(res, 0, 0); if (strncmp(val, "t", 1) == 0) conn->in_hot_standby = PG_BOOL_YES; else conn->in_hot_standby = PG_BOOL_NO; PQclear(res); /* Finish reading messages before continuing */ conn->status = CONNECTION_CONSUME; goto keep_going; } /* Something went wrong with "SELECT pg_is_in_recovery()". */ if (res) PQclear(res); /* Append error report to conn->errorMessage. */ appendPQExpBuffer(&conn->errorMessage, libpq_gettext("\"%s\" failed\n"), "SELECT pg_is_in_recovery()"); /* Close connection politely. */ conn->status = CONNECTION_OK; sendTerminateConn(conn); /* Try next host. */ conn->try_next_host = true; goto keep_going; } default: appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid connection state %d, " "probably indicative of memory corruption\n"), conn->status); goto error_return; } /* Unreachable */ error_return: /* * We used to close the socket at this point, but that makes it awkward * for those above us if they wish to remove this socket from their own * records (an fd_set for example). We'll just have this socket closed * when PQfinish is called (which is compulsory even after an error, since * the connection structure must be freed). */ conn->status = CONNECTION_BAD; return PGRES_POLLING_FAILED; }
1
512,493
my_decimal *val_decimal_from_item(Item *item, my_decimal *decimal_value) { DBUG_ASSERT(is_fixed()); my_decimal *value= item->val_decimal(decimal_value); if ((null_value= item->null_value)) value= NULL; return value; }
0
224,529
Status ValidateVariableResourceHandle( InferenceContext* c, std::vector<ShapeAndType>* shape_and_type) { auto* handle_data = c->input_handle_shapes_and_types(0); if (handle_data == nullptr || handle_data->empty()) { shape_and_type->emplace_back(c->UnknownShape(), DT_INVALID); } else { *shape_and_type = *handle_data; DataType value_dtype; TF_RETURN_IF_ERROR(c->GetAttr("dtype", &value_dtype)); if (shape_and_type->at(0).dtype != value_dtype) { return errors::InvalidArgument( "Trying to read variable with wrong dtype. " "Expected ", DataTypeString(shape_and_type->at(0).dtype), " got ", DataTypeString(value_dtype)); } } return Status::OK(); }
0
337,808
static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc, __u8 type, __u8 flags, int paylen, gfp_t gfp) { struct sctp_chunkhdr *chunk_hdr; struct sctp_chunk *retval; struct sk_buff *skb; struct sock *sk; int chunklen; chunklen = SCTP_PAD4(sizeof(*chunk_hdr) + paylen); if (chunklen > SCTP_MAX_CHUNK_LEN) goto nodata; /* No need to allocate LL here, as this is only a chunk. */ skb = alloc_skb(chunklen, gfp); if (!skb) goto nodata; /* Make room for the chunk header. */ chunk_hdr = (struct sctp_chunkhdr *)skb_put(skb, sizeof(*chunk_hdr)); chunk_hdr->type = type; chunk_hdr->flags = flags; chunk_hdr->length = htons(sizeof(*chunk_hdr)); sk = asoc ? asoc->base.sk : NULL; retval = sctp_chunkify(skb, asoc, sk, gfp); if (!retval) { kfree_skb(skb); goto nodata; } retval->chunk_hdr = chunk_hdr; retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(*chunk_hdr); /* Determine if the chunk needs to be authenticated */ if (sctp_auth_send_cid(type, asoc)) retval->auth = 1; return retval; nodata: return NULL; }
0
210,551
expand_case_fold_string(Node* node, regex_t* reg) { #define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION 8 int r, n, len, alt_num; UChar *start, *end, *p; Node *top_root, *root, *snode, *prev_node; OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; StrNode* sn = STR_(node); if (NODE_STRING_IS_AMBIG(node)) return 0; start = sn->s; end = sn->end; if (start >= end) return 0; r = 0; top_root = root = prev_node = snode = NULL_NODE; alt_num = 1; p = start; while (p < end) { n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag, p, end, items); if (n < 0) { r = n; goto err; } len = enclen(reg->enc, p); if (n == 0) { if (IS_NULL(snode)) { if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } prev_node = snode = onig_node_new_str(NULL, NULL); if (IS_NULL(snode)) goto mem_err; if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, snode))) { onig_node_free(snode); goto mem_err; } } } r = onig_node_str_cat(snode, p, p + len); if (r != 0) goto err; } else { alt_num *= (n + 1); if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break; if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node); if (r < 0) goto mem_err; if (r == 1) { if (IS_NULL(root)) { top_root = prev_node; } else { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } root = NODE_CAR(prev_node); } else { /* r == 0 */ if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } } snode = NULL_NODE; } p += len; } if (p < end) { Node *srem; r = expand_case_fold_make_rem_string(&srem, p, end, reg); if (r != 0) goto mem_err; if (IS_NOT_NULL(prev_node) && IS_NULL(root)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(srem); onig_node_free(prev_node); goto mem_err; } } if (IS_NULL(root)) { prev_node = srem; } else { if (IS_NULL(onig_node_list_add(root, srem))) { onig_node_free(srem); goto mem_err; } } } /* ending */ top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node); swap_node(node, top_root); onig_node_free(top_root); return 0; mem_err: r = ONIGERR_MEMORY; err: onig_node_free(top_root); return r; }
1
207,280
win_redr_status(win_T *wp, int ignore_pum UNUSED) { int row; char_u *p; int len; int fillchar; int attr; int this_ru_col; static int busy = FALSE; // It's possible to get here recursively when 'statusline' (indirectly) // invokes ":redrawstatus". Simply ignore the call then. if (busy) return; busy = TRUE; row = statusline_row(wp); wp->w_redr_status = FALSE; if (wp->w_status_height == 0) { // no status line, can only be last window redraw_cmdline = TRUE; } else if (!redrawing() // don't update status line when popup menu is visible and may be // drawn over it, unless it will be redrawn later || (!ignore_pum && pum_visible())) { // Don't redraw right now, do it later. wp->w_redr_status = TRUE; } #ifdef FEAT_STL_OPT else if (*p_stl != NUL || *wp->w_p_stl != NUL) { // redraw custom status line redraw_custom_statusline(wp); } #endif else { fillchar = fillchar_status(&attr, wp); get_trans_bufname(wp->w_buffer); p = NameBuff; len = (int)STRLEN(p); if (bt_help(wp->w_buffer) #ifdef FEAT_QUICKFIX || wp->w_p_pvw #endif || bufIsChanged(wp->w_buffer) || wp->w_buffer->b_p_ro) *(p + len++) = ' '; if (bt_help(wp->w_buffer)) { STRCPY(p + len, _("[Help]")); len += (int)STRLEN(p + len); } #ifdef FEAT_QUICKFIX if (wp->w_p_pvw) { STRCPY(p + len, _("[Preview]")); len += (int)STRLEN(p + len); } #endif if (bufIsChanged(wp->w_buffer) #ifdef FEAT_TERMINAL && !bt_terminal(wp->w_buffer) #endif ) { STRCPY(p + len, "[+]"); len += 3; } if (wp->w_buffer->b_p_ro) { STRCPY(p + len, _("[RO]")); len += (int)STRLEN(p + len); } this_ru_col = ru_col - (Columns - wp->w_width); if (this_ru_col < (wp->w_width + 1) / 2) this_ru_col = (wp->w_width + 1) / 2; if (this_ru_col <= 1) { p = (char_u *)"<"; // No room for file name! len = 1; } else if (has_mbyte) { int clen = 0, i; // Count total number of display cells. clen = mb_string2cells(p, -1); // Find first character that will fit. // Going from start to end is much faster for DBCS. for (i = 0; p[i] != NUL && clen >= this_ru_col - 1; i += (*mb_ptr2len)(p + i)) clen -= (*mb_ptr2cells)(p + i); len = clen; if (i > 0) { p = p + i - 1; *p = '<'; ++len; } } else if (len > this_ru_col - 1) { p += len - (this_ru_col - 1); *p = '<'; len = this_ru_col - 1; } screen_puts(p, row, wp->w_wincol, attr); screen_fill(row, row + 1, len + wp->w_wincol, this_ru_col + wp->w_wincol, fillchar, fillchar, attr); if (get_keymap_str(wp, (char_u *)"<%s>", NameBuff, MAXPATHL) && (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1)) screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff) - 1 + wp->w_wincol), attr); #ifdef FEAT_CMDL_INFO win_redr_ruler(wp, TRUE, ignore_pum); #endif } /* * May need to draw the character below the vertical separator. */ if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing()) { if (stl_connected(wp)) fillchar = fillchar_status(&attr, wp); else fillchar = fillchar_vsep(&attr); screen_putchar(fillchar, row, W_ENDCOL(wp), attr); } busy = FALSE; }
1
359,415
DEFUN (clear_ip_bgp_peer_vpnv4_soft_in, clear_ip_bgp_peer_vpnv4_soft_in_cmd, "clear ip bgp A.B.C.D vpnv4 unicast soft in", CLEAR_STR IP_STR BGP_STR "BGP neighbor address to clear\n" "Address family\n" "Address Family Modifier\n" "Soft reconfig\n" "Soft reconfig inbound update\n") { return bgp_clear_vty (vty, NULL, AFI_IP, SAFI_MPLS_VPN, clear_peer, BGP_CLEAR_SOFT_IN, argv[0]); }
0
230,305
njs_array_prototype_push(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs, njs_index_t unused) { int64_t length; njs_int_t ret; njs_uint_t i; njs_array_t *array; njs_value_t *this; length = 0; this = njs_argument(args, 0); ret = njs_value_to_object(vm, this); if (njs_slow_path(ret != NJS_OK)) { return ret; } if (njs_is_fast_array(this)) { array = njs_array(this); if (nargs != 0) { ret = njs_array_expand(vm, array, 0, nargs); if (njs_slow_path(ret != NJS_OK)) { return ret; } for (i = 1; i < nargs; i++) { /* GC: njs_retain(&args[i]); */ array->start[array->length++] = args[i]; } } njs_set_number(&vm->retval, array->length); return NJS_OK; } ret = njs_object_length(vm, this, &length); if (njs_slow_path(ret == NJS_ERROR)) { return ret; } if (njs_slow_path((length + nargs - 1) > NJS_MAX_LENGTH)) { njs_type_error(vm, "Invalid length"); return NJS_ERROR; } for (i = 1; i < nargs; i++) { ret = njs_value_property_i64_set(vm, this, length++, &args[i]); if (njs_slow_path(ret == NJS_ERROR)) { return ret; } } ret = njs_object_length_set(vm, this, length); if (njs_slow_path(ret == NJS_ERROR)) { return ret; } njs_set_number(&vm->retval, length); return NJS_OK; }
0
197,973
crun_command_exec (struct crun_global_arguments *global_args, int argc, char **argv, libcrun_error_t *err) { int first_arg = 0, ret = 0; libcrun_context_t crun_context = { 0, }; cleanup_process_schema runtime_spec_schema_config_schema_process *process = NULL; struct libcrun_container_exec_options_s exec_opts; memset (&exec_opts, 0, sizeof (exec_opts)); exec_opts.struct_size = sizeof (exec_opts); crun_context.preserve_fds = 0; crun_context.listen_fds = 0; argp_parse (&run_argp, argc, argv, ARGP_IN_ORDER, &first_arg, &exec_options); crun_assert_n_args (argc - first_arg, exec_options.process ? 1 : 2, -1); ret = init_libcrun_context (&crun_context, argv[first_arg], global_args, err); if (UNLIKELY (ret < 0)) return ret; crun_context.detach = exec_options.detach; crun_context.console_socket = exec_options.console_socket; crun_context.pid_file = exec_options.pid_file; crun_context.preserve_fds = exec_options.preserve_fds; if (getenv ("LISTEN_FDS")) { crun_context.listen_fds = strtoll (getenv ("LISTEN_FDS"), NULL, 10); crun_context.preserve_fds += crun_context.listen_fds; } if (exec_options.process) exec_opts.path = exec_options.process; else { process = xmalloc0 (sizeof (*process)); int i; process->args_len = argc; process->args = xmalloc0 ((argc + 1) * sizeof (*process->args)); for (i = 0; i < argc - first_arg; i++) process->args[i] = xstrdup (argv[first_arg + i + 1]); process->args[i] = NULL; if (exec_options.cwd) process->cwd = exec_options.cwd; process->terminal = exec_options.tty; process->env = exec_options.env; process->env_len = exec_options.env_size; process->user = make_oci_process_user (exec_options.user); if (exec_options.process_label != NULL) process->selinux_label = exec_options.process_label; if (exec_options.apparmor != NULL) process->apparmor_profile = exec_options.apparmor; if (exec_options.cap_size > 0) { runtime_spec_schema_config_schema_process_capabilities *capabilities = xmalloc (sizeof (runtime_spec_schema_config_schema_process_capabilities)); capabilities->effective = exec_options.cap; capabilities->effective_len = exec_options.cap_size; capabilities->inheritable = dup_array (exec_options.cap, exec_options.cap_size); capabilities->inheritable_len = exec_options.cap_size; capabilities->bounding = dup_array (exec_options.cap, exec_options.cap_size); capabilities->bounding_len = exec_options.cap_size; capabilities->ambient = dup_array (exec_options.cap, exec_options.cap_size); capabilities->ambient_len = exec_options.cap_size; capabilities->permitted = dup_array (exec_options.cap, exec_options.cap_size); capabilities->permitted_len = exec_options.cap_size; process->capabilities = capabilities; } // noNewPriviledges will remain `false` if basespec has `false` unless specified // Default is always `true` in generated basespec config if (exec_options.no_new_privs) process->no_new_privileges = 1; exec_opts.process = process; } exec_opts.cgroup = exec_options.cgroup; return libcrun_container_exec_with_options (&crun_context, argv[first_arg], &exec_opts, err); }
1
262,077
explicit BoostedTreesCalculateBestGainsPerFeatureOp( OpKernelConstruction* const context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("max_splits", &max_splits_)); OP_REQUIRES_OK(context, context->GetAttr("num_features", &num_features_)); }
0
235,765
void Compute(OpKernelContext* ctx) override { const Tensor* hypothesis_indices; const Tensor* hypothesis_values; const Tensor* hypothesis_shape; const Tensor* truth_indices; const Tensor* truth_values; const Tensor* truth_shape; OP_REQUIRES_OK(ctx, ctx->input("hypothesis_indices", &hypothesis_indices)); OP_REQUIRES_OK(ctx, ctx->input("hypothesis_values", &hypothesis_values)); OP_REQUIRES_OK(ctx, ctx->input("hypothesis_shape", &hypothesis_shape)); OP_REQUIRES_OK(ctx, ctx->input("truth_indices", &truth_indices)); OP_REQUIRES_OK(ctx, ctx->input("truth_values", &truth_values)); OP_REQUIRES_OK(ctx, ctx->input("truth_shape", &truth_shape)); OP_REQUIRES_OK( ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values, *hypothesis_shape, *truth_indices, *truth_values, *truth_shape)); TensorShape hypothesis_st_shape; OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape( hypothesis_shape->vec<int64_t>().data(), hypothesis_shape->NumElements(), &hypothesis_st_shape)); TensorShape truth_st_shape; OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape( truth_shape->vec<int64_t>().data(), truth_shape->NumElements(), &truth_st_shape)); // Assume indices are sorted in row-major order. std::vector<int64_t> sorted_order(truth_st_shape.dims()); std::iota(sorted_order.begin(), sorted_order.end(), 0); sparse::SparseTensor hypothesis; OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create( *hypothesis_indices, *hypothesis_values, hypothesis_st_shape, sorted_order, &hypothesis)); sparse::SparseTensor truth; OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create( *truth_indices, *truth_values, truth_st_shape, sorted_order, &truth)); // Group dims 0, 1, ..., RANK - 1. The very last dim is assumed // to store the variable length sequences. std::vector<int64_t> group_dims(truth_st_shape.dims() - 1); std::iota(group_dims.begin(), group_dims.end(), 0); TensorShape output_shape; for (int d = 0; d < static_cast<int>(group_dims.size()); ++d) { output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d), truth_st_shape.dim_size(d))); } const auto output_elements = output_shape.num_elements(); OP_REQUIRES( ctx, output_elements > 0, errors::InvalidArgument("Got output shape ", output_shape.DebugString(), " which has 0 elements")); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output("output", output_shape, &output)); auto output_t = output->flat<float>(); output_t.setZero(); std::vector<int64_t> output_strides(output_shape.dims()); output_strides[output_shape.dims() - 1] = 1; for (int d = output_shape.dims() - 2; d >= 0; --d) { output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1); } auto hypothesis_grouper = hypothesis.group(group_dims); auto truth_grouper = truth.group(group_dims); auto hypothesis_iter = hypothesis_grouper.begin(); auto truth_iter = truth_grouper.begin(); auto cmp = std::equal_to<T>(); while (hypothesis_iter != hypothesis_grouper.end() && truth_iter != truth_grouper.end()) { sparse::Group truth_i = *truth_iter; sparse::Group hypothesis_j = *hypothesis_iter; std::vector<int64_t> g_truth = truth_i.group(); std::vector<int64_t> g_hypothesis = hypothesis_j.group(); auto truth_seq = truth_i.values<T>(); auto hypothesis_seq = hypothesis_j.values<T>(); if (g_truth == g_hypothesis) { auto loc = std::inner_product(g_truth.begin(), g_truth.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, 0 <= loc && loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require writing to outside of " "the buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = gtl::LevenshteinDistance<T>(truth_seq, hypothesis_seq, cmp); if (normalize_) output_t(loc) /= truth_seq.size(); ++hypothesis_iter; ++truth_iter; } else if (g_truth > g_hypothesis) { // zero-length truth auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, 0 <= loc && loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require writing to outside of " "the buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = hypothesis_seq.size(); if (normalize_ && output_t(loc) != 0.0f) { output_t(loc) = std::numeric_limits<float>::infinity(); } ++hypothesis_iter; } else { // zero-length hypothesis auto loc = std::inner_product(g_truth.begin(), g_truth.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, 0 <= loc && loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require writing to outside of " "the buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = (normalize_) ? 1.0 : truth_seq.size(); ++truth_iter; } } while (hypothesis_iter != hypothesis_grouper.end()) { // zero-length truths sparse::Group hypothesis_j = *hypothesis_iter; std::vector<int64_t> g_hypothesis = hypothesis_j.group(); auto hypothesis_seq = hypothesis_j.values<T>(); auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, 0 <= loc && loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require writing to outside of the " "buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = hypothesis_seq.size(); if (normalize_ && output_t(loc) != 0.0f) { output_t(loc) = std::numeric_limits<float>::infinity(); } ++hypothesis_iter; } while (truth_iter != truth_grouper.end()) { // missing hypotheses sparse::Group truth_i = *truth_iter; std::vector<int64_t> g_truth = truth_i.group(); auto truth_seq = truth_i.values<T>(); auto loc = std::inner_product(g_truth.begin(), g_truth.end(), output_strides.begin(), int64_t{0}); OP_REQUIRES( ctx, 0 <= loc && loc < output_elements, errors::Internal("Got an inner product ", loc, " which would require writing to outside of the " "buffer for the output tensor (max elements ", output_elements, ")")); output_t(loc) = (normalize_) ? 1.0 : truth_seq.size(); ++truth_iter; } }
0
369,136
static clockid_t io_timeout_get_clock(struct io_timeout_data *data) { switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) { case IORING_TIMEOUT_BOOTTIME: return CLOCK_BOOTTIME; case IORING_TIMEOUT_REALTIME: return CLOCK_REALTIME; default: /* can't happen, vetted at prep time */ WARN_ON_ONCE(1); fallthrough; case 0: return CLOCK_MONOTONIC; }
0
218,746
static void XDrawTriangleEast(Display *display,const XWindowInfo *window_info, const XWidgetInfo *triangle_info) { int x1, x2, x3, y1, y2, y3; unsigned int bevel_width; XFontStruct *font_info; XPoint points[4]; /* Draw triangle matte. */ x1=triangle_info->x; y1=triangle_info->y; x2=triangle_info->x+triangle_info->width; y2=triangle_info->y+(triangle_info->height >> 1); x3=triangle_info->x; y3=triangle_info->y+triangle_info->height; bevel_width=triangle_info->bevel_width; points[0].x=x1; points[0].y=y1; points[1].x=x2; points[1].y=y2; points[2].x=x3; points[2].y=y3; XSetMatteColor(display,window_info,triangle_info->raised); (void) XFillPolygon(display,window_info->id,window_info->widget_context, points,3,Complex,CoordModeOrigin); /* Draw bottom bevel. */ points[0].x=x2; points[0].y=y2; points[1].x=x3; points[1].y=y3; points[2].x=x3-bevel_width; points[2].y=y3+bevel_width; points[3].x=x2+bevel_width; points[3].y=y2; XSetBevelColor(display,window_info,!triangle_info->raised); (void) XFillPolygon(display,window_info->id,window_info->widget_context, points,4,Complex,CoordModeOrigin); /* Draw Left bevel. */ points[0].x=x3; points[0].y=y3; points[1].x=x1; points[1].y=y1; points[2].x=x1-bevel_width+1; points[2].y=y1-bevel_width; points[3].x=x3-bevel_width+1; points[3].y=y3+bevel_width; XSetBevelColor(display,window_info,triangle_info->raised); (void) XFillPolygon(display,window_info->id,window_info->widget_context, points,4,Complex,CoordModeOrigin); /* Draw top bevel. */ points[0].x=x1; points[0].y=y1; points[1].x=x2; points[1].y=y2; points[2].x=x2+bevel_width; points[2].y=y2; points[3].x=x1-bevel_width; points[3].y=y1-bevel_width; (void) XFillPolygon(display,window_info->id,window_info->widget_context, points,4,Complex,CoordModeOrigin); (void) XSetFillStyle(display,window_info->widget_context,FillSolid); if (triangle_info->text == (char *) NULL) return; /* Write label to right of triangle. */ font_info=window_info->font_info; XSetTextColor(display,window_info,MagickTrue); x1=triangle_info->x+triangle_info->width+triangle_info->bevel_width+ (QuantumMargin >> 1); y1=triangle_info->y+((triangle_info->height- (font_info->ascent+font_info->descent)) >> 1)+font_info->ascent; (void) XDrawString(display,window_info->id,window_info->widget_context,x1,y1, triangle_info->text,Extent(triangle_info->text)); }
0
281,068
xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir, struct flow_cache_object *old_obj, void *ctx) { struct xfrm_policy *pol; if (old_obj) xfrm_pol_put(container_of(old_obj, struct xfrm_policy, flo)); pol = __xfrm_policy_lookup(net, fl, family, flow_to_policy_dir(dir)); if (IS_ERR_OR_NULL(pol)) return ERR_CAST(pol); /* Resolver returns two references: * one for cache and one for caller of flow_cache_lookup() */ xfrm_pol_hold(pol); return &pol->flo; }
0
332,379
swapchar(int op_type, pos_T *pos) { int c; int nc; c = gchar_pos(pos); // Only do rot13 encoding for ASCII characters. if (c >= 0x80 && op_type == OP_ROT13) return FALSE; if (op_type == OP_UPPER && c == 0xdf && (enc_latin1like || STRCMP(p_enc, "iso-8859-2") == 0)) { pos_T sp = curwin->w_cursor; // Special handling of German sharp s: change to "SS". curwin->w_cursor = *pos; del_char(FALSE); ins_char('S'); ins_char('S'); curwin->w_cursor = sp; inc(pos); } if (enc_dbcs != 0 && c >= 0x100) // No lower/uppercase letter return FALSE; nc = c; if (MB_ISLOWER(c)) { if (op_type == OP_ROT13) nc = ROT13(c, 'a'); else if (op_type != OP_LOWER) nc = MB_TOUPPER(c); } else if (MB_ISUPPER(c)) { if (op_type == OP_ROT13) nc = ROT13(c, 'A'); else if (op_type != OP_UPPER) nc = MB_TOLOWER(c); } if (nc != c) { if (enc_utf8 && (c >= 0x80 || nc >= 0x80)) { pos_T sp = curwin->w_cursor; curwin->w_cursor = *pos; // don't use del_char(), it also removes composing chars del_bytes(utf_ptr2len(ml_get_cursor()), FALSE, FALSE); ins_char(nc); curwin->w_cursor = sp; } else PBYTE(*pos, nc); return TRUE; } return FALSE; }
0
225,848
GF_Err gnra_box_read(GF_Box *s, GF_BitStream *bs) { return GF_OK; }
0
300,761
static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags, bool kern) { struct sock *new_sk, *sk = sock->sk; struct tipc_sock *new_tsock; struct msghdr m = {NULL,}; struct tipc_msg *msg; struct sk_buff *buf; long timeo; int res; lock_sock(sk); if (sk->sk_state != TIPC_LISTEN) { res = -EINVAL; goto exit; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); res = tipc_wait_for_accept(sock, timeo); if (res) goto exit; buf = skb_peek(&sk->sk_receive_queue); res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, kern); if (res) goto exit; security_sk_clone(sock->sk, new_sock->sk); new_sk = new_sock->sk; new_tsock = tipc_sk(new_sk); msg = buf_msg(buf); /* we lock on new_sk; but lockdep sees the lock on sk */ lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING); /* * Reject any stray messages received by new socket * before the socket lock was taken (very, very unlikely) */ tsk_rej_rx_queue(new_sk, TIPC_ERR_NO_PORT); /* Connect new socket to it's peer */ tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg)); tsk_set_importance(new_sk, msg_importance(msg)); if (msg_named(msg)) { new_tsock->conn_addrtype = TIPC_SERVICE_ADDR; msg_set_nametype(&new_tsock->phdr, msg_nametype(msg)); msg_set_nameinst(&new_tsock->phdr, msg_nameinst(msg)); } /* * Respond to 'SYN-' by discarding it & returning 'ACK'. * Respond to 'SYN+' by queuing it on new socket & returning 'ACK'. */ if (!msg_data_sz(msg)) { tsk_advance_rx_queue(sk); } else { __skb_dequeue(&sk->sk_receive_queue); __skb_queue_head(&new_sk->sk_receive_queue, buf); skb_set_owner_r(buf, new_sk); } __tipc_sendstream(new_sock, &m, 0); release_sock(new_sk); exit: release_sock(sk); return res; }
0
482,469
compileSwapDots(const FileInfo *file, CharsString *source, CharsString *dest) { int k = 0; int kk = 0; CharsString dotsSource; CharsString dotsDest; dest->length = 0; dotsSource.length = 0; while (k <= source->length) { if (source->chars[k] != ',' && k != source->length) dotsSource.chars[dotsSource.length++] = source->chars[k]; else { if (!parseDots(file, &dotsDest, &dotsSource)) return 0; dest->chars[dest->length++] = dotsDest.length + 1; for (kk = 0; kk < dotsDest.length; kk++) dest->chars[dest->length++] = dotsDest.chars[kk]; dotsSource.length = 0; } k++; } return 1; }
0
308,182
static u64 fastrpc_get_payload_size(struct fastrpc_invoke_ctx *ctx, int metalen) { u64 size = 0; int i; size = ALIGN(metalen, FASTRPC_ALIGN); for (i = 0; i < ctx->nscalars; i++) { if (ctx->args[i].fd == 0 || ctx->args[i].fd == -1) { if (ctx->olaps[i].offset == 0) size = ALIGN(size, FASTRPC_ALIGN); size += (ctx->olaps[i].mend - ctx->olaps[i].mstart); } } return size; }
0
312,409
parse_efm_option(char_u *efm) { efm_T *fmt_ptr = NULL; efm_T *fmt_first = NULL; efm_T *fmt_last = NULL; char_u *fmtstr = NULL; int len; int sz; // Each part of the format string is copied and modified from errorformat // to regex prog. Only a few % characters are allowed. // Get some space to modify the format string into. sz = efm_regpat_bufsz(efm); if ((fmtstr = alloc_id(sz, aid_qf_efm_fmtstr)) == NULL) goto parse_efm_error; while (efm[0] != NUL) { // Allocate a new eformat structure and put it at the end of the list fmt_ptr = ALLOC_CLEAR_ONE_ID(efm_T, aid_qf_efm_fmtpart); if (fmt_ptr == NULL) goto parse_efm_error; if (fmt_first == NULL) // first one fmt_first = fmt_ptr; else fmt_last->next = fmt_ptr; fmt_last = fmt_ptr; // Isolate one part in the 'errorformat' option len = efm_option_part_len(efm); if (efm_to_regpat(efm, len, fmt_ptr, fmtstr) == FAIL) goto parse_efm_error; if ((fmt_ptr->prog = vim_regcomp(fmtstr, RE_MAGIC + RE_STRING)) == NULL) goto parse_efm_error; // Advance to next part efm = skip_to_option_part(efm + len); // skip comma and spaces } if (fmt_first == NULL) // nothing found emsg(_(e_errorformat_contains_no_pattern)); goto parse_efm_end; parse_efm_error: free_efm_list(&fmt_first); parse_efm_end: vim_free(fmtstr); return fmt_first; }
0
259,254
static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (c->fc->nb_streams >= 1) { AVStream *const st = c->fc->streams[c->fc->nb_streams - 1]; FFStream *const sti = ffstream(st); AVCodecParameters *par = st->codecpar; if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') && par->codec_id == AV_CODEC_ID_H264 && atom.size > 11) { int cid; avio_skip(pb, 10); cid = avio_rb16(pb); /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */ if (cid == 0xd4d || cid == 0xd4e) par->width = 1440; return 0; } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') || par->codec_tag == MKTAG('A', 'V', 'j', '2') || par->codec_tag == MKTAG('A', 'V', 'd', 'n')) && atom.size >= 24) { int num, den; avio_skip(pb, 12); num = avio_rb32(pb); den = avio_rb32(pb); if (num <= 0 || den <= 0) return 0; switch (avio_rb32(pb)) { case 2: if (den >= INT_MAX / 2) return 0; den *= 2; case 1: sti->display_aspect_ratio = (AVRational){ num, den }; default: return 0; } } } return mov_read_avid(c, pb, atom); }
0
424,966
static void iwl_trans_pcie_release_nic_access(struct iwl_trans *trans, unsigned long *flags) { struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); lockdep_assert_held(&trans_pcie->reg_lock); /* * Fool sparse by faking we acquiring the lock - sparse will * track nic_access anyway. */ __acquire(&trans_pcie->reg_lock); if (trans_pcie->cmd_hold_nic_awake) goto out; __iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL, BIT(trans->trans_cfg->csr->flag_mac_access_req)); /* * Above we read the CSR_GP_CNTRL register, which will flush * any previous writes, but we need the write that clears the * MAC_ACCESS_REQ bit to be performed before any other writes * scheduled on different CPUs (after we drop reg_lock). */ out: spin_unlock_irqrestore(&trans_pcie->reg_lock, *flags); }
0
237,824
static int acurite_606_decode(r_device *decoder, bitbuffer_t *bitbuffer) { data_t *data; uint8_t *b; int row; int16_t temp_raw; // temperature as read from the data packet float temp_c; // temperature in C int battery_ok; // the battery status: 1 is good, 0 is low int sensor_id; // the sensor ID - basically a random number that gets reset whenever the battery is removed row = bitbuffer_find_repeated_row(bitbuffer, 3, 32); // expected are 6 rows if (row < 0) return DECODE_ABORT_EARLY; if (bitbuffer->bits_per_row[row] > 33) return DECODE_ABORT_LENGTH; b = bitbuffer->bb[row]; if (b[4] != 0) return DECODE_FAIL_SANITY; // reject all blank messages if (b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0) return DECODE_FAIL_SANITY; // calculate the checksum and only continue if we have a matching checksum uint8_t chk = lfsr_digest8(b, 3, 0x98, 0xf1); if (chk != b[3]) return DECODE_FAIL_MIC; // Processing the temperature: // Upper 4 bits are stored in nibble 1, lower 8 bits are stored in nibble 2 // upper 4 bits of nibble 1 are reserved for other usages (e.g. battery status) sensor_id = b[0]; battery_ok = (b[1] & 0x80) >> 7; temp_raw = (int16_t)((b[1] << 12) | (b[2] << 4)); temp_raw = temp_raw >> 4; temp_c = temp_raw * 0.1f; /* clang-format off */ data = data_make( "model", "", DATA_STRING, "Acurite-606TX", "id", "", DATA_INT, sensor_id, "battery_ok", "Battery", DATA_INT, battery_ok, "temperature_C", "Temperature", DATA_FORMAT, "%.1f C", DATA_DOUBLE, temp_c, "mic", "Integrity", DATA_STRING, "CHECKSUM", NULL); /* clang-format on */ decoder_output_data(decoder, data); return 1; }
0
384,201
static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data, struct nft_data_desc *desc, const struct nlattr *nla) { u8 genmask = nft_genmask_next(ctx->net); struct nlattr *tb[NFTA_VERDICT_MAX + 1]; struct nft_chain *chain; int err; err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla, nft_verdict_policy, NULL); if (err < 0) return err; if (!tb[NFTA_VERDICT_CODE]) return -EINVAL; data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE])); switch (data->verdict.code) { default: switch (data->verdict.code & NF_VERDICT_MASK) { case NF_ACCEPT: case NF_DROP: case NF_QUEUE: break; default: return -EINVAL; } fallthrough; case NFT_CONTINUE: case NFT_BREAK: case NFT_RETURN: break; case NFT_JUMP: case NFT_GOTO: if (tb[NFTA_VERDICT_CHAIN]) { chain = nft_chain_lookup(ctx->net, ctx->table, tb[NFTA_VERDICT_CHAIN], genmask); } else if (tb[NFTA_VERDICT_CHAIN_ID]) { chain = nft_chain_lookup_byid(ctx->net, ctx->table, tb[NFTA_VERDICT_CHAIN_ID]); if (IS_ERR(chain)) return PTR_ERR(chain); } else { return -EINVAL; } if (IS_ERR(chain)) return PTR_ERR(chain); if (nft_is_base_chain(chain)) return -EOPNOTSUPP; if (nft_chain_is_bound(chain)) return -EINVAL; if (desc->flags & NFT_DATA_DESC_SETELEM && chain->flags & NFT_CHAIN_BINDING) return -EINVAL; chain->use++; data->verdict.chain = chain; break; } desc->len = sizeof(data->verdict); return 0; }
0
344,253
lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) { if (y < 0) { /* shift right? */ if (y <= -NBITS) return 0; else return intop(>>, x, -y); } else { /* shift left */ if (y >= NBITS) return 0; else return intop(<<, x, y); } }
0
270,772
static unsigned char to_hexa(unsigned char c) { if (c < 10) c += '0'; else c += 'a' - 10; return c; }
0
238,812
set_csearch_until(int t_cmd) { last_t_cmd = t_cmd; }
0
289,249
static int snd_pcm_oss_make_ready_locked(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime; int err; runtime = substream->runtime; if (runtime->oss.params) { err = snd_pcm_oss_change_params_locked(substream); if (err < 0) return err; } if (runtime->oss.prepare) { err = snd_pcm_oss_prepare(substream); if (err < 0) return err; } return 0; }
0
175,699
virtual bool cellular_enabled() const { return false; }
0
390,616
_XkbSetDeviceInfoCheck(ClientPtr client, DeviceIntPtr dev, xkbSetDeviceInfoReq *stuff) { unsigned change; char *wire; xkbExtensionDeviceNotify ed; bzero((char *)&ed,SIZEOF(xkbExtensionDeviceNotify)); ed.deviceID= dev->id; wire= (char *)&stuff[1]; if (change&XkbXI_ButtonActionsMask) { int nBtns,sz,i; XkbAction * acts; DeviceIntPtr kbd; nBtns= dev->button->numButtons; acts= dev->button->xkb_acts; if (acts==NULL) { acts= _XkbTypedCalloc(nBtns,XkbAction); if (!acts) return BadAlloc; dev->button->xkb_acts= acts; } sz= stuff->nBtns*SIZEOF(xkbActionWireDesc); memcpy((char *)&acts[stuff->firstBtn],(char *)wire,sz); wire+= sz; ed.reason|= XkbXI_ButtonActionsMask; ed.firstBtn= stuff->firstBtn; ed.nBtns= stuff->nBtns; if (dev->key) kbd= dev; else kbd= inputInfo.keyboard; acts= &dev->button->xkb_acts[stuff->firstBtn]; for (i=0;i<stuff->nBtns;i++,acts++) { if (acts->type!=XkbSA_NoAction) XkbSetActionKeyMods(kbd->key->xkbInfo->desc,acts,0); } } if (stuff->change&XkbXI_IndicatorsMask) { int status= Success; wire= SetDeviceIndicators(wire,dev,change,stuff->nDeviceLedFBs, &status,client,&ed); if (status!=Success) return status; } if ((stuff->change)&&(ed.reason)) XkbSendExtensionDeviceNotify(dev,client,&ed); return Success; }
0
231,770
TEST_F(QuicUnencryptedServerTransportTest, TestBadPacketProtectionLevel) { // Version negotiation has no protection level. auto packet = VersionNegotiationPacketBuilder( *clientConnectionId /* src */, getTestConnectionId(1) /* dest */, {QuicVersion::MVFST}) .buildPacket(); EXPECT_CALL(*transportInfoCb_, onPacketDropped(_)); deliverData(packet.second->clone()); }
0
317,049
static int smack_socket_post_create(struct socket *sock, int family, int type, int protocol, int kern) { struct socket_smack *ssp; if (sock->sk == NULL) return 0; /* * Sockets created by kernel threads receive web label. */ if (unlikely(current->flags & PF_KTHREAD)) { ssp = sock->sk->sk_security; ssp->smk_in = &smack_known_web; ssp->smk_out = &smack_known_web; } if (family != PF_INET) return 0; /* * Set the outbound netlbl. */ return smack_netlbl_add(sock->sk); }
0
500,042
valid_cksumtype(krb5_cksumtype ctype) { if (!krb5_loaded) load_krb5_dll(); if ( p_valid_cksumtype ) return(p_valid_cksumtype(ctype)); else return KRB5KRB_ERR_GENERIC; }
0
446,104
static int atusb_command(struct atusb *atusb, u8 cmd, u8 arg) { struct usb_device *usb_dev = atusb->usb_dev; dev_dbg(&usb_dev->dev, "%s: cmd = 0x%x\n", __func__, cmd); return atusb_control_msg(atusb, usb_sndctrlpipe(usb_dev, 0), cmd, ATUSB_REQ_TO_DEV, arg, 0, NULL, 0, 1000); }
0
463,074
static void sungem_mmio_rxdma_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { SunGEMState *s = opaque; if (!(addr <= 0x28) && !(addr >= 0x100 && addr <= 0x120)) { qemu_log_mask(LOG_GUEST_ERROR, "Write to unknown RXDMA register 0x%"HWADDR_PRIx"\n", addr); return; } trace_sungem_mmio_rxdma_write(addr, val); /* Pre-write filter */ switch (addr) { /* Read only registers */ case RXDMA_DONE: case RXDMA_PCNT: case RXDMA_SMACHINE: case RXDMA_DPLOW: case RXDMA_DPHI: case RXDMA_FSZ: case RXDMA_FTAG: return; /* No actual write */ } s->rxdmaregs[addr >> 2] = val; /* Post write action */ switch (addr) { case RXDMA_KICK: trace_sungem_rx_kick(val); break; case RXDMA_CFG: sungem_update_masks(s); if ((s->macregs[MAC_RXCFG >> 2] & MAC_RXCFG_ENAB) != 0 && (s->rxdmaregs[RXDMA_CFG >> 2] & RXDMA_CFG_ENABLE) != 0) { qemu_flush_queued_packets(qemu_get_queue(s->nic)); } break; } }
0
439,126
static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, pixels_length, quantum; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) memset(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); if (sun_info.maplength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth != 1) && (sun_info.depth != 8) && (sun_info.depth != 24) && (sun_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (image->colors == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) { sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) { sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) { sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum(sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); break; } default: break; } image->matte=sun_info.depth == 32 ? MagickTrue : MagickFalse; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (sun_info.length == 0) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); number_pixels=(MagickSizeType) (image->columns*image->rows); if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8UL*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (HeapOverflowSanityCheck(sun_info.width,sun_info.depth) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; if (sun_info.length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); sun_data=(unsigned char *) AcquireQuantumMemory(sun_info.length, sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } quantum=sun_info.depth == 1 ? 15 : 7; bytes_per_line+=quantum; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+quantum)) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } bytes_per_line>>=4; if (HeapOverflowSanityCheck(height,bytes_per_line) != MagickFalse) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } pixels_length=height*bytes_per_line; sun_pixels=(unsigned char *) AcquireQuantumMemory(pixels_length+image->rows, sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(sun_pixels,0,(pixels_length+image->rows)* sizeof(*sun_pixels)); if (sun_info.type == RT_ENCODED) { status=DecodeImage(sun_data,sun_info.length,sun_pixels,pixels_length); if (status == MagickFalse) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } else { if (sun_info.length > pixels_length) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } (void) memcpy(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) SetPixelIndex(indexes+x+7-bit,((*p) & (0x01 << bit) ? 0x00 : 0x01)); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) SetPixelIndex(indexes+x+7-bit,(*p) & (0x01 << bit) ? 0x00 : 0x01); p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,ConstrainColormapIndex(image,*p)); p++; } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->matte != MagickFalse) bytes_per_pixel++; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (sun_info.type == RT_STANDARD) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); } else { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); } if (image->colors != 0) { SetPixelRed(q,image->colormap[(ssize_t) GetPixelRed(q)].red); SetPixelGreen(q,image->colormap[(ssize_t) GetPixelGreen(q)].green); SetPixelBlue(q,image->colormap[(ssize_t) GetPixelBlue(q)].blue); } q++; } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
0
462,323
status_add_symbol_id(ushort * idlist, int nid, ushort new_id) { int i; ushort *idp; ushort t1, t2; for (i = 0, idp = idlist; i < nid; i++) if (new_id <= *idp) break; if (new_id == *idp) /* duplicate item */ return nid; /* insert new_id in front of *idp */ for (t1 = new_id; i < nid; i++) { t2 = *idp; *idp++ = t1; t1 = t2; } *idp = t1; return nid + 1; }
0
508,300
static bool not_null_fields_have_null_values(TABLE *table) { Field **orig_field= table->field; Field **filled_field= table->field_to_fill(); if (filled_field != orig_field) { THD *thd=table->in_use; for (uint i=0; i < table->s->fields; i++) { Field *of= orig_field[i]; Field *ff= filled_field[i]; if (ff != of) { // copy after-update flags to of, copy before-update flags to ff swap_variables(uint32, of->flags, ff->flags); if (ff->is_real_null()) { ff->set_notnull(); // for next row WHERE condition in UPDATE if (convert_null_to_field_value_or_error(of) || thd->is_error()) return true; } } } } return false; }
0
252,442
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); }
0
244,150
GF_Err sgpd_box_read(GF_Box *s, GF_BitStream *bs) { u32 entry_count; GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s; ISOM_DECREASE_SIZE(p, 8); p->grouping_type = gf_bs_read_u32(bs); if (p->version>=1) { ISOM_DECREASE_SIZE(p, 4); p->default_length = gf_bs_read_u32(bs); } if (p->version>=2) { ISOM_DECREASE_SIZE(p, 4); p->default_description_index = gf_bs_read_u32(bs); } entry_count = gf_bs_read_u32(bs); if (entry_count>p->size) return GF_ISOM_INVALID_FILE; while (entry_count) { void *ptr; u32 parsed_bytes=0; u32 size = p->default_length; if ((p->version>=1) && !size) { size = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(p, 4); } ptr = sgpd_parse_entry(p->grouping_type, bs, (s32) p->size, size, &parsed_bytes); //don't return an error, just stop parsing so that we skip over the sgpd box if (!ptr) return GF_OK; gf_list_add(p->group_descriptions, ptr); ISOM_DECREASE_SIZE(p, parsed_bytes); entry_count--; } return GF_OK; }
0
218,761
MagickExport void XColorBrowserWidget(Display *display,XWindows *windows, const char *action,char *reply) { #define CancelButtonText "Cancel" #define ColornameText "Name:" #define ColorPatternText "Pattern:" #define GrabButtonText "Grab" #define ResetButtonText "Reset" char **colorlist, primary_selection[MaxTextExtent], reset_pattern[MaxTextExtent], text[MaxTextExtent]; ExceptionInfo *exception; int x, y; int i; static char glob_pattern[MaxTextExtent] = "*"; static MagickStatusType mask = (MagickStatusType) (CWWidth | CWHeight | CWX | CWY); Status status; unsigned int height, text_width, visible_colors, width; size_t colors, delay, state; XColor color; XEvent event; XFontStruct *font_info; XTextProperty window_name; XWidgetInfo action_info, cancel_info, expose_info, grab_info, list_info, mode_info, north_info, reply_info, reset_info, scroll_info, selection_info, slider_info, south_info, text_info; XWindowChanges window_changes; /* Get color list and sort in ascending order. */ assert(display != (Display *) NULL); assert(windows != (XWindows *) NULL); assert(action != (char *) NULL); assert(reply != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",action); XSetCursorState(display,windows,MagickTrue); XCheckRefreshWindows(display,windows); (void) CopyMagickString(reset_pattern,"*",MaxTextExtent); exception=AcquireExceptionInfo(); colorlist=GetColorList(glob_pattern,&colors,exception); if (colorlist == (char **) NULL) { /* Pattern failed, obtain all the colors. */ (void) CopyMagickString(glob_pattern,"*",MaxTextExtent); colorlist=GetColorList(glob_pattern,&colors,exception); if (colorlist == (char **) NULL) { XNoticeWidget(display,windows,"Unable to obtain colors names:", glob_pattern); (void) XDialogWidget(display,windows,action,"Enter color name:", reply); return; } } /* Determine Color Browser widget attributes. */ font_info=windows->widget.font_info; text_width=0; for (i=0; i < (int) colors; i++) if (WidgetTextWidth(font_info,colorlist[i]) > text_width) text_width=WidgetTextWidth(font_info,colorlist[i]); width=WidgetTextWidth(font_info,(char *) action); if (WidgetTextWidth(font_info,CancelButtonText) > width) width=WidgetTextWidth(font_info,CancelButtonText); if (WidgetTextWidth(font_info,ResetButtonText) > width) width=WidgetTextWidth(font_info,ResetButtonText); if (WidgetTextWidth(font_info,GrabButtonText) > width) width=WidgetTextWidth(font_info,GrabButtonText); width+=QuantumMargin; if (WidgetTextWidth(font_info,ColorPatternText) > width) width=WidgetTextWidth(font_info,ColorPatternText); if (WidgetTextWidth(font_info,ColornameText) > width) width=WidgetTextWidth(font_info,ColornameText); height=(unsigned int) (font_info->ascent+font_info->descent); /* Position Color Browser widget. */ windows->widget.width=(unsigned int) (width+MagickMin((int) text_width,(int) MaxTextWidth)+6*QuantumMargin); windows->widget.min_width=(unsigned int) (width+MinTextWidth+4*QuantumMargin); if (windows->widget.width < windows->widget.min_width) windows->widget.width=windows->widget.min_width; windows->widget.height=(unsigned int) ((81*height) >> 2)+((13*QuantumMargin) >> 1)+4; windows->widget.min_height=(unsigned int) (((23*height) >> 1)+((13*QuantumMargin) >> 1)+4); if (windows->widget.height < windows->widget.min_height) windows->widget.height=windows->widget.min_height; XConstrainWindowPosition(display,&windows->widget); /* Map Color Browser widget. */ (void) CopyMagickString(windows->widget.name,"Browse and Select a Color", MaxTextExtent); status=XStringListToTextProperty(&windows->widget.name,1,&window_name); if (status != False) { XSetWMName(display,windows->widget.id,&window_name); XSetWMIconName(display,windows->widget.id,&window_name); (void) XFree((void *) window_name.value); } window_changes.width=(int) windows->widget.width; window_changes.height=(int) windows->widget.height; window_changes.x=windows->widget.x; window_changes.y=windows->widget.y; (void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen, mask,&window_changes); (void) XMapRaised(display,windows->widget.id); windows->widget.mapped=MagickFalse; /* Respond to X events. */ XGetWidgetInfo((char *) NULL,&mode_info); XGetWidgetInfo((char *) NULL,&slider_info); XGetWidgetInfo((char *) NULL,&north_info); XGetWidgetInfo((char *) NULL,&south_info); XGetWidgetInfo((char *) NULL,&expose_info); XGetWidgetInfo((char *) NULL,&selection_info); visible_colors=0; delay=SuspendTime << 2; state=UpdateConfigurationState; do { if (state & UpdateConfigurationState) { int id; /* Initialize button information. */ XGetWidgetInfo(CancelButtonText,&cancel_info); cancel_info.width=width; cancel_info.height=(unsigned int) ((3*height) >> 1); cancel_info.x=(int) (windows->widget.width-cancel_info.width-QuantumMargin-2); cancel_info.y=(int) (windows->widget.height-cancel_info.height-QuantumMargin); XGetWidgetInfo(action,&action_info); action_info.width=width; action_info.height=(unsigned int) ((3*height) >> 1); action_info.x=cancel_info.x-(cancel_info.width+(QuantumMargin >> 1)+ (action_info.bevel_width << 1)); action_info.y=cancel_info.y; XGetWidgetInfo(GrabButtonText,&grab_info); grab_info.width=width; grab_info.height=(unsigned int) ((3*height) >> 1); grab_info.x=QuantumMargin; grab_info.y=((5*QuantumMargin) >> 1)+height; XGetWidgetInfo(ResetButtonText,&reset_info); reset_info.width=width; reset_info.height=(unsigned int) ((3*height) >> 1); reset_info.x=QuantumMargin; reset_info.y=grab_info.y+grab_info.height+QuantumMargin; /* Initialize reply information. */ XGetWidgetInfo(reply,&reply_info); reply_info.raised=MagickFalse; reply_info.bevel_width--; reply_info.width=windows->widget.width-width-((6*QuantumMargin) >> 1); reply_info.height=height << 1; reply_info.x=(int) (width+(QuantumMargin << 1)); reply_info.y=action_info.y-reply_info.height-QuantumMargin; /* Initialize mode information. */ XGetWidgetInfo((char *) NULL,&mode_info); mode_info.active=MagickTrue; mode_info.bevel_width=0; mode_info.width=(unsigned int) (action_info.x-(QuantumMargin << 1)); mode_info.height=action_info.height; mode_info.x=QuantumMargin; mode_info.y=action_info.y; /* Initialize scroll information. */ XGetWidgetInfo((char *) NULL,&scroll_info); scroll_info.bevel_width--; scroll_info.width=height; scroll_info.height=(unsigned int) (reply_info.y-grab_info.y- (QuantumMargin >> 1)); scroll_info.x=reply_info.x+(reply_info.width-scroll_info.width); scroll_info.y=grab_info.y-reply_info.bevel_width; scroll_info.raised=MagickFalse; scroll_info.trough=MagickTrue; north_info=scroll_info; north_info.raised=MagickTrue; north_info.width-=(north_info.bevel_width << 1); north_info.height=north_info.width-1; north_info.x+=north_info.bevel_width; north_info.y+=north_info.bevel_width; south_info=north_info; south_info.y=scroll_info.y+scroll_info.height-scroll_info.bevel_width- south_info.height; id=slider_info.id; slider_info=north_info; slider_info.id=id; slider_info.width-=2; slider_info.min_y=north_info.y+north_info.height+north_info.bevel_width+ slider_info.bevel_width+2; slider_info.height=scroll_info.height-((slider_info.min_y- scroll_info.y+1) << 1)+4; visible_colors=(unsigned int) (scroll_info.height* PerceptibleReciprocal((double) height+(height >> 3))); if (colors > visible_colors) slider_info.height=(unsigned int) ((visible_colors* slider_info.height)/colors); slider_info.max_y=south_info.y-south_info.bevel_width- slider_info.bevel_width-2; slider_info.x=scroll_info.x+slider_info.bevel_width+1; slider_info.y=slider_info.min_y; expose_info=scroll_info; expose_info.y=slider_info.y; /* Initialize list information. */ XGetWidgetInfo((char *) NULL,&list_info); list_info.raised=MagickFalse; list_info.bevel_width--; list_info.width=(unsigned int) (scroll_info.x-reply_info.x-(QuantumMargin >> 1)); list_info.height=scroll_info.height; list_info.x=reply_info.x; list_info.y=scroll_info.y; if (windows->widget.mapped == MagickFalse) state|=JumpListState; /* Initialize text information. */ *text='\0'; XGetWidgetInfo(text,&text_info); text_info.center=MagickFalse; text_info.width=reply_info.width; text_info.height=height; text_info.x=list_info.x-(QuantumMargin >> 1); text_info.y=QuantumMargin; /* Initialize selection information. */ XGetWidgetInfo((char *) NULL,&selection_info); selection_info.center=MagickFalse; selection_info.width=list_info.width; selection_info.height=(unsigned int) ((9*height) >> 3); selection_info.x=list_info.x; state&=(~UpdateConfigurationState); } if (state & RedrawWidgetState) { /* Redraw Color Browser window. */ x=QuantumMargin; y=text_info.y+((text_info.height-height) >> 1)+font_info->ascent; (void) XDrawString(display,windows->widget.id, windows->widget.annotate_context,x,y,ColorPatternText, Extent(ColorPatternText)); (void) CopyMagickString(text_info.text,glob_pattern,MaxTextExtent); XDrawWidgetText(display,&windows->widget,&text_info); XDrawBeveledButton(display,&windows->widget,&grab_info); XDrawBeveledButton(display,&windows->widget,&reset_info); XDrawBeveledMatte(display,&windows->widget,&list_info); XDrawBeveledMatte(display,&windows->widget,&scroll_info); XDrawTriangleNorth(display,&windows->widget,&north_info); XDrawBeveledButton(display,&windows->widget,&slider_info); XDrawTriangleSouth(display,&windows->widget,&south_info); x=QuantumMargin; y=reply_info.y+((reply_info.height-height) >> 1)+font_info->ascent; (void) XDrawString(display,windows->widget.id, windows->widget.annotate_context,x,y,ColornameText, Extent(ColornameText)); XDrawBeveledMatte(display,&windows->widget,&reply_info); XDrawMatteText(display,&windows->widget,&reply_info); XDrawBeveledButton(display,&windows->widget,&action_info); XDrawBeveledButton(display,&windows->widget,&cancel_info); XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset); selection_info.id=(~0); state|=RedrawActionState; state|=RedrawListState; state&=(~RedrawWidgetState); } if (state & UpdateListState) { char **checklist; size_t number_colors; status=XParseColor(display,windows->widget.map_info->colormap, glob_pattern,&color); if ((status != False) || (strchr(glob_pattern,'-') != (char *) NULL)) { /* Reply is a single color name-- exit. */ (void) CopyMagickString(reply,glob_pattern,MaxTextExtent); (void) CopyMagickString(glob_pattern,reset_pattern,MaxTextExtent); action_info.raised=MagickFalse; XDrawBeveledButton(display,&windows->widget,&action_info); break; } /* Update color list. */ checklist=GetColorList(glob_pattern,&number_colors,exception); if (number_colors == 0) { (void) CopyMagickString(glob_pattern,reset_pattern,MaxTextExtent); (void) XBell(display,0); } else { for (i=0; i < (int) colors; i++) colorlist[i]=DestroyString(colorlist[i]); if (colorlist != (char **) NULL) colorlist=(char **) RelinquishMagickMemory(colorlist); colorlist=checklist; colors=number_colors; } /* Sort color list in ascending order. */ slider_info.height= scroll_info.height-((slider_info.min_y-scroll_info.y+1) << 1)+1; if (colors > visible_colors) slider_info.height=(unsigned int) ((visible_colors*slider_info.height)/colors); slider_info.max_y=south_info.y-south_info.bevel_width- slider_info.bevel_width-2; slider_info.id=0; slider_info.y=slider_info.min_y; expose_info.y=slider_info.y; selection_info.id=(~0); list_info.id=(~0); state|=RedrawListState; /* Redraw color name & reply. */ *reply_info.text='\0'; reply_info.cursor=reply_info.text; (void) CopyMagickString(text_info.text,glob_pattern,MaxTextExtent); XDrawWidgetText(display,&windows->widget,&text_info); XDrawMatteText(display,&windows->widget,&reply_info); XDrawBeveledMatte(display,&windows->widget,&scroll_info); XDrawTriangleNorth(display,&windows->widget,&north_info); XDrawBeveledButton(display,&windows->widget,&slider_info); XDrawTriangleSouth(display,&windows->widget,&south_info); XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset); state&=(~UpdateListState); } if (state & JumpListState) { /* Jump scroll to match user color. */ list_info.id=(~0); for (i=0; i < (int) colors; i++) if (LocaleCompare(colorlist[i],reply) >= 0) { list_info.id=LocaleCompare(colorlist[i],reply) == 0 ? i : ~0; break; } if ((i < slider_info.id) || (i >= (int) (slider_info.id+visible_colors))) slider_info.id=i-(visible_colors >> 1); selection_info.id=(~0); state|=RedrawListState; state&=(~JumpListState); } if (state & RedrawListState) { /* Determine slider id and position. */ if (slider_info.id >= (int) (colors-visible_colors)) slider_info.id=(int) (colors-visible_colors); if ((slider_info.id < 0) || (colors <= visible_colors)) slider_info.id=0; slider_info.y=slider_info.min_y; if (colors != 0) slider_info.y+=((ssize_t) slider_info.id*(slider_info.max_y- slider_info.min_y+1)/colors); if (slider_info.id != selection_info.id) { /* Redraw scroll bar and file names. */ selection_info.id=slider_info.id; selection_info.y=list_info.y+(height >> 3)+2; for (i=0; i < (int) visible_colors; i++) { selection_info.raised=(slider_info.id+i) != list_info.id ? MagickTrue : MagickFalse; selection_info.text=(char *) NULL; if ((slider_info.id+i) < (int) colors) selection_info.text=colorlist[slider_info.id+i]; XDrawWidgetText(display,&windows->widget,&selection_info); selection_info.y+=(int) selection_info.height; } /* Update slider. */ if (slider_info.y > expose_info.y) { expose_info.height=(unsigned int) slider_info.y-expose_info.y; expose_info.y=slider_info.y-expose_info.height- slider_info.bevel_width-1; } else { expose_info.height=(unsigned int) expose_info.y-slider_info.y; expose_info.y=slider_info.y+slider_info.height+ slider_info.bevel_width+1; } XDrawTriangleNorth(display,&windows->widget,&north_info); XDrawMatte(display,&windows->widget,&expose_info); XDrawBeveledButton(display,&windows->widget,&slider_info); XDrawTriangleSouth(display,&windows->widget,&south_info); expose_info.y=slider_info.y; } state&=(~RedrawListState); } if (state & RedrawActionState) { static char colorname[MaxTextExtent]; /* Display the selected color in a drawing area. */ color=windows->widget.pixel_info->matte_color; (void) XParseColor(display,windows->widget.map_info->colormap, reply_info.text,&windows->widget.pixel_info->matte_color); XBestPixel(display,windows->widget.map_info->colormap,(XColor *) NULL, (unsigned int) windows->widget.visual_info->colormap_size, &windows->widget.pixel_info->matte_color); mode_info.text=colorname; (void) FormatLocaleString(mode_info.text,MaxTextExtent,"#%02x%02x%02x", windows->widget.pixel_info->matte_color.red, windows->widget.pixel_info->matte_color.green, windows->widget.pixel_info->matte_color.blue); XDrawBeveledButton(display,&windows->widget,&mode_info); windows->widget.pixel_info->matte_color=color; state&=(~RedrawActionState); } /* Wait for next event. */ if (north_info.raised && south_info.raised) (void) XIfEvent(display,&event,XScreenEvent,(char *) windows); else { /* Brief delay before advancing scroll bar. */ XDelay(display,delay); delay=SuspendTime; (void) XCheckIfEvent(display,&event,XScreenEvent,(char *) windows); if (north_info.raised == MagickFalse) if (slider_info.id > 0) { /* Move slider up. */ slider_info.id--; state|=RedrawListState; } if (south_info.raised == MagickFalse) if (slider_info.id < (int) colors) { /* Move slider down. */ slider_info.id++; state|=RedrawListState; } if (event.type != ButtonRelease) continue; } switch (event.type) { case ButtonPress: { if (MatteIsActive(slider_info,event.xbutton)) { /* Track slider. */ slider_info.active=MagickTrue; break; } if (MatteIsActive(north_info,event.xbutton)) if (slider_info.id > 0) { /* Move slider up. */ north_info.raised=MagickFalse; slider_info.id--; state|=RedrawListState; break; } if (MatteIsActive(south_info,event.xbutton)) if (slider_info.id < (int) colors) { /* Move slider down. */ south_info.raised=MagickFalse; slider_info.id++; state|=RedrawListState; break; } if (MatteIsActive(scroll_info,event.xbutton)) { /* Move slider. */ if (event.xbutton.y < slider_info.y) slider_info.id-=(visible_colors-1); else slider_info.id+=(visible_colors-1); state|=RedrawListState; break; } if (MatteIsActive(list_info,event.xbutton)) { int id; /* User pressed list matte. */ id=slider_info.id+(event.xbutton.y-(list_info.y+(height >> 1))+1)/ selection_info.height; if (id >= (int) colors) break; (void) CopyMagickString(reply_info.text,colorlist[id], MaxTextExtent); reply_info.highlight=MagickFalse; reply_info.marker=reply_info.text; reply_info.cursor=reply_info.text+Extent(reply_info.text); XDrawMatteText(display,&windows->widget,&reply_info); state|=RedrawActionState; if (id == list_info.id) { (void) CopyMagickString(glob_pattern,reply_info.text, MaxTextExtent); state|=UpdateListState; } selection_info.id=(~0); list_info.id=id; state|=RedrawListState; break; } if (MatteIsActive(grab_info,event.xbutton)) { /* User pressed Grab button. */ grab_info.raised=MagickFalse; XDrawBeveledButton(display,&windows->widget,&grab_info); break; } if (MatteIsActive(reset_info,event.xbutton)) { /* User pressed Reset button. */ reset_info.raised=MagickFalse; XDrawBeveledButton(display,&windows->widget,&reset_info); break; } if (MatteIsActive(mode_info,event.xbutton)) { /* User pressed mode button. */ if (mode_info.text != (char *) NULL) (void) CopyMagickString(reply_info.text,mode_info.text, MaxTextExtent); (void) CopyMagickString(primary_selection,reply_info.text, MaxTextExtent); (void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id, event.xbutton.time); reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) == windows->widget.id ? MagickTrue : MagickFalse; reply_info.marker=reply_info.text; reply_info.cursor=reply_info.text+Extent(reply_info.text); XDrawMatteText(display,&windows->widget,&reply_info); break; } if (MatteIsActive(action_info,event.xbutton)) { /* User pressed action button. */ action_info.raised=MagickFalse; XDrawBeveledButton(display,&windows->widget,&action_info); break; } if (MatteIsActive(cancel_info,event.xbutton)) { /* User pressed Cancel button. */ cancel_info.raised=MagickFalse; XDrawBeveledButton(display,&windows->widget,&cancel_info); break; } if (MatteIsActive(reply_info,event.xbutton) == MagickFalse) break; if (event.xbutton.button != Button2) { static Time click_time; /* Move text cursor to position of button press. */ x=event.xbutton.x-reply_info.x-(QuantumMargin >> 2); for (i=1; i <= Extent(reply_info.marker); i++) if (XTextWidth(font_info,reply_info.marker,i) > x) break; reply_info.cursor=reply_info.marker+i-1; if (event.xbutton.time > (click_time+DoubleClick)) reply_info.highlight=MagickFalse; else { /* Become the XA_PRIMARY selection owner. */ (void) CopyMagickString(primary_selection,reply_info.text, MaxTextExtent); (void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id, event.xbutton.time); reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) == windows->widget.id ? MagickTrue : MagickFalse; } XDrawMatteText(display,&windows->widget,&reply_info); click_time=event.xbutton.time; break; } /* Request primary selection. */ (void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING, windows->widget.id,event.xbutton.time); break; } case ButtonRelease: { if (windows->widget.mapped == MagickFalse) break; if (north_info.raised == MagickFalse) { /* User released up button. */ delay=SuspendTime << 2; north_info.raised=MagickTrue; XDrawTriangleNorth(display,&windows->widget,&north_info); } if (south_info.raised == MagickFalse) { /* User released down button. */ delay=SuspendTime << 2; south_info.raised=MagickTrue; XDrawTriangleSouth(display,&windows->widget,&south_info); } if (slider_info.active) { /* Stop tracking slider. */ slider_info.active=MagickFalse; break; } if (grab_info.raised == MagickFalse) { if (event.xbutton.window == windows->widget.id) if (MatteIsActive(grab_info,event.xbutton)) { /* Select a pen color from the X server. */ (void) XGetWindowColor(display,windows,reply_info.text); reply_info.marker=reply_info.text; reply_info.cursor=reply_info.text+Extent(reply_info.text); XDrawMatteText(display,&windows->widget,&reply_info); state|=RedrawActionState; } grab_info.raised=MagickTrue; XDrawBeveledButton(display,&windows->widget,&grab_info); } if (reset_info.raised == MagickFalse) { if (event.xbutton.window == windows->widget.id) if (MatteIsActive(reset_info,event.xbutton)) { (void) CopyMagickString(glob_pattern,reset_pattern, MaxTextExtent); state|=UpdateListState; } reset_info.raised=MagickTrue; XDrawBeveledButton(display,&windows->widget,&reset_info); } if (action_info.raised == MagickFalse) { if (event.xbutton.window == windows->widget.id) { if (MatteIsActive(action_info,event.xbutton)) { if (*reply_info.text == '\0') (void) XBell(display,0); else state|=ExitState; } } action_info.raised=MagickTrue; XDrawBeveledButton(display,&windows->widget,&action_info); } if (cancel_info.raised == MagickFalse) { if (event.xbutton.window == windows->widget.id) if (MatteIsActive(cancel_info,event.xbutton)) { *reply_info.text='\0'; state|=ExitState; } cancel_info.raised=MagickTrue; XDrawBeveledButton(display,&windows->widget,&cancel_info); } if (MatteIsActive(reply_info,event.xbutton) == MagickFalse) break; break; } case ClientMessage: { /* If client window delete message, exit. */ if (event.xclient.message_type != windows->wm_protocols) break; if (*event.xclient.data.l == (int) windows->wm_take_focus) { (void) XSetInputFocus(display,event.xclient.window,RevertToParent, (Time) event.xclient.data.l[1]); break; } if (*event.xclient.data.l != (int) windows->wm_delete_window) break; if (event.xclient.window == windows->widget.id) { *reply_info.text='\0'; state|=ExitState; break; } break; } case ConfigureNotify: { /* Update widget configuration. */ if (event.xconfigure.window != windows->widget.id) break; if ((event.xconfigure.width == (int) windows->widget.width) && (event.xconfigure.height == (int) windows->widget.height)) break; windows->widget.width=(unsigned int) MagickMax(event.xconfigure.width,(int) windows->widget.min_width); windows->widget.height=(unsigned int) MagickMax(event.xconfigure.height,(int) windows->widget.min_height); state|=UpdateConfigurationState; break; } case EnterNotify: { if (event.xcrossing.window != windows->widget.id) break; state&=(~InactiveWidgetState); break; } case Expose: { if (event.xexpose.window != windows->widget.id) break; if (event.xexpose.count != 0) break; state|=RedrawWidgetState; break; } case KeyPress: { static char command[MaxTextExtent]; static int length; static KeySym key_symbol; /* Respond to a user key press. */ if (event.xkey.window != windows->widget.id) break; length=XLookupString((XKeyEvent *) &event.xkey,command, (int) sizeof(command),&key_symbol,(XComposeStatus *) NULL); *(command+length)='\0'; if (AreaIsActive(scroll_info,event.xkey)) { /* Move slider. */ switch ((int) key_symbol) { case XK_Home: case XK_KP_Home: { slider_info.id=0; break; } case XK_Up: case XK_KP_Up: { slider_info.id--; break; } case XK_Down: case XK_KP_Down: { slider_info.id++; break; } case XK_Prior: case XK_KP_Prior: { slider_info.id-=visible_colors; break; } case XK_Next: case XK_KP_Next: { slider_info.id+=visible_colors; break; } case XK_End: case XK_KP_End: { slider_info.id=(int) colors; break; } } state|=RedrawListState; break; } if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter)) { /* Read new color or glob patterm. */ if (*reply_info.text == '\0') break; (void) CopyMagickString(glob_pattern,reply_info.text,MaxTextExtent); state|=UpdateListState; break; } if (key_symbol == XK_Control_L) { state|=ControlState; break; } if (state & ControlState) switch ((int) key_symbol) { case XK_u: case XK_U: { /* Erase the entire line of text. */ *reply_info.text='\0'; reply_info.cursor=reply_info.text; reply_info.marker=reply_info.text; reply_info.highlight=MagickFalse; break; } default: break; } XEditText(display,&reply_info,key_symbol,command,state); XDrawMatteText(display,&windows->widget,&reply_info); state|=JumpListState; status=XParseColor(display,windows->widget.map_info->colormap, reply_info.text,&color); if (status != False) state|=RedrawActionState; break; } case KeyRelease: { static char command[MaxTextExtent]; static KeySym key_symbol; /* Respond to a user key release. */ if (event.xkey.window != windows->widget.id) break; (void) XLookupString((XKeyEvent *) &event.xkey,command, (int) sizeof(command),&key_symbol,(XComposeStatus *) NULL); if (key_symbol == XK_Control_L) state&=(~ControlState); break; } case LeaveNotify: { if (event.xcrossing.window != windows->widget.id) break; state|=InactiveWidgetState; break; } case MapNotify: { mask&=(~CWX); mask&=(~CWY); break; } case MotionNotify: { /* Discard pending button motion events. */ while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ; if (slider_info.active) { /* Move slider matte. */ slider_info.y=event.xmotion.y- ((slider_info.height+slider_info.bevel_width) >> 1)+1; if (slider_info.y < slider_info.min_y) slider_info.y=slider_info.min_y; if (slider_info.y > slider_info.max_y) slider_info.y=slider_info.max_y; slider_info.id=0; if (slider_info.y != slider_info.min_y) slider_info.id=(int) ((colors*(slider_info.y- slider_info.min_y+1))/(slider_info.max_y-slider_info.min_y+1)); state|=RedrawListState; break; } if (state & InactiveWidgetState) break; if (grab_info.raised == MatteIsActive(grab_info,event.xmotion)) { /* Grab button status changed. */ grab_info.raised=!grab_info.raised; XDrawBeveledButton(display,&windows->widget,&grab_info); break; } if (reset_info.raised == MatteIsActive(reset_info,event.xmotion)) { /* Reset button status changed. */ reset_info.raised=!reset_info.raised; XDrawBeveledButton(display,&windows->widget,&reset_info); break; } if (action_info.raised == MatteIsActive(action_info,event.xmotion)) { /* Action button status changed. */ action_info.raised=action_info.raised == MagickFalse ? MagickTrue : MagickFalse; XDrawBeveledButton(display,&windows->widget,&action_info); break; } if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion)) { /* Cancel button status changed. */ cancel_info.raised=cancel_info.raised == MagickFalse ? MagickTrue : MagickFalse; XDrawBeveledButton(display,&windows->widget,&cancel_info); break; } break; } case SelectionClear: { reply_info.highlight=MagickFalse; XDrawMatteText(display,&windows->widget,&reply_info); break; } case SelectionNotify: { Atom type; int format; unsigned char *data; unsigned long after, length; /* Obtain response from primary selection. */ if (event.xselection.property == (Atom) None) break; status=XGetWindowProperty(display,event.xselection.requestor, event.xselection.property,0L,2047L,MagickTrue,XA_STRING,&type, &format,&length,&after,&data); if ((status != Success) || (type != XA_STRING) || (format == 32) || (length == 0)) break; if ((Extent(reply_info.text)+length) >= (MaxTextExtent-1)) (void) XBell(display,0); else { /* Insert primary selection in reply text. */ *(data+length)='\0'; XEditText(display,&reply_info,(KeySym) XK_Insert,(char *) data, state); XDrawMatteText(display,&windows->widget,&reply_info); state|=JumpListState; state|=RedrawActionState; } (void) XFree((void *) data); break; } case SelectionRequest: { XSelectionEvent notify; XSelectionRequestEvent *request; if (reply_info.highlight == MagickFalse) break; /* Set primary selection. */ request=(&(event.xselectionrequest)); (void) XChangeProperty(request->display,request->requestor, request->property,request->target,8,PropModeReplace, (unsigned char *) primary_selection,Extent(primary_selection)); notify.type=SelectionNotify; notify.send_event=MagickTrue; notify.display=request->display; notify.requestor=request->requestor; notify.selection=request->selection; notify.target=request->target; notify.time=request->time; if (request->property == None) notify.property=request->target; else notify.property=request->property; (void) XSendEvent(request->display,request->requestor,False, NoEventMask,(XEvent *) &notify); } default: break; } } while ((state & ExitState) == 0); XSetCursorState(display,windows,MagickFalse); (void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen); XCheckRefreshWindows(display,windows); /* Free color list. */ for (i=0; i < (int) colors; i++) colorlist[i]=DestroyString(colorlist[i]); if (colorlist != (char **) NULL) colorlist=(char **) RelinquishMagickMemory(colorlist); exception=DestroyExceptionInfo(exception); if ((*reply == '\0') || (strchr(reply,'-') != (char *) NULL)) return; status=XParseColor(display,windows->widget.map_info->colormap,reply,&color); if (status != False) return; XNoticeWidget(display,windows,"Color is unknown to X server:",reply); (void) CopyMagickString(reply,"gray",MaxTextExtent); }
0
381,860
static struct buffer_head *udf_getblk(struct inode *inode, udf_pblk_t block, int create, int *err) { struct buffer_head *bh; struct buffer_head dummy; dummy.b_state = 0; dummy.b_blocknr = -1000; *err = udf_get_block(inode, block, &dummy, create); if (!*err && buffer_mapped(&dummy)) { bh = sb_getblk(inode->i_sb, dummy.b_blocknr); if (buffer_new(&dummy)) { lock_buffer(bh); memset(bh->b_data, 0x00, inode->i_sb->s_blocksize); set_buffer_uptodate(bh); unlock_buffer(bh); mark_buffer_dirty_inode(bh, inode); } return bh; } return NULL; }
0
359,495
DEFUN (show_ip_bgp_ipv4_rsclient_summary, show_ip_bgp_ipv4_rsclient_summary_cmd, "show ip bgp ipv4 (unicast|multicast) rsclient summary", SHOW_STR IP_STR BGP_STR "Address family\n" "Address Family modifier\n" "Address Family modifier\n" "Information about Route Server Clients\n" "Summary of all Route Server Clients\n") { if (strncmp (argv[0], "m", 1) == 0) return bgp_show_rsclient_summary_vty (vty, NULL, AFI_IP, SAFI_MULTICAST); return bgp_show_rsclient_summary_vty (vty, NULL, AFI_IP, SAFI_UNICAST); }
0
402,660
sign_kmod(context *ctx, int infd, int outfd, int attached) { unsigned char *map; struct stat statbuf; ssize_t sig_len; int rc; rc = fstat(infd, &statbuf); if (rc != 0) { ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR, "could not stat input file: %m"); return rc; } map = mmap(NULL, statbuf.st_size, PROT_READ, MAP_PRIVATE, infd, 0); if (map == MAP_FAILED) { ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR, "could not map input file: %m"); return -1; } rc = kmod_generate_digest(ctx->cms, map, statbuf.st_size); if (rc < 0) goto out; if (attached) { rc = write_file(outfd, map, statbuf.st_size); if (rc) { ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR, "could not write module data: %m"); goto out; } } sig_len = kmod_write_signature(ctx->cms, outfd); if (sig_len < 0) { rc = sig_len; goto out; } rc = kmod_write_sig_info(ctx->cms, outfd, sig_len); out: munmap(map, statbuf.st_size); return rc; }
0
211,179
void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth) { depth++; bool bFirst = true ; // buffer const size_t dirSize = 32; DataBuf dir(dirSize); bool bPrint = option == kpsBasic || option == kpsRecursive; do { // Read top of directory io.seek(start,BasicIo::beg); io.read(dir.pData_, 2); uint16_t dirLength = byteSwap2(dir,0,bSwap); bool tooBig = dirLength > 500; if ( tooBig ) throw Error(55); if ( bFirst && bPrint ) { out << Internal::indent(depth) << Internal::stringFormat("STRUCTURE OF TIFF FILE (%c%c): ",c,c) << io.path() << std::endl; if ( tooBig ) out << Internal::indent(depth) << "dirLength = " << dirLength << std::endl; } // Read the dictionary for ( int i = 0 ; i < dirLength ; i ++ ) { if ( bFirst && bPrint ) { out << Internal::indent(depth) << " address | tag | " << " type | count | offset | value\n"; } bFirst = false; io.read(dir.pData_, 12); uint16_t tag = byteSwap2(dir,0,bSwap); uint16_t type = byteSwap2(dir,2,bSwap); uint32_t count = byteSwap4(dir,4,bSwap); uint32_t offset = byteSwap4(dir,8,bSwap); // Break for unknown tag types else we may segfault. if ( !typeValid(type) ) { std::cerr << "invalid type value detected in Image::printIFDStructure: " << type << std::endl; start = 0; // break from do loop throw Error(56); break; // break from for loop } std::string sp = "" ; // output spacer //prepare to print the value uint32_t kount = isPrintXMP(tag,option) ? count // haul in all the data : isPrintICC(tag,option) ? count // ditto : isStringType(type) ? (count > 32 ? 32 : count) // restrict long arrays : count > 5 ? 5 : count ; uint32_t pad = isStringType(type) ? 1 : 0; uint32_t size = isStringType(type) ? 1 : is2ByteType(type) ? 2 : is4ByteType(type) ? 4 : is8ByteType(type) ? 8 : 1 ; // if ( offset > io.size() ) offset = 0; // Denial of service? DataBuf buf(size*count + pad+20); // allocate a buffer std::memcpy(buf.pData_,dir.pData_+8,4); // copy dir[8:11] into buffer (short strings) const bool bOffsetIsPointer = count*size > 4; if ( bOffsetIsPointer ) { // read into buffer size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position io.read(buf.pData_,count*size);// read io.seek(restore,BasicIo::beg); // restore } if ( bPrint ) { const uint32_t address = start + 2 + i*12 ; const std::string offsetString = bOffsetIsPointer? Internal::stringFormat("%10u", offset): ""; out << Internal::indent(depth) << Internal::stringFormat("%8u | %#06x %-28s |%10s |%9u |%10s | " ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str()); if ( isShortType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap2(buf,k*size,bSwap); sp = " "; } } else if ( isLongType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap4(buf,k*size,bSwap); sp = " "; } } else if ( isRationalType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { uint32_t a = byteSwap4(buf,k*size+0,bSwap); uint32_t b = byteSwap4(buf,k*size+4,bSwap); out << sp << a << "/" << b; sp = " "; } } else if ( isStringType(type) ) { out << sp << Internal::binaryToString(buf, kount); } sp = kount == count ? "" : " ..."; out << sp << std::endl; if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd) ) { for ( size_t k = 0 ; k < count ; k++ ) { size_t restore = io.tell(); uint32_t offset = byteSwap4(buf,k*size,bSwap); printIFDStructure(io,out,option,offset,bSwap,c,depth); io.seek(restore,BasicIo::beg); } } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) { size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position byte* bytes=new byte[count] ; // allocate memory io.read(bytes,count) ; // read io.seek(restore,BasicIo::beg); // restore IptcData::printStructure(out,bytes,count,depth); delete[] bytes; // free } else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) { size_t restore = io.tell(); // save uint32_t jump= 10 ; byte bytes[20] ; const char* chars = (const char*) &bytes[0] ; io.seek(offset,BasicIo::beg); // position io.read(bytes,jump ) ; // read bytes[jump]=0 ; if ( ::strcmp("Nikon",chars) == 0 ) { // tag is an embedded tiff byte* bytes=new byte[count-jump] ; // allocate memory io.read(bytes,count-jump) ; // read MemIo memIo(bytes,count-jump) ; // create a file printTiffStructure(memIo,out,option,depth); delete[] bytes ; // free } else { // tag is an IFD io.seek(0,BasicIo::beg); // position printIFDStructure(io,out,option,offset,bSwap,c,depth); } io.seek(restore,BasicIo::beg); // restore } } if ( isPrintXMP(tag,option) ) { buf.pData_[count]=0; out << (char*) buf.pData_; } if ( isPrintICC(tag,option) ) { out.write((const char*)buf.pData_,count); } } if ( start ) { io.read(dir.pData_, 4); start = tooBig ? 0 : byteSwap4(dir,0,bSwap); } } while (start) ; if ( bPrint ) { out << Internal::indent(depth) << "END " << io.path() << std::endl; } out.flush(); depth--; }
1
318,979
f_assert_exception(typval_T *argvars, typval_T *rettv) { garray_T ga; char_u *error; if (in_vim9script() && (check_for_string_arg(argvars, 0) == FAIL || check_for_opt_string_arg(argvars, 1) == FAIL)) return; error = tv_get_string_chk(&argvars[0]); if (*get_vim_var_str(VV_EXCEPTION) == NUL) { prepare_assert_error(&ga); ga_concat(&ga, (char_u *)"v:exception is not set"); assert_error(&ga); ga_clear(&ga); rettv->vval.v_number = 1; } else if (error != NULL && strstr((char *)get_vim_var_str(VV_EXCEPTION), (char *)error) == NULL) { prepare_assert_error(&ga); fill_assert_error(&ga, &argvars[1], NULL, &argvars[0], get_vim_var_tv(VV_EXCEPTION), ASSERT_OTHER); assert_error(&ga); ga_clear(&ga); rettv->vval.v_number = 1; } }
0
369,346
static int io_mkdirat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) { struct io_mkdir *mkd = &req->mkdir; const char __user *fname; if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL)) return -EINVAL; if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in) return -EINVAL; if (unlikely(req->flags & REQ_F_FIXED_FILE)) return -EBADF; mkd->dfd = READ_ONCE(sqe->fd); mkd->mode = READ_ONCE(sqe->len); fname = u64_to_user_ptr(READ_ONCE(sqe->addr)); mkd->filename = getname(fname); if (IS_ERR(mkd->filename)) return PTR_ERR(mkd->filename); req->flags |= REQ_F_NEED_CLEANUP; return 0; }
0
338,190
bool WasmBinaryBuilder::maybeVisitRefTest(Expression*& out, uint32_t code) { if (code == BinaryConsts::RefTest) { auto* rtt = popNonVoidExpression(); auto* ref = popNonVoidExpression(); out = Builder(wasm).makeRefTest(ref, rtt); return true; } else if (code == BinaryConsts::RefTestStatic) { auto intendedType = getIndexedHeapType(); auto* ref = popNonVoidExpression(); out = Builder(wasm).makeRefTest(ref, intendedType); return true; } return false; }
0
219,967
int callback_glewlwyd_check_admin_session_delegate (const struct _u_request * request, struct _u_response * response, void * user_data) { struct config_elements * config = (struct config_elements *)user_data; char * session_uid; json_t * j_user, * j_delegate; int ret; if ((session_uid = get_session_id(config, request)) != NULL) { j_user = get_current_user_for_session(config, session_uid); if (check_result_value(j_user, G_OK) && json_object_get(json_object_get(j_user, "user"), "enabled") == json_true()) { if (is_scope_list_valid_for_session(config, config->admin_scope, session_uid) == G_OK) { j_delegate = get_user(config, u_map_get(request->map_url, "username"), NULL); if (check_result_value(j_delegate, G_OK)) { if (ulfius_set_response_shared_data(response, json_deep_copy(json_object_get(j_delegate, "user")), (void (*)(void *))&json_decref) != U_OK) { ret = U_CALLBACK_ERROR; } else { ret = U_CALLBACK_IGNORE; } } else { ret = U_CALLBACK_UNAUTHORIZED; } json_decref(j_delegate); } else { ret = U_CALLBACK_UNAUTHORIZED; } } else { ret = U_CALLBACK_UNAUTHORIZED; } json_decref(j_user); } else { ret = U_CALLBACK_UNAUTHORIZED; } o_free(session_uid); return ret; }
0
300,797
bool tipc_sk_overlimit2(struct sock *sk, struct sk_buff *skb) { unsigned int lim = rcvbuf_limit(sk, skb); unsigned int qsize = sk_rmem_alloc_get(sk); return (qsize > lim * 90 / 100); }
0
443,695
utf32be_is_mbc_ambiguous(OnigCaseFoldType flag, const UChar** pp, const UChar* end) { const UChar* p = *pp; (*pp) += 4; if (*(p+2) == 0 && *(p+1) == 0 && *p == 0) { int c, v; p += 3; if (*p == 0xdf && (flag & INTERNAL_ONIGENC_CASE_FOLD_MULTI_CHAR) != 0) { return TRUE; } c = *p; v = ONIGENC_IS_UNICODE_ISO_8859_1_BIT_CTYPE(c, (BIT_CTYPE_UPPER | BIT_CTYPE_LOWER)); if ((v | BIT_CTYPE_LOWER) != 0) { /* 0xaa, 0xb5, 0xba are lower case letter, but can't convert. */ if (c >= 0xaa && c <= 0xba) return FALSE; else return TRUE; } return (v != 0 ? TRUE : FALSE); } return FALSE; }
0
500,645
char *sftp_canonicalize_path(sftp_session sftp, const char *path) { sftp_status_message status = NULL; sftp_message msg = NULL; ssh_string name = NULL; ssh_string pathstr; ssh_buffer buffer; char *cname; uint32_t ignored; uint32_t id; if (sftp == NULL) return NULL; if (path == NULL) { ssh_set_error_invalid(sftp->session, __FUNCTION__); return NULL; } buffer = ssh_buffer_new(); if (buffer == NULL) { ssh_set_error_oom(sftp->session); return NULL; } pathstr = ssh_string_from_char(path); if (pathstr == 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, pathstr) < 0) { ssh_set_error_oom(sftp->session); ssh_buffer_free(buffer); ssh_string_free(pathstr); return NULL; } if (sftp_packet_write(sftp, SSH_FXP_REALPATH, buffer) < 0) { ssh_buffer_free(buffer); ssh_string_free(pathstr); return NULL; } ssh_buffer_free(buffer); ssh_string_free(pathstr); 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 */ name = buffer_get_ssh_string(msg->payload); sftp_message_free(msg); if (name == NULL) { /* TODO: error message? */ return NULL; } cname = ssh_string_to_char(name); ssh_string_free(name); if (cname == NULL) { ssh_set_error_oom(sftp->session); } return cname; } 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
222,559
void FunctionDefHelper::AttrValueWrapper::InitFromString(StringPiece val) { if (val.size() >= 2 && val[0] == '$') { proto.set_placeholder(val.data() + 1, val.size() - 1); } else { SetAttrValue(val, &proto); } }
0
282,881
static int rsi_load_bootup_params(struct rsi_common *common) { struct sk_buff *skb; struct rsi_boot_params *boot_params; rsi_dbg(MGMT_TX_ZONE, "%s: Sending boot params frame\n", __func__); skb = dev_alloc_skb(sizeof(struct rsi_boot_params)); if (!skb) { rsi_dbg(ERR_ZONE, "%s: Failed in allocation of skb\n", __func__); return -ENOMEM; } memset(skb->data, 0, sizeof(struct rsi_boot_params)); boot_params = (struct rsi_boot_params *)skb->data; rsi_dbg(MGMT_TX_ZONE, "%s:\n", __func__); if (common->channel_width == BW_40MHZ) { memcpy(&boot_params->bootup_params, &boot_params_40, sizeof(struct bootup_params)); rsi_dbg(MGMT_TX_ZONE, "%s: Packet 40MHZ <=== %d\n", __func__, UMAC_CLK_40BW); boot_params->desc_word[7] = cpu_to_le16(UMAC_CLK_40BW); } else { memcpy(&boot_params->bootup_params, &boot_params_20, sizeof(struct bootup_params)); if (boot_params_20.valid != cpu_to_le32(VALID_20)) { boot_params->desc_word[7] = cpu_to_le16(UMAC_CLK_20BW); rsi_dbg(MGMT_TX_ZONE, "%s: Packet 20MHZ <=== %d\n", __func__, UMAC_CLK_20BW); } else { boot_params->desc_word[7] = cpu_to_le16(UMAC_CLK_40MHZ); rsi_dbg(MGMT_TX_ZONE, "%s: Packet 20MHZ <=== %d\n", __func__, UMAC_CLK_40MHZ); } } /** * Bit{0:11} indicates length of the Packet * Bit{12:15} indicates host queue number */ boot_params->desc_word[0] = cpu_to_le16(sizeof(struct bootup_params) | (RSI_WIFI_MGMT_Q << 12)); boot_params->desc_word[1] = cpu_to_le16(BOOTUP_PARAMS_REQUEST); skb_put(skb, sizeof(struct rsi_boot_params)); return rsi_send_internal_mgmt_frame(common, skb); }
0
272,347
cms_context_init(cms_context *cms) { memset(cms, '\0', sizeof (*cms)); cms->log = cms_common_log; cms->arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!cms->arena) cnreterr(-1, cms, "could not create cryptographic arena"); cms->selected_digest = -1; INIT_LIST_HEAD(&cms->pk12_ins); cms->pk12_out.fd = -1; cms->db_out = cms->dbx_out = cms->dbt_out = -1; return 0; }
0
512,729
Item *get_copy(THD *thd) { return get_item_copy<Item_null>(thd, this); }
0
488,366
struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte) { unsigned long pfn; if (HAVE_PTE_SPECIAL) { if (likely(!pte_special(pte))) { VM_BUG_ON(!pfn_valid(pte_pfn(pte))); return pte_page(pte); } VM_BUG_ON(!(vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))); return NULL; } /* !HAVE_PTE_SPECIAL case follows: */ pfn = pte_pfn(pte); if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) { if (vma->vm_flags & VM_MIXEDMAP) { if (!pfn_valid(pfn)) return NULL; goto out; } else { unsigned long off; off = (addr - vma->vm_start) >> PAGE_SHIFT; if (pfn == vma->vm_pgoff + off) return NULL; if (!is_cow_mapping(vma->vm_flags)) return NULL; } } VM_BUG_ON(!pfn_valid(pfn)); /* * NOTE! We still have PageReserved() pages in the page tables. * * eg. VDSO mappings can cause them to exist. */ out: return pfn_to_page(pfn); }
0
412,337
static ut64 baddr(RzBinFile *bf) { QnxObj *qo = bf->o->bin_obj; return qo ? qo->lmfh.image_base : 0; }
0
211,181
apprentice_load(struct magic_set *ms, const char *fn, int action) { int errs = 0; uint32_t i, j; size_t files = 0, maxfiles = 0; char **filearr = NULL; struct stat st; struct magic_map *map; struct magic_entry_set mset[MAGIC_SETS]; php_stream *dir; php_stream_dirent d; TSRMLS_FETCH(); memset(mset, 0, sizeof(mset)); ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */ if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) { file_oomem(ms, sizeof(*map)); return NULL; } /* print silly verbose header for USG compat. */ if (action == FILE_CHECK) (void)fprintf(stderr, "%s\n", usg_hdr); /* load directory or file */ /* FIXME: Read file names and sort them to prevent non-determinism. See Debian bug #488562. */ if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) { int mflen; char mfn[MAXPATHLEN]; dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL); if (!dir) { errs++; goto out; } while (php_stream_readdir(dir, &d)) { if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) { file_oomem(ms, strlen(fn) + strlen(d.d_name) + 2); errs++; php_stream_closedir(dir); goto out; } if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) { continue; } if (files >= maxfiles) { size_t mlen; maxfiles = (maxfiles + 1) * 2; mlen = maxfiles * sizeof(*filearr); if ((filearr = CAST(char **, erealloc(filearr, mlen))) == NULL) { file_oomem(ms, mlen); efree(mfn); php_stream_closedir(dir); errs++; goto out; } } filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen); } php_stream_closedir(dir); qsort(filearr, files, sizeof(*filearr), cmpstrp); for (i = 0; i < files; i++) { load_1(ms, action, filearr[i], &errs, mset); efree(filearr[i]); } efree(filearr); } else load_1(ms, action, fn, &errs, mset); if (errs) goto out; for (j = 0; j < MAGIC_SETS; j++) { /* Set types of tests */ for (i = 0; i < mset[j].count; ) { if (mset[j].me[i].mp->cont_level != 0) { i++; continue; } i = set_text_binary(ms, mset[j].me, mset[j].count, i); } qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me), apprentice_sort); /* * Make sure that any level 0 "default" line is last * (if one exists). */ set_last_default(ms, mset[j].me, mset[j].count); /* coalesce per file arrays into a single one */ if (coalesce_entries(ms, mset[j].me, mset[j].count, &map->magic[j], &map->nmagic[j]) == -1) { errs++; goto out; } } out: for (j = 0; j < MAGIC_SETS; j++) magic_entry_free(mset[j].me, mset[j].count); if (errs) { for (j = 0; j < MAGIC_SETS; j++) { if (map->magic[j]) efree(map->magic[j]); } efree(map); return NULL; } return map; }
1
343,218
static void standalone_server(void) { int on; struct addrinfo hints, *res, *res6; fd_set rs; int max_fd; # ifndef NO_INETD standalone = 1; # endif memset(&hints, 0, sizeof hints); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_addr = NULL; on = 1; if (listenfd == -1 && no_ipv4 == 0 && getaddrinfo(standalone_ip, standalone_port, &hints, &res) == 0) { if ((listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1 || setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof on) != 0) { int old_errno; freeaddrinfo(res); cant_bind: old_errno = errno; perror(MSG_STANDALONE_FAILED); logfile(LOG_ERR, MSG_STANDALONE_FAILED ": [%s]", strerror(old_errno)); return; } # ifdef TCP_FASTOPEN { # ifdef __APPLE__ int tfo = 1; # else int tfo = 5; # endif setsockopt(listenfd, IPPROTO_TCP, TCP_FASTOPEN, (void *) &tfo, sizeof tfo); } # endif if (bind(listenfd, res->ai_addr, (socklen_t) res->ai_addrlen) != 0 || listen(listenfd, maxusers > 0U ? 3U + maxusers / 8U : DEFAULT_BACKLOG) != 0) { freeaddrinfo(res); goto cant_bind; } freeaddrinfo(res); set_cloexec_flag(listenfd); } if (listenfd6 == -1 && v6ready != 0) { hints.ai_family = AF_INET6; if (getaddrinfo(standalone_ip, standalone_port, &hints, &res6) == 0) { if ((listenfd6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP)) == -1 || setsockopt(listenfd6, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof on) != 0) { freeaddrinfo(res6); goto cant_bind; } # if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY) (void) setsockopt(listenfd6, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on, sizeof on); # endif # ifdef TCP_FASTOPEN { int tfo = maxusers > 0U ? 3U + maxusers / 8U : DEFAULT_BACKLOG; setsockopt(listenfd6, IPPROTO_TCP, TCP_FASTOPEN, (void *) &tfo, sizeof tfo); } # endif if (bind(listenfd6, res6->ai_addr, (socklen_t) res6->ai_addrlen) != 0 || listen(listenfd6, maxusers > 0U ? 3U + maxusers / 8U : DEFAULT_BACKLOG) != 0) { freeaddrinfo(res6); goto cant_bind; } freeaddrinfo(res6); set_cloexec_flag(listenfd6); } } if (listenfd == -1 && listenfd6 == -1) { # ifdef EADDRNOTAVAIL errno = EADDRNOTAVAIL; # endif goto cant_bind; } updatepidfile(); setprocessname("pure-ftpd (SERVER)"); FD_ZERO(&rs); if (listenfd > listenfd6) { max_fd = listenfd; } else { max_fd = listenfd6; } max_fd++; while (stop_server == 0) { safe_fd_set(listenfd, &rs); safe_fd_set(listenfd6, &rs); if (select(max_fd, &rs, NULL, NULL, NULL) <= 0) { if (errno != EINTR) { (void) sleep(1); } continue; } if (safe_fd_isset(listenfd, &rs)) { accept_client(listenfd); } if (safe_fd_isset(listenfd6, &rs)) { accept_client(listenfd6); } } }
0
345,201
int con_set_default_unimap(struct vc_data *vc) { int i, j, err = 0, err1; u16 *q; struct uni_pagedir *p; if (dflt) { p = *vc->vc_uni_pagedir_loc; if (p == dflt) return 0; dflt->refcount++; *vc->vc_uni_pagedir_loc = dflt; if (p && !--p->refcount) { con_release_unimap(p); kfree(p); } return 0; } /* The default font is always 256 characters */ err = con_do_clear_unimap(vc); if (err) return err; p = *vc->vc_uni_pagedir_loc; q = dfont_unitable; for (i = 0; i < 256; i++) for (j = dfont_unicount[i]; j; j--) { err1 = con_insert_unipair(p, *(q++), i); if (err1) err = err1; } if (con_unify_unimap(vc, p)) { dflt = *vc->vc_uni_pagedir_loc; return err; } for (i = 0; i <= 3; i++) set_inverse_transl(vc, p, i); /* Update all inverse translations */ set_inverse_trans_unicode(vc, p); dflt = p; return err; }
0
489,158
struct sctp_chunk *sctp_chunkify(struct sk_buff *skb, const struct sctp_association *asoc, struct sock *sk) { struct sctp_chunk *retval; retval = kmem_cache_zalloc(sctp_chunk_cachep, GFP_ATOMIC); if (!retval) goto nodata; if (!sk) { SCTP_DEBUG_PRINTK("chunkifying skb %p w/o an sk\n", skb); } INIT_LIST_HEAD(&retval->list); retval->skb = skb; retval->asoc = (struct sctp_association *)asoc; retval->resent = 0; retval->has_tsn = 0; retval->has_ssn = 0; retval->rtt_in_progress = 0; retval->sent_at = 0; retval->singleton = 1; retval->end_of_packet = 0; retval->ecn_ce_done = 0; retval->pdiscard = 0; /* sctpimpguide-05.txt Section 2.8.2 * M1) Each time a new DATA chunk is transmitted * set the 'TSN.Missing.Report' count for that TSN to 0. The * 'TSN.Missing.Report' count will be used to determine missing chunks * and when to fast retransmit. */ retval->tsn_missing_report = 0; retval->tsn_gap_acked = 0; retval->fast_retransmit = 0; /* If this is a fragmented message, track all fragments * of the message (for SEND_FAILED). */ retval->msg = NULL; /* Polish the bead hole. */ INIT_LIST_HEAD(&retval->transmitted_list); INIT_LIST_HEAD(&retval->frag_list); SCTP_DBG_OBJCNT_INC(chunk); atomic_set(&retval->refcnt, 1); nodata: return retval; }
0
196,689
void Compute(OpKernelContext* ctx) override { Buffer* buf = nullptr; OP_REQUIRES_OK(ctx, GetBuffer(ctx, def(), &buf)); core::ScopedUnref scope(buf); Buffer::Tuple tuple; std::size_t index = ctx->input(0).scalar<int>()(); OP_REQUIRES_OK(ctx, buf->Peek(index, &tuple)); OP_REQUIRES( ctx, tuple.size() == (size_t)ctx->num_outputs(), errors::InvalidArgument("Mismatch stage/unstage: ", tuple.size(), " vs. ", ctx->num_outputs())); for (size_t i = 0; i < tuple.size(); ++i) { ctx->set_output(i, tuple[i]); } }
1
262,087
bool operator==(const InstanceFeatureDimKey& other) const { return (instance == other.instance) && (feature_dim == other.feature_dim); }
0
219,044
Status ConstantFolding::SimplifyNode(NodeDef* node, GraphDef* optimized_graph, GraphProperties* properties) { bool graph_modified_cached = graph_modified_; graph_modified_ = false; bool use_shape_info = properties->has_properties(); RETURN_IF_MODIFIED(RemoveSplitOrSplitV(*properties, optimized_graph, node)); RETURN_IF_ERROR_OR_MODIFIED(RemoveShuffleOrTranspose( *properties, use_shape_info, optimized_graph, node)); RETURN_IF_MODIFIED( RemoveRandomShuffle(*properties, use_shape_info, optimized_graph, node)); RETURN_IF_ERROR_OR_MODIFIED( RemoveReverse(*properties, use_shape_info, optimized_graph, node)); RETURN_IF_ERROR_OR_MODIFIED( SimplifySlice(*properties, use_shape_info, optimized_graph, node)); RETURN_IF_ERROR_OR_MODIFIED( SimplifyStridedSlice(*properties, use_shape_info, optimized_graph, node)); RETURN_IF_ERROR_OR_MODIFIED( SimplifyTile(*properties, use_shape_info, optimized_graph, node)); RETURN_IF_ERROR_OR_MODIFIED( SimplifyPad(*properties, use_shape_info, optimized_graph, node)); RETURN_IF_MODIFIED( SimplifySqueeze(*properties, use_shape_info, optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED(SimplifyPack(optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED(MoveConstantsPastEnter(optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED(SimplifySwitch(optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED( SimplifyReduction(optimized_graph, *properties, node)); SET_AND_RETURN_IF_MODIFIED( SimplifyReshape(*properties, use_shape_info, node)); RETURN_IF_ERROR_OR_MODIFIED(SimplifyArithmeticOperations( *properties, use_shape_info, optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED(ReduceDivToReciprocalMul(optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED( ConstantPushDown(properties, optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED( MulConvPushDown(optimized_graph, node, *properties)); SET_AND_RETURN_IF_MODIFIED(PartialConstPropThroughIdentityN(node)); SET_AND_RETURN_IF_MODIFIED( PartialAssocOpConstFolding(optimized_graph, properties, node)); SET_AND_RETURN_IF_MODIFIED( MergeConcat(use_shape_info, properties, optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED( PartialConcatConstFolding(optimized_graph, properties, node)); SET_AND_RETURN_IF_MODIFIED( ConstantPushDownBiasAdd(properties, optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED(SimplifyCase(optimized_graph, node)); SET_AND_RETURN_IF_MODIFIED( SimplifySelect(*properties, optimized_graph, node)); RETURN_IF_MODIFIED( RemoveRedundantVariableUpdates(properties, optimized_graph, node)); graph_modified_ = graph_modified_cached; return Status::OK(); }
0
409,431
term_get_fg_color(char_u *r, char_u *g, char_u *b) { if (rfg_status.tr_progress == STATUS_GOT) { *r = fg_r; *g = fg_g; *b = fg_b; } }
0
270,110
TfLiteStatus CalculateShapeForBroadcast(TfLiteContext* context, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteIntArray** output_shape) { const int dims1 = NumDimensions(input1); const int dims2 = NumDimensions(input2); const int out_dims = std::max(dims1, dims2); std::unique_ptr<TfLiteIntArray, void (*)(TfLiteIntArray*)> shape( TfLiteIntArrayCreate(out_dims), TfLiteIntArrayFree); for (int i = 0; i < out_dims; ++i) { const int d1 = i >= dims1 ? 1 : SizeOfDimension(input1, dims1 - i - 1); const int d2 = i >= dims2 ? 1 : SizeOfDimension(input2, dims2 - i - 1); if (!(d1 == d2 || d1 == 1 || d2 == 1)) { context->ReportError(context, "Given shapes, %s and %s, are not broadcastable.", GetShapeDebugString(input1->dims).c_str(), GetShapeDebugString(input2->dims).c_str()); return kTfLiteError; } if (d1 == 0 || d2 == 0) { shape->data[out_dims - i - 1] = 0; } else { shape->data[out_dims - i - 1] = std::max(d1, d2); } } *output_shape = shape.release(); return kTfLiteOk; }
0
231,007
envadjust(mrb_state *mrb, mrb_value *oldbase, mrb_value *newbase, size_t oldsize) { mrb_callinfo *ci = mrb->c->cibase; if (newbase == oldbase) return; while (ci <= mrb->c->ci) { struct REnv *e = mrb_vm_ci_env(ci); mrb_value *st; if (e && MRB_ENV_ONSTACK_P(e) && (st = e->stack) && oldbase <= st && st < oldbase+oldsize) { ptrdiff_t off = e->stack - oldbase; e->stack = newbase + off; } if (ci->proc && MRB_PROC_ENV_P(ci->proc) && e != MRB_PROC_ENV(ci->proc)) { e = MRB_PROC_ENV(ci->proc); if (e && MRB_ENV_ONSTACK_P(e) && (st = e->stack) && oldbase <= st && st < oldbase+oldsize) { ptrdiff_t off = e->stack - oldbase; e->stack = newbase + off; } } ci->stack = newbase + (ci->stack - oldbase); ci++; } }
0
365,618
_asn1_set_name (asn1_node node, const char *name) { unsigned int nsize; if (node == NULL) return node; if (name == NULL) { node->name[0] = 0; node->name_hash = hash_pjw_bare (node->name, 0); return node; } nsize = _asn1_str_cpy (node->name, sizeof (node->name), name); node->name_hash = hash_pjw_bare (node->name, nsize); return node; }
0
503,889
SCM_DEFINE (scm_basename, "basename", 1, 1, 0, (SCM filename, SCM suffix), "Return the base name of the file name @var{filename}. The\n" "base name is the file name without any directory components.\n" "If @var{suffix} is provided, and is equal to the end of\n" "@var{filename}, it is removed also.") #define FUNC_NAME s_scm_basename { char *c_filename, *c_last_component; SCM res; scm_dynwind_begin (0); c_filename = scm_to_utf8_string (filename); scm_dynwind_free (c_filename); c_last_component = last_component (c_filename); if (!c_last_component) res = filename; else res = scm_from_utf8_string (c_last_component); scm_dynwind_end (); if (!SCM_UNBNDP (suffix) && scm_is_true (scm_string_suffix_p (suffix, filename, SCM_UNDEFINED, SCM_UNDEFINED, SCM_UNDEFINED, SCM_UNDEFINED))) res = scm_c_substring (res, 0, scm_c_string_length (res) - scm_c_string_length (suffix)); return res; }
0
411,920
tokenize_string(memarea_t *area, const char *start, const char *end, smartlist_t *out, token_rule_t *table, int flags) { const char **s; directory_token_t *tok = NULL; int counts[_NIL]; int i; int first_nonannotation; int prev_len = smartlist_len(out); tor_assert(area); s = &start; if (!end) end = start+strlen(start); for (i = 0; i < _NIL; ++i) counts[i] = 0; SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]); while (*s < end && (!tok || tok->tp != _EOF)) { tok = get_next_token(area, s, end, table); if (tok->tp == _ERR) { log_warn(LD_DIR, "parse error: %s", tok->error); token_clear(tok); return -1; } ++counts[tok->tp]; smartlist_add(out, tok); *s = eat_whitespace_eos(*s, end); } if (flags & TS_NOCHECK) return 0; if ((flags & TS_ANNOTATIONS_OK)) { first_nonannotation = -1; for (i = 0; i < smartlist_len(out); ++i) { tok = smartlist_get(out, i); if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) { first_nonannotation = i; break; } } if (first_nonannotation < 0) { log_warn(LD_DIR, "parse error: item contains only annotations"); return -1; } for (i=first_nonannotation; i < smartlist_len(out); ++i) { tok = smartlist_get(out, i); if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) { log_warn(LD_DIR, "parse error: Annotations mixed with keywords"); return -1; } } if ((flags & TS_NO_NEW_ANNOTATIONS)) { if (first_nonannotation != prev_len) { log_warn(LD_DIR, "parse error: Unexpected annotations."); return -1; } } } else { for (i=0; i < smartlist_len(out); ++i) { tok = smartlist_get(out, i); if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) { log_warn(LD_DIR, "parse error: no annotations allowed."); return -1; } } first_nonannotation = 0; } for (i = 0; table[i].t; ++i) { if (counts[table[i].v] < table[i].min_cnt) { log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t); return -1; } if (counts[table[i].v] > table[i].max_cnt) { log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t); return -1; } if (table[i].pos & AT_START) { if (smartlist_len(out) < 1 || (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) { log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t); return -1; } } if (table[i].pos & AT_END) { if (smartlist_len(out) < 1 || (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) { log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t); return -1; } } } return 0; }
0
199,952
mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module) { mp_ubyte insData[230]; mp_sint32 smpReloc[MP_MAXINSSAMPS]; mp_ubyte nbu[MP_MAXINSSAMPS]; mp_uint32 fileSize = 0; module->cleanUp(); // this will make code much easier to read TXMHeader* header = &module->header; TXMInstrument* instr = module->instr; TXMSample* smp = module->smp; TXMPattern* phead = module->phead; // we're already out of memory here if (!phead || !instr || !smp) return MP_OUT_OF_MEMORY; fileSize = f.sizeWithBaseOffset(); f.read(&header->sig,1,17); f.read(&header->name,1,20); f.read(&header->whythis1a,1,1); header->whythis1a=0; f.read(&header->tracker,1,20); f.readWords(&header->ver,1); if (header->ver != 0x102 && header->ver != 0x103 && // untested header->ver != 0x104) return MP_LOADER_FAILED; f.readDwords(&header->hdrsize,1); header->hdrsize-=4; mp_uint32 hdrSize = 0x110; if (header->hdrsize > hdrSize) hdrSize = header->hdrsize; mp_ubyte* hdrBuff = new mp_ubyte[hdrSize]; memset(hdrBuff, 0, hdrSize); f.read(hdrBuff, 1, header->hdrsize); header->ordnum = LittleEndian::GET_WORD(hdrBuff); header->restart = LittleEndian::GET_WORD(hdrBuff+2); header->channum = LittleEndian::GET_WORD(hdrBuff+4); header->patnum = LittleEndian::GET_WORD(hdrBuff+6); header->insnum = LittleEndian::GET_WORD(hdrBuff+8); header->freqtab = LittleEndian::GET_WORD(hdrBuff+10); header->tempo = LittleEndian::GET_WORD(hdrBuff+12); header->speed = LittleEndian::GET_WORD(hdrBuff+14); memcpy(header->ord, hdrBuff+16, 256); if(header->ordnum > MP_MAXORDERS) header->ordnum = MP_MAXORDERS; if(header->insnum > MP_MAXINS) return MP_LOADER_FAILED; delete[] hdrBuff; header->mainvol=255; header->flags = XModule::MODULE_XMNOTECLIPPING | XModule::MODULE_XMARPEGGIO | XModule::MODULE_XMPORTANOTEBUFFER | XModule::MODULE_XMVOLCOLUMNVIBRATO; header->uppernotebound = 119; mp_sint32 i,y,sc; for (i=0;i<32;i++) header->pan[i]=0x80; // old version? if (header->ver == 0x102 || header->ver == 0x103) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;y<header->insnum;y++) { f.readDwords(&instr[y].size,1); f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); mp_uword numSamples = 0; f.readWords(&numSamples,1); if(numSamples > MP_MAXINSSAMPS) return MP_LOADER_FAILED; instr[y].samp = numSamples; if (instr[y].size == 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); memset(insData, 0, 230); if (instr[y].size - 33 > 230) return MP_OUT_OF_MEMORY; f.read(insData, 1, instr[y].size - 33); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) { venv.env[l][1]<<=2; penv.env[l][1]<<=2; } if (!module->addVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;sc<instr[y].samp;sc++) { smp[g+s].flags=3; smp[g+s].venvnum=e+1; smp[g+s].penvnum=e+1; smp[g+s].vibtype=vibtype; smp[g+s].vibsweep=vibsweep; smp[g+s].vibdepth=vibdepth; smp[g+s].vibrate=vibrate; smp[g+s].volfade=volfade; // not sure why I did that, actually doesn't make sense //if (!(venv.type&1)) smp[g+s].volfade=0; f.readDwords(&smp[g+s].samplen,1); f.readDwords(&smp[g+s].loopstart,1); f.readDwords(&smp[g+s].looplen,1); smp[g+s].vol=XModule::vol64to255(f.readByte()); //f.read(&smp[g+s].vol,1,1); f.read(&smp[g+s].finetune,1,1); f.read(&smp[g+s].type,1,1); #ifdef VERBOSE printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16)); #endif f.read(&smp[g+s].pan,1,1); f.read(&smp[g+s].relnote,1,1); f.read(&smp[g+s].res,1,1); f.read(&smp[g+s].name,1,22); char line[30]; memset(line, 0, sizeof(line)); XModule::convertStr(line, smp[g+s].name, 23, false); if (line[0]) module->addSongMessageLine(line); // ignore empty samples #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16; #else s+=instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } for (y=0;y<header->patnum;y++) { if (header->ver == 0x104 || header->ver == 0x103) { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); f.readWords(&phead[y].rows,1); f.readWords(&phead[y].patdata,1); } else { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); phead[y].rows = (mp_uword)f.readByte()+1; f.readWords(&phead[y].patdata,1); } phead[y].effnum=2; phead[y].channum=(mp_ubyte)header->channum; phead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6]; // out of memory? if (phead[y].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[y].patternData,0,phead[y].rows*header->channum*6); if (phead[y].patdata) { mp_ubyte *buffer = new mp_ubyte[phead[y].patdata]; // out of memory? if (buffer == NULL) { return MP_OUT_OF_MEMORY; } f.read(buffer,1,phead[y].patdata); //printf("%i\n", phead[y].patdata); mp_sint32 pc = 0, bc = 0; for (mp_sint32 r=0;r<phead[y].rows;r++) { for (mp_sint32 c=0;c<header->channum;c++) { mp_ubyte slot[5]; memset(slot,0,5); if ((buffer[pc]&128)) { mp_ubyte pb = buffer[pc]; pc++; if ((pb&1)) { //phead[y].patternData[bc]=buffer[pc]; slot[0]=buffer[pc]; pc++; } if ((pb&2)) { //phead[y].patternData[bc+1]=buffer[pc]; slot[1]=buffer[pc]; pc++; } if ((pb&4)) { //phead[y].patternData[bc+2]=buffer[pc]; slot[2]=buffer[pc]; pc++; } if ((pb&8)) { //phead[y].patternData[bc+3]=buffer[pc]; slot[3]=buffer[pc]; pc++; } if ((pb&16)) { //phead[y].patternData[bc+4]=buffer[pc]; slot[4]=buffer[pc]; pc++; } } else { //memcpy(phead[y].patternData+bc,buffer+pc,5); memcpy(slot,buffer+pc,5); pc+=5; } char gl=0; for (mp_sint32 i=0;i<XModule::numValidXMEffects;i++) if (slot[3]==XModule::validXMEffects[i]) gl=1; if (!gl) slot[3]=slot[4]=0; if ((slot[3]==0xC)||(slot[3]==0x10)) { slot[4] = XModule::vol64to255(slot[4]); /*mp_sint32 bl = slot[4]; if (bl>64) bl=64; slot[4]=(bl*261120)>>16;*/ } if ((!slot[3])&&(slot[4])) slot[3]=0x20; if (slot[3]==0xE) { slot[3]=(slot[4]>>4)+0x30; slot[4]=slot[4]&0xf; } if (slot[3]==0x21) { slot[3]=(slot[4]>>4)+0x40; slot[4]=slot[4]&0xf; } if (slot[0]==97) slot[0]=XModule::NOTE_OFF; phead[y].patternData[bc]=slot[0]; phead[y].patternData[bc+1]=slot[1]; XModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]); phead[y].patternData[bc+4]=slot[3]; phead[y].patternData[bc+5]=slot[4]; /*if ((y==3)&&(c==2)) { for (mp_sint32 bl=0;bl<6;bl++) cprintf("%x ",phead[y].patternData[bc+bl]); cprintf("\r\n"); getch(); };*/ /*printf("Note : %i\r\n",phead[y].patternData[bc]); printf("Ins : %i\r\n",phead[y].patternData[bc+1]); printf("Vol : %i\r\n",phead[y].patternData[bc+2]); printf("Eff : %i\r\n",phead[y].patternData[bc+3]); printf("Effop: %i\r\n",phead[y].patternData[bc+4]); getch();*/ bc+=6; } // for c } // for r delete[] buffer; } } if (header->ver == 0x104) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;y<header->insnum;y++) { // fixes MOOH.XM loading problems // seems to store more instruments in the header than in the actual file if (f.posWithBaseOffset() >= fileSize) break; //TXMInstrument* ins = &instr[y]; f.readDwords(&instr[y].size,1); if (instr[y].size < 29) { mp_ubyte buffer[29]; memset(buffer, 0, sizeof(buffer)); f.read(buffer, 1, instr[y].size - 4); memcpy(instr[y].name, buffer, 22); instr[y].type = buffer[22]; instr[y].samp = LittleEndian::GET_WORD(buffer + 23); } else { f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); f.readWords(&instr[y].samp,1); } if (instr[y].samp > MP_MAXINSSAMPS) return MP_LOADER_FAILED; //printf("%i, %i\n", instr[y].size, instr[y].samp); if (instr[y].size <= 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); #ifdef VERBOSE printf("%i/%i: %i, %i, %i, %s\n",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name); #endif memset(insData, 0, 230); if (instr[y].size - 33 > 230) { //return -7; break; } f.read(insData, 1, instr[y].size - 33); /*printf("%i\r\n",instr[y].size); printf("%s\r\n",instr[y].name); printf("%i\r\n",instr[y].type); printf("%i\r\n",instr[y].samp); printf("%i\r\n",instr[y].shsize);*/ //getch(); memset(smpReloc, 0, sizeof(smpReloc)); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; //f.read(&nbu,1,96); memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; //f.readWords(&volfade,1); volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) { venv.env[l][1]<<=2; penv.env[l][1]<<=2; } if (!module->addVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;sc<instr[y].samp;sc++) { //TXMSample* smpl = &smp[g+s]; smp[g+s].flags=3; smp[g+s].venvnum=e+1; smp[g+s].penvnum=e+1; smp[g+s].vibtype=vibtype; smp[g+s].vibsweep=vibsweep; smp[g+s].vibdepth=vibdepth; smp[g+s].vibrate=vibrate; smp[g+s].volfade=volfade; // not sure why I did that, actually doesn't make sense //if (!(venv.type&1)) smp[g+s].volfade=0; f.readDwords(&smp[g+s].samplen,1); f.readDwords(&smp[g+s].loopstart,1); f.readDwords(&smp[g+s].looplen,1); smp[g+s].vol=XModule::vol64to255(f.readByte()); //f.read(&smp[g+s].vol,1,1); f.read(&smp[g+s].finetune,1,1); f.read(&smp[g+s].type,1,1); #ifdef VERBOSE printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16)); #endif f.read(&smp[g+s].pan,1,1); f.read(&smp[g+s].relnote,1,1); f.read(&smp[g+s].res,1,1); f.read(&smp[g+s].name,1,22); char line[30]; memset(line, 0, sizeof(line)); XModule::convertStr(line, smp[g+s].name, 23, false); if (line[0]) module->addSongMessageLine(line); #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } for (sc=0;sc<instr[y].samp;sc++) { if (smp[s].samplen) { bool adpcm = (smp[s].res == 0xAD); mp_uint32 oldSize = smp[s].samplen; if (smp[s].type&16) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA, adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT), oldSize); if (result != MP_OK) return result; if (adpcm) smp[s].res = 0; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } else { mp_sint32 s = 0; for (y=0;y<header->insnum;y++) { for (sc=0;sc<instr[y].samp;sc++) { if (smp[s].samplen) { mp_uint32 oldSize = smp[s].samplen; if (smp[s].type&16) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize); if (result != MP_OK) return result; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } } // convert modplug stereo samples for (mp_sint32 s = 0; s < header->smpnum; s++) { if (smp[s].type & 32) { // that's what's allowed, stupid modplug tracker smp[s].type &= 3+16; if (smp[s].sample == NULL) continue; if (!(smp[s].type&16)) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sbyte* sample = (mp_sbyte*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -128) s = -128; if (s > 127) s = 127; sample[i] = (mp_sbyte)s; } } else { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sword* sample = (mp_sword*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -32768) s = -32768; if (s > 32767) s = 32767; sample[i] = (mp_sword)s; } } } // correct loop type 0x03 (undefined) // will become ping pong loop // note that FT2 will refuse to load XM files with such a loop type if ((smp[s].type & 0x3) == 0x3) smp[s].type&=~1; } // correct number of patterns if necessary, otherwise the post processing will remove // the "invalid" patterns from the order list bool addPatterns = false; for (i = 0; i < header->ordnum; i++) if (header->ord[i]+1 > header->patnum) { header->patnum = header->ord[i]+1; addPatterns = true; } // if the pattern number has been adjusted, add some empty patterns if (addPatterns) { for (i = 0; i < header->patnum; i++) if (phead[i].patternData == NULL) { phead[i].rows = 64; phead[i].effnum = 2; phead[i].channum = (mp_ubyte)header->channum; phead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6]; // out of memory? if (phead[i].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[i].patternData,0,phead[i].rows*header->channum*6); } } // check for MODPLUG extensions if (f.posWithBaseOffset() + 8 <= fileSize) { char buffer[4]; f.read(buffer, 1, 4); if (memcmp(buffer, "text", 4) == 0) { mp_uint32 len = f.readDword(); module->allocateSongMessage(len+1); memset(module->message, 0, len+1); f.read(module->message, 1, len); } } module->postProcessSamples(); return MP_OK; }
1