/* * Given a menu descriptor, e.g. "File.New", find it in the menu hierarchy and * execute it. */ void ex_emenu(exarg_T *eap) { vimmenu_T *menu; char_u *name; char_u *saved_name; char_u *p; int idx; char_u *mode; saved_name = vim_strsave(eap->arg); menu = root_menu; name = saved_name; while (*name) { /* Find in the menu hierarchy */ p = menu_name_skip(name); while (menu != NULL) { if (menu_name_equal(name, menu)) { if (*p == NUL && menu->children != NULL) { EMSG(_("E333: Menu path must lead to a menu item")); menu = NULL; } else if (*p != NUL && menu->children == NULL) { EMSG(_(e_notsubmenu)); menu = NULL; } break; } menu = menu->next; } if (menu == NULL || *p == NUL) break; menu = menu->children; name = p; } free(saved_name); if (menu == NULL) { EMSG2(_("E334: Menu not found: %s"), eap->arg); return; } /* Found the menu, so execute. * Use the Insert mode entry when returning to Insert mode. */ if (restart_edit && !current_SID ) { mode = (char_u *)"Insert"; idx = MENU_INDEX_INSERT; } else if (eap->addr_count) { pos_T tpos; mode = (char_u *)"Visual"; idx = MENU_INDEX_VISUAL; /* GEDDES: This is not perfect - but it is a * quick way of detecting whether we are doing this from a * selection - see if the range matches up with the visual * select start and end. */ if ((curbuf->b_visual.vi_start.lnum == eap->line1) && (curbuf->b_visual.vi_end.lnum) == eap->line2) { /* Set it up for visual mode - equivalent to gv. */ VIsual_mode = curbuf->b_visual.vi_mode; tpos = curbuf->b_visual.vi_end; curwin->w_cursor = curbuf->b_visual.vi_start; curwin->w_curswant = curbuf->b_visual.vi_curswant; } else { /* Set it up for line-wise visual mode */ VIsual_mode = 'V'; curwin->w_cursor.lnum = eap->line1; curwin->w_cursor.col = 1; tpos.lnum = eap->line2; tpos.col = MAXCOL; tpos.coladd = 0; } /* Activate visual mode */ VIsual_active = TRUE; VIsual_reselect = TRUE; check_cursor(); VIsual = curwin->w_cursor; curwin->w_cursor = tpos; check_cursor(); /* Adjust the cursor to make sure it is in the correct pos * for exclusive mode */ if (*p_sel == 'e' && gchar_cursor() != NUL) ++curwin->w_cursor.col; } else { mode = (char_u *)"Normal"; idx = MENU_INDEX_NORMAL; } if (idx != MENU_INDEX_INVALID && menu->strings[idx] != NULL) { /* When executing a script or function execute the commands right now. * Otherwise put them in the typeahead buffer. */ if (current_SID != 0) exec_normal_cmd(menu->strings[idx], menu->noremap[idx], menu->silent[idx]); else ins_typebuf(menu->strings[idx], menu->noremap[idx], 0, TRUE, menu->silent[idx]); } else EMSG2(_("E335: Menu not defined for %s mode"), mode); }
static int Python_Init(void) { if (!initialised) { #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000 PyObject *site; #endif #ifdef DYNAMIC_PYTHON if (!python_enabled(TRUE)) { EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); goto fail; } #endif #ifdef PYTHON_HOME Py_SetPythonHome(PYTHON_HOME); #endif init_structs(); #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000 /* Disable implicit 'import site', because it may cause Vim to exit * when it can't be found. */ Py_NoSiteFlag++; #endif #if !defined(MACOS) || defined(MACOS_X_UNIX) Py_Initialize(); #else PyMac_Initialize(); #endif #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000 /* 'import site' explicitly. */ site = PyImport_ImportModule("site"); if (site == NULL) { EMSG(_("E887: Sorry, this command is disabled, the Python's site module could not be loaded.")); goto fail; } Py_DECREF(site); #endif /* Initialise threads, and below save the state using * PyEval_SaveThread. Without the call to PyEval_SaveThread, thread * specific state (such as the system trace hook), will be lost * between invocations of Python code. */ PyEval_InitThreads(); #ifdef DYNAMIC_PYTHON get_exceptions(); #endif if (PythonIO_Init_io()) goto fail; if (PythonMod_Init()) goto fail; globals = PyModule_GetDict(PyImport_AddModule("__main__")); /* Remove the element from sys.path that was added because of our * argv[0] value in PythonMod_Init(). Previously we used an empty * string, but depending on the OS we then get an empty entry or * the current directory in sys.path. */ PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)"); /* lock is created and acquired in PyEval_InitThreads() and thread * state is created in Py_Initialize() * there _PyGILState_NoteThreadState() also sets gilcounter to 1 * (python must have threads enabled!) * so the following does both: unlock GIL and save thread state in TLS * without deleting thread state */ #ifndef PY_CAN_RECURSE saved_python_thread = #endif PyEval_SaveThread(); initialised = 1; } return 0; fail: /* We call PythonIO_Flush() here to print any Python errors. * This is OK, as it is possible to call this function even * if PythonIO_Init_io() has not completed successfully (it will * not do anything in this case). */ PythonIO_Flush(); return -1; }
int sc_main(int argc, char* argv[]) { if (argc != 7) { EMSG("Internal error in the call to sc_main.\nExpected: %s nb_cycles nb_proc nb_nodes nb_ifaces topology_file output_file\n", argv[0]); return EXIT_FAILURE; } int ncycles, nb_proc, nb_nodes, nb_iface; sscanf(argv[1],"%d",&ncycles); sscanf(argv[2],"%d",&nb_proc); sscanf(argv[3],"%d",&nb_nodes); sscanf(argv[4],"%d",&nb_iface); char *topo_file = argv[5]; char *output_file = argv[6]; struct timespec begin; struct timespec end; xsim_topology_init(topo_file, nb_nodes); /* To remove the warning about the deprecated usage */ // sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", SC_DO_NOTHING); char str[30]; char fifo_str[30]; xsim_sc_node<DSPIN_DATA_SIZE> * sc_node[nb_nodes]; xsim_sc_fifo_time<DSPIN_DATA_SIZE> * fifo[nb_nodes][nb_nodes][nb_iface]; int n = 0; int m = 0; int i = 0; for (n = 0 ; n<nb_nodes ; n++) { sprintf(str, "node[%x]", n); sc_node[n] = new xsim_sc_node<DSPIN_DATA_SIZE>(str, nb_nodes, nb_iface, n); } for (n = 0 ; n<nb_nodes ; n++) { for (m = 0 ; m<nb_nodes ; m++) { for (i=0 ; i<nb_iface ; i++) { sprintf(fifo_str, "fifo[%d]->[%d]_%dif", n, m, i); fifo[n][m][i] = new xsim_sc_fifo_time<DSPIN_DATA_SIZE>(fifo_str, xsim_topology_travel_time(n, m)+1); } } } for (n = 0 ; n<nb_nodes ; n++) { for (m = 0 ; m<nb_nodes ; m++) { /* n indicates the source ; m indicates the destination */ for (i=0 ; i<nb_iface ; i++) { sc_node[n]->wrapper_send[i]->out[m](*fifo[n][m][i]); sc_node[n]->wrapper_recv[i]->in[m] (*fifo[m][n][i]); fifo[m][n][i]->event_register(sc_node[n]->wrapper_recv[i]->event_receive_a_msg); } } } xsim_topology_free(nb_nodes); printf("Initialization successful\n"); float per = MIN_PER; for (n = 0 ; n<nb_nodes ; n++) { sc_node[n]->set_percent((float)per/100); //sc_node.set_percent((float)per/100) * PER[z*NUM_Y*NUM_X + y*NUM_X + x] * ((MAX_PACKET_LENGTH+MIN_PACKET_LENGTH)/2); } printf("Run the simulation.\n"); /* begin measure */ clock_gettime(CLOCK_REALTIME, &(begin)); sc_start(ncycles, TIMING); /* end measure */ clock_gettime(CLOCK_REALTIME, &(end)); /* output the measures */ int size = snprintf(NULL, 0, COMMAND); char *command = (char*) malloc(sizeof(char) * (size+1)); sprintf(command, COMMAND); system(command); free(command); fprintf(stderr, "End of simulation\n"); for (n = 0 ; n<nb_nodes ; n++) { delete sc_node[n]; for (m = 0 ; m<nb_nodes ; m++) { for (i=0 ; i<nb_iface ; i++) { delete fifo[n][m][i]; } } } return EXIT_SUCCESS; };
static inline int get_int(int *current, char *line, int line_nb) { int res = 0; switch (line[*current]) { case '0': break; case '1': break; case '2': break; case '3': break; case '4': break; case '5': break; case '6': break; case '7': break; case '8': break; case '9': break; default: EMSG("line %d: expected a number, find: %c.\n", line_nb, line[*current]); return -1; } while (1) { switch (line[*current]) { case '0': res *= 10; break; case '1': res *= 10; res += 1; break; case '2': res *= 10; res += 2; break; case '3': res *= 10; res += 3; break; case '4': res *= 10; res += 4; break; case '5': res *= 10; res += 5; break; case '6': res *= 10; res += 6; break; case '7': res *= 10; res += 7; break; case '8': res *= 10; res += 8; break; case '9': res *= 10; res += 9; break; default: return res; } (*current)++; } }
// Replace any terminal code strings in from[] with the equivalent internal // vim representation. This is used for the "from" and "to" part of a // mapping, and the "to" part of a menu command. // Any strings like "<C-UP>" are also replaced, unless 'cpoptions' contains // '<'. // K_SPECIAL by itself is replaced by K_SPECIAL KS_SPECIAL KE_FILLER. // // The replacement is done in result[] and finally copied into allocated // memory. If this all works well *bufp is set to the allocated memory and a // pointer to it is returned. If something fails *bufp is set to NULL and from // is returned. // // CTRL-V characters are removed. When "from_part" is TRUE, a trailing CTRL-V // is included, otherwise it is removed (for ":map xx ^V", maps xx to // nothing). When 'cpoptions' does not contain 'B', a backslash can be used // instead of a CTRL-V. char_u * replace_termcodes ( char_u *from, char_u **bufp, int from_part, int do_lt, // also translate <lt> int special // always accept <key> notation ) { ssize_t i; size_t slen; char_u key; size_t dlen = 0; char_u *src; int do_backslash; // backslash is a special character int do_special; // recognize <> key codes char_u *result; // buffer for resulting string do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL); do_special = (vim_strchr(p_cpo, CPO_SPECI) == NULL) || special; // Allocate space for the translation. Worst case a single character is // replaced by 6 bytes (shifted special key), plus a NUL at the end. result = xmalloc(STRLEN(from) * 6 + 1); src = from; // Check for #n at start only: function key n if (from_part && src[0] == '#' && VIM_ISDIGIT(src[1])) { // function key result[dlen++] = K_SPECIAL; result[dlen++] = 'k'; if (src[1] == '0') { result[dlen++] = ';'; // #0 is F10 is "k;" } else { result[dlen++] = src[1]; // #3 is F3 is "k3" } src += 2; } // Copy each byte from *from to result[dlen] while (*src != NUL) { // If 'cpoptions' does not contain '<', check for special key codes, // like "<C-S-LeftMouse>" if (do_special && (do_lt || STRNCMP(src, "<lt>", 4) != 0)) { // Replace <SID> by K_SNR <script-nr> _. // (room: 5 * 6 = 30 bytes; needed: 3 + <nr> + 1 <= 14) if (STRNICMP(src, "<SID>", 5) == 0) { if (current_SID <= 0) { EMSG(_(e_usingsid)); } else { src += 5; result[dlen++] = K_SPECIAL; result[dlen++] = (int)KS_EXTRA; result[dlen++] = (int)KE_SNR; sprintf((char *)result + dlen, "%" PRId64, (int64_t)current_SID); dlen += STRLEN(result + dlen); result[dlen++] = '_'; continue; } } slen = trans_special(&src, result + dlen, TRUE); if (slen) { dlen += slen; continue; } } if (do_special) { char_u *p, *s, len; // Replace <Leader> by the value of "mapleader". // Replace <LocalLeader> by the value of "maplocalleader". // If "mapleader" or "maplocalleader" isn't set use a backslash. if (STRNICMP(src, "<Leader>", 8) == 0) { len = 8; p = get_var_value((char_u *)"g:mapleader"); } else if (STRNICMP(src, "<LocalLeader>", 13) == 0) { len = 13; p = get_var_value((char_u *)"g:maplocalleader"); } else { len = 0; p = NULL; } if (len != 0) { // Allow up to 8 * 6 characters for "mapleader". if (p == NULL || *p == NUL || STRLEN(p) > 8 * 6) { s = (char_u *)"\\"; } else { s = p; } while (*s != NUL) { result[dlen++] = *s++; } src += len; continue; } } // Remove CTRL-V and ignore the next character. // For "from" side the CTRL-V at the end is included, for the "to" // part it is removed. // If 'cpoptions' does not contain 'B', also accept a backslash. key = *src; if (key == Ctrl_V || (do_backslash && key == '\\')) { ++src; // skip CTRL-V or backslash if (*src == NUL) { if (from_part) { result[dlen++] = key; } break; } } // skip multibyte char correctly for (i = (*mb_ptr2len)(src); i > 0; --i) { // If the character is K_SPECIAL, replace it with K_SPECIAL // KS_SPECIAL KE_FILLER. // If compiled with the GUI replace CSI with K_CSI. if (*src == K_SPECIAL) { result[dlen++] = K_SPECIAL; result[dlen++] = KS_SPECIAL; result[dlen++] = KE_FILLER; } else { result[dlen++] = *src; } ++src; } } result[dlen] = NUL; *bufp = xrealloc(result, dlen + 1); return *bufp; }
/* * Initialization routine for vim_findfile(). * * Returns the newly allocated search context or NULL if an error occurred. * * Don't forget to clean up by calling vim_findfile_cleanup() if you are done * with the search context. * * Find the file 'filename' in the directory 'path'. * The parameter 'path' may contain wildcards. If so only search 'level' * directories deep. The parameter 'level' is the absolute maximum and is * not related to restricts given to the '**' wildcard. If 'level' is 100 * and you use '**200' vim_findfile() will stop after 100 levels. * * 'filename' cannot contain wildcards! It is used as-is, no backslashes to * escape special characters. * * If 'stopdirs' is not NULL and nothing is found downward, the search is * restarted on the next higher directory level. This is repeated until the * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the * format ";*<dirname>*\(;<dirname>\)*;\=$". * * If the 'path' is relative, the starting dir for the search is either VIM's * current dir or if the path starts with "./" the current files dir. * If the 'path' is absolute, the starting dir is that part of the path before * the first wildcard. * * Upward search is only done on the starting dir. * * If 'free_visited' is TRUE the list of already visited files/directories is * cleared. Set this to FALSE if you just want to search from another * directory, but want to be sure that no directory from a previous search is * searched again. This is useful if you search for a file at different places. * The list of visited files/dirs can also be cleared with the function * vim_findfile_free_visited(). * * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both. * * A search context returned by a previous call to vim_findfile_init() can be * passed in the parameter "search_ctx_arg". This context is reused and * reinitialized with the new parameters. The list of already visited * directories from this context is only deleted if the parameter * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed * if the reinitialization fails. * * If you don't have a search context from a previous call "search_ctx_arg" * must be NULL. * * This function silently ignores a few errors, vim_findfile() will have * limited functionality then. */ void * vim_findfile_init ( char_u *path, char_u *filename, char_u *stopdirs, int level, int free_visited, int find_what, void *search_ctx_arg, int tagfile, /* expanding names of tags files */ char_u *rel_fname /* file name to use for "." */ ) { char_u *wc_part; ff_stack_T *sptr; ff_search_ctx_T *search_ctx; /* If a search context is given by the caller, reuse it, else allocate a * new one. */ if (search_ctx_arg != NULL) search_ctx = search_ctx_arg; else { search_ctx = xcalloc(1, sizeof(ff_search_ctx_T)); } search_ctx->ffsc_find_what = find_what; search_ctx->ffsc_tagfile = tagfile; /* clear the search context, but NOT the visited lists */ ff_clear(search_ctx); /* clear visited list if wanted */ if (free_visited == TRUE) vim_findfile_free_visited(search_ctx); else { /* Reuse old visited lists. Get the visited list for the given * filename. If no list for the current filename exists, creates a new * one. */ search_ctx->ffsc_visited_list = ff_get_visited_list(filename, &search_ctx->ffsc_visited_lists_list); if (search_ctx->ffsc_visited_list == NULL) goto error_return; search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename, &search_ctx->ffsc_dir_visited_lists_list); if (search_ctx->ffsc_dir_visited_list == NULL) goto error_return; } if (ff_expand_buffer == NULL) { ff_expand_buffer = xmalloc(MAXPATHL); } /* Store information on starting dir now if path is relative. * If path is absolute, we do that later. */ if (path[0] == '.' && (vim_ispathsep(path[1]) || path[1] == NUL) && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL) && rel_fname != NULL) { size_t len = (size_t)(path_tail(rel_fname) - rel_fname); if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL) { /* Make the start dir an absolute path name. */ STRLCPY(ff_expand_buffer, rel_fname, len + 1); search_ctx->ffsc_start_dir = (char_u *)FullName_save((char *)ff_expand_buffer, FALSE); } else search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len); if (*++path != NUL) ++path; } else if (*path == NUL || !vim_isAbsName(path)) { #ifdef BACKSLASH_IN_FILENAME /* "c:dir" needs "c:" to be expanded, otherwise use current dir */ if (*path != NUL && path[1] == ':') { char_u drive[3]; drive[0] = path[0]; drive[1] = ':'; drive[2] = NUL; if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL) goto error_return; path += 2; } else #endif if (os_dirname(ff_expand_buffer, MAXPATHL) == FAIL) goto error_return; search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer); #ifdef BACKSLASH_IN_FILENAME /* A path that starts with "/dir" is relative to the drive, not to the * directory (but not for "//machine/dir"). Only use the drive name. */ if ((*path == '/' || *path == '\\') && path[1] != path[0] && search_ctx->ffsc_start_dir[1] == ':') search_ctx->ffsc_start_dir[2] = NUL; #endif } /* * If stopdirs are given, split them into an array of pointers. * If this fails (mem allocation), there is no upward search at all or a * stop directory is not recognized -> continue silently. * If stopdirs just contains a ";" or is empty, * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This * is handled as unlimited upward search. See function * ff_path_in_stoplist() for details. */ if (stopdirs != NULL) { char_u *walker = stopdirs; while (*walker == ';') walker++; size_t dircount = 1; search_ctx->ffsc_stopdirs_v = xmalloc(sizeof(char_u *)); do { char_u *helper; void *ptr; helper = walker; ptr = xrealloc(search_ctx->ffsc_stopdirs_v, (dircount + 1) * sizeof(char_u *)); search_ctx->ffsc_stopdirs_v = ptr; walker = vim_strchr(walker, ';'); if (walker) { assert(walker - helper >= 0); search_ctx->ffsc_stopdirs_v[dircount-1] = vim_strnsave(helper, (size_t)(walker - helper)); walker++; } else /* this might be "", which means ascent till top * of directory tree. */ search_ctx->ffsc_stopdirs_v[dircount-1] = vim_strsave(helper); dircount++; } while (walker != NULL); search_ctx->ffsc_stopdirs_v[dircount-1] = NULL; } search_ctx->ffsc_level = level; /* split into: * -fix path * -wildcard_stuff (might be NULL) */ wc_part = vim_strchr(path, '*'); if (wc_part != NULL) { int64_t llevel; int len; char *errpt; /* save the fix part of the path */ assert(wc_part - path >= 0); search_ctx->ffsc_fix_path = vim_strnsave(path, (size_t)(wc_part - path)); /* * copy wc_path and add restricts to the '**' wildcard. * The octet after a '**' is used as a (binary) counter. * So '**3' is transposed to '**^C' ('^C' is ASCII value 3) * or '**76' is transposed to '**N'( 'N' is ASCII value 76). * If no restrict is given after '**' the default is used. * Due to this technique the path looks awful if you print it as a * string. */ len = 0; while (*wc_part != NUL) { if (len + 5 >= MAXPATHL) { EMSG(_(e_pathtoolong)); break; } if (STRNCMP(wc_part, "**", 2) == 0) { ff_expand_buffer[len++] = *wc_part++; ff_expand_buffer[len++] = *wc_part++; llevel = strtol((char *)wc_part, &errpt, 10); if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255) ff_expand_buffer[len++] = (char_u)llevel; else if ((char_u *)errpt != wc_part && llevel == 0) /* restrict is 0 -> remove already added '**' */ len -= 2; else ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND; wc_part = (char_u *)errpt; if (*wc_part != NUL && !vim_ispathsep(*wc_part)) { EMSG2(_( "E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR); goto error_return; } } else ff_expand_buffer[len++] = *wc_part++; } ff_expand_buffer[len] = NUL; search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer); } else search_ctx->ffsc_fix_path = vim_strsave(path); if (search_ctx->ffsc_start_dir == NULL) { /* store the fix part as startdir. * This is needed if the parameter path is fully qualified. */ search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path); search_ctx->ffsc_fix_path[0] = NUL; } /* create an absolute path */ if (STRLEN(search_ctx->ffsc_start_dir) + STRLEN(search_ctx->ffsc_fix_path) + 3 >= MAXPATHL) { EMSG(_(e_pathtoolong)); goto error_return; } STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir); add_pathsep((char *)ff_expand_buffer); { size_t eb_len = STRLEN(ff_expand_buffer); char_u *buf = xmalloc(eb_len + STRLEN(search_ctx->ffsc_fix_path) + 1); STRCPY(buf, ff_expand_buffer); STRCPY(buf + eb_len, search_ctx->ffsc_fix_path); if (os_isdir(buf)) { STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path); add_pathsep((char *)ff_expand_buffer); } else { char_u *p = path_tail(search_ctx->ffsc_fix_path); char_u *wc_path = NULL; char_u *temp = NULL; int len = 0; if (p > search_ctx->ffsc_fix_path) { len = (int)(p - search_ctx->ffsc_fix_path) - 1; STRNCAT(ff_expand_buffer, search_ctx->ffsc_fix_path, len); add_pathsep((char *)ff_expand_buffer); } else { len = (int)STRLEN(search_ctx->ffsc_fix_path); } if (search_ctx->ffsc_wc_path != NULL) { wc_path = vim_strsave(search_ctx->ffsc_wc_path); temp = xmalloc(STRLEN(search_ctx->ffsc_wc_path) + STRLEN(search_ctx->ffsc_fix_path + len) + 1); STRCPY(temp, search_ctx->ffsc_fix_path + len); STRCAT(temp, search_ctx->ffsc_wc_path); xfree(search_ctx->ffsc_wc_path); xfree(wc_path); search_ctx->ffsc_wc_path = temp; } } xfree(buf); } sptr = ff_create_stack_element(ff_expand_buffer, search_ctx->ffsc_wc_path, level, 0); ff_push(search_ctx, sptr); search_ctx->ffsc_file_to_search = vim_strsave(filename); return search_ctx; error_return: /* * We clear the search context now! * Even when the caller gave us a (perhaps valid) context we free it here, * as we might have already destroyed it. */ vim_findfile_cleanup(search_ctx); return NULL; }
static void error_print(int state) { #ifndef DYNAMIC_RUBY #if !(defined(RUBY_VERSION) && RUBY_VERSION >= 19) \ && !(defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19) RUBYEXTERN VALUE ruby_errinfo; #endif #endif VALUE eclass; VALUE einfo; char buff[BUFSIZ]; #define TAG_RETURN 0x1 #define TAG_BREAK 0x2 #define TAG_NEXT 0x3 #define TAG_RETRY 0x4 #define TAG_REDO 0x5 #define TAG_RAISE 0x6 #define TAG_THROW 0x7 #define TAG_FATAL 0x8 #define TAG_MASK 0xf switch (state) { case TAG_RETURN: EMSG(_("E267: unexpected return")); break; case TAG_NEXT: EMSG(_("E268: unexpected next")); break; case TAG_BREAK: EMSG(_("E269: unexpected break")); break; case TAG_REDO: EMSG(_("E270: unexpected redo")); break; case TAG_RETRY: EMSG(_("E271: retry outside of rescue clause")); break; case TAG_RAISE: case TAG_FATAL: #ifdef RUBY19_OR_LATER eclass = CLASS_OF(rb_errinfo()); einfo = rb_obj_as_string(rb_errinfo()); #else eclass = CLASS_OF(ruby_errinfo); einfo = rb_obj_as_string(ruby_errinfo); #endif if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0) { EMSG(_("E272: unhandled exception")); } else { VALUE epath; char *p; epath = rb_class_path(eclass); vim_snprintf(buff, BUFSIZ, "%s: %s", RSTRING_PTR(epath), RSTRING_PTR(einfo)); p = strchr(buff, '\n'); if (p) *p = '\0'; EMSG(buff); } break; default: vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state); EMSG(buff); break; } }
/// Shrink a hashtable when there is too much empty space. /// Grow a hashtable when there is not enough empty space. /// /// @param ht /// @param minitems minimal number of items /// /// @returns OK or FAIL (out of memory). static int hash_may_resize(hashtab_T *ht, int minitems) { hashitem_T temparray[HT_INIT_SIZE]; hashitem_T *oldarray, *newarray; hashitem_T *olditem, *newitem; unsigned newi; int todo; long_u oldsize, newsize; long_u minsize; long_u newmask; hash_T perturb; // Don't resize a locked table. if (ht->ht_locked > 0) { return OK; } #ifdef HT_DEBUG if (ht->ht_used > ht->ht_filled) { EMSG("hash_may_resize(): more used than filled"); } if (ht->ht_filled >= ht->ht_mask + 1) { EMSG("hash_may_resize(): table completely filled"); } #endif // ifdef HT_DEBUG if (minitems == 0) { // Return quickly for small tables with at least two NULL items. NULL // items are required for the lookup to decide a key isn't there. if ((ht->ht_filled < HT_INIT_SIZE - 1) && (ht->ht_array == ht->ht_smallarray)) { return OK; } // Grow or refill the array when it's more than 2/3 full (including // removed items, so that they get cleaned up). // Shrink the array when it's less than 1/5 full. When growing it is // at least 1/4 full (avoids repeated grow-shrink operations) oldsize = ht->ht_mask + 1; if ((ht->ht_filled * 3 < oldsize * 2) && (ht->ht_used > oldsize / 5)) { return OK; } if (ht->ht_used > 1000) { // it's big, don't make too much room minsize = ht->ht_used * 2; } else { // make plenty of room minsize = ht->ht_used * 4; } } else { // Use specified size. if ((long_u)minitems < ht->ht_used) { // just in case... minitems = (int)ht->ht_used; } // array is up to 2/3 full minsize = minitems * 3 / 2; } newsize = HT_INIT_SIZE; while (newsize < minsize) { // make sure it's always a power of 2 newsize <<= 1; if (newsize == 0) { // overflow return FAIL; } } if (newsize == HT_INIT_SIZE) { // Use the small array inside the hashdict structure. newarray = ht->ht_smallarray; if (ht->ht_array == newarray) { // Moving from ht_smallarray to ht_smallarray! Happens when there // are many removed items. Copy the items to be able to clean up // removed items. mch_memmove(temparray, newarray, sizeof(temparray)); oldarray = temparray; } else { oldarray = ht->ht_array; } } else { // Allocate an array. newarray = (hashitem_T *)alloc((unsigned)(sizeof(hashitem_T) * newsize)); if (newarray == NULL) { // Out of memory. When there are NULL items still return OK. // Otherwise set ht_error, because lookup may result in a hang if // we add another item. if (ht->ht_filled < ht->ht_mask) { return OK; } ht->ht_error = TRUE; return FAIL; } oldarray = ht->ht_array; } memset(newarray, 0, (size_t)(sizeof(hashitem_T) * newsize)); // Move all the items from the old array to the new one, placing them in // the right spot. The new array won't have any removed items, thus this // is also a cleanup action. newmask = newsize - 1; todo = (int)ht->ht_used; for (olditem = oldarray; todo > 0; ++olditem) { if (!HASHITEM_EMPTY(olditem)) { // The algorithm to find the spot to add the item is identical to // the algorithm to find an item in hash_lookup(). But we only // need to search for a NULL key, thus it's simpler. newi = (unsigned)(olditem->hi_hash & newmask); newitem = &newarray[newi]; if (newitem->hi_key != NULL) { for (perturb = olditem->hi_hash;; perturb >>= PERTURB_SHIFT) { newi = (unsigned)((newi << 2U) + newi + perturb + 1U); newitem = &newarray[newi & newmask]; if (newitem->hi_key == NULL) { break; } } } *newitem = *olditem; todo--; } }
/* * Encode "val" into "gap". * Return FAIL or OK. */ static int json_encode_item(garray_T *gap, typval_T *val, int copyID, int options) { char_u numbuf[NUMBUFLEN]; char_u *res; list_T *l; dict_T *d; switch (val->v_type) { case VAR_SPECIAL: switch (val->vval.v_number) { case VVAL_FALSE: ga_concat(gap, (char_u *)"false"); break; case VVAL_TRUE: ga_concat(gap, (char_u *)"true"); break; case VVAL_NONE: if ((options & JSON_JS) != 0 && (options & JSON_NO_NONE) == 0) /* empty item */ break; /* FALLTHROUGH */ case VVAL_NULL: ga_concat(gap, (char_u *)"null"); break; } break; case VAR_NUMBER: vim_snprintf((char *)numbuf, NUMBUFLEN, "%ld", (long)val->vval.v_number); ga_concat(gap, numbuf); break; case VAR_STRING: res = val->vval.v_string; write_string(gap, res); break; case VAR_FUNC: case VAR_JOB: case VAR_CHANNEL: /* no JSON equivalent TODO: better error */ EMSG(_(e_invarg)); return FAIL; case VAR_LIST: l = val->vval.v_list; if (l == NULL) ga_concat(gap, (char_u *)"null"); else { if (l->lv_copyID == copyID) ga_concat(gap, (char_u *)"[]"); else { listitem_T *li; l->lv_copyID = copyID; ga_append(gap, '['); for (li = l->lv_first; li != NULL && !got_int; ) { if (json_encode_item(gap, &li->li_tv, copyID, options & JSON_JS) == FAIL) return FAIL; if ((options & JSON_JS) && li->li_next == NULL && li->li_tv.v_type == VAR_SPECIAL && li->li_tv.vval.v_number == VVAL_NONE) /* add an extra comma if the last item is v:none */ ga_append(gap, ','); li = li->li_next; if (li != NULL) ga_append(gap, ','); } ga_append(gap, ']'); l->lv_copyID = 0; } } break; case VAR_DICT: d = val->vval.v_dict; if (d == NULL) ga_concat(gap, (char_u *)"null"); else { if (d->dv_copyID == copyID) ga_concat(gap, (char_u *)"{}"); else { int first = TRUE; int todo = (int)d->dv_hashtab.ht_used; hashitem_T *hi; d->dv_copyID = copyID; ga_append(gap, '{'); for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; if (first) first = FALSE; else ga_append(gap, ','); if ((options & JSON_JS) && is_simple_key(hi->hi_key)) ga_concat(gap, hi->hi_key); else write_string(gap, hi->hi_key); ga_append(gap, ':'); if (json_encode_item(gap, &dict_lookup(hi)->di_tv, copyID, options | JSON_NO_NONE) == FAIL) return FAIL; } ga_append(gap, '}'); d->dv_copyID = 0; } } break; case VAR_FLOAT: #ifdef FEAT_FLOAT vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", val->vval.v_float); ga_concat(gap, numbuf); break; #endif case VAR_UNKNOWN: EMSG2(_(e_intern2), "json_encode_item()"); return FAIL; } return OK; }
static void init_runtime(unsigned long pageable_part) { size_t n; size_t init_size = (size_t)__init_size; size_t pageable_size = __pageable_end - __pageable_start; size_t hash_size = (pageable_size / SMALL_PAGE_SIZE) * TEE_SHA256_HASH_SIZE; tee_mm_entry_t *mm; uint8_t *paged_store; uint8_t *hashes; assert(pageable_size % SMALL_PAGE_SIZE == 0); assert(hash_size == (size_t)__tmp_hashes_size); /* * This needs to be initialized early to support address lookup * in MEM_AREA_TEE_RAM */ tee_pager_early_init(); thread_init_boot_thread(); init_asan(); malloc_add_pool(__heap1_start, __heap1_end - __heap1_start); malloc_add_pool(__heap2_start, __heap2_end - __heap2_start); hashes = malloc(hash_size); IMSG_RAW("\n"); IMSG("Pager is enabled. Hashes: %zu bytes", hash_size); assert(hashes); asan_memcpy_unchecked(hashes, __tmp_hashes_start, hash_size); /* * Need tee_mm_sec_ddr initialized to be able to allocate secure * DDR below. */ teecore_init_ta_ram(); carve_out_asan_mem(&tee_mm_sec_ddr); mm = tee_mm_alloc(&tee_mm_sec_ddr, pageable_size); assert(mm); paged_store = phys_to_virt(tee_mm_get_smem(mm), MEM_AREA_TA_RAM); /* * Load pageable part in the dedicated allocated area: * - Move pageable non-init part into pageable area. Note bootloader * may have loaded it anywhere in TA RAM hence use memmove(). * - Copy pageable init part from current location into pageable area. */ memmove(paged_store + init_size, phys_to_virt(pageable_part, core_mmu_get_type_by_pa(pageable_part)), __pageable_part_end - __pageable_part_start); asan_memcpy_unchecked(paged_store, __init_start, init_size); /* Check that hashes of what's in pageable area is OK */ DMSG("Checking hashes of pageable area"); for (n = 0; (n * SMALL_PAGE_SIZE) < pageable_size; n++) { const uint8_t *hash = hashes + n * TEE_SHA256_HASH_SIZE; const uint8_t *page = paged_store + n * SMALL_PAGE_SIZE; TEE_Result res; DMSG("hash pg_idx %zu hash %p page %p", n, hash, page); res = hash_sha256_check(hash, page, SMALL_PAGE_SIZE); if (res != TEE_SUCCESS) { EMSG("Hash failed for page %zu at %p: res 0x%x", n, page, res); panic(); } } /* * Assert prepaged init sections are page aligned so that nothing * trails uninited at the end of the premapped init area. */ assert(!(init_size & SMALL_PAGE_MASK)); /* * Initialize the virtual memory pool used for main_mmu_l2_ttb which * is supplied to tee_pager_init() below. */ init_vcore(&tee_mm_vcore); /* * Assign alias area for pager end of the small page block the rest * of the binary is loaded into. We're taking more than needed, but * we're guaranteed to not need more than the physical amount of * TZSRAM. */ mm = tee_mm_alloc2(&tee_mm_vcore, (vaddr_t)tee_mm_vcore.hi - TZSRAM_SIZE, TZSRAM_SIZE); assert(mm); tee_pager_set_alias_area(mm); /* * Claim virtual memory which isn't paged. * Linear memory (flat map core memory) ends there. */ mm = tee_mm_alloc2(&tee_mm_vcore, VCORE_UNPG_RX_PA, (vaddr_t)(__pageable_start - VCORE_UNPG_RX_PA)); assert(mm); /* * Allocate virtual memory for the pageable area and let the pager * take charge of all the pages already assigned to that memory. */ mm = tee_mm_alloc2(&tee_mm_vcore, (vaddr_t)__pageable_start, pageable_size); assert(mm); tee_pager_add_core_area(tee_mm_get_smem(mm), tee_mm_get_bytes(mm), TEE_MATTR_PRX, paged_store, hashes); tee_pager_add_pages((vaddr_t)__pageable_start, init_size / SMALL_PAGE_SIZE, false); tee_pager_add_pages((vaddr_t)__pageable_start + init_size, (pageable_size - init_size) / SMALL_PAGE_SIZE, true); /* * There may be physical pages in TZSRAM before the core load address. * These pages can be added to the physical pages pool of the pager. * This setup may happen when a the secure bootloader runs in TZRAM * and its memory can be reused by OP-TEE once boot stages complete. */ tee_pager_add_pages(tee_mm_vcore.lo, (VCORE_UNPG_RX_PA - tee_mm_vcore.lo) / SMALL_PAGE_SIZE, true); }
xsim_node_t * xsim_node_init(xsim_t *xsim, int node_id) { int i = 0, ret; xsim_msg_box_t *box = NULL; xsim_node_t *res = NULL; /* * Allocation first + vars */ res = malloc(sizeof(xsim_node_t)); res->node_id = node_id; res->nb_nodes = xsim->nb_nodes; res->nb_iface = xsim->nb_x; res->seq_id = 0; res->current_time = 0; /* Init iface */ res->iface = malloc(sizeof(xsim_iface_t*) * res->nb_iface); for (i=0 ; i<res->nb_iface ; i++) { res->iface[i] = xsim_iface_new(res, i); } /* Init recv_queue */ res->recv_queue = malloc(sizeof(xsim_msg_list_t *) * xsim->nb_x); for(i = 0; i < res->nb_iface; i++) { res->recv_queue[i] = xsim_msg_list_new(); } /* Init send_queue */ res->send_queue = xsim_FIFO_list_new(); xsim_barrier_init(&res->list_barrier, 2); /* * Attach shared memory */ box = xsim->shm_addr; res->msg_box = box; xsim_msg_box_node_init(box, node_id); res->current = xsim_msg_list_first(&(box->msg_queue)); /* Init the table which is used to check if we do not forget message */ res->seq_msg_table = malloc(sizeof(uint32_t) * res->nb_nodes); memset(res->seq_msg_table, 0, sizeof(uint32_t) * res->nb_nodes); #if defined(PERFORMANCE_EVALUATION) && defined(BENCHMARK) xsim_barrier_wait(&box->init_barrier); /* test the performance evaluation output */ xsim_perf_benchmark(res); #endif /* * The barrier is usefull to avoid that a listener is running * during the benchmark measure. */ xsim_barrier_wait(&box->init_barrier); DMSG("Ready to go\n"); res->list_state = LIST_STATE_STARTING; ret = pthread_create(&(res->listener), NULL, &xsim_listener, (void *)res); if( ret != 0 ) { EMSG("Listener creation error\n"); } /* * Wait for listener to be started. */ xsim_barrier_wait(&res->list_barrier); //DMSG("<%2d> my listener is ready\n", res->node_id); return res; }
/* * Do the :menu command and relatives. */ void ex_menu ( exarg_T *eap /* Ex command arguments */ ) { char_u *menu_path; int modes; char_u *map_to; int noremap; int silent = FALSE; int special = FALSE; int unmenu; char_u *map_buf; char_u *arg; char_u *p; int i; int pri_tab[MENUDEPTH + 1]; int enable = MAYBE; /* TRUE for "menu enable", FALSE for "menu * disable */ vimmenu_T menuarg; modes = get_menu_cmd_modes(eap->cmd, eap->forceit, &noremap, &unmenu); arg = eap->arg; for (;; ) { if (STRNCMP(arg, "<script>", 8) == 0) { noremap = REMAP_SCRIPT; arg = skipwhite(arg + 8); continue; } if (STRNCMP(arg, "<silent>", 8) == 0) { silent = TRUE; arg = skipwhite(arg + 8); continue; } if (STRNCMP(arg, "<special>", 9) == 0) { special = TRUE; arg = skipwhite(arg + 9); continue; } break; } /* Locate an optional "icon=filename" argument. */ if (STRNCMP(arg, "icon=", 5) == 0) { arg += 5; while (*arg != NUL && *arg != ' ') { if (*arg == '\\') STRMOVE(arg, arg + 1); mb_ptr_adv(arg); } if (*arg != NUL) { *arg++ = NUL; arg = skipwhite(arg); } } /* * Fill in the priority table. */ for (p = arg; *p; ++p) if (!VIM_ISDIGIT(*p) && *p != '.') break; if (vim_iswhite(*p)) { for (i = 0; i < MENUDEPTH && !vim_iswhite(*arg); ++i) { pri_tab[i] = getdigits_int(&arg); if (pri_tab[i] == 0) pri_tab[i] = 500; if (*arg == '.') ++arg; } arg = skipwhite(arg); } else if (eap->addr_count && eap->line2 != 0) { pri_tab[0] = eap->line2; i = 1; } else i = 0; while (i < MENUDEPTH) pri_tab[i++] = 500; pri_tab[MENUDEPTH] = -1; /* mark end of the table */ /* * Check for "disable" or "enable" argument. */ if (STRNCMP(arg, "enable", 6) == 0 && vim_iswhite(arg[6])) { enable = TRUE; arg = skipwhite(arg + 6); } else if (STRNCMP(arg, "disable", 7) == 0 && vim_iswhite(arg[7])) { enable = FALSE; arg = skipwhite(arg + 7); } /* * If there is no argument, display all menus. */ if (*arg == NUL) { show_menus(arg, modes); return; } menu_path = arg; if (*menu_path == '.') { EMSG2(_(e_invarg2), menu_path); goto theend; } map_to = menu_translate_tab_and_shift(arg); /* * If there is only a menu name, display menus with that name. */ if (*map_to == NUL && !unmenu && enable == MAYBE) { show_menus(menu_path, modes); goto theend; } else if (*map_to != NUL && (unmenu || enable != MAYBE)) { EMSG(_(e_trailing)); goto theend; } if (enable != MAYBE) { /* * Change sensitivity of the menu. * For the PopUp menu, remove a menu for each mode separately. * Careful: menu_nable_recurse() changes menu_path. */ if (STRCMP(menu_path, "*") == 0) /* meaning: do all menus */ menu_path = (char_u *)""; if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; ++i) if (modes & (1 << i)) { p = popup_mode_name(menu_path, i); menu_nable_recurse(root_menu, p, MENU_ALL_MODES, enable); free(p); } } menu_nable_recurse(root_menu, menu_path, modes, enable); } else if (unmenu) { /* * Delete menu(s). */ if (STRCMP(menu_path, "*") == 0) /* meaning: remove all menus */ menu_path = (char_u *)""; /* * For the PopUp menu, remove a menu for each mode separately. */ if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; ++i) if (modes & (1 << i)) { p = popup_mode_name(menu_path, i); remove_menu(&root_menu, p, MENU_ALL_MODES, TRUE); free(p); } } /* Careful: remove_menu() changes menu_path */ remove_menu(&root_menu, menu_path, modes, FALSE); } else { /* * Add menu(s). * Replace special key codes. */ if (STRICMP(map_to, "<nop>") == 0) { /* "<Nop>" means nothing */ map_to = (char_u *)""; map_buf = NULL; } else if (modes & MENU_TIP_MODE) map_buf = NULL; /* Menu tips are plain text. */ else map_to = replace_termcodes(map_to, &map_buf, FALSE, TRUE, special); menuarg.modes = modes; menuarg.noremap[0] = noremap; menuarg.silent[0] = silent; add_menu_path(menu_path, &menuarg, pri_tab, map_to ); /* * For the PopUp menu, add a menu for each mode separately. */ if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; ++i) if (modes & (1 << i)) { p = popup_mode_name(menu_path, i); // Include all modes, to make ":amenu" work menuarg.modes = modes; add_menu_path(p, &menuarg, pri_tab, map_to); free(p); } } free(map_buf); } theend: ; }
/* * Remove the (sub)menu with the given name from the menu hierarchy * Called recursively. */ static int remove_menu ( vimmenu_T **menup, char_u *name, int modes, int silent /* don't give error messages */ ) { vimmenu_T *menu; vimmenu_T *child; char_u *p; if (*menup == NULL) return OK; /* Got to bottom of hierarchy */ /* Get name of this element in the menu hierarchy */ p = menu_name_skip(name); /* Find the menu */ while ((menu = *menup) != NULL) { if (*name == NUL || menu_name_equal(name, menu)) { if (*p != NUL && menu->children == NULL) { if (!silent) EMSG(_(e_notsubmenu)); return FAIL; } if ((menu->modes & modes) != 0x0) { #if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) /* * If we are removing all entries for this menu,MENU_ALL_MODES, * Then kill any tearoff before we start */ if (*p == NUL && modes == MENU_ALL_MODES) { if (IsWindow(menu->tearoff_handle)) DestroyWindow(menu->tearoff_handle); } #endif if (remove_menu(&menu->children, p, modes, silent) == FAIL) return FAIL; } else if (*name != NUL) { if (!silent) EMSG(_(e_othermode)); return FAIL; } /* * When name is empty, we are removing all menu items for the given * modes, so keep looping, otherwise we are just removing the named * menu item (which has been found) so break here. */ if (*name != NUL) break; /* Remove the menu item for the given mode[s]. If the menu item * is no longer valid in ANY mode, delete it */ menu->modes &= ~modes; if (modes & MENU_TIP_MODE) free_menu_string(menu, MENU_INDEX_TIP); if ((menu->modes & MENU_ALL_MODES) == 0) free_menu(menup); else menup = &menu->next; } else menup = &menu->next; } if (*name != NUL) { if (menu == NULL) { if (!silent) EMSG2(_(e_nomenu), name); return FAIL; } /* Recalculate modes for menu based on the new updated children */ menu->modes &= ~modes; #if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) if ((s_tearoffs) && (menu->children != NULL)) /* there's a tear bar.. */ child = menu->children->next; /* don't count tearoff bar */ else #endif child = menu->children; for (; child != NULL; child = child->next) menu->modes |= child->modes; if (modes & MENU_TIP_MODE) { free_menu_string(menu, MENU_INDEX_TIP); #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) \ && (defined(FEAT_BEVAL) || defined(FEAT_GUI_GTK)) /* Need to update the menu tip. */ if (gui.in_use) gui_mch_menu_set_tip(menu); #endif } if ((menu->modes & MENU_ALL_MODES) == 0) { /* The menu item is no longer valid in ANY mode, so delete it */ #if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) if (s_tearoffs && menu->children != NULL) /* there's a tear bar.. */ free_menu(&menu->children); #endif *menup = menu; free_menu(menup); } } return OK; }
/* * Add the menu with the given name to the menu hierarchy */ static int add_menu_path ( char_u *menu_path, vimmenu_T *menuarg, /* passes modes, iconfile, iconidx, icon_builtin, silent[0], noremap[0] */ int *pri_tab, char_u *call_data ) { char_u *path_name; int modes = menuarg->modes; vimmenu_T **menup; vimmenu_T *menu = NULL; vimmenu_T *parent; vimmenu_T **lower_pri; char_u *p; char_u *name; char_u *dname; char_u *next_name; int i; int c; int d; int pri_idx = 0; int old_modes = 0; int amenu; char_u *en_name; char_u *map_to = NULL; /* Make a copy so we can stuff around with it, since it could be const */ path_name = vim_strsave(menu_path); menup = &root_menu; parent = NULL; name = path_name; while (*name) { /* Get name of this element in the menu hierarchy, and the simplified * name (without mnemonic and accelerator text). */ next_name = menu_name_skip(name); map_to = menutrans_lookup(name, (int)STRLEN(name)); if (map_to != NULL) { en_name = name; name = map_to; } else en_name = NULL; dname = menu_text(name, NULL, NULL); if (dname == NULL) goto erret; if (*dname == NUL) { /* Only a mnemonic or accelerator is not valid. */ EMSG(_("E792: Empty menu name")); goto erret; } /* See if it's already there */ lower_pri = menup; menu = *menup; while (menu != NULL) { if (menu_name_equal(name, menu) || menu_name_equal(dname, menu)) { if (*next_name == NUL && menu->children != NULL) { if (!sys_menu) EMSG(_("E330: Menu path must not lead to a sub-menu")); goto erret; } if (*next_name != NUL && menu->children == NULL ) { if (!sys_menu) EMSG(_(e_notsubmenu)); goto erret; } break; } menup = &menu->next; /* Count menus, to find where this one needs to be inserted. * Ignore menus that are not in the menubar (PopUp and Toolbar) */ if (parent != NULL || menu_is_menubar(menu->name)) { if (menu->priority <= pri_tab[pri_idx]) { lower_pri = menup; } } menu = menu->next; } if (menu == NULL) { if (*next_name == NUL && parent == NULL) { EMSG(_("E331: Must not add menu items directly to menu bar")); goto erret; } if (menu_is_separator(dname) && *next_name != NUL) { EMSG(_("E332: Separator cannot be part of a menu path")); goto erret; } /* Not already there, so lets add it */ menu = xcalloc(1, sizeof(vimmenu_T)); menu->modes = modes; menu->enabled = MENU_ALL_MODES; menu->name = vim_strsave(name); /* separate mnemonic and accelerator text from actual menu name */ menu->dname = menu_text(name, &menu->mnemonic, &menu->actext); if (en_name != NULL) { menu->en_name = vim_strsave(en_name); menu->en_dname = menu_text(en_name, NULL, NULL); } else { menu->en_name = NULL; menu->en_dname = NULL; } menu->priority = pri_tab[pri_idx]; menu->parent = parent; /* * Add after menu that has lower priority. */ menu->next = *lower_pri; *lower_pri = menu; old_modes = 0; } else { old_modes = menu->modes; /* * If this menu option was previously only available in other * modes, then make sure it's available for this one now * Also enable a menu when it's created or changed. */ { menu->modes |= modes; menu->enabled |= modes; } } menup = &menu->children; parent = menu; name = next_name; free(dname); dname = NULL; if (pri_tab[pri_idx + 1] != -1) ++pri_idx; } free(path_name); /* * Only add system menu items which have not been defined yet. * First check if this was an ":amenu". */ amenu = ((modes & (MENU_NORMAL_MODE | MENU_INSERT_MODE)) == (MENU_NORMAL_MODE | MENU_INSERT_MODE)); if (sys_menu) modes &= ~old_modes; if (menu != NULL && modes) { p = (call_data == NULL) ? NULL : vim_strsave(call_data); /* loop over all modes, may add more than one */ for (i = 0; i < MENU_MODES; ++i) { if (modes & (1 << i)) { /* free any old menu */ free_menu_string(menu, i); /* For "amenu", may insert an extra character. * Don't do this if adding a tearbar (addtearoff == FALSE). * Don't do this for "<Nop>". */ c = 0; d = 0; if (amenu && call_data != NULL && *call_data != NUL ) { switch (1 << i) { case MENU_VISUAL_MODE: case MENU_SELECT_MODE: case MENU_OP_PENDING_MODE: case MENU_CMDLINE_MODE: c = Ctrl_C; break; case MENU_INSERT_MODE: c = Ctrl_BSL; d = Ctrl_O; break; } } if (c != 0) { menu->strings[i] = xmalloc(STRLEN(call_data) + 5 ); menu->strings[i][0] = c; if (d == 0) STRCPY(menu->strings[i] + 1, call_data); else { menu->strings[i][1] = d; STRCPY(menu->strings[i] + 2, call_data); } if (c == Ctrl_C) { int len = (int)STRLEN(menu->strings[i]); /* Append CTRL-\ CTRL-G to obey 'insertmode'. */ menu->strings[i][len] = Ctrl_BSL; menu->strings[i][len + 1] = Ctrl_G; menu->strings[i][len + 2] = NUL; } } else menu->strings[i] = p; menu->noremap[i] = menuarg->noremap[0]; menu->silent[i] = menuarg->silent[0]; } } #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) \ && (defined(FEAT_BEVAL) || defined(FEAT_GUI_GTK)) /* Need to update the menu tip. */ if (modes & MENU_TIP_MODE) gui_mch_menu_set_tip(menu); #endif } return OK; erret: free(path_name); free(dname); /* Delete any empty submenu we added before discovering the error. Repeat * for higher levels. */ while (parent != NULL && parent->children == NULL) { if (parent->parent == NULL) menup = &root_menu; else menup = &parent->parent->children; for (; *menup != NULL && *menup != parent; menup = &((*menup)->next)) ; if (*menup == NULL) /* safety check */ break; parent = parent->parent; free_menu(menup); } return FAIL; }
static TEE_Result test_rewrite(TEE_ObjectHandle object, size_t data_size, uint8_t *chunk_buf, size_t chunk_size, uint32_t *spent_time_in_ms) { TEE_Time start_time, stop_time; size_t remain_bytes = data_size; TEE_Result res = TEE_SUCCESS; uint32_t read_bytes = 0; TEE_GetSystemTime(&start_time); while (remain_bytes) { size_t write_size; int32_t negative_chunk_size; if (remain_bytes < chunk_size) write_size = remain_bytes; else write_size = chunk_size; negative_chunk_size = -(int32_t)write_size; /* Read a chunk */ res = TEE_ReadObjectData(object, chunk_buf, write_size, &read_bytes); if (res != TEE_SUCCESS) { EMSG("Failed to read data, res=0x%08x", res); goto exit; } if (read_bytes != write_size) { EMSG("Partial data read, bytes=%u", read_bytes); res = TEE_ERROR_CORRUPT_OBJECT; goto exit; } /* Seek to the position before read */ res = TEE_SeekObjectData(object, negative_chunk_size, TEE_DATA_SEEK_CUR); if (res != TEE_SUCCESS) { EMSG("Failed to seek to previous offset"); goto exit; } /* Write a chunk*/ res = TEE_WriteObjectData(object, chunk_buf, write_size); if (res != TEE_SUCCESS) { EMSG("Failed to write data, res=0x%08x", res); goto exit; } remain_bytes -= write_size; } TEE_GetSystemTime(&stop_time); *spent_time_in_ms = get_delta_time_in_ms(start_time, stop_time); IMSG("start: %u.%u(s), stop: %u.%u(s), delta: %u(ms)", start_time.seconds, start_time.millis, stop_time.seconds, stop_time.millis, *spent_time_in_ms); exit: return res; }
/* * ":delmarks[!] [marks]" */ void ex_delmarks(exarg_T *eap) { char_u *p; int from, to; int i; int lower; int digit; int n; if (*eap->arg == NUL && eap->forceit) /* clear all marks */ clrallmarks(curbuf); else if (eap->forceit) EMSG(_(e_invarg)); else if (*eap->arg == NUL) EMSG(_(e_argreq)); else { /* clear specified marks only */ for (p = eap->arg; *p != NUL; ++p) { lower = ASCII_ISLOWER(*p); digit = VIM_ISDIGIT(*p); if (lower || digit || ASCII_ISUPPER(*p)) { if (p[1] == '-') { /* clear range of marks */ from = *p; to = p[2]; if (!(lower ? ASCII_ISLOWER(p[2]) : (digit ? VIM_ISDIGIT(p[2]) : ASCII_ISUPPER(p[2]))) || to < from) { EMSG2(_(e_invarg2), p); return; } p += 2; } else /* clear one lower case mark */ from = to = *p; for (i = from; i <= to; ++i) { if (lower) curbuf->b_namedm[i - 'a'].lnum = 0; else { if (digit) n = i - '0' + NMARKS; else n = i - 'A'; namedfm[n].fmark.mark.lnum = 0; vim_free(namedfm[n].fname); namedfm[n].fname = NULL; } } } else switch (*p) { case '"': curbuf->b_last_cursor.lnum = 0; break; case '^': curbuf->b_last_insert.lnum = 0; break; case '.': curbuf->b_last_change.lnum = 0; break; case '[': curbuf->b_op_start.lnum = 0; break; case ']': curbuf->b_op_end.lnum = 0; break; case '<': curbuf->b_visual.vi_start.lnum = 0; break; case '>': curbuf->b_visual.vi_end.lnum = 0; break; case ' ': break; default: EMSG2(_(e_invarg2), p); return; } } } }
static TEE_Result ta_stroage_benchmark_chunk_access_test(uint32_t nCommandID, uint32_t param_types, TEE_Param params[4]) { TEE_Result res; size_t data_size; size_t chunk_size; TEE_ObjectHandle object = TEE_HANDLE_NULL; uint8_t *chunk_buf; uint32_t *spent_time_in_ms = ¶ms[2].value.a; bool do_verify; ASSERT_PARAM_TYPE(param_types, TEE_PARAM_TYPES( TEE_PARAM_TYPE_VALUE_INPUT, TEE_PARAM_TYPE_VALUE_INPUT, TEE_PARAM_TYPE_VALUE_OUTPUT, TEE_PARAM_TYPE_NONE)); data_size = params[0].value.a; chunk_size = params[0].value.b; do_verify = params[1].value.a; if (data_size == 0) data_size = DEFAULT_DATA_SIZE; if (chunk_size == 0) chunk_size = DEFAULT_CHUNK_SIZE; IMSG("command id: %u, test data size: %zd, chunk size: %zd\n", nCommandID, data_size, chunk_size); chunk_buf = TEE_Malloc(chunk_size, TEE_MALLOC_FILL_ZERO); if (!chunk_buf) { EMSG("Failed to allocate memory"); res = TEE_ERROR_OUT_OF_MEMORY; goto exit; } fill_buffer(chunk_buf, chunk_size); res = prepare_test_file(data_size, chunk_buf, chunk_size); if (res != TEE_SUCCESS) { EMSG("Failed to create test file, res=0x%08x", res); goto exit_free_chunk_buf; } res = TEE_OpenPersistentObject(TEE_STORAGE_PRIVATE, filename, sizeof(filename), TEE_DATA_FLAG_ACCESS_READ | TEE_DATA_FLAG_ACCESS_WRITE | TEE_DATA_FLAG_ACCESS_WRITE_META | TEE_DATA_FLAG_OVERWRITE, &object); if (res != TEE_SUCCESS) { EMSG("Failed to open persistent object, res=0x%08x", res); goto exit_remove_object; } switch (nCommandID) { case TA_STORAGE_BENCHMARK_CMD_TEST_READ: res = test_read(object, data_size, chunk_buf, chunk_size, spent_time_in_ms); break; case TA_STORAGE_BENCHMARK_CMD_TEST_WRITE: res = test_write(object, data_size, chunk_buf, chunk_size, spent_time_in_ms); break; case TA_STORAGE_BENCHMARK_CMD_TEST_REWRITE: res = test_rewrite(object, data_size, chunk_buf, chunk_size, spent_time_in_ms); break; default: res = TEE_ERROR_BAD_PARAMETERS; } if (res != TEE_SUCCESS) goto exit_remove_object; if (do_verify) res = verify_file_data(object, data_size, chunk_buf, chunk_size); exit_remove_object: TEE_CloseAndDeletePersistentObject1(object); exit_free_chunk_buf: TEE_Free(chunk_buf); exit: return res; }
// // Returns: address of non-freeable region at the high end, // else NULL on failure. // void * hpcrun_malloc(size_t size) { hpcrun_meminfo_t *mi; void *addr; // Lush wants to ask for 0 bytes and get back NULL. if (size == 0) { return NULL; } mi = &TD_GET(memstore); size = round_up(size); // For a large request that doesn't fit within the existing // memstore, mmap a separate region for it. if (size > memsize/5 && allow_extra_mmap && (mi->mi_start == NULL || size > mi->mi_high - mi->mi_low)) { addr = hpcrun_mmap_anon(size); if (addr == NULL) { if (! out_of_mem_mesg) { EMSG("%s: out of memory, shutting down sampling", __func__); out_of_mem_mesg = 1; } hpcrun_disable_sampling(); num_failures++; return NULL; } TMSG(MALLOC, "%s: size = %ld, addr = %p", __func__, size, addr); total_non_freeable += size; return addr; } // See if we need to allocate a new memstore. if (mi->mi_start == NULL || mi->mi_high - mi->mi_low < low_memsize || mi->mi_high - mi->mi_low < size) { if (allow_extra_mmap) { hpcrun_make_memstore(mi, 0); } else { if (! out_of_mem_mesg) { EMSG("%s: out of memory, shutting down sampling", __func__); out_of_mem_mesg = 1; } hpcrun_disable_sampling(); } } // There is no memstore, for some reason. if (mi->mi_start == NULL) { TMSG(MALLOC, "%s: size = %ld, failure: no memstore", __func__, size); num_failures++; return NULL; } // Not enough space in existing memstore. addr = mi->mi_high - size; if (addr <= mi->mi_low) { TMSG(MALLOC, "%s: size = %ld, failure: out of memory", __func__, size); num_failures++; return NULL; } // Success mi->mi_high = addr; total_non_freeable += size; TMSG(MALLOC, "%s: size = %ld, addr = %p", __func__, size, addr); return addr; }
/* * Create a balloon-evaluation area for a Widget. * There can be either a "mesg" for a fixed string or "mesgCB" to generate a * message by calling this callback function. * When "mesg" is not NULL it must remain valid for as long as the balloon is * used. It is not freed here. * Returns a pointer to the resulting object (NULL when out of memory). */ BalloonEval * gui_mch_create_beval_area( void *target, char_u *mesg, void (*mesgCB)(BalloonEval *, int), void *clientData) { #ifndef FEAT_GUI_GTK char *display_name; /* get from gui.dpy */ int screen_num; char *p; #endif BalloonEval *beval; if (mesg != NULL && mesgCB != NULL) { EMSG(_("E232: Cannot create BalloonEval with both message and callback")); return NULL; } beval = (BalloonEval *)alloc(sizeof(BalloonEval)); if (beval != NULL) { #ifdef FEAT_GUI_GTK beval->target = GTK_WIDGET(target); beval->balloonShell = NULL; beval->timerID = 0; #else beval->target = (Widget)target; beval->balloonShell = NULL; beval->timerID = (XtIntervalId)NULL; beval->appContext = XtWidgetToApplicationContext((Widget)target); #endif beval->showState = ShS_NEUTRAL; beval->x = 0; beval->y = 0; beval->msg = mesg; beval->msgCB = mesgCB; beval->clientData = clientData; /* * Set up event handler which will keep its eyes on the pointer, * and when the pointer rests in a certain spot for a given time * interval, show the beval. */ addEventHandler(beval->target, beval); createBalloonEvalWindow(beval); #ifndef FEAT_GUI_GTK /* * Now create and save the screen width and height. Used in drawing. */ display_name = DisplayString(gui.dpy); p = strrchr(display_name, '.'); if (p != NULL) screen_num = atoi(++p); else screen_num = 0; beval->screen_width = DisplayWidth(gui.dpy, screen_num); beval->screen_height = DisplayHeight(gui.dpy, screen_num); #endif } return beval; }
void avl_balance(avl_tree_t **root){ HMSG("balance() ... \n"); switch( (*root)->flags ){ case AVL_FLAGS_LEFT_UNBAL: { avl_tree_t *left_root = (*root)->left; switch(left_root->flags){ case AVL_FLAGS_BALANCED: IMSG("Balanced sub-tree\n"); break; case AVL_FLAGS_LEFT_HEAVY: /* Nothing to do ... */ HMSG("LEFT LEFT\n"); break; case AVL_FLAGS_RIGHT_HEAVY: HMSG("LEFT RIGHT\n"); avl_left_rotate( &((*root)->left)); break; case AVL_FLAGS_LEFT_UNBAL: case AVL_FLAGS_RIGHT_UNBAL: EMSG("Unbalanced sub-tree !!!\n"); break; default: EMSG("Inconsistent Flags\n"); } avl_right_rotate(root); } break; case AVL_FLAGS_RIGHT_UNBAL: { avl_tree_t *right_root = (*root)->right; switch(right_root->flags){ case AVL_FLAGS_BALANCED: IMSG("Balanced sub-tree\n"); break; case AVL_FLAGS_LEFT_HEAVY: HMSG("RIGHT LEFT\n"); avl_right_rotate( &((*root)->right)); break; case AVL_FLAGS_RIGHT_HEAVY: /* Nothing to do ... */ HMSG("RIGHT RIGHT\n"); break; case AVL_FLAGS_LEFT_UNBAL: case AVL_FLAGS_RIGHT_UNBAL: EMSG("Unbalanced sub-tree !!!\n"); break; default: EMSG("Inconsistent Flags\n"); } avl_left_rotate(root); } break; case AVL_FLAGS_BALANCED: case AVL_FLAGS_LEFT_HEAVY: case AVL_FLAGS_RIGHT_HEAVY: EMSG("useless call of avl_balance()\n"); break; default: EMSG("Inconsistent Flags\n"); } }
void xsim_topology_load_info(char *file, int nb_node) { FILE *fptr = fopen(file, "r"); if (fptr == NULL) { EMSG("Error when loading file: %s.\n", file); return; } int current = 0; int i = 0; int j = 0; int time = 1; int line_nb = 0; char *line = (char*)malloc(sizeof(char) * LINESIZE); while (fgets(line, LINESIZE, fptr) != NULL) { line_nb++; current = 0; SKIP_SPACE; if ((line[current] == '#') /* It is a commentaire */ || (line[current] == '\n')) /* It is an empty line */ continue; i = get_int(¤t, line, line_nb); if (i < 0) continue; if (i >= nb_node) {/* This node does not match the configuration */ EMSG("line %d: the node number is too high compare to the configuration given as parameters: got %d .\n", line_nb, i); continue; } NEXT_TOKEN; if (current > LINESIZE-2) { EMSG("line %d: line too long: max characters in one line: %d\n", line_nb, LINESIZE); continue; } if ((line[current] != '-') || (line[current+1] != '>')) { EMSG("line %d: Token \"->\" expected. Find: %c%c.\n", line_nb, line[current], line[current+1]); continue; } current += 2; NEXT_TOKEN; j = get_int(¤t, line, line_nb); if (j < 0) continue; if (j >= nb_node) {/* This node does not match the configuration */ EMSG("line %d: the node number is too high compare to the configuration given as parameters: got %d.\n", line_nb, j); continue; } NEXT_TOKEN; if (line[current] != ':') { EMSG("line %d: Token ':' expected. Find: %c.\n", line_nb, line[current]); continue; } current++; NEXT_TOKEN; time = get_int(¤t, line, line_nb); if (time <= 0) {/* This travel time is not possible */ EMSG("line %d: the travel time read is not possible: %d.\n", line_nb, time); continue; } /* The rest of the line is not important - skip it and memorized the result*/ topology[i][j] = time; } free(line); fclose(fptr); return; }
/// Resize hastable (new size can be given or automatically computed). /// /// @param minitems Minimum number of items the new table should hold. /// If zero, new size will depend on currently used items: /// - Shrink when too much empty space. /// - Grow when not enough empty space. /// If non-zero, passed minitems will be used. static void hash_may_resize(hashtab_T *ht, size_t minitems) { // Don't resize a locked table. if (ht->ht_locked > 0) { return; } #ifdef HT_DEBUG if (ht->ht_used > ht->ht_filled) { EMSG("hash_may_resize(): more used than filled"); } if (ht->ht_filled >= ht->ht_mask + 1) { EMSG("hash_may_resize(): table completely filled"); } #endif // ifdef HT_DEBUG size_t minsize; if (minitems == 0) { // Return quickly for small tables with at least two NULL items. // items are required for the lookup to decide a key isn't there. if ((ht->ht_filled < HT_INIT_SIZE - 1) && (ht->ht_array == ht->ht_smallarray)) { return; } // Grow or refill the array when it's more than 2/3 full (including // removed items, so that they get cleaned up). // Shrink the array when it's less than 1/5 full. When growing it is // at least 1/4 full (avoids repeated grow-shrink operations) size_t oldsize = ht->ht_mask + 1; if ((ht->ht_filled * 3 < oldsize * 2) && (ht->ht_used > oldsize / 5)) { return; } if (ht->ht_used > 1000) { // it's big, don't make too much room minsize = ht->ht_used * 2; } else { // make plenty of room minsize = ht->ht_used * 4; } } else { // Use specified size. if (minitems < ht->ht_used) { // just in case... minitems = ht->ht_used; } // array is up to 2/3 full minsize = minitems * 3 / 2; } size_t newsize = HT_INIT_SIZE; while (newsize < minsize) { // make sure it's always a power of 2 newsize <<= 1; // assert newsize didn't overflow assert(newsize != 0); } bool newarray_is_small = newsize == HT_INIT_SIZE; bool keep_smallarray = newarray_is_small && ht->ht_array == ht->ht_smallarray; // Make sure that oldarray and newarray do not overlap, // so that copying is possible. hashitem_T temparray[HT_INIT_SIZE]; hashitem_T *oldarray = keep_smallarray ? memcpy(temparray, ht->ht_smallarray, sizeof(temparray)) : ht->ht_array; hashitem_T *newarray = newarray_is_small ? ht->ht_smallarray : xmalloc(sizeof(hashitem_T) * newsize); memset(newarray, 0, sizeof(hashitem_T) * newsize); // Move all the items from the old array to the new one, placing them in // the right spot. The new array won't have any removed items, thus this // is also a cleanup action. hash_T newmask = newsize - 1; size_t todo = ht->ht_used; for (hashitem_T *olditem = oldarray; todo > 0; ++olditem) { if (HASHITEM_EMPTY(olditem)) { continue; } // The algorithm to find the spot to add the item is identical to // the algorithm to find an item in hash_lookup(). But we only // need to search for a NULL key, thus it's simpler. hash_T newi = olditem->hi_hash & newmask; hashitem_T *newitem = &newarray[newi]; if (newitem->hi_key != NULL) { for (hash_T perturb = olditem->hi_hash;; perturb >>= PERTURB_SHIFT) { newi = 5 * newi + perturb + 1; newitem = &newarray[newi & newmask]; if (newitem->hi_key == NULL) { break; } } } *newitem = *olditem; todo--; } if (ht->ht_array != ht->ht_smallarray) { xfree(ht->ht_array); } ht->ht_array = newarray; ht->ht_mask = newmask; ht->ht_filled = ht->ht_used; }
/// ":loadkeymap" command: load the following lines as the keymap. /// /// @param eap void ex_loadkeymap(exarg_T *eap) { char_u *line; char_u *p; char_u *s; kmap_T *kp; #define KMAP_LLEN 200 // max length of "to" and "from" together char_u buf[KMAP_LLEN + 11]; int i; char_u *save_cpo = p_cpo; if (!getline_equal(eap->getline, eap->cookie, getsourceline)) { EMSG(_("E105: Using :loadkeymap not in a sourced file")); return; } // Stop any active keymap and clear the table. keymap_unload(); curbuf->b_kmap_state = 0; ga_init(&curbuf->b_kmap_ga, (int)sizeof(kmap_T), 20); // Set 'cpoptions' to "C" to avoid line continuation. p_cpo = (char_u *)"C"; // Get each line of the sourced file, break at the end. for (;;) { line = eap->getline(0, eap->cookie, 0); if (line == NULL) { break; } p = skipwhite(line); if ((*p != '"') && (*p != NUL)) { ga_grow(&curbuf->b_kmap_ga, 1); kp = (kmap_T *)curbuf->b_kmap_ga.ga_data + curbuf->b_kmap_ga.ga_len; s = skiptowhite(p); kp->from = vim_strnsave(p, (int)(s - p)); p = skipwhite(s); s = skiptowhite(p); kp->to = vim_strnsave(p, (int)(s - p)); if ((STRLEN(kp->from) + STRLEN(kp->to) >= KMAP_LLEN) || (*kp->from == NUL) || (*kp->to == NUL)) { if (*kp->to == NUL) { EMSG(_("E791: Empty keymap entry")); } free(kp->from); free(kp->to); } else { ++curbuf->b_kmap_ga.ga_len; } } free(line); } // setup ":lnoremap" to map the keys for (i = 0; i < curbuf->b_kmap_ga.ga_len; ++i) { vim_snprintf((char *)buf, sizeof(buf), "<buffer> %s %s", ((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].from, ((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].to); (void)do_map(2, buf, LANGMAP, FALSE); } p_cpo = save_cpo; curbuf->b_kmap_state |= KEYMAP_LOADED; status_redraw_curbuf(); }
/* * Shrink a hashtable when there is too much empty space. * Grow a hashtable when there is not enough empty space. * Returns OK or FAIL (out of memory). */ static int hash_may_resize( hashtab_T *ht, int minitems) /* minimal number of items */ { hashitem_T temparray[HT_INIT_SIZE]; hashitem_T *oldarray, *newarray; hashitem_T *olditem, *newitem; unsigned newi; int todo; long_u oldsize, newsize; long_u minsize; long_u newmask; hash_T perturb; /* Don't resize a locked table. */ if (ht->ht_locked > 0) return OK; #ifdef HT_DEBUG if (ht->ht_used > ht->ht_filled) EMSG("hash_may_resize(): more used than filled"); if (ht->ht_filled >= ht->ht_mask + 1) EMSG("hash_may_resize(): table completely filled"); #endif if (minitems == 0) { /* Return quickly for small tables with at least two NULL items. NULL * items are required for the lookup to decide a key isn't there. */ if (ht->ht_filled < HT_INIT_SIZE - 1 && ht->ht_array == ht->ht_smallarray) return OK; /* * Grow or refill the array when it's more than 2/3 full (including * removed items, so that they get cleaned up). * Shrink the array when it's less than 1/5 full. When growing it is * at least 1/4 full (avoids repeated grow-shrink operations) */ oldsize = ht->ht_mask + 1; if (ht->ht_filled * 3 < oldsize * 2 && ht->ht_used > oldsize / 5) return OK; if (ht->ht_used > 1000) minsize = ht->ht_used * 2; /* it's big, don't make too much room */ else minsize = ht->ht_used * 4; /* make plenty of room */ } else { /* Use specified size. */ if ((long_u)minitems < ht->ht_used) /* just in case... */ minitems = (int)ht->ht_used; minsize = minitems * 3 / 2; /* array is up to 2/3 full */ } newsize = HT_INIT_SIZE; while (newsize < minsize) { newsize <<= 1; /* make sure it's always a power of 2 */ if (newsize == 0) return FAIL; /* overflow */ } if (newsize == HT_INIT_SIZE) { /* Use the small array inside the hashdict structure. */ newarray = ht->ht_smallarray; if (ht->ht_array == newarray) { /* Moving from ht_smallarray to ht_smallarray! Happens when there * are many removed items. Copy the items to be able to clean up * removed items. */ mch_memmove(temparray, newarray, sizeof(temparray)); oldarray = temparray; } else oldarray = ht->ht_array; } else { /* Allocate an array. */ newarray = (hashitem_T *)alloc((unsigned) (sizeof(hashitem_T) * newsize)); if (newarray == NULL) { /* Out of memory. When there are NULL items still return OK. * Otherwise set ht_error, because lookup may result in a hang if * we add another item. */ if (ht->ht_filled < ht->ht_mask) return OK; ht->ht_error = TRUE; return FAIL; } oldarray = ht->ht_array; } vim_memset(newarray, 0, (size_t)(sizeof(hashitem_T) * newsize)); /* * Move all the items from the old array to the new one, placing them in * the right spot. The new array won't have any removed items, thus this * is also a cleanup action. */ newmask = newsize - 1; todo = (int)ht->ht_used; for (olditem = oldarray; todo > 0; ++olditem) if (!HASHITEM_EMPTY(olditem)) { /* * The algorithm to find the spot to add the item is identical to * the algorithm to find an item in hash_lookup(). But we only * need to search for a NULL key, thus it's simpler. */ newi = (unsigned)(olditem->hi_hash & newmask); newitem = &newarray[newi]; if (newitem->hi_key != NULL) for (perturb = olditem->hi_hash; ; perturb >>= PERTURB_SHIFT) { newi = (unsigned)((newi << 2U) + newi + perturb + 1U); newitem = &newarray[newi & newmask]; if (newitem->hi_key == NULL) break; } *newitem = *olditem; --todo; }
/* * External interface */ static void DoPyCommand(const char *cmd, rangeinitializer init_range, runner run, void *arg) { #ifndef PY_CAN_RECURSE static int recursive = 0; #endif #if defined(MACOS) && !defined(MACOS_X_UNIX) GrafPtr oldPort; #endif #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) char *saved_locale; #endif #ifdef PY_CAN_RECURSE PyGILState_STATE pygilstate; #endif #ifndef PY_CAN_RECURSE if (recursive) { EMSG(_("E659: Cannot invoke Python recursively")); return; } ++recursive; #endif #if defined(MACOS) && !defined(MACOS_X_UNIX) GetPort(&oldPort); /* Check if the Python library is available */ if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress) goto theend; #endif if (Python_Init()) goto theend; init_range(arg); Python_Release_Vim(); /* leave vim */ #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) /* Python only works properly when the LC_NUMERIC locale is "C". */ saved_locale = setlocale(LC_NUMERIC, NULL); if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0) saved_locale = NULL; else { /* Need to make a copy, value may change when setting new locale. */ saved_locale = (char *) PY_STRSAVE(saved_locale); (void)setlocale(LC_NUMERIC, "C"); } #endif #ifdef PY_CAN_RECURSE pygilstate = PyGILState_Ensure(); #else Python_RestoreThread(); /* enter python */ #endif run((char *) cmd, arg #ifdef PY_CAN_RECURSE , &pygilstate #endif ); #ifdef PY_CAN_RECURSE PyGILState_Release(pygilstate); #else Python_SaveThread(); /* leave python */ #endif #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) if (saved_locale != NULL) { (void)setlocale(LC_NUMERIC, saved_locale); PyMem_Free(saved_locale); } #endif Python_Lock_Vim(); /* enter vim */ PythonIO_Flush(); #if defined(MACOS) && !defined(MACOS_X_UNIX) SetPort(oldPort); #endif theend: #ifndef PY_CAN_RECURSE --recursive; #endif return; }
/* * Load library and get all pointers. * Parameter 'libname' provides name of DLL. * Return OK or FAIL. */ static int py3_runtime_link_init(char *libname, int verbose) { int i; void *ucs_from_string, *ucs_decode, *ucs_as_encoded_string; # if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON) /* Can't have Python and Python3 loaded at the same time. * It cause a crash, because RTLD_GLOBAL is needed for * standard C extension libraries of one or both python versions. */ if (python_loaded()) { if (verbose) EMSG(_("E837: This Vim cannot execute :py3 after using :python")); return FAIL; } # endif if (hinstPy3 != 0) return OK; hinstPy3 = load_dll(libname); if (!hinstPy3) { if (verbose) EMSG2(_(e_loadlib), libname); return FAIL; } for (i = 0; py3_funcname_table[i].ptr; ++i) { if ((*py3_funcname_table[i].ptr = symbol_from_dll(hinstPy3, py3_funcname_table[i].name)) == NULL) { close_dll(hinstPy3); hinstPy3 = 0; if (verbose) EMSG2(_(e_loadfunc), py3_funcname_table[i].name); return FAIL; } } /* Load unicode functions separately as only the ucs2 or the ucs4 functions * will be present in the library. */ # if PY_VERSION_HEX >= 0x030300f0 ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicode_FromString"); ucs_decode = symbol_from_dll(hinstPy3, "PyUnicode_Decode"); ucs_as_encoded_string = symbol_from_dll(hinstPy3, "PyUnicode_AsEncodedString"); # else ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_FromString"); ucs_decode = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_Decode"); ucs_as_encoded_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_AsEncodedString"); if (!ucs_from_string || !ucs_decode || !ucs_as_encoded_string) { ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS4_FromString"); ucs_decode = symbol_from_dll(hinstPy3, "PyUnicodeUCS4_Decode"); ucs_as_encoded_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS4_AsEncodedString"); } # endif if (ucs_from_string && ucs_decode && ucs_as_encoded_string) { py3_PyUnicode_FromString = ucs_from_string; py3_PyUnicode_Decode = ucs_decode; py3_PyUnicode_AsEncodedString = ucs_as_encoded_string; } else { close_dll(hinstPy3); hinstPy3 = 0; if (verbose) EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*"); return FAIL; } return OK; }
static void METHOD_FN(process_event_list, int lush_metrics) { // fetch the event string for the sample source char* _p = METHOD_CALL(self, get_event_str); // // EVENT: Only 1 wallclock event // char* event = start_tok(_p); char name[1024]; // local buffer needed for extract_ev_threshold TMSG(_TST_CTL,"checking event spec = %s",event); // extract event threshold hpcrun_extract_ev_thresh(event, sizeof(name), name, &period, DEFAULT_THRESHOLD); // store event threshold METHOD_CALL(self, store_event, _TST_EVENT, period); TMSG(OPTIONS,"_TST period set to %ld",period); // set up file local variables for sample source control int seconds = period / 1000000; int microseconds = period % 1000000; TMSG(OPTIONS,"init timer w sample_period = %ld, seconds = %ld, usec = %ld", period, seconds, microseconds); // signal once after the given delay itimer.it_value.tv_sec = seconds; itimer.it_value.tv_usec = microseconds; // macros define whether automatic restart or not itimer.it_interval.tv_sec = AUTOMATIC_ITIMER_RESET_SECONDS(seconds); itimer.it_interval.tv_usec = AUTOMATIC_ITIMER_RESET_MICROSECONDS(microseconds); // handle metric allocation hpcrun_pre_allocate_metrics(1 + lush_metrics); int metric_id = hpcrun_new_metric(); METHOD_CALL(self, store_metric_id, _TST_EVENT, metric_id); // set metric information in metric table #ifdef USE_ELAPSED_TIME_FOR_WALLCLOCK # define sample_period 1 #else # define sample_period period #endif TMSG(_TST_CTL, "setting metric _TST, period = %ld", sample_period); hpcrun_set_metric_info_and_period(metric_id, "_TST", MetricFlags_ValFmt_Int, sample_period, metric_property_none); if (lush_metrics == 1) { int mid_idleness = hpcrun_new_metric(); lush_agents->metric_time = metric_id; lush_agents->metric_idleness = mid_idleness; hpcrun_set_metric_info_and_period(mid_idleness, "idleness (ms)", MetricFlags_ValFmt_Real, sample_period, metric_property_none); } event = next_tok(); if (more_tok()) { EMSG("MULTIPLE _TST events detected! Using first event spec: %s"); } }
static int Python3_Init(void) { if (!py3initialised) { #ifdef DYNAMIC_PYTHON3 if (!python3_enabled(TRUE)) { EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); goto fail; } #endif init_structs(); #ifdef PYTHON3_HOME Py_SetPythonHome(PYTHON3_HOME); #endif PyImport_AppendInittab("vim", Py3Init_vim); #if !defined(MACOS) || defined(MACOS_X_UNIX) Py_Initialize(); #else PyMac_Initialize(); #endif /* Initialise threads, and below save the state using * PyEval_SaveThread. Without the call to PyEval_SaveThread, thread * specific state (such as the system trace hook), will be lost * between invocations of Python code. */ PyEval_InitThreads(); #ifdef DYNAMIC_PYTHON3 get_py3_exceptions(); #endif if (PythonIO_Init_io()) goto fail; globals = PyModule_GetDict(PyImport_AddModule("__main__")); /* Remove the element from sys.path that was added because of our * argv[0] value in Py3Init_vim(). Previously we used an empty * string, but depending on the OS we then get an empty entry or * the current directory in sys.path. * Only after vim has been imported, the element does exist in * sys.path. */ PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))"); /* lock is created and acquired in PyEval_InitThreads() and thread * state is created in Py_Initialize() * there _PyGILState_NoteThreadState() also sets gilcounter to 1 * (python must have threads enabled!) * so the following does both: unlock GIL and save thread state in TLS * without deleting thread state */ PyEval_SaveThread(); py3initialised = 1; } return 0; fail: /* We call PythonIO_Flush() here to print any Python errors. * This is OK, as it is possible to call this function even * if PythonIO_Init_io() has not completed successfully (it will * not do anything in this case). */ PythonIO_Flush(); return -1; }
/* * Load library and get all pointers. * Parameter 'libname' provides name of DLL. * Return OK or FAIL. */ static int python_runtime_link_init(char *libname, int verbose) { int i; void *ucs_as_encoded_string; #if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3) /* Can't have Python and Python3 loaded at the same time. * It cause a crash, because RTLD_GLOBAL is needed for * standard C extension libraries of one or both python versions. */ if (python3_loaded()) { if (verbose) EMSG(_("E836: This Vim cannot execute :python after using :py3")); return FAIL; } #endif if (hinstPython) return OK; hinstPython = load_dll(libname); if (!hinstPython) { if (verbose) EMSG2(_(e_loadlib), libname); return FAIL; } for (i = 0; python_funcname_table[i].ptr; ++i) { if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython, python_funcname_table[i].name)) == NULL) { close_dll(hinstPython); hinstPython = 0; if (verbose) EMSG2(_(e_loadfunc), python_funcname_table[i].name); return FAIL; } } /* Load unicode functions separately as only the ucs2 or the ucs4 functions * will be present in the library. */ ucs_as_encoded_string = symbol_from_dll(hinstPython, "PyUnicodeUCS2_AsEncodedString"); if (ucs_as_encoded_string == NULL) ucs_as_encoded_string = symbol_from_dll(hinstPython, "PyUnicodeUCS4_AsEncodedString"); if (ucs_as_encoded_string != NULL) py_PyUnicode_AsEncodedString = ucs_as_encoded_string; else { close_dll(hinstPython); hinstPython = 0; if (verbose) EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*"); return FAIL; } return OK; }
int main(int argc, char *argv[]) { struct thread_arg arg = { .fd = -1 }; bool daemonize = false; char *dev = NULL; int e; int i; e = pthread_mutex_init(&arg.mutex, NULL); if (e) { EMSG("pthread_mutex_init: %s", strerror(e)); EMSG("terminating..."); exit(EXIT_FAILURE); } if (argc > 3) return usage(EXIT_FAILURE); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-d")) daemonize = true; else if (!strcmp(argv[i], "-h")) return usage(EXIT_SUCCESS); else dev = argv[i]; } if (dev) { arg.fd = open_dev(dev, &arg.gen_caps); if (arg.fd < 0) { EMSG("failed to open \"%s\"", argv[1]); exit(EXIT_FAILURE); } } else { arg.fd = get_dev_fd(&arg.gen_caps); if (arg.fd < 0) { EMSG("failed to find an OP-TEE supplicant device"); exit(EXIT_FAILURE); } } if (tee_supp_fs_init() != 0) { EMSG("error tee_supp_fs_init"); exit(EXIT_FAILURE); } if (daemonize && daemon(0, 0) < 0) { EMSG("daemon(): %s", strerror(errno)); exit(EXIT_FAILURE); } while (!arg.abort) { if (!process_one_request(&arg)) arg.abort = true; } close(arg.fd); return EXIT_FAILURE; } bool tee_supp_param_is_memref(struct tee_ioctl_param *param) { switch (param->attr & TEE_IOCTL_PARAM_ATTR_TYPE_MASK) { case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: return true; default: return false; } } bool tee_supp_param_is_value(struct tee_ioctl_param *param) { switch (param->attr & TEE_IOCTL_PARAM_ATTR_TYPE_MASK) { case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: return true; default: return false; } } void *tee_supp_param_to_va(struct tee_ioctl_param *param) { struct tee_shm *tshm; size_t end_offs; if (!tee_supp_param_is_memref(param)) return NULL; end_offs = param->u.memref.size + param->u.memref.shm_offs; if (end_offs < param->u.memref.size || end_offs < param->u.memref.shm_offs) return NULL; tshm = find_tshm(param->u.memref.shm_id); if (!tshm) return NULL; if (end_offs > tshm->size) return NULL; return (uint8_t *)tshm->p + param->u.memref.shm_offs; } void tee_supp_mutex_lock(pthread_mutex_t *mu) { int e = pthread_mutex_lock(mu); if (e) { EMSG("pthread_mutex_lock: %s", strerror(e)); EMSG("terminating..."); exit(EXIT_FAILURE); } }