static void setup_readline(void) { #ifdef SAVE_LOCALE char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); if (!saved_locale) Py_FatalError("not enough memory to save locale"); #endif #ifdef __APPLE__ /* the libedit readline emulation resets key bindings etc * when calling rl_initialize. So call it upfront */ if (using_libedit_emulation) rl_initialize(); /* Detect if libedit's readline emulation uses 0-based * indexing or 1-based indexing. */ add_history("1"); if (history_get(1) == NULL) { libedit_history_start = 0; } else { libedit_history_start = 1; } clear_history(); #endif /* __APPLE__ */ using_history(); rl_readline_name = "python"; #if defined(PYOS_OS2) && defined(PYCC_GCC) /* Allow $if term= in .inputrc to work */ rl_terminal_name = getenv("TERM"); #endif /* Force rebind of TAB to insert-tab */ rl_bind_key('\t', rl_insert); /* Bind both ESC-TAB and ESC-ESC to the completion function */ rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); /* Set our hook functions */ rl_startup_hook = on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK rl_pre_input_hook = on_pre_input_hook; #endif /* Set our completion function */ rl_attempted_completion_function = flex_complete; /* Set Python word break characters */ completer_word_break_characters = rl_completer_word_break_characters = strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); /* All nonalphanums except '.' */ begidx = PyInt_FromLong(0L); endidx = PyInt_FromLong(0L); #ifndef __APPLE__ if (!isatty(STDOUT_FILENO)) { /* Issue #19884: stdout is no a terminal. Disable meta modifier keys to not write the ANSI sequence "\033[1034h" into stdout. On terminals supporting 8 bit characters like TERM=xterm-256color (which is now the default Fedora since Fedora 18), the meta key is used to enable support of 8 bit characters (ANSI sequence "\033[1034h"). With libedit, this call makes readline() crash. */ rl_variable_bind ("enable-meta-key", "off"); } #endif /* Initialize (allows .inputrc to override) * * XXX: A bug in the readline-2.2 library causes a memory leak * inside this function. Nothing we can do about it. */ #ifdef __APPLE__ if (using_libedit_emulation) rl_read_init_file(NULL); else #endif /* __APPLE__ */ rl_initialize(); RESTORE_LOCALE(saved_locale) }
static void Console(CYOptions &options) { CYPool pool; passwd *passwd; if (const char *username = getenv("LOGNAME")) passwd = getpwnam(username); else passwd = getpwuid(getuid()); const char *basedir(pool.strcat(passwd->pw_dir, "/.cycript", NULL)); const char *histfile(pool.strcat(basedir, "/history", NULL)); size_t histlines(0); rl_initialize(); rl_readline_name = name_; mkdir(basedir, 0700); read_history(histfile); bool bypass(false); bool debug(false); bool expand(false); bool syntax(true); out_ = &std::cout; // rl_completer_word_break_characters is broken in libedit rl_basic_word_break_characters = break_; rl_completer_word_break_characters = break_; rl_attempted_completion_function = &Complete; rl_bind_key('\t', rl_complete); struct sigaction action; sigemptyset(&action.sa_mask); action.sa_handler = &sigint; action.sa_flags = 0; sigaction(SIGINT, &action, NULL); restart: for (;;) { command_.clear(); std::vector<std::string> lines; bool extra(false); const char *prompt("cy# "); if (setjmp(ctrlc_) != 0) { mode_ = Working; *out_ << std::endl; goto restart; } read: #if RL_READLINE_VERSION >= 0x0600 if (syntax) { rl_prep_term_function = CYDisplayStart; rl_redisplay_function = CYDisplayUpdate; rl_deprep_term_function = CYDisplayFinish; } else { rl_prep_term_function = rl_prep_terminal; rl_redisplay_function = rl_redisplay; rl_deprep_term_function = rl_deprep_terminal; } #endif mode_ = Parsing; char *line(readline(prompt)); mode_ = Working; if (line == NULL) break; if (line[0] == '\0') goto read; if (!extra) { extra = true; if (line[0] == '?') { std::string data(line + 1); if (data == "bypass") { bypass = !bypass; *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl; } else if (data == "debug") { debug = !debug; *out_ << "debug == " << (debug ? "true" : "false") << std::endl; } else if (data == "expand") { expand = !expand; *out_ << "expand == " << (expand ? "true" : "false") << std::endl; } else if (data == "syntax") { syntax = !syntax; *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl; } add_history(line); ++histlines; goto restart; } } command_ += line; char *begin(line), *end(line + strlen(line)); while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) { *nl = '\0'; lines.push_back(begin); begin = nl + 1; } lines.push_back(begin); free(line); std::string code; if (bypass) code = command_; else { CYLocalPool pool; std::istringstream stream(command_); CYDriver driver(stream); cy::parser parser(driver); Setup(driver, parser); if (parser.parse() != 0 || !driver.errors_.empty()) { for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) { cy::position begin(error->location_.begin); if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) { cy::position end(error->location_.end); if (begin.line != lines.size()) { std::cerr << " | "; std::cerr << lines[begin.line - 1] << std::endl; } std::cerr << "...."; for (size_t i(0); i != begin.column; ++i) std::cerr << '.'; if (begin.line != end.line || begin.column == end.column) std::cerr << '^'; else for (size_t i(0), e(end.column - begin.column); i != e; ++i) std::cerr << '^'; std::cerr << std::endl; std::cerr << " | "; std::cerr << error->message_ << std::endl; add_history(command_.c_str()); ++histlines; goto restart; } } driver.errors_.clear(); command_ += '\n'; prompt = "cy> "; goto read; } if (driver.program_ == NULL) goto restart; if (client_ != -1) code = command_; else { std::ostringstream str; CYOutput out(str, options); Setup(out, driver, options); out << *driver.program_; code = str.str(); } } add_history(command_.c_str()); ++histlines; if (debug) { Write(syntax, code.c_str(), code.size(), std::cout); std::cout << std::endl; } Run(client_, syntax, code, out_, expand); } if (append_history$ != NULL) { _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600)))); (*append_history$)(histlines, histfile); } else { write_history(histfile); } *out_ << std::endl; }
int_fast8_t main(int argc, char *argv[]) { FILE *fp; long i, j; int quiet=0; long tmplong; // FILE *fp; const gsl_rng_type * rndgenType; double v1; char prompt[200]; int terminate = 0; char str[200]; char command[200]; int nbtk; char *cmdargstring; struct timeval rldelay; FILE *fpcmd; FILE *fpcmdout; int OKcmd; char fline[200]; int r; struct stat st; FILE *fpclififo; char buf[100]; int fifofd, c=0; int fdmax; fd_set cli_fdin_set; int n; ssize_t bytes; size_t total_bytes; char buf0[1]; char buf1[1024]; int initstartup = 0; /// becomes 1 after startup int blockCLIinput = 0; int CLIinit1 = 0; int cliwaitus=100; struct timeval tv; // sleep 100 us after reading FIFO strcpy(data.processname, argv[0]); TYPESIZE[0] = 0; TYPESIZE[1] = sizeof(char); TYPESIZE[2] = sizeof(int); TYPESIZE[3] = sizeof(float); TYPESIZE[4] = sizeof(double); TYPESIZE[5] = 2*sizeof(float); TYPESIZE[6] = 2*sizeof(double); TYPESIZE[7] = sizeof(unsigned short); TYPESIZE[8] = sizeof(long); atexit(fnExit1); data.Debug = 0; data.overwrite = 0; data.precision = 0; // float is default precision data.SHARED_DFT = 0; // do not allocate shared memory for images data.NBKEWORD_DFT = 10; // allocate memory for 10 keyword per image sprintf(data.SAVEDIR, "."); data.CLIlogON = 0; // log every command data.fifoON = 1; // signal handling data.sigact.sa_handler = sig_handler; sigemptyset(&data.sigact.sa_mask); data.sigact.sa_flags = 0; data.signal_USR1 = 0; data.signal_USR2 = 0; data.signal_TERM = 0; data.signal_INT = 0; data.signal_BUS = 0; data.signal_SEGV = 0; data.signal_ABRT = 0; data.signal_HUP = 0; data.signal_PIPE = 0; // if (signal(SIGINT, sig_handler) == SIG_ERR) // printf("\ncan't catch SIGINT\n"); if (sigaction(SIGUSR1, &data.sigact, NULL) == -1) printf("\ncan't catch SIGUSR1\n"); if (sigaction(SIGUSR2, &data.sigact, NULL) == -1) printf("\ncan't catch SIGUSR2\n"); // to take advantage of kernel priority: // owner=root mode=4755 #ifndef __MACH__ getresuid(&euid_real, &euid_called, &suid); //This sets it to the privileges of the normal user r = seteuid(euid_real); #endif // initialize readline // Tell readline to use custom completion function rl_attempted_completion_function = CLI_completion; rl_initialize (); // Get command-line options command_line( argc, argv ); // initialize fifo to process name /*if(data.fifoON==1) { sprintf(data.fifoname, "%s.fifo", data.processname); printf("fifo name : %s\n", data.fifoname); } */ // if( Verbose ) { fprintf(stdout, "%s: compiled %s %s\n",__FILE__,__DATE__,__TIME__); } CLIPID = getpid(); // sprintf(promptname, "%s", data.processname); sprintf(prompt,"%c[%d;%dm%s >%c[%dm ",0x1B, 1, 36, data.processname, 0x1B, 0); //sprintf(prompt, "%s> ", PACKAGE_NAME); printf("type \"help\" for instructions\n"); # ifdef _OPENMP printf("Running with openMP, max threads = %d (defined by environment variable OMP_NUM_THREADS)\n", omp_get_max_threads()); # endif // sprintf(DocDir,"%s",DOCDIR); // sprintf(SrcDir,"%s",SOURCEDIR); // sprintf(BuildFile,"%s",__FILE__); // sprintf(BuildDate,"%s",__DATE__); // sprintf(BuildTime,"%s",__TIME__); // Initialize random-number generator // //rndgenType = gsl_rng_ranlxs2; // best algorithm but slow //rndgenType = gsl_rng_ranlxs0; // not quite as good, slower rndgenType = gsl_rng_rand; // not as good but ~10x faster fast data.rndgen = gsl_rng_alloc (rndgenType); gsl_rng_set (data.rndgen,time(NULL)); // warm up for(i=0; i<10; i++) v1 = gsl_rng_uniform (data.rndgen); /*-------------------------------------------------- | Check command-line arguements +-------------------------------------------------*/ /* Initialize data control block */ main_init(); // initialize readline rl_callback_handler_install(prompt, (rl_vcpfunc_t*) &rl_cb); // fifo fdmax = fileno(stdin); // printf("FIFO = %d\n", data.fifoON); if(data.fifoON == 1) { printf("Creating fifo %s\n", data.fifoname); mkfifo(data.fifoname, 0666); fifofd = open(data.fifoname, O_RDWR | O_NONBLOCK); if (fifofd == -1) { perror("open"); return EXIT_FAILURE; } if(fifofd>fdmax) fdmax = fifofd; } tmplong = data.NB_MAX_VARIABLE; C_ERRNO = 0; // initialize C error variable to 0 (no error) terminate = 0; while(terminate==0) { data.CMDexecuted = 0; if( fopen( "STOPCLI","r" ) != NULL ) { fprintf(stdout, "STOPCLI FILE FOUND. Exiting...\n"); exit(1); } if(Listimfile==1) { fp = fopen("imlist.txt", "w"); list_image_ID_ofp_simple(fp); fclose(fp); } /* Keep the number of image addresses available * NB_IMAGES_BUFFER above the number of used images * * Keep the number of variables addresses available * NB_VARIABLES_BUFFER above the number of used variables */ if( re_alloc() != 0 ) { fprintf(stderr,"%c[%d;%dm ERROR [ FILE: %s FUNCTION: %s LINE: %d ] %c[%d;m\n", (char) 27, 1, 31, __FILE__, __func__, __LINE__, (char) 27, 0); fprintf(stderr,"%c[%d;%dm Memory re-allocation failed %c[%d;m\n", (char) 27, 1, 31, (char) 27, 0); exit(0); } compute_image_memory(data); compute_nb_image(data); /** If fifo is on and file CLIstatup.txt exists, load it */ if(initstartup == 0) if(data.fifoON==1) { printf("IMPORTING FILE %s\n", CLIstartupfilename); sprintf(command, "cat %s > %s 2> /dev/null", CLIstartupfilename, data.fifoname); r = system(command); } initstartup = 1; // ------------------------------------------------------------- // get user input // ------------------------------------------------------------- tv.tv_sec = 0; tv.tv_usec = cliwaitus; FD_ZERO(&cli_fdin_set); // Initializes the file descriptor set cli_fdin_set to have zero bits for all file descriptors. if(data.fifoON==1) FD_SET(fifofd, &cli_fdin_set); // Sets the bit for the file descriptor fifofd in the file descriptor set cli_fdin_set. FD_SET(fileno(stdin), &cli_fdin_set); // Sets the bit for the file descriptor fifofd in the file descriptor set cli_fdin_set. while(CLIexecuteCMDready == 0) { n = select(fdmax+1, &cli_fdin_set, NULL, NULL, &tv); if (n==0) // nothing received, need to re-init and go back to select call { tv.tv_sec = 0; tv.tv_usec = cliwaitus; FD_ZERO(&cli_fdin_set); // Initializes the file descriptor set cli_fdin_set to have zero bits for all file descriptors. if(data.fifoON==1) FD_SET(fifofd, &cli_fdin_set); // Sets the bit for the file descriptor fifofd in the file descriptor set cli_fdin_set. FD_SET(fileno(stdin), &cli_fdin_set); // Sets the bit for the file descriptor fifofd in the file descriptor set cli_fdin_set. continue; } if (n == -1) { if(errno==EINTR) // no command received { continue; } else { perror("select"); return EXIT_FAILURE; } } blockCLIinput = 0; if(data.fifoON==1) { if (FD_ISSET(fifofd, &cli_fdin_set)) { total_bytes = 0; for (;;) { bytes = read(fifofd, buf0, 1); if (bytes > 0) { buf1[total_bytes] = buf0[0]; total_bytes += (size_t)bytes; } else { if (errno == EWOULDBLOCK) { break; } else { perror("read"); return EXIT_FAILURE; } } if(buf0[0]=='\n') { buf1[total_bytes-1] = '\0'; line = buf1; CLI_execute_line(); printf("%s", prompt); fflush(stdout); break; } } blockCLIinput = 1; // keep blocking input while fifo is not empty } } if(blockCLIinput == 0) if (FD_ISSET(fileno(stdin), &cli_fdin_set)) { rl_callback_read_char(); } } CLIexecuteCMDready = 0; if(data.CMDexecuted==0) printf("Command not found, or command with no effect\n"); } return(0); }
void InitSystem ( Int argc, Char * argv [], UInt handleSignals ) { Char * *ptrlist; UInt i; /* loop variable */ Int res; /* return from option processing function */ /* Initialize global and static variables */ SyCTRD = 1; SyCompilePlease = 0; SyDebugLoading = 0; SyLineEdit = 1; #ifdef HPCGAP SyUseReadline = 0; #else SyUseReadline = 1; #endif SyMsgsFlagBags = 0; SyNrCols = 0; SyNrColsLocked = 0; SyNrRows = 0; SyNrRowsLocked = 0; SyQuiet = 0; SyInitializing = 0; #ifdef SYS_IS_64_BIT SyStorMin = 128 * 1024L; SyStorMax = 2048*1024L; /* This is in kB! */ SyAllocPool = 4096L*1024*1024; /* Note this is in bytes! */ #else SyStorMin = 64 * 1024L; SyStorMax = 1024*1024L; /* This is in kB! */ SyAllocPool = 1536L*1024*1024; /* Note this is in bytes! */ #endif SyStorOverrun = 0; SyStorKill = 0; SyUseModule = 1; SyWindow = 0; for (i = 0; i < 2; i++) { UInt j; for (j = 0; j < 7; j++) { SyGasmanNumbers[i][j] = 0; } } preAllocAmount = 4*1024*1024; InitSysFiles(); #ifdef HAVE_LIBREADLINE rl_readline_name = "GAP"; rl_initialize (); #endif if (handleSignals) { SyInstallAnswerIntr(); } #if defined(SYS_DEFAULT_PATHS) SySetGapRootPath( SYS_DEFAULT_PATHS ); #else SySetInitialGapRootPaths(); #endif /* save the original command line for export to GAP */ SyOriginalArgc = argc; SyOriginalArgv = argv; /* scan the command line for options that we have to process in the kernel */ /* we just scan the whole command line looking for the keys for the options we recognise */ /* anything else will presumably be dealt with in the library */ while ( argc > 1 ) { if (argv[1][0] == '-' ) { if ( strlen(argv[1]) != 2 && argv[1][1] != '-') { fputs("gap: sorry, options must not be grouped '", stderr); fputs(argv[1], stderr); fputs("'.\n", stderr); goto usage; } for (i = 0; options[i].shortkey != argv[1][1] && (argv[1][1] != '-' || argv[1][2] == 0 || strcmp(options[i].longkey, argv[1] + 2)) && (options[i].shortkey != 0 || options[i].longkey[0] != 0); i++) ; if (argc < 2 + options[i].minargs) { Char buf[2]; fputs("gap: option ", stderr); fputs(argv[1], stderr); fputs(" requires at least ", stderr); buf[0] = options[i].minargs + '0'; buf[1] = '\0'; fputs(buf, stderr); fputs(" arguments\n", stderr); goto usage; } if (options[i].handler) { res = (*options[i].handler)(argv+2, options[i].otherArg); switch (res) { case -1: goto usage; /* case -2: goto fullusage; */ default: ; /* fall through and continue */ } } else res = options[i].minargs; /* recordOption(argv[1][1], res, argv+2); */ argv += 1 + res; argc -= 1 + res; } else { argv++; argc--; } } /* adjust SyUseReadline if no readline support available or for XGAP */ #if !defined(HAVE_LIBREADLINE) SyUseReadline = 0; #endif if (SyWindow) SyUseReadline = 0; /* now that the user has had a chance to give -x and -y, we determine the size of the screen ourselves */ getwindowsize(); /* fix max if it is lower than min */ if ( SyStorMax != 0 && SyStorMax < SyStorMin ) { SyStorMax = SyStorMin; } /* fix pool size if larger than SyStorKill */ if ( SyStorKill != 0 && SyAllocPool != 0 && SyAllocPool > 1024 * SyStorKill ) { SyAllocPool = SyStorKill * 1024; } /* fix pool size if it is given and lower than SyStorMax */ if ( SyAllocPool != 0 && SyAllocPool < SyStorMax * 1024) { SyAllocPool = SyStorMax * 1024; } /* when running in package mode set ctrl-d and line editing */ if ( SyWindow ) { /* SyLineEdit = 1; SyCTRD = 1; */ SyRedirectStderrToStdOut(); syWinPut( 0, "@p", "1." ); } if (SyAllocPool == 0) { /* premalloc stuff */ /* allocate in small chunks, and write something to them * (the GNU clib uses mmap for large chunks and give it back to the * system after free'ing; also it seems that memory is only really * allocated (pagewise) when it is first used) */ ptrlist = (Char **)malloc((1+preAllocAmount/1000)*sizeof(Char*)); for (i = 1; i*1000 < preAllocAmount; i++) { ptrlist[i-1] = (Char *)malloc( 1000 ); if (ptrlist[i-1] != NULL) ptrlist[i-1][900] = 13; } for (i = 1; (i+1)*1000 < preAllocAmount; i++) if (ptrlist[i-1] != NULL) free(ptrlist[i-1]); free(ptrlist); /* ptr = (Char *)malloc( preAllocAmount ); ptr1 = (Char *)malloc(4); if ( ptr != 0 ) free( ptr ); */ } /* should GAP load 'init/lib.g' on initialization */ if ( SyCompilePlease || SyRestoring ) { SyLoadSystemInitFile = 0; } /* the compiler will *not* read in the .gaprc file if ( gaprc && ! ( SyCompilePlease || SyRestoring ) ) { sySetGapRCFile(); } */ /* the users home directory */ if ( getenv("HOME") != 0 ) { strxcpy(DotGapPath, getenv("HOME"), sizeof(DotGapPath)); # if defined(SYS_IS_DARWIN) && SYS_IS_DARWIN /* On Darwin, add .gap to the sys roots, but leave */ /* DotGapPath at $HOME/Library/Preferences/GAP */ strxcat(DotGapPath, "/.gap;", sizeof(DotGapPath)); if (!IgnoreGapRC) { SySetGapRootPath(DotGapPath); } strxcpy(DotGapPath, getenv("HOME"), sizeof(DotGapPath)); strxcat(DotGapPath, "/Library/Preferences/GAP;", sizeof(DotGapPath)); # elif defined(__CYGWIN__) strxcat(DotGapPath, "/_gap;", sizeof(DotGapPath)); # else strxcat(DotGapPath, "/.gap;", sizeof(DotGapPath)); # endif if (!IgnoreGapRC) { SySetGapRootPath(DotGapPath); } DotGapPath[strlen(DotGapPath)-1] = '\0'; /* and in this case we can also expand paths which start with a tilde ~ */ Char userhome[GAP_PATH_MAX]; strxcpy(userhome, getenv("HOME"), sizeof(userhome)); const UInt userhomelen = strlen(userhome); for (i = 0; i < MAX_GAP_DIRS && SyGapRootPaths[i][0]; i++) { const UInt pathlen = strlen(SyGapRootPaths[i]); if (SyGapRootPaths[i][0] == '~' && userhomelen + pathlen < sizeof(SyGapRootPaths[i])) { SyMemmove(SyGapRootPaths[i] + userhomelen, /* don't copy the ~ but the trailing '\0' */ SyGapRootPaths[i] + 1, pathlen); memcpy(SyGapRootPaths[i], userhome, userhomelen); } } } /* now we start */ return; /* print a usage message */ usage: fputs("usage: gap [OPTIONS] [FILES]\n", stderr); fputs(" run the Groups, Algorithms and Programming system, Version ", stderr); fputs(SyBuildVersion, stderr); fputs("\n", stderr); fputs(" use '-h' option to get help.\n", stderr); fputs("\n", stderr); SyExit( 1 ); }
/* in interactive mode, write to stdout */ print_pop_error(ctx, stdout); retval = -1; /* an error 'taints' the execution */ } else { duk_pop(ctx); } } done: if (buffer) { free(buffer); buffer = NULL; } return retval; } #else /* NO_READLINE */ static int handle_interactive(duk_context *ctx) { const char *prompt = "duk> "; char *buffer = NULL; int retval = 0; int rc; duk_eval_string(ctx, GREET_CODE("")); duk_pop(ctx); /* * Note: using readline leads to valgrind-reported leaks inside * readline itself. Execute code from an input file (and not * through stdin) for clean valgrind runs. */ rl_initialize(); for (;;) { if (buffer) { free(buffer); buffer = NULL; } buffer = readline(prompt); if (!buffer) { break; } if (buffer && buffer[0] != (char) 0) { add_history(buffer); } duk_push_pointer(ctx, (void *) buffer); duk_push_uint(ctx, (duk_uint_t) strlen(buffer)); duk_push_string(ctx, "input"); interactive_mode = 1; /* global */ rc = duk_safe_call(ctx, wrapped_compile_execute, 3 /*nargs*/, 1 /*nret*/); #if defined(DUK_CMDLINE_AJSHEAP) ajsheap_clear_exec_timeout(); #endif if (buffer) { free(buffer); buffer = NULL; } if (rc != DUK_EXEC_SUCCESS) { /* in interactive mode, write to stdout */ print_pop_error(ctx, stdout); retval = -1; /* an error 'taints' the execution */ } else { duk_pop(ctx); } } if (buffer) { free(buffer); buffer = NULL; } return retval; }