/* find the real compiler. We just search the PATH to find a executable of the same name that isn't a link to ourselves */ static void find_compiler(int argc, char **argv) { char *base; char *path; orig_args = args_init(argc, argv); base = str_basename(argv[0]); /* we might be being invoked like "ccache gcc -c foo.c" */ if (strcmp(base, MYNAME) == 0) { args_remove_first(orig_args); free(base); if (strchr(argv[1],'/')) { /* a full path was given */ return; } base = str_basename(argv[1]); } /* support user override of the compiler */ if ((path=getenv("CCACHE_CC"))) { base = strdup(path); } orig_args->argv[0] = find_executable(base, MYNAME); /* can't find the compiler! */ if (!orig_args->argv[0]) { stats_update(STATS_COMPILER); perror(base); exit(1); } }
/* search $PATH for an executable file; * return 1 if found; * return 0 otherwise; */ int FAST_FUNC executable_exists(const char *filename) { char *path = xstrdup(getenv("PATH")); char *tmp = path; char *ret = find_executable(filename, &tmp); free(path); free(ret); return ret != NULL; }
static void append_executable(sl* list, const char* fn, const char* me) { char* exec = find_executable(fn, me); if (!exec) { ERROR("Error, couldn't find executable \"%s\"", fn); exit(-1); } sl_append_nocopy(list, shell_escape(exec)); free(exec); }
static bool find_executable(const char* path, const char* name, char* dest, bool recurse, errors_t* errors) { TCHAR full_path[MAX_PATH + 1]; TCHAR best_path[MAX_PATH + 1]; strcpy(full_path, path); strcat(full_path, name); if((GetFileAttributes(full_path) != INVALID_FILE_ATTRIBUTES)) { strncpy(dest, full_path, MAX_PATH); return true; } if (recurse) { PONY_ERRNO err; PONY_DIR* dir = pony_opendir(path, &err); if (dir != NULL) { uint64_t best_version = 0; // look for directories with versions PONY_DIRINFO* result; while ((result = pony_dir_entry_next(dir)) != NULL) { char *entry = pony_dir_info_name(result); if (entry == NULL || entry[0] == NULL || entry[0] == '.') continue; strncpy(full_path, path, MAX_PATH); strncat(full_path, entry, MAX_PATH - strlen(full_path)); if ((GetFileAttributes(full_path) != FILE_ATTRIBUTE_DIRECTORY)) continue; uint64_t ver = get_version(entry); if (ver == 0) continue; if (ver > best_version) { best_version = ver; strncpy(best_path, full_path, MAX_PATH); strncat(best_path, "\\", MAX_PATH - strlen(best_path)); } } pony_closedir(dir); if (best_version > 0) return find_executable(best_path, name, dest, true, errors); } } return false; }
char* uGetImageProcPath(char *buf, sys_call_error_fun fun) { #ifdef _WIN32 char *p = buf; if (GetModuleFileName(0, buf, U_MAX_PATH + 1) != 0) { p = strrchr(buf, '\\'); if (!p) p = buf; } else sys_call_error("GetModuleFileName"); *p = '\0'; return buf; #else #ifdef HAVE_PROC_EXE char *p = buf; int len = 0; char tmp[U_MAX_PATH + 1]; strcpy(tmp, "/proc/"); int2c_str(getpid(), tmp + strlen("/proc/")); strcat(tmp, PROC_EXE_SUFFIX); len = readlink(tmp, buf, U_MAX_PATH); if (len != -1) { buf[len] = '\0'; p = strrchr(buf, '/'); if (!p) p = buf; } else sys_call_error("uGetImageProcPath"); *p = '\0'; return buf; #else char *p = buf; if (find_executable(program_name_argv_0, buf, U_MAX_PATH + 1) == 0) { p = strrchr(buf, '/'); if (!p) p = buf; } *p = '\0'; return buf; #endif #endif }
static void prepare_relocate (const char *orig_installprefix, const char *orig_installdir, const char *argv0) { const char *curr_prefix; /* Determine the full pathname of the current executable. */ executable_fullname = find_executable (argv0); /* Determine the current installation prefix from it. */ curr_prefix = compute_curr_prefix (orig_installprefix, orig_installdir, executable_fullname); if (curr_prefix != NULL) /* Now pass this prefix to all copies of the relocate.c source file. */ set_relocation_prefix (orig_installprefix, curr_prefix); }
char *find_file(char *filename, char *exename) { char *p; static char pathname[MAX_FILENAME_LEN + 1]; if (file_exists(filename)) return strcpy(pathname, filename); if ((p = find_executable(exename)) == NULL) return NULL; strcpy(pathname, p); while ((p = strrchr(pathname, '/')) != NULL || (p = strrchr(pathname, '\\')) != NULL) { strcpy(p + 1, filename); if (file_exists(pathname)) return pathname; *p = 0; } return NULL; }
int which_main(int argc UNUSED_PARAM, char **argv) { const char *env_path; int status = 0; env_path = getenv("PATH"); if (!env_path) env_path = bb_default_root_path; opt_complementary = "-1"; /* at least one argument */ getopt32(argv, "a"); argv += optind; do { int missing = 1; /* If file contains a slash don't use PATH */ if (strchr(*argv, '/')) { if (file_is_executable(*argv)) { missing = 0; puts(*argv); } } else { char *path; char *tmp; char *p; path = tmp = xstrdup(env_path); while ((p = find_executable(*argv, &tmp)) != NULL) { missing = 0; puts(p); free(p); if (!option_mask32) /* -a not set */ break; } free(path); } status |= missing; } while (*++argv); return status; }
int main(int argc, char *argv[]) { char *fullPath; fullPath = getenv("PATH"); int i= 0, fd; if(argc < 2){ printf("no argument passed \n"); return 1; } //*Passing argument to parameters of function find_executable and returning the value of the executable file as to file discriptor*// fd = find_executable(fullPath, argv[1]); if (fd < 0) err(-1, "failed to find %s in %s", argv[1], fullPath); printf("Executing FD: %d\n", fd); cap_enter();//*Enabling Capsicum capability mode*// fexecve(fd, argv + 1, environ); err(-1, "fexecve() failed"); }
/* something went badly wrong - just execute the real compiler */ static void failed(void) { char *e; /* delete intermediate pre-processor file if needed */ if (i_tmpfile) { if (!direct_i_file) { unlink(i_tmpfile); } free(i_tmpfile); i_tmpfile = NULL; } /* delete the cpp stderr file if necessary */ if (cpp_stderr) { unlink(cpp_stderr); free(cpp_stderr); cpp_stderr = NULL; } /* strip any local args */ args_strip(orig_args, "--ccache-"); if ((e=getenv("CCACHE_PREFIX"))) { char *p = find_executable(e, MYNAME); if (!p) { perror(e); exit(1); } args_add_prefix(orig_args, p); } execv(orig_args->argv[0], orig_args->argv); cc_log("execv returned (%s)!\n", strerror(errno)); perror(orig_args->argv[0]); exit(1); }
int main(int argc, char **argv) { debug_config(progname); // By default, turn on fast abort option since we know each job is of very similar size (in terms of runtime). // One can also set the fast_abort_multiplier by the '-f' option. wq_option_fast_abort_multiplier = 10; get_options(argc, argv, progname); outfile = fopen(outfilename, "a+"); if(!outfile) { fprintf(stderr, "%s: couldn't open %s: %s\n", progname, outfilename, strerror(errno)); exit(1); } if(!find_executable(filter_program_name, "PATH", filter_program_path, sizeof(filter_program_path))) { fprintf(stderr, "%s: couldn't find %s in your PATH.\n", progname, filter_program_path); exit(1); } if(work_queue_master_mode == WORK_QUEUE_MASTER_MODE_CATALOG && !project) { fprintf(stderr, "sand_filter: sand filter master running in catalog mode. Please use '-N' option to specify the name of this project.\n"); fprintf(stderr, "sand_filter: Run \"%s -h\" for help with options.\n", argv[0]); return 1; } q = work_queue_create(port); if(!q) { fprintf(stderr, "%s: couldn't listen on port %d: %s\n", progname, port, strerror(errno)); exit(1); } port = work_queue_port(q); if(port_file) { opts_write_port_file(port_file,port); } // advanced work queue options work_queue_specify_master_mode(q, work_queue_master_mode); work_queue_specify_name(q, project); work_queue_specify_priority(q, priority); load_sequences(sequence_filename); debug(D_DEBUG, "Sequence loaded.\n", curr_rect_y, curr_rect_x); init_checkpoint(); start_time = time(0); int curr_start_x = 0, curr_start_y = 0, curr_rect_x = 0, curr_rect_y = 0; while(1) { while(work_queue_hungry(q)) { if(curr_start_y >= num_seqs) break; display_progress(); if(checkpoint[curr_rect_y][curr_rect_x] != CHECKPOINT_STATUS_SUCCESS) task_submit(q, curr_rect_x, curr_rect_y); // Increment the x rectangle curr_rect_x++; curr_start_x += rectangle_size; // If we've reached the end of a row, move to the // next row by incrementing the y rectangle. if(curr_start_x >= num_seqs) { curr_rect_y++; curr_start_y += rectangle_size; curr_rect_x = curr_rect_y; curr_start_x = curr_rect_x * rectangle_size; } } if(work_queue_empty(q) && curr_start_y >= num_seqs) break; struct work_queue_task *t = work_queue_wait(q, 5); if(t) task_complete(t); display_progress(); } printf("%s: candidates generated: %lu\n", progname, cand_count); if(checkpoint_file) { fclose(checkpoint_file); } fprintf(outfile, "EOF\n"); fclose(outfile); work_queue_delete(q); if(!do_not_unlink) delete_dir(outdirname); return 0; }
void rdp_connect(GtkButton *connect, gpointer erdp) { /*get the string info*/ GtkEntry *rip = (GtkEntry *) find_child(erdp, "address"); GtkEntry *ruser = (GtkEntry *) find_child(erdp, "user"); GtkEntry *rpass = (GtkEntry *) find_child(erdp, "pass"); GtkEntry *arguments = (GtkEntry *) find_child(erdp, "arguments"); GtkCheckButton *fullscreen = (GtkCheckButton *) find_child(erdp, "fullscreen"); GtkCheckButton *decorations = (GtkCheckButton *) find_child(erdp, "decorations"); GtkCheckButton *smartscaling = (GtkCheckButton *) find_child(erdp, "smartscaling"); GtkCheckButton *sound = (GtkCheckButton *) find_child(erdp, "sound"); GtkCheckButton *clipboard = (GtkCheckButton *) find_child(erdp, "clipboard"); GtkCheckButton *homedir = (GtkCheckButton *) find_child(erdp, "homedir"); char *xfreerdp = find_executable("xfreerdp"); printf("Xfreerdp path: %s\n", xfreerdp); /*format my strings correctly*/ char *fip = g_strconcat("/v:", gtk_entry_get_text(rip), NULL); char *fuser = g_strconcat("/u:", gtk_entry_get_text(ruser), NULL); char *fpass = g_strconcat("/p:", gtk_entry_get_text(rpass), NULL); /*check to see if the connection is valid*/ if(check_connect(fip, fuser, fpass) != TRUE) { return; } /*check what options to add to rdp from the options tickboxes*/ char **opts = malloc(sizeof(char *)); opts[0] = NULL; opts = add_opt(&opts, xfreerdp); opts = add_opt(&opts, "/cert-ignore"); opts = add_opt(&opts, "/auto-reconnect"); opts = add_opt(&opts, fip); opts = add_opt(&opts, fuser); opts = add_opt(&opts, fpass); if(gtk_toggle_button_get_active((GtkToggleButton*)fullscreen) == TRUE) { opts = add_opt(&opts, "/f"); } if(gtk_toggle_button_get_active((GtkToggleButton*)decorations) == TRUE) { opts = add_opt(&opts, "/disp"); opts = add_opt(&opts, "/fonts"); opts = add_opt(&opts, "/aero"); opts = add_opt(&opts, "/window-drag"); opts = add_opt(&opts, "/menu-anims"); } if(gtk_toggle_button_get_active((GtkToggleButton*)smartscaling) == TRUE) { GdkRectangle *workarea = g_new(GdkRectangle, 1); GdkScreen *screen = gdk_screen_get_default(); gint monitor = gdk_screen_get_primary_monitor(screen); gdk_screen_get_monitor_workarea(screen, monitor, workarea); int width = workarea->width; int height = workarea->height; char sizebuff[32]; snprintf(sizebuff, 31, "/size:%dx%d", width, height); opts = add_opt(&opts, sizebuff); snprintf(sizebuff, 31, "/smart-sizing:%dx%d", width, height); opts = add_opt(&opts, sizebuff); } if(gtk_toggle_button_get_active((GtkToggleButton*)sound) == TRUE) { opts = add_opt(&opts, "/sound"); } if(gtk_toggle_button_get_active((GtkToggleButton*)clipboard) == TRUE) { opts = add_opt(&opts, "/clipboard"); } if(gtk_toggle_button_get_active((GtkToggleButton*)homedir) == TRUE) { opts = add_opt(&opts, "/home-drive"); } /* add the user specified options. We do no error checking */ char *argtext = strdup(gtk_entry_get_text(arguments)); char *argbuff = strtok(argtext, " "); while(argbuff != NULL) { opts = add_opt(&opts, argbuff); strtok(NULL, " "); } /*and call xfreerdp*/ int i; printf("Calling: "); for(i=0; opts[i] != NULL; i++) { if(strncmp(opts[i], "/p:", 3) == 0) { printf("/p:**** "); continue; } printf("%s ", opts[i]); } printf("\n"); execv(xfreerdp, opts); /*code never gets here*/ return; }
int main(int argc, char **argv) { signed char c; struct work_queue *q; int port = WORK_QUEUE_DEFAULT_PORT; static const char *port_file = NULL; int work_queue_master_mode = WORK_QUEUE_MASTER_MODE_STANDALONE; char *project = NULL; int priority = 0; debug_config("allpairs_master"); extra_files_list = list_create(); struct option long_options[] = { {"debug", required_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"port", required_argument, 0, 'p'}, {"random-port", required_argument, 0, 'Z'}, {"extra-args", required_argument, 0, 'e'}, {"width", required_argument, 0, 'x'}, {"height", required_argument, 0, 'y'}, {"advertise", no_argument, 0, 'a'}, //deprecated, left here for backwards compatibility {"project-name", required_argument, 0, 'N'}, {"debug-file", required_argument, 0, 'o'}, {"output-file", required_argument, 0, 'O'}, {"wqstats-file", required_argument, 0, 's'}, {"input-file", required_argument, 0, 'f'}, {"estimated-time", required_argument, 0, 't'}, {"priority", required_argument, 0, 'P'}, {0,0,0,0} }; while((c = getopt_long(argc, argv, "ad:e:f:hN:p:P:t:vx:y:Z:O:o:s:", long_options, NULL)) >= 0) { switch (c) { case 'a': work_queue_master_mode = WORK_QUEUE_MASTER_MODE_CATALOG; break; case 'd': debug_flags_set(optarg); break; case 'e': extra_arguments = optarg; break; case 'f': list_push_head(extra_files_list,optarg); break; case 'o': debug_config_file(optarg); break; case 'O': free(output_filename); output_filename=xxstrdup(optarg); break; case 's': free(wqstats_filename); wqstats_filename=xxstrdup(optarg); break; case 'h': show_help(progname); exit(0); break; case 'N': work_queue_master_mode = WORK_QUEUE_MASTER_MODE_CATALOG; free(project); project = xxstrdup(optarg); break; case 'p': port = atoi(optarg); break; case 'P': priority = atoi(optarg); break; case 't': compare_program_time = atof(optarg); break; case 'v': cctools_version_print(stdout, progname); exit(0); break; case 'x': xblock = atoi(optarg); break; case 'y': yblock = atoi(optarg); break; case 'Z': port_file = optarg; port = 0; break; default: show_help(progname); return 1; } } cctools_version_debug(D_DEBUG, argv[0]); if((argc - optind) < 3) { show_help(progname); exit(1); } struct text_list *seta = text_list_load(argv[optind]); if(!seta) { fprintf(stderr,"%s: couldn't open %s: %s\n",progname,argv[optind+1],strerror(errno)); return 1; } fprintf(stdout, "%s: %s has %d elements\n",progname,argv[optind],text_list_size(seta)); struct text_list *setb = text_list_load(argv[optind+1]); if(!setb) { fprintf(stderr,"%s: couldn't open %s: %s\n",progname,argv[optind+1],strerror(errno)); return 1; } fprintf(stdout, "%s: %s has %d elements\n",progname,argv[optind+1],text_list_size(setb)); if (!find_executable("allpairs_multicore","PATH",allpairs_multicore_program,sizeof(allpairs_multicore_program))) { fprintf(stderr,"%s: couldn't find allpairs_multicore in path\n",progname); return 1; } debug(D_DEBUG,"using multicore executable %s",allpairs_multicore_program); xstop = text_list_size(seta); ystop = text_list_size(setb); if(allpairs_compare_function_get(argv[optind+2])) { strcpy(allpairs_compare_program,argv[optind+2]); debug(D_DEBUG,"using internal function %s",allpairs_compare_program); use_external_program = 0; } else { if(!find_executable(argv[optind+2],"PATH",allpairs_compare_program,sizeof(allpairs_compare_program))) { fprintf(stderr,"%s: %s is neither an executable nor an internal comparison function.\n",progname,allpairs_compare_program); return 1; } debug(D_DEBUG,"using comparison executable %s",allpairs_compare_program); use_external_program = 1; } if(!xblock || !yblock) { estimate_block_size(seta,setb,&xblock,&yblock); } fprintf(stdout, "%s: using block size of %dx%d\n",progname,xblock,yblock); if(work_queue_master_mode == WORK_QUEUE_MASTER_MODE_CATALOG && !project) { fprintf(stderr, "allpairs: allpairs master running in catalog mode. Please use '-N' option to specify the name of this project.\n"); fprintf(stderr, "allpairs: Run \"%s -h\" for help with options.\n", argv[0]); return 1; } q = work_queue_create(port); //Read the port the queue is actually running, in case we just called //work_queue_create(LINK_PORT_ANY) port = work_queue_port(q); if(!q) { fprintf(stderr,"%s: could not create work queue on port %d: %s\n",progname,port,strerror(errno)); return 1; } if(port_file) opts_write_port_file(port_file, port); if(wqstats_filename) work_queue_specify_log(q, wqstats_filename); // advanced work queue options work_queue_specify_master_mode(q, work_queue_master_mode); work_queue_specify_name(q, project); work_queue_specify_priority(q, priority); fprintf(stdout, "%s: listening for workers on port %d...\n",progname,work_queue_port(q)); while(1) { struct work_queue_task *task = NULL; while(work_queue_hungry(q)) { task = ap_task_create(seta,setb); if(task) { work_queue_submit(q, task); } else { break; } } if(!task && work_queue_empty(q)) break; task = work_queue_wait(q,5); if(task) task_complete(task); } work_queue_delete(q); return 0; }
static bool find_msvcrt_and_linker(compile_t *c, vcvars_t* vcvars, errors_t* errors) { search_t vs; TCHAR link_path[MAX_PATH + 1]; TCHAR lib_path[MAX_PATH + 1]; vsinfo_t* info; for (info = vs_infos; info->version != NULL; info++) { if(c->opt->verbosity >= VERBOSITY_TOOL_INFO) fprintf(stderr, "searching for VS in registry: %s\\%s\n", info->reg_path, info->reg_key); if (!find_registry_value(info->reg_path, info->reg_key, &vs)) continue; strncpy(link_path, info->bin_path, MAX_PATH); strncat(link_path, "link.exe", MAX_PATH - strlen(link_path)); strncpy(lib_path, info->bin_path, MAX_PATH); strncat(lib_path, "lib.exe", MAX_PATH - strlen(lib_path)); // VS2017 may have multiple VC++ installs; search for the latest one if (info->search_path != NULL) { strncat(vs.path, info->search_path, MAX_PATH - strlen(vs.path)); if(c->opt->verbosity >= VERBOSITY_TOOL_INFO) fprintf(stderr, "searching for %s .. \\%s and \\%s\n", vs.path, link_path, lib_path); if (find_executable(vs.path, link_path, vcvars->link, true, errors)) { strncpy(vs.path, vcvars->link, MAX_PATH); size_t ver_index = strlen(vcvars->link) - strlen(link_path); strncpy(vs.version, vs.path + ver_index, MAX_PATH); vs.path[ver_index] = 0; if (find_executable(vs.path, lib_path, vcvars->ar, false, errors)) { strncpy(vcvars->msvcrt, vs.path, MAX_PATH); strncat(vcvars->msvcrt, info->lib_path, MAX_PATH - strlen(vcvars->msvcrt)); if(c->opt->verbosity >= VERBOSITY_TOOL_INFO) { fprintf(stderr, "linker: %s\n", vcvars->link); fprintf(stderr, "libtool: %s\n", vcvars->ar); fprintf(stderr, "libdir: %s\n", vcvars->msvcrt); } return true; } } } else // VS2015 has one place for VC++ { if (find_executable(vs.path, link_path, vcvars->link, false, errors) && find_executable(vs.path, lib_path, vcvars->ar, false, errors)) { strncpy(vs.version, info->version, MAX_VER_LEN); strncpy(vcvars->msvcrt, vs.path, MAX_PATH); strncat(vcvars->msvcrt, info->lib_path, MAX_PATH - strlen(vcvars->msvcrt)); if(c->opt->verbosity >= VERBOSITY_TOOL_INFO) { fprintf(stderr, "linker: %s\n", vcvars->link); fprintf(stderr, "libtool: %s\n", vcvars->ar); fprintf(stderr, "libdir: %s\n", vcvars->msvcrt); } return true; } } } errorf(errors, NULL, "unable to locate a Microsoft link.exe; please " "install Visual Studio 2015 or later: https://www.visualstudio.com/"); return false; }
int main(int argc, char** args) { int c; anbool help = FALSE; char* outdir = NULL; char* cmd; int i, j, f; int inputnum; int rtn; sl* engineargs; int nbeargs; anbool fromstdin = FALSE; anbool overwrite = FALSE; anbool cont = FALSE; anbool skip_solved = FALSE; anbool makeplots = TRUE; double plotscale = 1.0; char* inbgfn = NULL; char* bgfn = NULL; char* me; anbool verbose = FALSE; int loglvl = LOG_MSG; char* outbase = NULL; anbool usecurl = TRUE; bl* opts; augment_xylist_t theallaxy; augment_xylist_t* allaxy = &theallaxy; int nmyopts; char* removeopts = "ixo\x01"; char* newfits; char* kmz = NULL; char* scamp = NULL; char* scampconfig = NULL; char* index_xyls; anbool just_augment = FALSE; anbool engine_batch = FALSE; bl* batchaxy = NULL; bl* batchsf = NULL; sl* outfiles; sl* tempfiles; // these are deleted after the outer loop over input files sl* tempfiles2; sl* tempdirs; anbool timestamp = FALSE; anbool tempaxy = FALSE; errors_print_on_exit(stderr); fits_use_error_system(); me = find_executable(args[0], NULL); engineargs = sl_new(16); append_executable(engineargs, "astrometry-engine", me); // output filenames. outfiles = sl_new(16); tempfiles = sl_new(4); tempfiles2 = sl_new(4); tempdirs = sl_new(4); rtn = 0; nmyopts = sizeof(options)/sizeof(an_option_t); opts = opts_from_array(options, nmyopts, NULL); augment_xylist_add_options(opts); // remove duplicate short options. for (i=0; i<nmyopts; i++) { an_option_t* opt1 = bl_access(opts, i); for (j=nmyopts; j<bl_size(opts); j++) { an_option_t* opt2 = bl_access(opts, j); if (opt2->shortopt == opt1->shortopt) bl_remove_index(opts, j); } } // remove unwanted augment-xylist options. for (i=0; i<strlen(removeopts); i++) { for (j=nmyopts; j<bl_size(opts); j++) { an_option_t* opt2 = bl_access(opts, j); if (opt2->shortopt == removeopts[i]) bl_remove_index(opts, j); } } // which options are left? /*{ char options[256]; memset(options, 0, 256); printf("options:\n"); for (i=0; i<bl_size(opts); i++) { an_option_t* opt = bl_access(opts, i); printf(" %c (%i) %s\n", opt->shortopt, (int)opt->shortopt, opt->name); options[(int)((opt->shortopt + 256) % 256)] = 1; } printf("Remaining short opts:\n"); for (i=0; i<256; i++) { if (!options[i]) printf(" %c (%i, 0x%x)\n", (char)i, i, i); } }*/ augment_xylist_init(allaxy); // default output filename patterns. allaxy->axyfn = "%s.axy"; allaxy->matchfn = "%s.match"; allaxy->rdlsfn = "%s.rdls"; allaxy->solvedfn = "%s.solved"; allaxy->wcsfn = "%s.wcs"; allaxy->corrfn = "%s.corr"; newfits = "%s.new"; index_xyls = "%s-indx.xyls"; while (1) { int res; c = opts_getopt(opts, argc, args); //printf("option %c (%i)\n", c, (int)c); if (c == -1) break; switch (c) { case '\x91': allaxy->axyfn = optarg; break; case '\x90': tempaxy = TRUE; break; case '\x88': timestamp = TRUE; break; case '\x84': plotscale = atof(optarg); break; case '\x85': inbgfn = optarg; break; case '\x87': allaxy->assume_fits_image = TRUE; break; case '(': engine_batch = TRUE; break; case '@': just_augment = TRUE; break; case 'U': index_xyls = optarg; break; case 'n': scampconfig = optarg; break; case 'i': scamp = optarg; break; case 'Z': kmz = optarg; break; case 'N': newfits = optarg; break; case 'h': help = TRUE; break; case 'v': sl_append(engineargs, "--verbose"); verbose = TRUE; allaxy->verbosity++; loglvl++; break; case 'D': outdir = optarg; break; case 'o': outbase = optarg; break; case 'b': case '\x89': sl_append(engineargs, "--config"); append_escape(engineargs, optarg); break; case 'f': fromstdin = TRUE; break; case 'O': overwrite = TRUE; break; case 'p': makeplots = FALSE; break; case 'G': usecurl = FALSE; break; case 'K': cont = TRUE; break; case 'J': skip_solved = TRUE; break; default: res = augment_xylist_parse_option(c, optarg, allaxy); if (res) { rtn = -1; goto dohelp; } } } if ((optind == argc) && !fromstdin) { printf("ERROR: You didn't specify any files to process.\n"); help = TRUE; } if (help) { dohelp: print_help(args[0], opts); exit(rtn); } bl_free(opts); // --dont-augment: advertised as just write xy file, // so quit after doing that. if (allaxy->dont_augment) { just_augment = TRUE; } log_init(loglvl); if (timestamp) log_set_timestamp(TRUE); if (kmz && starts_with(kmz, "-")) logmsg("Do you really want to save KMZ to the file named \"%s\" ??\n", kmz); if (starts_with(newfits, "-")) { logmsg("Do you really want to save the new FITS file to the file named \"%s\" ??\n", newfits); } if (engine_batch) { batchaxy = bl_new(16, sizeof(augment_xylist_t)); batchsf = bl_new(16, sizeof(solve_field_args_t)); } // Allow (some of the) default filenames to be disabled by setting them to "none". allaxy->matchfn = none_is_null(allaxy->matchfn); allaxy->rdlsfn = none_is_null(allaxy->rdlsfn); allaxy->solvedfn = none_is_null(allaxy->solvedfn); allaxy->solvedinfn = none_is_null(allaxy->solvedinfn); allaxy->wcsfn = none_is_null(allaxy->wcsfn); allaxy->corrfn = none_is_null(allaxy->corrfn); newfits = none_is_null(newfits); index_xyls = none_is_null(index_xyls); if (outdir) { if (mkdir_p(outdir)) { ERROR("Failed to create output directory %s", outdir); exit(-1); } } // number of engine args not specific to a particular file nbeargs = sl_size(engineargs); f = optind; inputnum = 0; while (1) { char* infile = NULL; anbool isxyls; char* reason; int len; char* base; char* basedir; char* basefile = NULL; char *objsfn=NULL; char *ppmfn=NULL; char* downloadfn = NULL; char* suffix = NULL; sl* cmdline; anbool ctrlc; anbool isurl; augment_xylist_t theaxy; augment_xylist_t* axy = &theaxy; int j; solve_field_args_t thesf; solve_field_args_t* sf = &thesf; anbool want_pnm = FALSE; // reset augment-xylist args. memcpy(axy, allaxy, sizeof(augment_xylist_t)); memset(sf, 0, sizeof(solve_field_args_t)); if (fromstdin) { char fnbuf[1024]; if (!fgets(fnbuf, sizeof(fnbuf), stdin)) { if (ferror(stdin)) SYSERROR("Failed to read a filename from stdin"); break; } len = strlen(fnbuf); if (fnbuf[len-1] == '\n') fnbuf[len-1] = '\0'; infile = fnbuf; logmsg("Reading input file \"%s\"...\n", infile); } else { if (f == argc) break; infile = args[f]; f++; logmsg("Reading input file %i of %i: \"%s\"...\n", f - optind, argc - optind, infile); } inputnum++; cmdline = sl_new(16); if (!engine_batch) { // Remove arguments that might have been added in previous trips through this loop sl_remove_from(engineargs, nbeargs); } // Choose the base path/filename for output files. if (outbase) asprintf_safe(&basefile, outbase, inputnum, infile); else basefile = basename_safe(infile); //logverb("Base filename: %s\n", basefile); isurl = (!file_exists(infile) && (starts_with(infile, "http://") || starts_with(infile, "ftp://"))); if (outdir) basedir = strdup(outdir); else { if (isurl) basedir = strdup("."); else basedir = dirname_safe(infile); } //logverb("Base directory: %s\n", basedir); asprintf_safe(&base, "%s/%s", basedir, basefile); //logverb("Base name for output files: %s\n", base); // trim .gz, .bz2 // hmm, we drop the suffix in this case... len = strlen(base); if (ends_with(base, ".gz")) base[len-3] = '\0'; else if (ends_with(base, ".bz2")) base[len-4] = '\0'; len = strlen(base); // trim .xx / .xxx / .xxxx if (len >= 5) { for (j=3; j<=5; j++) { if (base[len - j] == '/') break; if (base[len - j] == '.') { base[len - j] = '\0'; suffix = base + len - j + 1; break; } } } logverb("Base: \"%s\", basefile \"%s\", basedir \"%s\", suffix \"%s\"\n", base, basefile, basedir, suffix); if (tempaxy) { axy->axyfn = create_temp_file("axy", axy->tempdir); sl_append_nocopy(tempfiles2, axy->axyfn); } else axy->axyfn = sl_appendf(outfiles, axy->axyfn, base); if (axy->matchfn) axy->matchfn = sl_appendf(outfiles, axy->matchfn, base); if (axy->rdlsfn) axy->rdlsfn = sl_appendf(outfiles, axy->rdlsfn, base); if (axy->solvedfn) axy->solvedfn = sl_appendf(outfiles, axy->solvedfn, base); if (axy->wcsfn) axy->wcsfn = sl_appendf(outfiles, axy->wcsfn, base); if (axy->corrfn) axy->corrfn = sl_appendf(outfiles, axy->corrfn, base); if (axy->cancelfn) axy->cancelfn = sl_appendf(outfiles, axy->cancelfn, base); if (axy->keepxylsfn) axy->keepxylsfn = sl_appendf(outfiles, axy->keepxylsfn, base); if (axy->pnmfn) axy->pnmfn = sl_appendf(outfiles, axy->pnmfn, base); if (newfits) sf->newfitsfn = sl_appendf(outfiles, newfits, base); if (kmz) sf->kmzfn = sl_appendf(outfiles, kmz, base); if (index_xyls) sf->indxylsfn = sl_appendf(outfiles, index_xyls, base); if (scamp) sf->scampfn = sl_appendf(outfiles, scamp, base); if (scampconfig) sf->scampconfigfn = sl_appendf(outfiles, scampconfig, base); if (makeplots) { objsfn = sl_appendf(outfiles, "%s-objs.png", base); sf->redgreenfn = sl_appendf(outfiles, "%s-indx.png", base); sf->ngcfn = sl_appendf(outfiles, "%s-ngc.png", base); } if (isurl) { if (suffix) downloadfn = sl_appendf(outfiles, "%s.%s", base, suffix); else downloadfn = sl_appendf(outfiles, "%s", base); } if (axy->solvedinfn) asprintf_safe(&axy->solvedinfn, axy->solvedinfn, base); // Do %s replacement on --verify-wcs entries... if (sl_size(axy->verifywcs)) { sl* newlist = sl_new(4); for (j=0; j<sl_size(axy->verifywcs); j++) sl_appendf(newlist, sl_get(axy->verifywcs, j), base); axy->verifywcs = newlist; } // ... and plot-bg if (inbgfn) asprintf_safe(&bgfn, inbgfn, base); if (axy->solvedinfn && axy->solvedfn && streq(axy->solvedfn, axy->solvedinfn)) { // solved input and output files are the same: don't delete the input! sl_remove_string(outfiles, axy->solvedfn); free(axy->solvedfn); axy->solvedfn = axy->solvedinfn; } free(basedir); free(basefile); if (skip_solved) { char* tocheck[] = { axy->solvedinfn, axy->solvedfn }; for (j=0; j<sizeof(tocheck)/sizeof(char*); j++) { if (!tocheck[j]) continue; logverb("Checking for solved file %s\n", tocheck[j]); if (file_exists(tocheck[j])) { logmsg("Solved file exists: %s; skipping this input file.\n", tocheck[j]); goto nextfile; } else { logverb("File \"%s\" does not exist.\n", tocheck[j]); } } } // Check for overlap between input and output filenames for (i = 0; i < sl_size(outfiles); i++) { char* fn = sl_get(outfiles, i); if (streq(fn, infile)) { logmsg("Output filename \"%s\" is the same as your input file.\n" "Refusing to continue.\n" "You can either choose a different output filename, or\n" "rename your input file to have a different extension.\n", fn); goto nextfile; } } // Check for (and possibly delete) existing output filenames. for (i = 0; i < sl_size(outfiles); i++) { char* fn = sl_get(outfiles, i); if (!file_exists(fn)) continue; if (cont) { } else if (overwrite) { if (unlink(fn)) { SYSERROR("Failed to delete an already-existing output file \"%s\"", fn); exit(-1); } } else { logmsg("Output file already exists: \"%s\".\n" "Use the --overwrite flag to overwrite existing files,\n" " or the --continue flag to not overwrite existing files but still try solving.\n", fn); logmsg("Continuing to next input file.\n"); goto nextfile; } } // if we're making "redgreen" plot, we need: if (sf->redgreenfn) { // -- index xylist if (!sf->indxylsfn) { sf->indxylsfn = create_temp_file("indxyls", axy->tempdir); sl_append_nocopy(tempfiles, sf->indxylsfn); } // -- match file. if (!axy->matchfn) { axy->matchfn = create_temp_file("match", axy->tempdir); sl_append_nocopy(tempfiles, axy->matchfn); } } // if index xyls file is needed, we need: if (sf->indxylsfn) { // -- wcs if (!axy->wcsfn) { axy->wcsfn = create_temp_file("wcs", axy->tempdir); sl_append_nocopy(tempfiles, axy->wcsfn); } // -- rdls if (!axy->rdlsfn) { axy->rdlsfn = create_temp_file("rdls", axy->tempdir); sl_append_nocopy(tempfiles, axy->rdlsfn); } } // Download URL... if (isurl) { sl_append(cmdline, usecurl ? "curl" : "wget"); if (!verbose) sl_append(cmdline, usecurl ? "--silent" : "--quiet"); sl_append(cmdline, usecurl ? "--output" : "-O"); append_escape(cmdline, downloadfn); append_escape(cmdline, infile); cmd = sl_implode(cmdline, " "); logmsg("Downloading...\n"); if (run_command(cmd, &ctrlc)) { ERROR("%s command %s", sl_get(cmdline, 0), (ctrlc ? "was cancelled" : "failed")); exit(-1); } sl_remove_all(cmdline); free(cmd); infile = downloadfn; } if (makeplots) want_pnm = TRUE; if (axy->assume_fits_image) { axy->imagefn = infile; if (axy->pnmfn) want_pnm = TRUE; } else { logverb("Checking if file \"%s\" ext %i is xylist or image: ", infile, axy->extension); fflush(NULL); reason = NULL; isxyls = xylist_is_file_xylist(infile, axy->extension, axy->xcol, axy->ycol, &reason); logverb(isxyls ? "xyls\n" : "image\n"); if (!isxyls) logverb(" (not xyls because: %s)\n", reason); free(reason); fflush(NULL); if (isxyls) axy->xylsfn = infile; else { axy->imagefn = infile; want_pnm = TRUE; } } if (want_pnm && !axy->pnmfn) { ppmfn = create_temp_file("ppm", axy->tempdir); sl_append_nocopy(tempfiles, ppmfn); axy->pnmfn = ppmfn; axy->force_ppm = TRUE; } axy->keep_fitsimg = (newfits || scamp); if (augment_xylist(axy, me)) { ERROR("augment-xylist failed"); exit(-1); } if (just_augment) goto nextfile; if (makeplots) { // Check that the plotting executables were built... char* exec = find_executable("plotxy", me); free(exec); if (!exec) { logmsg("Couldn't find \"plotxy\" executable - maybe you didn't build the plotting programs?\n"); logmsg("Disabling plots.\n"); makeplots = FALSE; } } if (makeplots) { // source extraction overlay if (plot_source_overlay(axy, me, objsfn, plotscale, bgfn)) makeplots = FALSE; } append_escape(engineargs, axy->axyfn); if (file_readable(axy->wcsfn)) axy->wcs_last_mod = file_get_last_modified_time(axy->wcsfn); else axy->wcs_last_mod = 0; if (!engine_batch) { run_engine(engineargs); after_solved(axy, sf, makeplots, me, verbose, axy->tempdir, tempdirs, tempfiles, plotscale, bgfn); } else { bl_append(batchaxy, axy); bl_append(batchsf, sf ); } fflush(NULL); // clean up and move on to the next file. nextfile: free(base); sl_free2(cmdline); if (!engine_batch) { free(axy->fitsimgfn); free(axy->solvedinfn); free(bgfn); // erm. if (axy->verifywcs != allaxy->verifywcs) sl_free2(axy->verifywcs); sl_remove_all(outfiles); if (!axy->no_delete_temp) delete_temp_files(tempfiles, tempdirs); } errors_print_stack(stdout); errors_clear_stack(); logmsg("\n"); } if (engine_batch) { run_engine(engineargs); for (i=0; i<bl_size(batchaxy); i++) { augment_xylist_t* axy = bl_access(batchaxy, i); solve_field_args_t* sf = bl_access(batchsf, i); after_solved(axy, sf, makeplots, me, verbose, axy->tempdir, tempdirs, tempfiles, plotscale, bgfn); errors_print_stack(stdout); errors_clear_stack(); logmsg("\n"); free(axy->fitsimgfn); free(axy->solvedinfn); // erm. if (axy->verifywcs != allaxy->verifywcs) sl_free2(axy->verifywcs); } if (!allaxy->no_delete_temp) delete_temp_files(tempfiles, tempdirs); bl_free(batchaxy); bl_free(batchsf); } if (!allaxy->no_delete_temp) delete_temp_files(tempfiles2, NULL); sl_free2(outfiles); sl_free2(tempfiles); sl_free2(tempfiles2); sl_free2(tempdirs); sl_free2(engineargs); free(me); augment_xylist_free_contents(allaxy); return 0; }
/* something went badly wrong - just execute the real compiler */ static void failed(void) { char *e; /* delete intermediate pre-processor file if needed */ if (i_tmpfile) { if (!direct_i_file) { unlink(i_tmpfile); } free(i_tmpfile); i_tmpfile = NULL; } /* delete the cpp stderr file if necessary */ if (cpp_stderr) { unlink(cpp_stderr); free(cpp_stderr); cpp_stderr = NULL; } /* strip any local args */ args_strip(orig_args, "--ccache-"); if ((e=getenv("CCACHE_PREFIX"))) { char *p = find_executable(e, MYNAME); if (!p) { cc_log("could not find executable (%s)\n", e); perror(e); exit(1); } args_add_prefix(orig_args, p); } if (ccache_verbose) { display_execute_args(orig_args->argv); } if (swig) { putenv("CCACHE_OUTFILES"); } #ifndef _WIN32 execv(orig_args->argv[0], orig_args->argv); cc_log("execv returned (%s)!\n", strerror(errno)); perror(orig_args->argv[0]); exit(1); #else /* execv on Windows causes the 'non-regular' testcase to fail, so use Win32 API instead */ { PROCESS_INFORMATION pinfo; STARTUPINFO sinfo; BOOL ret; DWORD exitcode; char *args; ZeroMemory(&pinfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&sinfo, sizeof(STARTUPINFO)); sinfo.cb = sizeof(STARTUPINFO); args = argvtos(orig_args->argv); ret = CreateProcessA(orig_args->argv[0], args, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo); if (!ret) { exitcode = 1; cc_log("CreateProcessA failed starting %s\n", orig_args->argv[0]); perror_win32(orig_args->argv[0]); } else { WaitForSingleObject(pinfo.hProcess, INFINITE); GetExitCodeProcess(pinfo.hProcess, &exitcode); CloseHandle(pinfo.hProcess); CloseHandle(pinfo.hThread); } free(args); exit(exitcode); } #endif }
/* * prb_child_create() - this routine instantiates and rendevous with the * target child process. This routine returns an opaque handle for the * childs /proc entry. */ prb_status_t prb_child_create(const char *cmdname, char * const *cmdargs, const char *loption, const char *libtnfprobe_path, char * const *envp, prb_proc_ctl_t **ret_val) { prb_status_t prbstat; pid_t childpid; char executable_name[PATH_MAX + 2]; extern char **environ; char * const * env_to_use; size_t loptlen, probepathlen; volatile shmem_msg_t *smp; /* initialize shmem communication buffer to cause child to wait */ prbstat = prb_shmem_init(&smp); if (prbstat) return (prbstat); /* fork to create the child process */ childpid = fork(); if (childpid == (pid_t) - 1) { DBG(perror("prb_child_create: fork failed")); return (prb_status_map(errno)); } if (childpid == 0) { char *oldenv; char *newenv; /* ---- CHILD PROCESS ---- */ DBG_TNF_PROBE_1(prb_child_create_1, "libtnfctl", "sunw%verbosity 1; sunw%debug 'child process created'", tnf_long, pid, getpid()); if (envp) { env_to_use = envp; goto ContChild; } /* append libtnfprobe.so to the LD_PRELOAD environment */ loptlen = (loption) ? strlen(loption) : 0; /* probepathlen has a "/" added in ("+ 1") */ probepathlen = (libtnfprobe_path) ? (strlen(libtnfprobe_path) + 1) : 0; oldenv = getenv(PRELOAD); if (oldenv) { newenv = (char *) malloc(strlen(PRELOAD) + 1 + /* "=" */ strlen(oldenv) + 1 + /* " " */ probepathlen + strlen(LIBPROBE) + 1 + /* " " */ loptlen + 1); /* NULL */ if (!newenv) goto ContChild; (void) strcpy(newenv, PRELOAD); (void) strcat(newenv, "="); (void) strcat(newenv, oldenv); (void) strcat(newenv, " "); if (probepathlen) { (void) strcat(newenv, libtnfprobe_path); (void) strcat(newenv, "/"); } (void) strcat(newenv, LIBPROBE); if (loptlen) { (void) strcat(newenv, " "); (void) strcat(newenv, loption); } } else { newenv = (char *) malloc(strlen(PRELOAD) + 1 + /* "=" */ probepathlen + strlen(LIBPROBE) + 1 + /* " " */ loptlen + 1); /* NULL */ if (!newenv) goto ContChild; (void) strcpy(newenv, PRELOAD); (void) strcat(newenv, "="); if (probepathlen) { (void) strcat(newenv, libtnfprobe_path); (void) strcat(newenv, "/"); } (void) strcat(newenv, LIBPROBE); if (loptlen) { (void) strcat(newenv, " "); (void) strcat(newenv, loption); } } (void) putenv((char *) newenv); env_to_use = environ; /* * We don't check the return value of putenv because the * desired libraries might already be in the target, even * if our effort to change the environment fails. We * should continue either way ... */ ContChild: /* wait until the parent releases us */ (void) prb_shmem_wait(smp); DBG_TNF_PROBE_1(prb_child_create_2, "libtnfctl", "sunw%verbosity 2; " "sunw%debug 'child process about to exec'", tnf_string, cmdname, cmdname); /* * make the child it's own process group. * This is so that signals delivered to parent are not * also delivered to child. */ (void) setpgrp(); prbstat = find_executable(cmdname, executable_name); if (prbstat) { DBG((void) fprintf(stderr, "prb_child_create: %s\n", prb_status_str(prbstat))); /* parent waits for exit */ _exit(1); } if (execve(executable_name, cmdargs, env_to_use) == -1) { DBG(perror("prb_child_create: exec failed")); _exit(1); } /* Never reached */ _exit(1); } /* ---- PARENT PROCESS ---- */ /* child is waiting for us */ prbstat = sync_child(childpid, smp, ret_val); if (prbstat) { return (prbstat); } return (PRB_STATUS_OK); }
/* process the compiler options to form the correct set of options for obtaining the preprocessor output */ static void process_args(int argc, char **argv) { int i; int found_c_opt = 0; int found_S_opt = 0; struct stat st; char *e; stripped_args = args_init(0, NULL); args_add(stripped_args, argv[0]); for (i=1; i<argc; i++) { /* some options will never work ... */ if (strcmp(argv[i], "-E") == 0) { failed(); } /* these are too hard */ if (strcmp(argv[i], "-fbranch-probabilities")==0 || strcmp(argv[i], "-M") == 0 || strcmp(argv[i], "-MM") == 0 || strcmp(argv[i], "-x") == 0) { cc_log("argument %s is unsupported\n", argv[i]); stats_update(STATS_UNSUPPORTED); failed(); continue; } /* we must have -c */ if (strcmp(argv[i], "-c") == 0) { args_add(stripped_args, argv[i]); found_c_opt = 1; continue; } /* -S changes the default extension */ if (strcmp(argv[i], "-S") == 0) { args_add(stripped_args, argv[i]); found_S_opt = 1; continue; } /* we need to work out where the output was meant to go */ if (strcmp(argv[i], "-o") == 0) { if (i == argc-1) { cc_log("missing argument to %s\n", argv[i]); stats_update(STATS_ARGS); failed(); } output_file = argv[i+1]; i++; continue; } /* alternate form of -o, with no space */ if (strncmp(argv[i], "-o", 2) == 0) { output_file = &argv[i][2]; continue; } /* debugging is handled specially, so that we know if we can strip line number info */ if (strncmp(argv[i], "-g", 2) == 0) { args_add(stripped_args, argv[i]); if (strcmp(argv[i], "-g0") != 0) { enable_unify = 0; } continue; } /* The user knows best: just swallow the next arg */ if (strcmp(argv[i], "--ccache-skip") == 0) { i++; if (i == argc) { failed(); } args_add(stripped_args, argv[i]); continue; } /* options that take an argument */ { const char *opts[] = {"-I", "-include", "-imacros", "-iprefix", "-iwithprefix", "-iwithprefixbefore", "-L", "-D", "-U", "-x", "-MF", "-MT", "-MQ", "-isystem", "-aux-info", "--param", "-A", "-Xlinker", "-u", "-idirafter", NULL}; int j; for (j=0;opts[j];j++) { if (strcmp(argv[i], opts[j]) == 0) { if (i == argc-1) { cc_log("missing argument to %s\n", argv[i]); stats_update(STATS_ARGS); failed(); } args_add(stripped_args, argv[i]); args_add(stripped_args, argv[i+1]); i++; break; } } if (opts[j]) continue; } /* other options */ if (argv[i][0] == '-') { args_add(stripped_args, argv[i]); continue; } /* if an argument isn't a plain file then assume its an option, not an input file. This allows us to cope better with unusual compiler options */ if (stat(argv[i], &st) != 0 || !S_ISREG(st.st_mode)) { args_add(stripped_args, argv[i]); continue; } if (input_file) { if (check_extension(argv[i], NULL)) { cc_log("multiple input files (%s and %s)\n", input_file, argv[i]); stats_update(STATS_MULTIPLE); } else if (!found_c_opt) { cc_log("called for link with %s\n", argv[i]); if (strstr(argv[i], "conftest.")) { stats_update(STATS_CONFTEST); } else { stats_update(STATS_LINK); } } else { cc_log("non C/C++ file %s\n", argv[i]); stats_update(STATS_NOTC); } failed(); } input_file = argv[i]; } if (!input_file) { cc_log("No input file found\n"); stats_update(STATS_NOINPUT); failed(); } i_extension = check_extension(input_file, &direct_i_file); if (i_extension == NULL) { cc_log("Not a C/C++ file - %s\n", input_file); stats_update(STATS_NOTC); failed(); } if (!found_c_opt) { cc_log("No -c option found for %s\n", input_file); /* I find that having a separate statistic for autoconf tests is useful, as they are the dominant form of "called for link" in many cases */ if (strstr(input_file, "conftest.")) { stats_update(STATS_CONFTEST); } else { stats_update(STATS_LINK); } failed(); } /* don't try to second guess the compilers heuristics for stdout handling */ if (output_file && strcmp(output_file, "-") == 0) { stats_update(STATS_OUTSTDOUT); failed(); } if (!output_file) { char *p; output_file = x_strdup(input_file); if ((p = strrchr(output_file, '/'))) { output_file = p+1; } p = strrchr(output_file, '.'); if (!p || !p[1]) { cc_log("badly formed output_file %s\n", output_file); stats_update(STATS_ARGS); failed(); } p[1] = found_S_opt ? 's' : 'o'; p[2] = 0; } /* cope with -o /dev/null */ if (strcmp(output_file,"/dev/null") != 0 && stat(output_file, &st) == 0 && !S_ISREG(st.st_mode)) { cc_log("Not a regular file %s\n", output_file); stats_update(STATS_DEVICE); failed(); } if ((e=getenv("CCACHE_PREFIX"))) { char *p = find_executable(e, MYNAME); if (!p) { perror(e); exit(1); } args_add_prefix(stripped_args, p); } }
/* process the compiler options to form the correct set of options for obtaining the preprocessor output */ static void process_args(int argc, char **argv) { int i; int found_c_opt = 0; int found_S_opt = 0; struct stat st; char *e; /* is gcc being asked to output dependencies? */ int generating_dependencies = 0; /* is the dependency makefile name overridden with -MF? */ int dependency_filename_specified = 0; /* is the dependency makefile target name specified with -MQ or -MF? */ int dependency_target_specified = 0; stripped_args = args_init(0, NULL); args_add(stripped_args, argv[0]); /* -c not required for SWIG */ if (swig) { found_c_opt = 1; } for (i=1; i<argc; i++) { /* some options will never work ... */ if (strcmp(argv[i], "-E") == 0) { failed(); } /* these are too hard */ if (strcmp(argv[i], "-fbranch-probabilities")==0 || strcmp(argv[i], "-fprofile-arcs") == 0 || strcmp(argv[i], "-ftest-coverage") == 0 || strcmp(argv[i], "--coverage") == 0 || strcmp(argv[i], "-M") == 0 || strcmp(argv[i], "-MM") == 0 || strcmp(argv[i], "-x") == 0) { cc_log("argument %s is unsupported\n", argv[i]); stats_update(STATS_UNSUPPORTED); failed(); continue; } /* we must have -c */ if (strcmp(argv[i], "-c") == 0) { if (!strip_c_option) { args_add(stripped_args, argv[i]); } found_c_opt = 1; continue; } /* -S changes the default extension */ if (strcmp(argv[i], "-S") == 0) { args_add(stripped_args, argv[i]); found_S_opt = 1; continue; } /* we need to work out where the output was meant to go */ if (strcmp(argv[i], "-o") == 0) { if (i == argc-1) { cc_log("missing argument to %s\n", argv[i]); stats_update(STATS_ARGS); failed(); } output_file = argv[i+1]; i++; continue; } /* alternate form of -o, with no space */ if (!swig) { /* some of SWIG's arguments begin with -o */ if (strncmp(argv[i], "-o", 2) == 0) { output_file = &argv[i][2]; continue; } } /* debugging is handled specially, so that we know if we can strip line number info */ if (strncmp(argv[i], "-g", 2) == 0) { args_add(stripped_args, argv[i]); if (strcmp(argv[i], "-g0") != 0) { enable_unify = 0; } continue; } /* The user knows best: just swallow the next arg */ if (strcmp(argv[i], "--ccache-skip") == 0) { i++; if (i == argc) { failed(); } args_add(stripped_args, argv[i]); continue; } /* These options require special handling, because they behave differently with gcc -E, when the output file is not specified. */ if (strcmp(argv[i], "-MD") == 0 || strcmp(argv[i], "-MMD") == 0) { generating_dependencies = 1; } else if (strcmp(argv[i], "-MF") == 0) { dependency_filename_specified = 1; } else if (strcmp(argv[i], "-MQ") == 0 || strcmp(argv[i], "-MT") == 0) { dependency_target_specified = 1; } /* the input file is already preprocessed */ if (swig && strcmp(argv[i], "-nopreprocess") == 0) { direct_i_file = 1; continue; } /* options that take an argument */ { const char *opts[] = {"-I", "-include", "-imacros", "-iprefix", "-iwithprefix", "-iwithprefixbefore", "-L", "-D", "-U", "-x", "-MF", "-MT", "-MQ", "-isystem", "-aux-info", "--param", "-A", "-Xlinker", "-u", "-idirafter", NULL}; int j; for (j=0;opts[j];j++) { if (strcmp(argv[i], opts[j]) == 0) { if (i == argc-1) { cc_log("missing argument to %s\n", argv[i]); stats_update(STATS_ARGS); failed(); } args_add(stripped_args, argv[i]); args_add(stripped_args, argv[i+1]); i++; break; } } if (opts[j]) continue; } /* other options */ if (argv[i][0] == '-') { args_add(stripped_args, argv[i]); continue; } /* if an argument isn't a plain file then assume its an option, not an input file. This allows us to cope better with unusual compiler options */ if (stat(argv[i], &st) != 0 || !S_ISREG(st.st_mode)) { args_add(stripped_args, argv[i]); continue; } if (input_file) { if (check_extension(argv[i], NULL)) { cc_log("multiple input files (%s and %s)\n", input_file, argv[i]); stats_update(STATS_MULTIPLE); } else if (!found_c_opt) { cc_log("called for link with %s\n", argv[i]); if (strstr(argv[i], "conftest.")) { stats_update(STATS_CONFTEST); } else { stats_update(STATS_LINK); } } else { cc_log("non C/C++ file %s\n", argv[i]); stats_update(STATS_NOTC); } failed(); } input_file = argv[i]; } if (!input_file) { cc_log("No input file found\n"); stats_update(STATS_NOINPUT); failed(); } if (swig) { i_extension = check_extension(input_file, NULL); } else { i_extension = check_extension(input_file, &direct_i_file); } if (i_extension == NULL) { cc_log("Not a C/C++ file - %s\n", input_file); stats_update(STATS_NOTC); failed(); } if (!found_c_opt) { cc_log("No -c option found for %s\n", input_file); /* I find that having a separate statistic for autoconf tests is useful, as they are the dominant form of "called for link" in many cases */ if (strstr(input_file, "conftest.")) { stats_update(STATS_CONFTEST); } else { stats_update(STATS_LINK); } failed(); } /* don't try to second guess the compilers heuristics for stdout handling */ if (output_file && strcmp(output_file, "-") == 0) { stats_update(STATS_OUTSTDOUT); failed(); } if (!swig && !output_file) { char *p; output_file = x_strdup(input_file); if ((p = strrchr(output_file, '/'))) { output_file = p+1; } p = strrchr(output_file, '.'); if (!p || !p[1]) { cc_log("badly formed output_file %s\n", output_file); stats_update(STATS_ARGS); failed(); } p[1] = found_S_opt ? 's' : 'o'; p[2] = 0; } /* If dependencies are generated, configure the preprocessor */ if (generating_dependencies && output_file) { if (!dependency_filename_specified) { char *default_depfile_name = x_strdup(output_file); char *p = strrchr(default_depfile_name, '.'); if (p) { if (strlen(p) < 2) { cc_log("badly formed dependency file %s\n", output_file); stats_update(STATS_ARGS); failed(); return; } *p = 0; } else { int len = p - default_depfile_name; p = x_malloc(len + 3); strncpy(default_depfile_name, p, len - 1); free(default_depfile_name); default_depfile_name = p; } strcat(default_depfile_name, ".d"); args_add(stripped_args, "-MF"); args_add(stripped_args, default_depfile_name); } if (!dependency_target_specified) { args_add(stripped_args, "-MT"); args_add(stripped_args, output_file); } } /* cope with -o /dev/null */ if (output_file && strcmp(output_file,"/dev/null") != 0 && stat(output_file, &st) == 0 && !S_ISREG(st.st_mode)) { cc_log("Not a regular file %s\n", output_file); stats_update(STATS_DEVICE); failed(); } if ((e=getenv("CCACHE_PREFIX"))) { char *p = find_executable(e, MYNAME); if (!p) { cc_log("could not find executable (%s)\n", e); stats_update(STATS_ENVIRONMMENT); perror(e); exit(1); } args_add_prefix(stripped_args, p); } }
int main(int argc, char **argv) { char c; struct work_queue *q; int port = WORK_QUEUE_DEFAULT_PORT; extra_files_list = list_create(); while((c = getopt(argc, argv, "e:f:t:x:y:p:N:E:d:vh")) != (char) -1) { switch (c) { case 'e': extra_arguments = optarg; break; case 'f': list_push_head(extra_files_list,optarg); break; case 't': compare_program_time = atof(optarg); break; case 'x': xblock = atoi(optarg); break; case 'y': yblock = atoi(optarg); break; case 'p': port = atoi(optarg); break; case 'N': setenv("WORK_QUEUE_NAME", optarg, 1); break; case 'E': setenv("WORK_QUEUE_PRIORITY", optarg, 1); break; case 'd': debug_flags_set(optarg); break; case 'v': show_version(progname); exit(0); break; case 'h': show_help(progname); exit(0); break; default: show_help(progname); return 1; } } if((argc - optind) < 3) { show_help(progname); exit(1); } struct text_list *seta = text_list_load(argv[optind]); if(!seta) { fprintf(stderr,"%s: couldn't open %s: %s\n",progname,argv[optind+1],strerror(errno)); return 1; } fprintf(stderr, "%s: %s has %d elements\n",progname,argv[optind],text_list_size(seta)); struct text_list *setb = text_list_load(argv[optind+1]); if(!setb) { fprintf(stderr,"%s: couldn't open %s: %s\n",progname,argv[optind+1],strerror(errno)); return 1; } fprintf(stderr, "%s: %s has %d elements\n",progname,argv[optind+1],text_list_size(setb)); if (!find_executable("allpairs_multicore","PATH",allpairs_multicore_program,sizeof(allpairs_multicore_program))) { fprintf(stderr,"%s: couldn't find allpairs_multicore in path\n",progname); return 1; } debug(D_DEBUG,"using multicore executable %s",allpairs_multicore_program); xstop = text_list_size(seta); ystop = text_list_size(setb); if(allpairs_compare_function_get(argv[optind+2])) { strcpy(allpairs_compare_program,argv[optind+2]); debug(D_DEBUG,"using internal function %s",allpairs_compare_program); use_external_program = 0; } else { if(!find_executable(argv[optind+2],"PATH",allpairs_compare_program,sizeof(allpairs_compare_program))) { fprintf(stderr,"%s: %s is neither an executable nor an internal comparison function.\n",progname,allpairs_compare_program); return 1; } debug(D_DEBUG,"using comparison executable %s",allpairs_compare_program); use_external_program = 1; } if(!xblock || !yblock) { estimate_block_size(seta,setb,&xblock,&yblock); } fprintf(stderr, "%s: using block size of %dx%d\n",progname,xblock,yblock); q = work_queue_create(port); if(!q) { fprintf(stderr,"%s: could not create work queue on port %d: %s\n",progname,port,strerror(errno)); return 1; } fprintf(stderr, "%s: listening for workers on port %d...\n",progname,work_queue_port(q)); while(1) { struct work_queue_task *task = NULL; while(work_queue_hungry(q)) { task = ap_task_create(seta,setb); if(task) { work_queue_submit(q, task); } else { break; } } if(!task && work_queue_empty(q)) break; task = work_queue_wait(q,5); if(task) task_complete(task); } work_queue_delete(q); return 0; }
bool hash_command_output(struct mdfour *hash, const char *command, const char *compiler) { #ifdef _WIN32 SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; HANDLE pipe_out[2]; PROCESS_INFORMATION pi; STARTUPINFO si; DWORD exitcode; bool cmd = false; char *sh = NULL; char *win32args; char *path; BOOL ret; bool ok; int fd; #else pid_t pid; int pipefd[2]; #endif #ifdef _WIN32 /* trim leading space */ while (isspace(*command)) { command++; } /* add "echo" command */ if (str_startswith(command, "echo")) { command = format("cmd.exe /c \"%s\"", command); cmd = true; } else if (str_startswith(command, "%compiler%") && str_eq(compiler, "echo")) { command = format("cmd.exe /c \"%s%s\"", compiler, command + 10); cmd = true; } else { command = x_strdup(command); } #endif struct args *args = args_init_from_string(command); int i; for (i = 0; i < args->argc; i++) { if (str_eq(args->argv[i], "%compiler%")) { args_set(args, i, compiler); } } cc_log_argv("Executing compiler check command ", args->argv); #ifdef _WIN32 memset(&pi, 0x00, sizeof(pi)); memset(&si, 0x00, sizeof(si)); path = find_executable(args->argv[0], NULL); if (!path) { path = args->argv[0]; } sh = win32getshell(path); if (sh) { path = sh; } si.cb = sizeof(STARTUPINFO); CreatePipe(&pipe_out[0], &pipe_out[1], &sa, 0); SetHandleInformation(pipe_out[0], HANDLE_FLAG_INHERIT, 0); si.hStdOutput = pipe_out[1]; si.hStdError = pipe_out[1]; si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.dwFlags = STARTF_USESTDHANDLES; if (!cmd) { win32args = win32argvtos(sh, args->argv); } else { win32args = (char *) command; /* quoted */ } ret = CreateProcess(path, win32args, NULL, NULL, 1, 0, NULL, NULL, &si, &pi); CloseHandle(pipe_out[1]); args_free(args); free(win32args); if (cmd) { free((char *) command); /* original argument was replaced above */ } if (ret == 0) { stats_update(STATS_COMPCHECK); return false; } fd = _open_osfhandle((intptr_t) pipe_out[0], O_BINARY); ok = hash_fd(hash, fd); if (!ok) { cc_log("Error hashing compiler check command output: %s", strerror(errno)); stats_update(STATS_COMPCHECK); } WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &exitcode); CloseHandle(pipe_out[0]); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if (exitcode != 0) { cc_log("Compiler check command returned %d", (int) exitcode); stats_update(STATS_COMPCHECK); return false; } return ok; #else if (pipe(pipefd) == -1) { fatal("pipe failed"); } pid = fork(); if (pid == -1) { fatal("fork failed"); } if (pid == 0) { /* Child. */ close(pipefd[0]); close(0); dup2(pipefd[1], 1); dup2(pipefd[1], 2); _exit(execvp(args->argv[0], args->argv)); return false; /* Never reached. */ } else { /* Parent. */ int status; bool ok; args_free(args); close(pipefd[1]); ok = hash_fd(hash, pipefd[0]); if (!ok) { cc_log("Error hashing compiler check command output: %s", strerror(errno)); stats_update(STATS_COMPCHECK); } close(pipefd[0]); if (waitpid(pid, &status, 0) != pid) { cc_log("waitpid failed"); return false; } if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { cc_log("Compiler check command returned %d", WEXITSTATUS(status)); stats_update(STATS_COMPCHECK); return false; } return ok; } #endif }
int main(int argc, char** args) { int c; int rtn; int help_flag = 0; bl* opts; char* me; augment_xylist_t theargs; augment_xylist_t* axy = &theargs; me = find_executable(args[0], NULL); opts = bl_new(4, sizeof(an_option_t)); augment_xylist_add_options(opts); augment_xylist_init(axy); while (1) { c = opts_getopt(opts, argc, args); if (c == -1) break; switch (c) { case 0: fprintf(stderr, "Unknown option '-%c'\n", optopt); exit(-1); case '?': break; case 'h': help_flag = 1; break; default: if (augment_xylist_parse_option(c, optarg, axy)) { exit(-1); } break; } } rtn = 0; if (optind != argc) { int i; printf("Unknown arguments:\n "); for (i=optind; i<argc; i++) { printf("%s ", args[i]); } printf("\n"); help_flag = 1; rtn = -1; } if (!axy->axyfn) { printf("Output filename (-o / --out) is required.\n"); help_flag = 1; rtn = -1; } if (!(axy->imagefn || axy->xylsfn)) { printf("Require either an image (-i / --image) or an XYlist (-x / --xylist) input file.\n"); help_flag = 1; rtn = -1; } if (help_flag) { print_help(args[0], opts); exit(rtn); } bl_free(opts); rtn = augment_xylist(axy, me); augment_xylist_free_contents(axy); return rtn; }
int main(int argc, char** args) { char* default_configfn = "astrometry.cfg"; char* default_config_path = "../etc"; int c; char* configfn = NULL; int i; engine_t* engine; char* mydir = NULL; char* basedir = NULL; char* me; anbool help = FALSE; sl* strings = sl_new(4); char* cancelfn = NULL; char* solvedfn = NULL; int loglvl = LOG_MSG; anbool tostderr = FALSE; char* infn = NULL; FILE* fin = NULL; anbool fromstdin = FALSE; bl* opts = opts_from_array(myopts, sizeof(myopts)/sizeof(an_option_t), NULL); sl* inds = sl_new(4); char* datalog = NULL; engine = engine_new(); while (1) { c = opts_getopt(opts, argc, args); if (c == -1) break; switch (c) { case 'D': datalog = optarg; break; case 'p': engine->inparallel = TRUE; break; case 'i': sl_append(inds, optarg); break; case 'd': basedir = optarg; break; case 'f': infn = optarg; fromstdin = streq(infn, "-"); break; case 'E': tostderr = TRUE; break; case 'h': help = TRUE; break; case 'v': loglvl++; break; case 's': solvedfn = optarg; case 'C': cancelfn = optarg; break; case 'c': configfn = strdup(optarg); break; case '?': break; default: printf("Unknown flag %c\n", c); exit( -1); } } if (optind == argc && !infn) { // Need extra args: filename printf("You must specify at least one input file!\n\n"); help = TRUE; } if (help) { print_help(args[0], opts); exit(0); } bl_free(opts); gslutils_use_error_system(); log_init(loglvl); if (tostderr) log_to(stderr); if (datalog) { datalogfid = fopen(datalog, "wb"); if (!datalogfid) { SYSERROR("Failed to open data log file \"%s\" for writing", datalog); return -1; } atexit(close_datalogfid); data_log_init(100); data_log_enable_all(); data_log_to(datalogfid); data_log_start(); } if (infn) { logverb("Reading input filenames from %s\n", (fromstdin ? "stdin" : infn)); if (!fromstdin) { fin = fopen(infn, "rb"); if (!fin) { ERROR("Failed to open file %s for reading input filenames", infn); exit(-1); } } else fin = stdin; } // directory containing the 'engine' executable: me = find_executable(args[0], NULL); if (!me) me = strdup(args[0]); mydir = sl_append(strings, dirname(me)); free(me); // Read config file if (!configfn) { int i; sl* trycf = sl_new(4); sl_appendf(trycf, "%s/%s/%s", mydir, default_config_path, default_configfn); // if I'm in /usr/bin, look for config file in /etc if (streq(mydir, "/usr/bin")) { sl_appendf(trycf, "/etc/%s", default_configfn); } sl_appendf(trycf, "%s/%s", mydir, default_configfn); sl_appendf(trycf, "./%s", default_configfn); sl_appendf(trycf, "./%s/%s", default_config_path, default_configfn); for (i=0; i<sl_size(trycf); i++) { char* cf = sl_get(trycf, i); if (file_exists(cf)) { configfn = strdup(cf); logverb("Using config file \"%s\"\n", cf); break; } else { logverb("Config file \"%s\" doesn't exist.\n", cf); } } if (!configfn) { char* cflist = sl_join(trycf, "\n "); logerr("Couldn't find config file: tried:\n %s\n", cflist); free(cflist); } sl_free2(trycf); } if (!streq(configfn, "none")) { if (engine_parse_config_file(engine, configfn)) { logerr("Failed to parse (or encountered an error while interpreting) config file \"%s\"\n", configfn); exit( -1); } } if (sl_size(inds)) { // Expand globs. for (i=0; i<sl_size(inds); i++) { char* s = sl_get(inds, i); glob_t myglob; int flags = GLOB_TILDE | GLOB_BRACE; if (glob(s, flags, NULL, &myglob)) { SYSERROR("Failed to expand wildcards in index-file path \"%s\"", s); exit(-1); } for (c=0; c<myglob.gl_pathc; c++) { if (engine_add_index(engine, myglob.gl_pathv[c])) { ERROR("Failed to add index \"%s\"", myglob.gl_pathv[c]); exit(-1); } } globfree(&myglob); } } if (!pl_size(engine->indexes)) { logerr("\n\n" "---------------------------------------------------------------------\n" "You must list at least one index in the config file (%s)\n\n" "See http://astrometry.net/use.html about how to get some index files.\n" "---------------------------------------------------------------------\n" "\n", configfn); exit(-1); } if (engine->minwidth <= 0.0 || engine->maxwidth <= 0.0) { logerr("\"minwidth\" and \"maxwidth\" in the config file %s must be positive!\n", configfn); exit(-1); } free(configfn); if (!il_size(engine->default_depths)) { parse_depth_string(engine->default_depths, "10 20 30 40 50 60 70 80 90 100 " "110 120 130 140 150 160 170 180 190 200"); } engine->cancelfn = cancelfn; engine->solvedfn = solvedfn; i = optind; while (1) { char* jobfn; job_t* job; struct timeval tv1, tv2; if (infn) { // Read name of next input file to be read. logverb("\nWaiting for next input filename...\n"); jobfn = read_string_terminated(fin, "\n\r\0", 3, FALSE); if (strlen(jobfn) == 0) break; } else { if (i == argc) break; jobfn = args[i]; i++; } gettimeofday(&tv1, NULL); logmsg("Reading file \"%s\"...\n", jobfn); job = engine_read_job_file(engine, jobfn); if (!job) { ERROR("Failed to read job file \"%s\"", jobfn); exit(-1); } if (basedir) { logverb("Setting job's output base directory to %s\n", basedir); job_set_output_base_dir(job, basedir); } if (engine_run_job(engine, job)) logerr("Failed to run_job()\n"); job_free(job); gettimeofday(&tv2, NULL); logverb("Spent %g seconds on this field.\n", millis_between(&tv1, &tv2)/1000.0); } engine_free(engine); sl_free2(strings); sl_free2(inds); if (fin && !fromstdin) fclose(fin); return 0; }
PidType CubitProcess::start(const std::string& app, const std::vector<std::string>& args, bool hide) { #ifndef WIN32 std::vector<const char*> c_args(args.size()+2); int idx = 0; c_args[idx++] = app.c_str(); for(unsigned int i=0; i<args.size(); i++) { c_args[idx++] = args[i].c_str(); } c_args[idx++] = NULL; std::string app_real = find_executable(app); // temporarily block delivery of child signals // TODO: does this overwrite currently set signals for the process? sigset_t newsig; sigemptyset(&newsig); sigaddset(&newsig, SIGCHLD); sigprocmask(SIG_BLOCK, &newsig, &oldsig); pid_t pid = fork(); if(pid < 0) return 0; if(pid == 0) { execv(app_real.c_str(), const_cast<char**>(&c_args[0])); perror(app_real.c_str()); exit(EXIT_FAILURE); } return pid; #else STARTUPINFOW si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // hide child window if(hide) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; } std::string real_app = find_executable(app); std::replace(real_app.begin(), real_app.end(), '/', '\\'); std::string q_string = quote_string(app); std::wstring call = CubitString::toUtf16(q_string); std::string joined_args = join_args(args); call += L" "; call += CubitString::toUtf16(joined_args).c_str(); // Start the child process. if( CreateProcessW( CubitString::toUtf16(real_app).c_str(), // path to cubit executable const_cast<wchar_t*>(call.c_str()), // Command line. NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. TRUE, // Set handle inheritance to TRUE. 0, // No creation flags. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi ) // Pointer to PROCESS_INFORMATION structure. ) { return pi; } pi.hProcess = 0; return pi; #endif }