/* * This function finds the pathname to a block device with a given * device number. It returns a pointer to allocated memory to the * pathname on success, and NULL on failure. */ char *ext2fs_find_block_device(dev_t device) { struct dir_list *list = 0, *new_list = 0; struct dir_list *current; char *ret_path = 0; /* * Add the starting directories to search... */ add_to_dirlist("/devices", &list); add_to_dirlist("/devfs", &list); add_to_dirlist("/dev", &list); while (list) { current = list; list = list->next; #ifdef DEBUG printf("Scanning directory %s\n", current->name); #endif scan_dir(current->name, device, &new_list, &ret_path); free(current->name); free(current); if (ret_path) break; /* * If we're done checking at this level, descend to * the next level of subdirectories. (breadth-first) */ if (list == 0) { list = new_list; new_list = 0; } } free_dirlist(&list); free_dirlist(&new_list); return ret_path; }
void scan_dir( const char* dir, int recursive, time_t start_time, YR_RULES* rules, YR_CALLBACK_FUNC callback) { static char path_and_mask[MAX_PATH]; snprintf(path_and_mask, sizeof(path_and_mask), "%s\\*", dir); WIN32_FIND_DATA FindFileData; HANDLE hFind = FindFirstFile(path_and_mask, &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { do { char full_path[MAX_PATH]; snprintf(full_path, sizeof(full_path), "%s\\%s", dir, FindFileData.cFileName); if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { file_queue_put(full_path); } else if (recursive && FindFileData.cFileName[0] != '.' ) { scan_dir(full_path, recursive, start_time, rules, callback); } } while (FindNextFile(hFind, &FindFileData)); FindClose(hFind); } }
Directory::Directory(const ACE_TString& dirname, const ACE_TString& logical, Directory* parent) : parent_(parent, false) , physical_dirname_(dirname) , logical_dirname_(logical) { add_slash(physical_dirname_); bool ok(true); DDS_Dirent dir; if (dir.open(physical_dirname_.c_str()) == -1) { ok = false; if (errno == ENOENT && dds_mkdir(physical_dirname_.c_str()) != -1 && dir.open(physical_dirname_.c_str()) != -1) { ok = true; } } if (!ok) throw std::runtime_error("Can't open or create directory"); scan_dir(ACE_TEXT(""), dir, 0); }
static int do_loop(void) { path_t src_name; path_t exe_name; path_t src_path; path_t exe_path; path_t log_path; path_t exe_out; path_t log_out; path_t txt_out; path_t report_dir, status_dir; path_t pkt_name, run_name, work_run_name; char *pkt_ptr; size_t pkt_len; int r, i; tpTask tsk = 0; unsigned char msgbuf[512]; int ce_flag; struct compile_request_packet *req = 0; struct compile_reply_packet rpl; void *rpl_pkt = 0; size_t rpl_size = 0; const unsigned char *tail_message = 0; #if HAVE_TRUNCATE - 0 struct stat stb; #endif /* HAVE_TRUNCATE */ FILE *log_f = 0; struct section_language_data *lang = 0; const struct section_global_data *global = serve_state.global; // if (cr_serialize_init(&serve_state) < 0) return -1; interrupt_init(); interrupt_disable(); while (1) { // terminate if signaled if (interrupt_get_status() || interrupt_restart_requested()) break; r = scan_dir(global->compile_queue_dir, pkt_name, sizeof(pkt_name)); if (r < 0) { switch (-r) { case ENOMEM: case ENOENT: case ENFILE: err("trying to recover, sleep for 5 seconds"); interrupt_enable(); os_Sleep(5000); interrupt_disable(); continue; default: err("unrecoverable error, exiting"); return -1; } } if (!r) { interrupt_enable(); os_Sleep(global->sleep_time); interrupt_disable(); continue; } pkt_ptr = 0; pkt_len = 0; r = generic_read_file(&pkt_ptr, 0, &pkt_len, SAFE | REMOVE, global->compile_queue_dir, pkt_name, ""); if (r == 0) continue; if (r < 0 || !pkt_ptr) { // it looks like there's no reasonable recovery strategy // so, just ignore the error continue; } r = compile_request_packet_read(pkt_len, pkt_ptr, &req); xfree(pkt_ptr); pkt_ptr = 0; if (r < 0) { /* * the incoming packet is completely broken, so just drop it */ goto cleanup_and_continue; } if (!req->contest_id) { // special packets r = req->lang_id; req = compile_request_packet_free(req); switch (r) { case 1: interrupt_flag_interrupt(); break; case 2: interrupt_flag_sighup(); break; } continue; } memset(&rpl, 0, sizeof(rpl)); rpl.judge_id = req->judge_id; rpl.contest_id = req->contest_id; rpl.run_id = req->run_id; rpl.ts1 = req->ts1; rpl.ts1_us = req->ts1_us; rpl.use_uuid = req->use_uuid; rpl.uuid[0] = req->uuid[0]; rpl.uuid[1] = req->uuid[1]; rpl.uuid[2] = req->uuid[2]; rpl.uuid[3] = req->uuid[3]; get_current_time(&rpl.ts2, &rpl.ts2_us); rpl.run_block_len = req->run_block_len; rpl.run_block = req->run_block; /* !!! shares memory with req */ msgbuf[0] = 0; /* prepare paths useful to report messages to the serve */ snprintf(report_dir, sizeof(report_dir), "%s/%06d/report", global->compile_dir, rpl.contest_id); snprintf(status_dir, sizeof(status_dir), "%s/%06d/status", global->compile_dir, rpl.contest_id); if (req->use_uuid > 0) { snprintf(run_name, sizeof(run_name), "%s", ej_uuid_unparse(req->uuid, NULL)); } else { snprintf(run_name, sizeof(run_name), "%06d", rpl.run_id); } snprintf(work_run_name, sizeof(work_run_name), "%06d", rpl.run_id); pathmake(log_out, report_dir, "/", run_name, NULL); snprintf(txt_out, sizeof(txt_out), "%s/%s.txt", report_dir, run_name); make_all_dir(status_dir, 0777); make_dir(report_dir, 0777); if (!r) { /* * there is something wrong, but we have contest_id, judge_id * and run_id in place, so we can report an error back * to serve */ snprintf(msgbuf, sizeof(msgbuf), "invalid compile packet\n"); goto report_internal_error; } if (req->style_check_only && req->style_checker && req->style_checker[0]) { check_style_only(global, req, &rpl, pkt_name, run_name, work_run_name, report_dir, status_dir); req = 0; continue; } if (req->lang_id <= 0 || req->lang_id > serve_state.max_lang || !(lang = serve_state.langs[req->lang_id])) { snprintf(msgbuf, sizeof(msgbuf), "invalid lang_id %d\n", req->lang_id); goto report_internal_error; } pathmake(src_name, work_run_name, lang->src_sfx, NULL); pathmake(exe_name, work_run_name, lang->exe_sfx, NULL); pathmake(src_path, global->compile_work_dir, "/", src_name, NULL); pathmake(exe_path, global->compile_work_dir, "/", exe_name, NULL); pathmake(log_path, global->compile_work_dir, "/", "log", NULL); /* the resulting executable file */ snprintf(exe_out, sizeof(exe_out), "%s/%s%s", report_dir, run_name, lang->exe_sfx); /* move the source file into the working dir */ r = generic_copy_file(REMOVE, global->compile_src_dir, pkt_name, lang->src_sfx, 0, global->compile_work_dir, src_name, ""); if (!r) { snprintf(msgbuf, sizeof(msgbuf), "the source file is missing\n"); err("the source file is missing"); goto report_internal_error; } if (r < 0) { snprintf(msgbuf, sizeof(msgbuf), "error reading the source file\n"); err("cannot read the source file"); goto report_internal_error; } tail_message = 0; ce_flag = 0; if (req->output_only) { // copy src_path -> exe_path generic_copy_file(0, NULL, src_path, NULL, 0, NULL, exe_path, NULL); ce_flag = 0; rpl.status = RUN_OK; } else { if (req->style_checker) { /* run style checker */ //info("Starting: %s %s", req->style_checker, src_path); tsk = task_New(); task_AddArg(tsk, req->style_checker); task_AddArg(tsk, src_path); task_SetPathAsArg0(tsk); task_SetWorkingDir(tsk, global->compile_work_dir); task_EnableProcessGroup(tsk); task_SetRedir(tsk, 0, TSR_FILE, "/dev/null", TSK_READ); task_SetRedir(tsk, 1, TSR_FILE, log_path, TSK_REWRITE, 0777); task_SetRedir(tsk, 2, TSR_DUP, 1); if (req->sc_env_num > 0) { for (i = 0; i < req->sc_env_num; i++) task_PutEnv(tsk, req->sc_env_vars[i]); } if (lang->compile_real_time_limit > 0) { task_SetMaxRealTime(tsk, lang->compile_real_time_limit); } task_EnableAllSignals(tsk); task_PrintArgs(tsk); if (task_Start(tsk) < 0) { err("Failed to start style checker process"); tail_message = "\n\nFailed to start style checker"; ce_flag = 1; rpl.status = RUN_STYLE_ERR; } else { task_Wait(tsk); if (task_IsTimeout(tsk)) { err("Style checker process timed out"); tail_message = "\n\nStyle checker process timed out"; ce_flag = 1; rpl.status = RUN_STYLE_ERR; } else if (task_IsAbnormal(tsk)) { info("Style checker failed"); ce_flag = 1; rpl.status = RUN_STYLE_ERR; } else { info("Style checker sucessful"); ce_flag = 0; rpl.status = RUN_OK; } } task_Delete(tsk); tsk = 0; } if (!ce_flag) { //info("Starting: %s %s %s", lang->cmd, src_name, exe_name); tsk = task_New(); task_AddArg(tsk, lang->cmd); task_AddArg(tsk, src_name); task_AddArg(tsk, exe_name); task_SetPathAsArg0(tsk); task_EnableProcessGroup(tsk); if (((ssize_t) req->max_vm_size) > 0) { task_SetVMSize(tsk, req->max_vm_size); } else if (((ssize_t) lang->max_vm_size) > 0) { task_SetVMSize(tsk, lang->max_vm_size); } else if (((ssize_t) global->compile_max_vm_size) > 0) { task_SetVMSize(tsk, global->compile_max_vm_size); } if (((ssize_t) req->max_stack_size) > 0) { task_SetStackSize(tsk, req->max_stack_size); } else if (((ssize_t) lang->max_stack_size) > 0) { task_SetStackSize(tsk, lang->max_stack_size); } else if (((ssize_t) global->compile_max_stack_size) > 0) { task_SetStackSize(tsk, global->compile_max_stack_size); } if (((ssize_t) req->max_file_size) > 0) { task_SetMaxFileSize(tsk, req->max_file_size); } else if (((ssize_t) lang->max_file_size) > 0) { task_SetMaxFileSize(tsk, lang->max_file_size); } else if (((ssize_t) global->compile_max_file_size) > 0) { task_SetMaxFileSize(tsk, global->compile_max_file_size); } if (req->env_num > 0) { for (i = 0; i < req->env_num; i++) task_PutEnv(tsk, req->env_vars[i]); } task_SetWorkingDir(tsk, global->compile_work_dir); task_SetRedir(tsk, 0, TSR_FILE, "/dev/null", TSK_READ); task_SetRedir(tsk, 1, TSR_FILE, log_path, TSK_APPEND, 0777); task_SetRedir(tsk, 2, TSR_DUP, 1); if (lang->compile_real_time_limit > 0) { task_SetMaxRealTime(tsk, lang->compile_real_time_limit); } task_EnableAllSignals(tsk); /* if (cr_serialize_lock(&serve_state) < 0) { // FIXME: propose reasonable recovery? return -1; } */ task_PrintArgs(tsk); task_Start(tsk); task_Wait(tsk); /* if (cr_serialize_unlock(&serve_state) < 0) { // FIXME: propose reasonable recovery? return -1; } */ if (task_IsTimeout(tsk)) { err("Compilation process timed out"); tail_message = "\n\nCompilation process timed out"; ce_flag = 1; rpl.status = RUN_COMPILE_ERR; } else if (task_IsAbnormal(tsk)) { info("Compilation failed"); ce_flag = 1; rpl.status = RUN_COMPILE_ERR; } else { info("Compilation sucessful"); ce_flag = 0; rpl.status = RUN_OK; } } } get_current_time(&rpl.ts3, &rpl.ts3_us); if (compile_reply_packet_write(&rpl, &rpl_size, &rpl_pkt) < 0) goto cleanup_and_continue; while (1) { if (ce_flag) { #if HAVE_TRUNCATE - 0 // truncate log file at size 1MB if (stat(log_path, &stb) >= 0 && stb.st_size > MAX_LOG_SIZE) { truncate(log_path, MAX_LOG_SIZE); if ((log_f = fopen(log_path, "a"))) { fprintf(log_f, "\n\nCompilation log is truncated by ejudge!\n"); fclose(log_f); log_f = 0; } } #endif // append tail_message if (tail_message && (log_f = fopen(log_path, "a"))) { fprintf(log_f, "%s\n", tail_message); fclose(log_f); log_f = 0; } r = generic_copy_file(0, 0, log_path, "", 0, 0, log_out, ""); } else { r = generic_copy_file(0, 0, exe_path, "", 0, 0, exe_out, ""); generic_copy_file(0, 0, log_path, "", 0, 0, txt_out, ""); } if (r >= 0 && generic_write_file(rpl_pkt, rpl_size, SAFE, status_dir, run_name, "") >= 0) break; info("waiting 5 seconds hoping for things to change"); interrupt_enable(); os_Sleep(5000); interrupt_disable(); } goto cleanup_and_continue; report_internal_error:; rpl.status = RUN_CHECK_FAILED; get_current_time(&rpl.ts3, &rpl.ts3_us); if (compile_reply_packet_write(&rpl, &rpl_size, &rpl_pkt) < 0) goto cleanup_and_continue; if (generic_write_file(msgbuf, strlen(msgbuf), 0, 0, log_out, 0) < 0) goto cleanup_and_continue; if (generic_write_file(rpl_pkt, rpl_size, SAFE, status_dir, run_name, 0) < 0) unlink(log_out); goto cleanup_and_continue; cleanup_and_continue:; task_Delete(tsk); tsk = 0; clear_directory(global->compile_work_dir); xfree(rpl_pkt); rpl_pkt = 0; req = compile_request_packet_free(req); } /* while (1) */ return 0; }
/* * find_x_proc * ----------- * This function scans the /proc dir in order to find the X process * for the given display, knowing the X server file inode and device. */ static pid_t find_x_proc(int disp_nr, dev_t lxdev, ino_t lxino) { /*static*/ char xdisp[10]; /*static*/ char xcmd_ref[MAXPATHLEN+1]; struct stat stbuf; pid_t proc = -1; struct dirent **namelist = NULL; int curn = 0,names = 0; int lencmd ; /* These are the display string searched in X cmd running (e.g.: :1) */ /* and the searched value of the link (e.g.: "[0301]:286753") */ (void) sprintf( xdisp, ":%d", disp_nr ); (void) sprintf( xcmd_ref, "[%04x]:%ld", (int)lxdev, (long)lxino ); lencmd = strlen(xcmd_ref); if ( stat( PROCDIR, &stbuf ) == -1 ) return( (pid_t)-1 ); namelist = (struct dirent **) malloc(sizeof (struct dirent *)); if ((names = scan_dir(PROCDIR, &namelist, proc_dir_select, alphasort)) == -1 ) { free(namelist); return( (pid_t)-1 ); } while ( curn < names ) { char pname[MAXPATHLEN+1]; char buf[MAXPATHLEN+1]; (void) sprintf( pname, PROCDIR "/%s/exe", namelist[curn]->d_name ); (void) memset((char *) buf, 0, sizeof (buf)); if ( readlink( pname, buf, MAXPATHLEN ) <= 0 ) { /* This is unreadable, let's continue */ curn++; continue; } /* * If the strings are equals, we found an X process, but is it the one * managing the wanted display ? * We are going to try to know it by reading the command line used to * invoke the server. */ if ( !strncmp( buf, xcmd_ref, lencmd ) ) { char cmdlinepath[MAXPATHLEN+1]; char cmdlinebuf[1024]; /* 1k should be enough */ int cmdlinefd; off_t cmdlinesz; char *p; proc =(pid_t)atoi( namelist[curn]->d_name ); (void) sprintf( cmdlinepath, PROCDIR "/%s/cmdline", namelist[curn]->d_name ); if ( ( cmdlinefd = open( cmdlinepath, O_RDONLY ) ) == -1 ) { curn++; continue; } /* Ask the kernel what it was (actually do ps) * If stat'ed the cmdline proc file as a size of zero * No means to dynamically allocate buffer ! */ if ( ( cmdlinesz = read( cmdlinefd, cmdlinebuf, 1023 ) ) == -1) { close( cmdlinefd ); curn++; continue; } /* * The command line proc file contains all command line args * separated by NULL characters. We are going to replace all ^@ * with a space, then we'll searched for the display string * (:0, :1, ..., :N). If a match is found, then we got the good * process. If no match is found, then we can assume this is the * good process only if we are searching for the display #0 manager * (the default display). In other case the process is discarded. */ p = cmdlinebuf; while ( p < cmdlinebuf+cmdlinesz ) { if ( !*p ) *p = ' '; p++; } close( cmdlinefd ); if ( strstr( cmdlinebuf, xdisp ) ) break; else if ( !disp_nr ) break; else proc =(pid_t)-1; } curn++; } free(namelist); return proc; }
int main (int argc, char *argv[]) { scan_dir (mask_linestrips, process_linestrips); return 0; }
int wmain( int argc, wchar_t* argv[] ) { int i; if (argc == 1 || (wcscmp( argv[1], L"/?" ) == 0 || wcscmp( argv[1], L"--help" ) == 0)) { puts( "Detect It Easy Console (Library) by Jason Hood <*****@*****.**>.\n" "Version " PVERS " (" PDATE "). Freeware.\n" "\n" "Determine file type by examination of contents.\n" "\n" "diecl [-1abeEhnorv] [-d DB] FILE...\n" "\n" "-1\tsingle line output\n" "-a\tshow all files (don't ignore unscannable)\n" "-b\tadd a blank line between directories (when using -r)\n" "-d\tuse DB as the database directory\n" "-e\tshow errors\n" "-E\tshow entropy\n" "-h\tinclude hidden/system files when expanding wildcards\n" "-n\tdon't align names (within a directory, when using -1)\n" "-o\tdon't show options\n" "-r\trecurse into subdirectories (of the current directory)\n" "-v\tdon't show version\n" "\n" "A default database may be chosen with the DIE_DB environment variable." ); return 0; } if (argc > 1 && wcscmp( argv[1], L"--version" ) == 0) { printf( "diecl version " PVERS " (" PDATE "). DIE v%s.\n", DIE_versionA() ); return 0; } // Process and remove the options. db = _wgetenv( L"DIE_DB" ); for (i = 1; i < argc; ++i) { if (*argv[i] == '-') { while (*++argv[i]) { switch (*argv[i]) { case 'a': all ^= 1; break; case 'b': blank ^= 1; break; case 'h': hidden ^= FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM; break; case 'n': no_align ^= 1; break; case 'r': recurse ^= 1; break; case '1': flags ^= DIE_SINGLELINEOUTPUT|DIE_SHOWFILEFORMATONCE; break; case 'e': flags ^= DIE_SHOWERRORS; break; case 'E': flags ^= DIE_SHOWENTROPY; break; case 'o': flags ^= DIE_SHOWOPTIONS; break; case 'v': flags ^= DIE_SHOWVERSION; break; case 'd': if (argv[i][1]) { db = argv[i] + 1; argv[i] = L""; } else { db = argv[++i]; if (db) argv[i] = L""; argv[i-1] = L""; } goto next; } } } next: ; } --argc; ++argv; buf_size = 512; buf = malloc( buf_size ); scan_dir( argc, argv ); if (recurse) scan_dirs( argc, argv ); return 0; }
void ShowPlayList( void ) { plItem * next; if ( PlayList ) gtkActive( PlayList ); else PlayList=create_PlayList(); if ( old_path && *old_path ) { char * currentdir = strdup( old_path ); char * tpath,* pos; GtkCTreeNode * node,* nextnode; gboolean leaf; tpath=strdup( "/" ); pos=strtok( currentdir,"/" ); node=gtk_ctree_find_by_row_data_custom( GTK_CTREE( CTDirTree ),NULL,"/",compare_func ); do { char * tpathnew = g_strconcat( tpath,pos,"/",NULL ); free( tpath ); tpath=tpathnew; nextnode=gtk_ctree_find_by_row_data_custom( GTK_CTREE( CTDirTree ),node,tpath,compare_func ); if ( !nextnode ) break; node=nextnode; pos=strtok( NULL,"/" ); gtk_ctree_get_node_info( GTK_CTREE( CTDirTree ),node,NULL,NULL,NULL,NULL,NULL,NULL,&leaf,NULL ); if ( !leaf && pos ) gtk_ctree_expand( GTK_CTREE( CTDirTree ),node ); else { DirNodeType * DirNode; gtk_ctree_select( GTK_CTREE( CTDirTree ),node ); DirNode=gtk_ctree_node_get_row_data( GTK_CTREE( CTDirTree ),node ); current_path=DirNode->path; scan_dir( DirNode->path ); free( CLFileSelected ); CLFileSelected=calloc( 1,NrOfEntrys * sizeof( int ) ); break; } } while( pos ); free( tpath ); free( currentdir ); } else gtk_ctree_select( GTK_CTREE( CTDirTree ),parent ); gtk_clist_freeze( GTK_CLIST( CLSelected ) ); gtk_clist_clear( GTK_CLIST( CLSelected ) ); next = listMgr( PLAYLIST_GET,0 ); if ( next ) { gchar * name, * path; while ( next || next->next ) { char * text[1][3]; text[0][2]=""; name = g_filename_to_utf8( next->name, -1, NULL, NULL, NULL ); path = g_filename_to_utf8( next->path, -1, NULL, NULL, NULL ); text[0][0]=name ? name : next->name; text[0][1]=path ? path : next->path; gtk_clist_append( GTK_CLIST( CLSelected ),text[0] ); g_free( path ); g_free( name ); NrOfSelected++; if ( next->next ) next=next->next; else break; } CLListSelected=calloc( 1,NrOfSelected * sizeof( int ) ); } gtk_clist_thaw( GTK_CLIST( CLSelected ) ); gtk_widget_show( PlayList ); }
int main(int argc, char* argv[]) { sc_context ctx = {0}; long rc, i; char *c, *a; printf("SMACDIG. Smart Card Digging Utilities. Version 0.50720 by " "Ilya O. Levin\nRaw and uncondition detection of DF/EF objects " "within smart cards\n\n"); if (argc>1) c = argv[1]; else { printf("Usage: smacdig reader [target [initial id]]\n\n" "Examples:\n\t smacdig axalto\n" "\t smacdig \"AKS ifdh\" 3f00/6666 1FFE\n" ); c=sc_listreaders(); if (c) { printf("\nAvailable readers:\n"); a = strtok(c, "\n"); while (a != NULL) { printf("* %s\n", a); a = strtok(NULL, "\n");} } else printf("Unable to list smart card readers\n"); free (c); return 0; } if (argc>2) { a = strtok(argv[2], "/\\"); while (a != NULL) { dir[idr++] = (unsigned short) strtoul(a, NULL, 16); if (idr == 255) break; a = strtok(NULL, "/\\"); } } if (idr<1) dir[idr++] = 0x3f00; if (argc>3) startid = (unsigned short) strtoul(argv[3], NULL, 16); printf("* connecting to \"%s\" - ", c); rc = sc_init(&ctx, c); if (rc == SC_OK) { printf("ok\n* Active reader: \"%s\"\n* Target: ", ctx.rdr); for (rc=0;rc<(int)idr;rc++) printf("/%04x", dir[rc]); printf("\n"); printf("* probing for commands class - "); rc = sc_selectfile(&ctx, 0x3f00); for (i=0; (rc==SC_OK)&&(ctx.sw[0]!=0x61)&&(ctx.sw[0]!=0x90)&&(i<256) ;i++) { ctx.CLA = (unsigned char) i; rc = sc_selectfile(&ctx, 0x3f00); } if ( (ctx.sw[0]!=0x61) && (ctx.sw[0]!=0x90) ) printf("failed\n"); else { printf("ok [CLA:%02x]\n* enumerating from %04x\n", ctx.CLA, startid); rc=scan_dir(&ctx); printf("* enumeration %s\n", (rc==SC_OK)?"done":"failed"); } sc_finish(&ctx); } else printf("failed (%s)\n", rc_symb(rc)); return 0; } /* main */
// Modified from http://www.zemris.fer.hr/predmeti/os1/misc/Unix2Win.htm void scan_dir(char *dirname, int countfiles) { char dir[MAX_PATH+1]; char subdir[MAX_PATH+1]; #if defined(_WIN32) char entry[MAX_PATH]; wchar_t wdir[MAX_PATH+1]; HANDLE hList; WIN32_FIND_DATAW FileData; #else char* entry; int r; DIR *dp; char cwd[MAX_PATH]; struct dirent* dir_entry; struct stat stat_info; #endif // Get the proper directory path if ( (strlen(initial_dir) + strlen(dirname) + 4) > sizeof(dir) ) { fprintf(stderr, "Path overflow.\n"); return; } sprintf(dir, "%s%c%s", initial_dir, NATIVE_SEPARATOR, dirname); // Get the first file #if defined(_WIN32) strcat(dir, "\\*"); MultiByteToWideChar(CP_UTF8, 0, dir, -1, wdir, MAX_PATH); hList = FindFirstFileW(wdir, &FileData); if (hList == INVALID_HANDLE_VALUE) return; #else dp = opendir(dir); if (dp == NULL) return; dir_entry = readdir(dp); if (dir_entry == NULL) return; #endif // Traverse through the directory structure do { // Check if the object is a directory or not #if defined(_WIN32) WideCharToMultiByte(CP_UTF8, 0, FileData.cFileName, -1, entry, MAX_PATH, NULL, NULL); if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { #else entry = dir_entry->d_name; getcwd(cwd, sizeof(cwd)); chdir(dir); r = NATIVE_STAT(entry, &stat_info); chdir(cwd); if (r != 0) { continue; } if (S_ISDIR(stat_info.st_mode)) { #endif if ( (strcmp(entry, ".") != 0) && (strcmp(entry, "..") != 0)) { // Get the full path for sub directory if ( (strlen(dirname) + strlen(entry) + 2) > sizeof(subdir) ) { fprintf(stderr, "Path overflow.\n"); return; } sprintf(subdir, "%s%c%s", dirname, NATIVE_SEPARATOR, entry); scan_dir(subdir, countfiles); } } else { if (!countfiles) { if ( (embeddable[nb_embeddables].file_name = malloc(strlen(initial_dir) + strlen(dirname) + strlen(entry) + 2) ) == NULL) { return; } if ( (embeddable[nb_embeddables].extraction_subdir = malloc(strlen(dirname)) ) == NULL) { return; } sprintf(embeddable[nb_embeddables].file_name, "%s%s%c%s", initial_dir, dirname, NATIVE_SEPARATOR, entry); if (dirname[0] == NATIVE_SEPARATOR) { sprintf(embeddable[nb_embeddables].extraction_subdir, "%s", dirname+1); } else { safe_free(embeddable[nb_embeddables].extraction_subdir); embeddable[nb_embeddables].extraction_subdir = NATIVE_STRDUP("."); } } nb_embeddables++; } } #if defined(_WIN32) while ( FindNextFileW(hList, &FileData) || (GetLastError() != ERROR_NO_MORE_FILES) ); FindClose(hList); #else while ((dir_entry = readdir(dp)) != NULL); closedir(dp); #endif } void add_user_files(void) { int i; get_full_path(USER_DIR, initial_dir, sizeof(initial_dir)); // Dry run to count additional files scan_dir("", -1); if (nb_embeddables == nb_embeddables_fixed) { fprintf(stderr, "No user embeddable files found.\n"); fprintf(stderr, "Note that the USER_DIR path must be provided in Windows format\n"); fprintf(stderr, "(eg: 'C:\\signed-driver').if compiling from a Windows platform.\n"); return; } // Extend the array to add the user files embeddable = calloc(nb_embeddables, sizeof(struct emb)); if (embeddable == NULL) { fprintf(stderr, "Could not include user embeddable files.\n"); return; } // Copy the fixed part of our table into our new array for (i=0; i<nb_embeddables_fixed; i++) { embeddable[i].reuse_last = 0; embeddable[i].file_name = embeddable_fixed[i].file_name; embeddable[i].extraction_subdir = embeddable_fixed[i].extraction_subdir; } nb_embeddables = nb_embeddables_fixed; // Fill in the array scan_dir("", 0); }
void Directory::scan_dir(const ACE_TString& relative, DDS_Dirent& dir, unsigned int overflow_index) { ACE_TString path = physical_dirname_ + relative; add_slash(path); while (DDS_DIRENT* ent = dir.read()) { if (ent->d_name[0] == ACE_TEXT('.') && (!ent->d_name[1] || (ent->d_name[1] == ACE_TEXT('.') && !ent->d_name[2]))) { continue; // skip '.' and '..' } ACE_TString file = path + ent->d_name; if (is_dir(file.c_str())) { ACE_TString phys(relative); add_slash(phys); phys += ent->d_name; if (ACE_OS::strncmp(ent->d_name, ACE_TEXT("_overflow."), 10) == 0) { unsigned int n = ACE_OS::atoi(ent->d_name + 10); DDS_Dirent overflow(file.c_str()); scan_dir(ent->d_name, overflow, n); } else if (ACE_OS::strlen(ent->d_name) <= FSS_MAX_FILE_NAME_ENCODED) { dirs_[b32h_decode(ent->d_name)] = phys; ++overflow_[overflow_index]; } else { CwdGuard cg(file); std::ifstream fn("_fullname"); std::string fullname; if (!std::getline(fn, fullname)) { throw std::runtime_error("Can't read .../_fullname"); } ACE_TString full_t(ACE_TEXT_CHAR_TO_TCHAR(fullname.c_str())); dirs_[full_t] = phys; ++overflow_[overflow_index]; String_Index_t idx = phys.rfind(ACE_TEXT('.')); if (idx == ACE_TString::npos) { throw std::runtime_error("Badly formatted long dir name"); } ACE_TString prefix(phys.c_str(), idx); unsigned int serial = ACE_OS::atoi(&phys[idx + 1]); unsigned int& counter = long_names_[prefix]; if (serial >= counter) counter = serial + 1; } } else { // regular file if (ent->d_name[0] != ACE_TEXT('_')) { files_[b32h_decode(ent->d_name)] = ent->d_name; ++overflow_[overflow_index]; } } } }
static int callback_lws_table_dirlisting(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { struct per_session_data__tbl_dir *pss = (struct per_session_data__tbl_dir *)user; char j[LWS_PRE + 16384], *p = j + LWS_PRE, *start = p, *q, *q1, *w, *end = j + sizeof(j) - LWS_PRE, e[384], s[384], s1[384]; const struct lws_protocol_vhost_options *pmo; struct fobj *f; int n, first = 1; switch (reason) { case LWS_CALLBACK_PROTOCOL_INIT: /* per vhost */ break; case LWS_CALLBACK_ESTABLISHED: lwsl_debug("LWS_CALLBACK_ESTABLISHED\n"); /* * send client the lwsgt table layout */ start = "{\"cols\":[" " {\"name\": \"Date\"}," " {\"name\": \"Size\", \"align\": \"right\"}," " {\"name\": \"Icon\"}," " {\"name\": \"Name\", \"href\": \"uri\"}," " {\"name\": \"uri\", \"hide\": \"1\" }" " ]" "}"; if (lws_write(wsi, (unsigned char *)start, strlen(start), LWS_WRITE_TEXT) < 0) return -1; /* send a view update next */ lws_callback_on_writable(wsi); break; case LWS_CALLBACK_RECEIVE: if (len > sizeof(pss->reldir) - 1) len = sizeof(pss->reldir) - 1; if (!strstr(in, "..") && !strchr(in, '~')) strncpy(pss->reldir, in, len); else len = 0; pss->reldir[len] = '\0'; if (pss->reldir[0] == '/' && !pss->reldir[1]) pss->reldir[0] = '\0'; lwsl_info("%s\n", pss->reldir); lws_callback_on_writable(wsi); break; case LWS_CALLBACK_SERVER_WRITEABLE: if (scan_dir(wsi, pss)) return 1; p += lws_snprintf(p, end - p, "{\"breadcrumbs\":["); q = pss->reldir; if (!q[0]) p += lws_snprintf(p, end - p, "{\"name\":\"top\"}"); while (*q) { q1 = strchr(q, '/'); if (!q1) { if (first) strcpy(s, "top1"); else strcpy(s, q); s1[0] = '\0'; q += strlen(q); } else { n = lws_ptr_diff(q1, q); if (n > (int)sizeof(s) - 1) n = sizeof(s) - 1; if (first) { strcpy(s1, "/"); strcpy(s, "top"); } else { strncpy(s, q, n); s[n] = '\0'; n = lws_ptr_diff(q1, pss->reldir); if (n > (int)sizeof(s1) - 1) n = sizeof(s1) - 1; strncpy(s1, pss->reldir, n); s1[n] = '\0'; } q = q1 + 1; } if (!first) p += lws_snprintf(p, end - p, ","); else first = 0; p += lws_snprintf(p, end - p, "{\"name\":\"%s\"", lws_json_purify(e, s, sizeof(e))); if (*q) { w = s1; while (w[0] == '/' && w[1] == '/') w++; p += lws_snprintf(p, end - p, ",\"url\":\"%s\"", lws_json_purify(e, w, sizeof(e))); } p += lws_snprintf(p, end - p, "}"); if (!q1) break; } p += lws_snprintf(p, end - p, "],\"data\":["); f = pss->base.next; while (f) { /* format in JSON */ p += lws_snprintf(p, end - p, "{\"Icon\":\"%s\",", lws_json_purify(e, f->icon, sizeof(e))); p += lws_snprintf(p, end - p, " \"Date\":\"%s\",", lws_json_purify(e, f->date, sizeof(e))); p += lws_snprintf(p, end - p, " \"Size\":\"%ld\",", f->size); if (f->uri) p += lws_snprintf(p, end - p, " \"uri\":\"%s\",", lws_json_purify(e, f->uri, sizeof(e))); p += lws_snprintf(p, end - p, " \"Name\":\"%s\"}", lws_json_purify(e, f->name, sizeof(e))); f = f->next; if (f) p += lws_snprintf(p, end - p, ","); } p += lws_snprintf(p, end - p, "]}"); free_scan_dir(pss); if (lws_write(wsi, (unsigned char *)start, p - start, LWS_WRITE_TEXT) < 0) return -1; break; case LWS_CALLBACK_HTTP_PMO: /* find the per-mount options we're interested in */ lwsl_debug("LWS_CALLBACK_HTTP_PMO\n"); pmo = (struct lws_protocol_vhost_options *)in; while (pmo) { if (!strcmp(pmo->name, "dir")) /* path to list files */ pss->dir = pmo->value; pmo = pmo->next; } if (!pss->dir[0]) { lwsl_err("dirlisting: \"dir\" pmo missing\n"); return 1; } break; case LWS_CALLBACK_HTTP_DROP_PROTOCOL: //lwsl_notice("LWS_CALLBACK_HTTP_DROP_PROTOCOL\n"); #if UV_VERSION_MAJOR > 0 lws_protocol_dir_kill_monitor(pss); #endif break; default: return 0; } return 0; }
int main(int argc, char const* argv[]) { int i, pid, errors; YARA_CONTEXT* context; FILE* rule_file; TAG* tag; TAG* next_tag; yr_init(); context = yr_create_context(); if (context == NULL) return 0; if (!process_cmd_line(context, argc, argv)) { yr_destroy_context(context); return 0; } if (argc == 1 || ((optind == argc) && (! compile_only))) { yr_destroy_context(context); show_help(); return 0; } context->error_report_function = report_error; for (i = optind; i < (compile_only ? argc : argc - 1); i++) { rule_file = fopen(argv[i], "r"); if (rule_file != NULL) { yr_push_file_name(context, argv[i]); errors = yr_compile_file(rule_file, context); fclose(rule_file); if (errors) /* errors during compilation */ { yr_destroy_context(context); return 2; } } else { fprintf(stderr, "could not open file: %s\n", argv[i]); if (compile_only) return 2; } } if (optind == (compile_only ? argc : argc - 1)) /* no rule files, read rules from stdin */ { yr_push_file_name(context, "stdin"); errors = yr_compile_file(stdin, context); if (errors > 0) /* errors during compilation */ { yr_destroy_context(context); return 0; } } if (compile_only) { printf("syntax check OK\n"); return 0; } if (is_numeric(argv[argc - 1])) { pid = atoi(argv[argc - 1]); switch (i = yr_scan_proc(pid, context, callback, (void*) argv[argc - 1])) { case ERROR_SUCCESS: break; case ERROR_COULD_NOT_ATTACH_TO_PROCESS: fprintf(stderr, "can not attach to process (try running as root)\n"); break; case ERROR_INSUFICIENT_MEMORY: fprintf(stderr, "not enough memory\n"); break; default: fprintf(stderr, "internal error: %d\n", i); break; } } else if (is_directory(argv[argc - 1])) { scan_dir(argv[argc - 1], recursive_search, context, callback); } else { yr_scan_file(argv[argc - 1], context, callback, (void*) argv[argc - 1]); } yr_destroy_context(context); /* free tag list allocated by process_cmd_line */ tag = specified_tags_list; while(tag != NULL) { next_tag = tag->next; free(tag); tag = next_tag; } return 1; }
int main( int argc, char const* argv[]) { YR_COMPILER* compiler; YR_RULES* rules; FILE* rule_file; EXTERNAL* external; int pid; int i; int errors; int result; THREAD thread[MAX_THREADS]; if (!process_cmd_line(argc, argv)) return 0; if (argc == 1 || optind == argc) { show_help(); return 0; } yr_initialize(); result = yr_rules_load(argv[optind], &rules); if (result == ERROR_UNSUPPORTED_FILE_VERSION || result == ERROR_CORRUPT_FILE) { print_scanning_error(result); return; } if (result == ERROR_SUCCESS) { external = externals_list; while (external != NULL) { switch (external->type) { case EXTERNAL_TYPE_INTEGER: yr_rules_define_integer_variable( rules, external->name, external->integer); break; case EXTERNAL_TYPE_BOOLEAN: yr_rules_define_boolean_variable( rules, external->name, external->boolean); break; case EXTERNAL_TYPE_STRING: yr_rules_define_string_variable( rules, external->name, external->string); break; } external = external->next; } } else { if (yr_compiler_create(&compiler) != ERROR_SUCCESS) return 0; external = externals_list; while (external != NULL) { switch (external->type) { case EXTERNAL_TYPE_INTEGER: yr_compiler_define_integer_variable( compiler, external->name, external->integer); break; case EXTERNAL_TYPE_BOOLEAN: yr_compiler_define_boolean_variable( compiler, external->name, external->boolean); break; case EXTERNAL_TYPE_STRING: yr_compiler_define_string_variable( compiler, external->name, external->string); break; } external = external->next; } compiler->error_report_function = print_compiler_error; rule_file = fopen(argv[optind], "r"); if (rule_file != NULL) { yr_compiler_push_file_name(compiler, argv[optind]); errors = yr_compiler_add_file(compiler, rule_file, NULL); fclose(rule_file); if (errors == 0) yr_compiler_get_rules(compiler, &rules); yr_compiler_destroy(compiler); if (errors > 0) { yr_finalize(); return 0; } } else { fprintf(stderr, "could not open file: %s\n", argv[optind]); return 0; } } mutex_init(&output_mutex); if (is_numeric(argv[argc - 1])) { pid = atoi(argv[argc - 1]); result = yr_rules_scan_proc( rules, pid, callback, (void*) argv[argc - 1], fast_scan, timeout); if (result != ERROR_SUCCESS) print_scanning_error(result); } else if (is_directory(argv[argc - 1])) { file_queue_init(); for (i = 0; i < threads; i++) { if (create_thread(&thread[i], scanning_thread, (void*) rules) != 0) return ERROR_COULD_NOT_CREATE_THREAD; } scan_dir( argv[argc - 1], recursive_search, rules, callback); file_queue_finish(); // Wait for scan threads to finish for (i = 0; i < threads; i++) thread_join(&thread[i]); file_queue_destroy(); } else { result = yr_rules_scan_file( rules, argv[argc - 1], callback, (void*) argv[argc - 1], fast_scan, timeout); if (result != ERROR_SUCCESS) { fprintf(stderr, "Error scanning %s: ", argv[argc - 1]); print_scanning_error(result); } } yr_rules_destroy(rules); yr_finalize(); mutex_destroy(&output_mutex); cleanup(); return 1; }
int main(void) { tui_init(); tab_window *ltab = malloc(sizeof *ltab); tab_window *rtab = malloc(sizeof *ltab); int ch; void (*p)(tab_window *, const char *); tab_window *active_tab; ltab->win = tui_new_win(0, 0, LINES, COLS / 2 , 2); rtab->win = tui_new_win(0, COLS / 2, LINES, COLS / 2, 2); mvwprintw(ltab->win->decoration, 1,1, "/"); mvwprintw(rtab->win->decoration, 1,1, "/"); set_panel_userptr(ltab->win->panel, rtab); set_panel_userptr(rtab->win->panel, ltab); top_panel(ltab->win->panel); active_tab = ltab; strncpy(ltab->path, "/", PATH_MAX - 1); strncpy(rtab->path, "/", PATH_MAX - 1); ltab->items_num = scan_dir(ltab->path, <ab->files, dirsortbyname); rtab->items_num = scan_dir(rtab->path, &rtab->files, dirsortbyname); tui_make_menu(ltab, event_handler); tui_make_menu(rtab, event_handler); touchwin(panel_window(active_tab->win->panel)); update_panels(); doupdate(); while ((ch = getch()) != KEY_F(12)) { p = (void (*)(tab_window *, const char *))(uintptr_t)item_userptr(current_item(active_tab->menu)); switch (ch) { case '\t': active_tab = (tab_window *) panel_userptr(active_tab->win->panel); top_panel(active_tab->win->panel); break; case KEY_DOWN: menu_driver(active_tab->menu, REQ_DOWN_ITEM); break; case KEY_UP: menu_driver(active_tab->menu, REQ_UP_ITEM); break; case KEY_NPAGE: menu_driver(active_tab->menu, REQ_SCR_DPAGE); break; case KEY_PPAGE: menu_driver(active_tab->menu, REQ_SCR_UPAGE); break; case KEY_HOME: menu_driver(active_tab->menu, REQ_FIRST_ITEM); break; case KEY_END: menu_driver(active_tab->menu, REQ_LAST_ITEM); break; case 13: // enter p(active_tab, "select"); break; case KEY_F(2): p(active_tab, "remove"); break; case KEY_F(3): p(active_tab, "rename"); break; default:break; } touchwin(panel_window(active_tab->win->panel)); update_panels(); doupdate(); } for(int i = 0; i < ltab->items_num ; ++i) { free(ltab->files[i]); } free(ltab->files); for(int i = 0; i < rtab->items_num; ++i) { free(rtab->files[i]); } free(rtab->files); tui_destroy_menu(rtab); tui_destroy_menu(ltab); tui_del_win(ltab); tui_del_win(rtab); free(ltab); free(rtab); endwin(); }
int main(int argc, char **argv) { FILE *file = fopen("Makefile", "wb"); writestr("all: ", file); // writestr("clanSignals ", file); writestr("clanCore ", file); writestr("clanApp ", file); writestr("clanNetwork ", file); writestr("clanDisplay ", file); writestr("clanGL ", file); // writestr("clanSDL ", file); writestr("clanSound ", file); writestr("clanMikMod ", file); writestr("clanVorbis ", file); writestr("clanGUI ", file); // writestr("clanGUIStyleSilver ", file); writestr("ClanLib\n", file); writestr("\t@echo Build complete!\n\n", file); /* std::vector<std::string> signalsDeps; std::string signalsLinkExtra; create_project_targets(file, "clanSignals", scan_dir("Sources/Signals", true), scan_dir("Sources/API", true), signalsDeps, signalsLinkExtra); */ std::vector<std::string> coreDeps; std::string coreLinkExtra = "-lz -lpthread -framework Carbon"; // coreDeps.push_back("clanSignals"); create_project_targets(file, "clanCore", scan_dir("Sources/Core", true), scan_dir("Sources/API", true), coreDeps, coreLinkExtra); std::vector<std::string> appDeps; std::string appLinkExtra; appDeps.push_back("clanCore"); // appDeps.push_back("clanSignals"); create_project_targets(file, "clanApp", scan_dir("Sources/Application", true), scan_dir("Sources/API", true), appDeps, appLinkExtra); std::vector<std::string> networkDeps; std::string networkLinkExtra; // networkDeps.push_back("clanSignals"); networkDeps.push_back("clanCore"); create_project_targets(file, "clanNetwork", scan_dir("Sources/Network", true), scan_dir("Sources/API", true), networkDeps, networkLinkExtra); std::vector<std::string> displayDeps; std::string displayLinkExtra = "-lpng -ljpeg"; // displayDeps.push_back("clanSignals"); displayDeps.push_back("clanCore"); create_project_targets(file, "clanDisplay", scan_dir("Sources/Display", true), scan_dir("Sources/API", true), displayDeps, displayLinkExtra); std::vector<std::string> glDeps; std::string glLinkExtra = "-framework OpenGL -framework AGL -framework Carbon"; // glDeps.push_back("clanSignals"); glDeps.push_back("clanCore"); glDeps.push_back("clanDisplay"); create_project_targets(file, "clanGL", scan_dir("Sources/GL", true), scan_dir("Sources/API", true), glDeps, glLinkExtra); /* std::vector<std::string> sdlDeps; std::string sdlLinkExtra = "-lsdl -lobjc"; sdlDeps.push_back("clanSignals"); sdlDeps.push_back("clanCore"); sdlDeps.push_back("clanDisplay"); create_project_targets(file, "clanSDL", scan_dir("Sources/SDL", true), scan_dir("Sources/API", true), sdlDeps, sdlLinkExtra); */ std::vector<std::string> soundDeps; std::string soundLinkExtra = "-framework CoreAudio"; // soundDeps.push_back("clanSignals"); soundDeps.push_back("clanCore"); create_project_targets(file, "clanSound", scan_dir("Sources/Sound", true), scan_dir("Sources/API", true), soundDeps, soundLinkExtra); std::vector<std::string> mikmodDeps; std::string mikmodLinkExtra = "-lmikmod"; // mikmodDeps.push_back("clanSignals"); mikmodDeps.push_back("clanCore"); mikmodDeps.push_back("clanSound"); create_project_targets(file, "clanMikMod", scan_dir("Sources/MikMod", true), scan_dir("Sources/API", true), mikmodDeps, mikmodLinkExtra); std::vector<std::string> vorbisDeps; std::string vorbisLinkExtra = "-logg -lvorbis"; // vorbisDeps.push_back("clanSignals"); vorbisDeps.push_back("clanCore"); vorbisDeps.push_back("clanSound"); create_project_targets(file, "clanVorbis", scan_dir("Sources/Vorbis", true), scan_dir("Sources/API", true), vorbisDeps, vorbisLinkExtra); std::vector<std::string> GUIDeps; std::string GUILinkExtra; // GUIDeps.push_back("clanSignals"); GUIDeps.push_back("clanCore"); GUIDeps.push_back("clanDisplay"); create_project_targets(file, "clanGUI", scan_dir("Sources/GUI", true), scan_dir("Sources/API", true), GUIDeps, GUILinkExtra); /* std::vector<std::string> GUIStyleSilverDeps; std::string GUIStyleSilverLinkExtra; GUIStyleSilverDeps.push_back("clanSignals"); GUIStyleSilverDeps.push_back("clanCore"); GUIStyleSilverDeps.push_back("clanDisplay"); GUIStyleSilverDeps.push_back("clanGUI"); create_project_targets(file, "clanGUIStyleSilver", scan_dir("Sources/GUIStyleSilver", true), scan_dir("Sources/API", true), GUIStyleSilverDeps, GUIStyleSilverLinkExtra); */ std::vector<std::string> umbrellaDeps; // umbrellaDeps.push_back("clanSignals"); umbrellaDeps.push_back("clanCore"); umbrellaDeps.push_back("clanDisplay"); umbrellaDeps.push_back("clanGUI"); // umbrellaDeps.push_back("clanGUIStyleSilver"); umbrellaDeps.push_back("clanSound"); umbrellaDeps.push_back("clanApp"); umbrellaDeps.push_back("clanNetwork"); umbrellaDeps.push_back("clanGL"); // umbrellaDeps.push_back("clanSDL"); umbrellaDeps.push_back("clanVorbis"); umbrellaDeps.push_back("clanMikMod"); create_umbrella_project(file, scan_dir("Sources/API", true), umbrellaDeps); fclose(file); return 0; }
static int scan_dir (char *path, char *name, char *topdir, conf_t * cfg, int level) { int i; DIR *dir; struct dirent *de; struct stat st; char tmp[256]; FILE *f; FILE *cf; char cfg_name[64]; char cfg_header[64]; int cfg_seen = 0; conf_t conf; int ndirs = 0; char *subdirs[MAX_SUBDIRS]; int nobjects = 0; char *objects[MAX_OBJECTS], *obj_src[MAX_OBJECTS]; int nsources = 0; char *sources[MAX_OBJECTS]; char obj[128], *p, *suffix; char *objdir = "OBJDIR"; int include_local_makefile = 0; #define MAX_FILENAME 128 char *filenames[MAX_FILENAME]; int n_filenames = 0; char tmp_endian[100]=""; char autogen_sources[1024]=""; memcpy (&conf, cfg, sizeof (conf)); if (conf.mode == MD_MODULE_) conf.mode = MD_MODULE; if (conf.mode == MD_KERNEL_) conf.mode = MD_KERNEL; sprintf (tmp, "%s/.name", path); if ((cf = fopen (tmp, "r")) != NULL) { char *p; if (fgets(tmp, sizeof(tmp)-1, cf)==NULL) strcpy(tmp, name); fclose (cf); p=tmp+strlen(tmp)-1; if (*p=='\n')*p=0; conf.purpose=strdup(tmp); } else { conf.purpose=strdup(name); } sprintf (tmp, "%s/.config", path); if ((cf = fopen (tmp, "r")) != NULL) { if (!parse_config (cf, &conf, path)) { /* Not compatible with this environment */ fclose (cf); return 0; } fclose (cf); } else if (conf.mode == MD_MODULE && exact_architectures) /* .config required for this arch */ { printf ("Ignoring %s - No CPU specified\n", path); return 0; } sprintf (tmp, "%s/.nativemake", path); /* Use the existing makefile */ if (stat (tmp, &st) != -1) { return 1; } sprintf (cfg_name, "%s_cfg.c", name); sprintf (cfg_header, "%s_cfg.h", name); sprintf (tmp, "%s/Makefile.%s", path, conf.system); unlink (tmp); sprintf (tmp, "%s/Makefile", path); unlink (tmp); sprintf (tmp, "%s/.nomake", path); if (stat (tmp, &st) != -1) return 0; sprintf (tmp, "%s/.makefile", path); if (stat (tmp, &st) != -1) include_local_makefile = 1; if (kernelonly) if (conf.mode == MD_USERLAND || conf.mode == MD_SBIN) return 0; if (useronly) if (conf.mode == MD_KERNEL || conf.mode == MD_MODULE || conf.mode == MD_KERNEL_ || conf.mode == MD_MODULE_) return 0; if (conf.mode == MD_MODULE) driver_gen (name, &conf, cfg_name, cfg_header, path, topdir); if ((dir = opendir (path)) == NULL) { perror (path); fprintf(stderr, "scan_dir(%s): Opendir failed\n", path); exit (-1); } while ((de = readdir (dir)) != NULL) { if (de->d_name[0] == '.') continue; if (n_filenames >= MAX_FILENAME) { fprintf (stderr, "Too many files in directory %s\n", path); exit (-1); } filenames[n_filenames++] = strdup (de->d_name); } qsort (filenames, n_filenames, sizeof (char *), cmpstringp); for (i = 0; i < n_filenames; i++) { sprintf (tmp, "%s/%s", path, filenames[i]); if (stat (tmp, &st) == -1) { perror (tmp); continue; } if (S_ISDIR (st.st_mode)) { char top[256]; if (topdir == NULL) strcpy (top, ".."); else sprintf (top, "../%s", topdir); if (scan_dir (tmp, filenames[i], top, &conf, level + 1)) { if (ndirs >= MAX_SUBDIRS) { fprintf (stderr, "Too many subdirs in %s\n", path); exit (-1); } subdirs[ndirs++] = strdup (filenames[i]); } continue; } /* printf("%s/%s\n", path, filenames[i]); */ if (nobjects >= MAX_OBJECTS || nsources >= MAX_OBJECTS) { fprintf (stderr, "Too many objects in %s\n", path); exit (-1); } strcpy (obj, filenames[i]); p = obj; suffix = ""; while (*p) { if (*p == '.') suffix = p; p++; } if (strcmp (suffix, ".c") == 0) { sources[nsources++] = strdup (obj); if (strcmp (obj, cfg_name) == 0) cfg_seen = 1; } if (config_phpmake) { if (strcmp(suffix, ".PHc") == 0) { if (*autogen_sources != 0) strcat(autogen_sources, " "); *suffix=0; strcat(autogen_sources, obj); strcat(autogen_sources, ".c"); *suffix='.'; strcpy(suffix, ".c"); } else if (strcmp(suffix, ".PHh") == 0) { if (*autogen_sources != 0) strcat(autogen_sources, " "); *suffix=0; strcat(autogen_sources, obj); strcat(autogen_sources, ".h"); *suffix='.'; } else if (strcmp(suffix, ".PHinc") == 0) { if (*autogen_sources != 0) strcat(autogen_sources, " "); *suffix=0; strcat(autogen_sources, obj); strcat(autogen_sources, ".inc"); *suffix='.'; } } else { char source[256], target[256]; if (strcmp(suffix, ".PHc") == 0) { *suffix=0; sprintf (source, "%s.PHc", obj); sprintf (target, "%s/%s.c", path, obj); *suffix='.'; if (symlink (source, target) == -1) { perror(source); exit(1); } } else if (strcmp(suffix, ".PHh") == 0) { *suffix=0; sprintf (source, "%s.PHh", obj); sprintf (target, "%s/%s.h", path, obj); *suffix='.'; if (symlink (source, target) == -1) { perror(source); exit(1); } } else if (strcmp(suffix, ".PHinc") == 0) { *suffix=0; sprintf (source, "%s.PHinc", obj); sprintf (target, "%s/%s.inc", path, obj); *suffix='.'; printf("Symlink %s -> %s\n", source, target); if (symlink (source, target) == -1) { perror(source); exit(1); } } } if (strcmp (suffix, ".c") == 0 || strcmp (suffix, ".C") == 0 || strcmp (suffix, ".cpp") == 0) { obj_src[nobjects] = strdup (obj); *suffix = 0; strcat (obj, ".o"); objects[nobjects++] = strdup (obj); } } closedir (dir); sprintf (tmp, "%s/.depend", path); unlink (tmp); sprintf (tmp, "touch %s/.depend", path); system (tmp); if (level == 1 && *this_os && !useronly) { subdirs[ndirs++] = strdup (this_os); } #if 0 // This block is no longer necessary because the driver_gen () call was moved. // Now the _cfg.c file should get created so that it gets picked by the readdir() loop. // However keep it here for a while. if (!cfg_seen && conf.mode == MD_MODULE) { # if !defined(linux) && !defined(__FreeBSD__) sprintf (tmp, "%s_cfg.c", name); sources[nsources++] = strdup (tmp); obj_src[nobjects] = strdup (tmp); sprintf (tmp, "%s_cfg.o", name); objects[nobjects++] = strdup (tmp); # endif } #endif #if 0 // This stuff has been moved above the readdir() loop. if (conf.mode == MD_MODULE) driver_gen (name, &conf, cfg_name, cfg_header, path, topdir); #endif if (do_cleanup || (ndirs == 0 && nobjects == 0)) { return 0; } if (config_phpmake) sprintf (tmp, "%s/Makefile.php", path); else sprintf (tmp, "%s/Makefile", path); #if 0 if ((f = fopen (tmp, "w")) == NULL) { perror (tmp); exit (-1); } if (include_local_makefile) { fprintf (f, "\n"); fprintf (f, "include .makefile\n"); fprintf (f, "\n"); } fprintf (f, "all:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f Makefile.`uname -s` all\n\n"); fprintf (f, "config:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f make.defs config\n\n"); fprintf (f, "purge:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f make.defs purge\n\n"); fprintf (f, "dirs:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f Makefile.`uname -s` dirs\n\n"); fprintf (f, "clean:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f Makefile.`uname -s` clean\n\n"); fprintf (f, "lint:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f Makefile.`uname -s` lint\n\n"); fprintf (f, "dep:\n"); fprintf (f, "\t$(MAKE) $(BUILDFLAGS) BUILDFLAGS=\"$(BUILDFLAGS)\" -f Makefile.`uname -s` dep\n\n"); fclose (f); sprintf (tmp, "%s/Makefile.%s", path, conf.system); #endif if ((f = fopen (tmp, "w")) == NULL) { perror (tmp); exit (-1); } fprintf (f, "# Makefile for %s module %s\n\n", conf.project_name, name); if (config_phpmake) fprintf (f, "<?php require getenv(\"PHPMAKE_LIBPATH\") . \"library.php\"; phpmake_makefile_top_rules(); ?>\n"); fprintf (f, "CC=%s\n", conf.ccomp); // fprintf (f, "LD=ld\n"); fprintf (f, "HOSTCC=%s\n", hostcc); fprintf (f, "CPLUSPLUS=%s\n", conf.cplusplus); #ifdef VXWORKS vxworks_genheader (f, path); #endif #if defined(__SCO_VERSION__) if (*conf.cflags != 0) fprintf (f, "CFLAGS=%s\n", conf.cflags); #endif if (*conf.ldflags != 0) fprintf (f, "LDFLAGS=%s\n", conf.ldflags); if (strcmp(conf.endianess, "UNKNOWN") != 0) sprintf (tmp_endian, " -DOSS_%s_ENDIAN", conf.endianess); fprintf (f, "OSFLAGS=%s%s\n", conf.OSflags, tmp_endian); fprintf (f, "OS=%s\n", conf.system); fprintf (f, "ARCH=%s\n", conf.arch); if (topdir == NULL) fprintf (f, "TOPDIR=.\n"); else fprintf (f, "TOPDIR=%s\n", topdir); fprintf (f, "OBJDIR=$(TOPDIR)/target/objects\n"); fprintf (f, "TMPDIR=.\n"); fprintf (f, "MODDIR=$(TOPDIR)/target/modules\n"); fprintf (f, "BINDIR=$(TOPDIR)/target/bin\n"); fprintf (f, "LIBDIR=$(TOPDIR)/target/lib\n"); fprintf (f, "SBINDIR=$(TOPDIR)/target/sbin\n"); if ((p = getenv("OSSLIBDIR")) != NULL) fprintf (f, "OSSLIBDIR=\"%s\"\n", p); fprintf (f, "THISOS=%s\n", this_os); if (config_phpmake) fprintf (f, "CFLAGS+=-D__USE_PHPMAKE__\n"); if (conf.mode == MD_KERNEL || conf.mode == MD_MODULE) { #if defined(__SCO_VERSION__) fprintf (f, "CFLAGS=-O -D_KERNEL -D_DDI=8\n"); #else fprintf (f, "CFLAGS += -D_KERNEL\n"); #endif #ifdef HAVE_KERNEL_FLAGS add_kernel_flags (f); #endif } #ifndef __SCO_VERSION__ else { fprintf (f, "CFLAGS+=-O\n"); } #endif #if !defined(__SCO_VERSION__) if (*conf.cflags != 0) fprintf (f, "CFLAGS += %s\n", conf.cflags); if (conf.mode == MD_SHLIB) fprintf (f, "CFLAGS += %s\n", shlib_cflags); #endif if (conf.mode != MD_KERNEL) objdir = "TMPDIR"; if (nincludes > 0) { int i; fprintf (f, "INCLUDES="); for (i = 0; i < nincludes; i++) { if (i > 0) fprintf (f, " "); if (includes[i][0] == '/') fprintf (f, "%s", includes[i]); else fprintf (f, "-I$(TOPDIR)/%s", includes[i]); } fprintf (f, "\n"); } if (ndirs > 0) { int i; if (config_phpmake) { fprintf (f, "<?php\n"); fprintf (f, "\t$subdirs=array("); for (i = 0; i < ndirs; i++) { if (i > 0) fprintf (f, ", "); fprintf (f, "\"%s\"", subdirs[i]); } fprintf (f, ");\n"); fprintf (f, "phpmake_print_subdirs($subdirs);\n"); fprintf (f, "?>\n"); } else { fprintf (f, "SUBDIRS="); for (i = 0; i < ndirs; i++) { if (i > 0) fprintf (f, " "); fprintf (f, "%s", subdirs[i]); } fprintf (f, "\n"); } } if (nobjects > 0) { int i; fprintf (f, "OBJECTS="); for (i = 0; i < nobjects; i++) { if (i > 0) fprintf (f, " "); fprintf (f, "$(%s)/%s", objdir, objects[i]); } fprintf (f, "\n"); } if (conf.mode == MD_MODULE) { fprintf (f, "TARGETS=$(MODDIR)/%s $(MODDIR)/%s.o\n", name, name); fprintf (f, "DEPDIR=$(TMPDIR)\n"); } else if ((conf.mode == MD_USERLAND) && nobjects > 0) { fprintf (f, "TARGETS=$(BINDIR)/%s\n", name); fprintf (f, "DEPDIR=$(BINDIR)/\n"); } else if ((conf.mode == MD_SBIN) && nobjects > 0) { fprintf (f, "TARGETS=$(SBINDIR)/%s\n", name); fprintf (f, "DEPDIR=$(SBINDIR)/\n"); } else { fprintf (f, "TARGETS=%s\n", name); fprintf (f, "DEPDIR=\n"); } if (nsources > 0) { int i; fprintf (f, "CSOURCES="); for (i = 0; i < nsources; i++) { if (i > 0) fprintf (f, " "); fprintf (f, "%s", sources[i]); } fprintf (f, "\n"); } if (*autogen_sources != 0) fprintf (f, "AUTOGEN_SOURCES=%s\n", autogen_sources); fprintf (f, "\n"); if (include_local_makefile) { fprintf (f, "include .makefile\n"); fprintf (f, "\n"); } if (config_phpmake) fprintf (f, "<?php phpmake_makefile_rules(); ?>\n"); /* * Create the default target */ fprintf (f, "all: "); if (conf.mode == MD_USERLAND && nsources > 0) { fprintf (f, "$(TARGETS) "); } else if (conf.mode == MD_MODULE) { if (nobjects > 0) fprintf (f, "$(MODDIR)/%s.o ", name); } else if (conf.mode == MD_SHLIB) { fprintf (f, "$(LIBDIR)/%s.so ", name); } else if (conf.mode != MD_KERNEL) { if (nobjects > 0) { if (conf.mode == MD_SBIN) fprintf (f, "$(SBINDIR)/%s ", name); else fprintf (f, "$(BINDIR)/%s ", name); } } else { if (nobjects > 0) fprintf (f, "$(AUTOGEN_SOURCES) objects "); } if (ndirs > 0) fprintf (f, "subdirs "); fprintf (f, "\n"); #if 0 if (level == 1) fprintf (f, "\t-sh $(THISOS)/build.sh \"$(ARCH)\" \"$(INCLUDES)\" \"$(CFLAGS)\"\n"); fprintf (f, "\n"); #endif /* * Create the lint target */ fprintf (f, "lint: "); if (nobjects > 0) fprintf (f, "lint_sources "); if (ndirs > 0) fprintf (f, "lint_subdirs "); fprintf (f, "\n\n"); /* * Create the dep target */ fprintf (f, "dep: "); if (nobjects > 0) fprintf (f, "$(AUTOGEN_SOURCES) dep_local "); if (ndirs > 0) fprintf (f, "dep_subdirs "); fprintf (f, "\n\n"); fprintf (f, "include $(TOPDIR)/make.defs\n"); fprintf (f, "\n"); if (conf.mode == MD_USERLAND) { fprintf (f, "%s:\t$(BINDIR)/%s\n\n", name, name); fprintf (f, "$(BINDIR)/%s:\t$(OBJECTS)\n", name); fprintf (f, "\t$(CC) $(CFLAGS) $(LIBRARIES) $(LDFLAGS) -s -o $(BINDIR)/%s $(OBJECTS) %s\n", name, extra_libraries); fprintf (f, "\n\n"); } if (conf.mode == MD_SHLIB) { fprintf (f, "%s.so:\t$(LIBDIR)/%s.so\n\n", name, name); fprintf (f, "$(LIBDIR)/%s.so:\t$(OBJECTS)\n", name); #if defined(linux) /* gcc -shared works much better than ld on Linux */ fprintf (f, "\t$(CC) $(LDFLAGS) %s -o $(LIBDIR)/%s.so $(OBJECTS)\n", shlib_cflags, name); #else fprintf (f, "\t$(LD) $(LDFLAGS) %s -o $(LIBDIR)/%s.so $(OBJECTS)\n", shlib_ldflags, name); #endif fprintf (f, "\n\n"); } if (conf.mode == MD_SBIN) { fprintf (f, "%s:\t$(SBINDIR)/%s\n\n", name, name); fprintf (f, "$(SBINDIR)/%s:\t$(OBJECTS)\n", name); fprintf (f, "\t$(CC) $(CFLAGS) $(LIBRARIES) $(LDFLAGS) -s -o $(SBINDIR)/%s $(OBJECTS) %s\n", name, extra_libraries); fprintf (f, "\n\n"); } if (conf.mode == MD_MODULE) { fprintf (f, "$(MODDIR)/%s.o:\t$(OBJECTS)\n", name); fprintf (f, "\t$(LD) $(LDARCH) -r -o $(MODDIR)/%s.o $(OBJECTS)\n", name); fprintf (f, "\n\n"); } if (nobjects > 0) { int i; for (i = 0; i < nobjects; i++) { fprintf (f, "$(%s)/%s:\t%s\n", objdir, objects[i], obj_src[i]); if (is_cplusplus (obj_src[i])) fprintf (f, "\t$(CPLUSPLUS) -c $(CFLAGS) $(OSFLAGS) $(INCLUDES) %s -o $(%s)/%s\n", obj_src[i], objdir, objects[i]); else fprintf (f, "\t$(CC) -c $(CFLAGS) $(OSFLAGS) $(LIBRARIES) $(INCLUDES) %s -o $(%s)/%s\n", obj_src[i], objdir, objects[i]); fprintf (f, "\n"); } } fprintf (f, "clean: clean_local"); if (ndirs > 0) fprintf (f, " clean_subdirs"); fprintf (f, "\n\n"); fclose (f); return 1; }
static int do_loop(void) { int r; path_t report_path; path_t full_report_path; path_t pkt_name; unsigned char exe_pkt_name[64]; unsigned char run_base[64]; path_t full_report_dir; path_t full_status_dir; path_t full_full_dir; char exe_name[64]; int tester_id; struct section_tester_data tn, *tst; int got_quit_packet = 0; struct run_reply_packet reply_pkt; void *reply_pkt_buf = 0; size_t reply_pkt_buf_size = 0; unsigned char errmsg[512]; const struct section_global_data *global = serve_state.global; const unsigned char *arch = 0; char *srp_b = 0; size_t srp_z = 0; struct super_run_in_packet *srp = NULL; struct super_run_in_global_packet *srgp = NULL; struct super_run_in_problem_packet *srpp = NULL; memset(&tn, 0, sizeof(tn)); //if (cr_serialize_init(&serve_state) < 0) return -1; interrupt_init(); interrupt_disable(); while (1) { interrupt_enable(); /* time window for immediate signal delivery */ interrupt_disable(); // terminate, if signaled if (interrupt_get_status()) break; if (interrupt_restart_requested()) { restart_flag = 1; } if (restart_flag) break; r = scan_dir(global->run_queue_dir, pkt_name, sizeof(pkt_name)); if (r < 0) return -1; if (!r) { if (got_quit_packet && managed_mode_flag) { return 0; } if (managed_mode_flag && global->inactivity_timeout > 0 && last_activity_time + global->inactivity_timeout < time(0)) { info("no activity for %d seconds, exiting",global->inactivity_timeout); return 0; } interrupt_enable(); os_Sleep(global->sleep_time); interrupt_disable(); continue; } last_activity_time = time(0); srp = super_run_in_packet_free(srp); xfree(srp_b); srp_b = NULL; srp_z = 0; r = generic_read_file(&srp_b, 0, &srp_z, SAFE | REMOVE, global->run_queue_dir, pkt_name, ""); if (r == 0) continue; if (r < 0) return -1; if (!strcmp(pkt_name, "QUIT")) { if (managed_mode_flag) { got_quit_packet = 1; info("got force quit run packet"); } else { restart_flag = 1; } xfree(srp_b); srp_b = NULL; srp_z = 0; continue; } fprintf(stderr, "packet: <<%.*s>>\n", (int) srp_z, srp_b); srp = super_run_in_packet_parse_cfg_str(pkt_name, srp_b, srp_z); //xfree(srp_b); srp_b = NULL; srp_z = 0; if (!srp) { err("failed to parse file %s", pkt_name); continue; } if (!(srgp = srp->global)) { err("packet %s has no global section", pkt_name); continue; } if (srgp->contest_id <= 0) { err("packet %s: undefined contest_id", pkt_name); continue; } if (managed_mode_flag && srgp->restart > 0) { got_quit_packet = 1; info("got force quit run packet"); continue; } if (srgp->restart > 0) { restart_flag = 1; continue; } /* if (req_pkt->contest_id == -1) { r = generic_write_file(req_buf, req_buf_size, SAFE, serve_state.global->run_queue_dir, pkt_name, ""); if (r < 0) return -1; info("force quit packet is ignored in unmanaged mode"); scan_dir_add_ignored(serve_state.global->run_queue_dir, pkt_name); continue; } */ if (!(srpp = srp->problem)) { err("packet %s: no [problem] section", pkt_name); continue; } /* if we are asked to do full testing, but don't want */ if ((global->skip_full_testing > 0 && !srgp->accepting_mode) || (global->skip_accept_testing > 0 && srgp->accepting_mode)) { r = generic_write_file(srp_b, srp_z, SAFE, global->run_queue_dir, pkt_name, ""); if (r < 0) return -1; info("skipping problem %s", srpp->short_name); scan_dir_add_ignored(global->run_queue_dir, pkt_name); continue; } /* if this problem is marked as "skip_testing" put the * packet back to the spool directory */ #if 0 if (cur_prob->skip_testing > 0) { r = generic_write_file(srp_b, srp_z, SAFE, global->run_queue_dir, pkt_name, ""); if (r < 0) return -1; info("skipping problem %s", cur_prob->short_name); scan_dir_add_ignored(global->run_queue_dir, pkt_name); continue; } #endif snprintf(run_base, sizeof(run_base), "%06d", srgp->run_id); report_path[0] = 0; full_report_path[0] = 0; if (srpp->type_val == PROB_TYPE_TESTS) { //cr_serialize_lock(&serve_state); run_inverse_testing(&serve_state, srp, &reply_pkt, pkt_name, global->run_exe_dir, report_path, sizeof(report_path), utf8_mode); //cr_serialize_unlock(&serve_state); } else { arch = srgp->arch; if (!arch) arch = ""; if (srpp->type_val > 0 && arch && !*arch) { // any tester will work for output-only problems arch = 0; } /* regular problem */ if (!(tester_id = find_tester(&serve_state, srpp->id, arch))){ snprintf(errmsg, sizeof(errmsg), "no tester found for %d, %s\n", srpp->id, srgp->arch); goto report_check_failed_and_continue; } info("fount tester %d for pair %d,%s", tester_id, srpp->id, srgp->arch); tst = serve_state.testers[tester_id]; if (tst->any) { info("tester %d is a default tester", tester_id); r = prepare_tester_refinement(&serve_state, &tn, tester_id, srpp->id); ASSERT(r >= 0); tst = &tn; } /* if this tester is marked as "skip_testing" put the * packet back to the spool directory */ if (tst->skip_testing > 0) { r = generic_write_file(srp_b, srp_z, SAFE, global->run_queue_dir, pkt_name, ""); if (r < 0) return -1; info("skipping tester <%s,%s>", srpp->short_name, tst->arch); scan_dir_add_ignored(global->run_queue_dir, pkt_name); if (tst == &tn) { sarray_free(tst->start_env); tst->start_env = 0; sarray_free(tst->super); tst->super = 0; } continue; } snprintf(exe_pkt_name, sizeof(exe_pkt_name), "%s%s", pkt_name, srgp->exe_sfx); snprintf(exe_name, sizeof(exe_name), "%s%s", run_base, srgp->exe_sfx); r = generic_copy_file(REMOVE, global->run_exe_dir, exe_pkt_name, "", 0, global->run_work_dir, exe_name, ""); if (r <= 0) { snprintf(errmsg, sizeof(errmsg), "failed to copy executable file %s/%s\n", global->run_exe_dir, exe_pkt_name); goto report_check_failed_and_continue; } /* start filling run_reply_packet */ memset(&reply_pkt, 0, sizeof(reply_pkt)); reply_pkt.judge_id = srgp->judge_id; reply_pkt.contest_id = srgp->contest_id; reply_pkt.run_id = srgp->run_id; reply_pkt.notify_flag = srgp->notify_flag; reply_pkt.user_status = -1; reply_pkt.user_tests_passed = -1; reply_pkt.user_score = -1; reply_pkt.ts1 = srgp->ts1; reply_pkt.ts1_us = srgp->ts1_us; reply_pkt.ts2 = srgp->ts2; reply_pkt.ts2_us = srgp->ts2_us; reply_pkt.ts3 = srgp->ts3; reply_pkt.ts3_us = srgp->ts3_us; reply_pkt.ts4 = srgp->ts4; reply_pkt.ts4_us = srgp->ts4_us; get_current_time(&reply_pkt.ts5, &reply_pkt.ts5_us); //if (cr_serialize_lock(&serve_state) < 0) return -1; run_tests(ejudge_config, &serve_state, tst, srp, &reply_pkt, srgp->accepting_mode, srpp->accept_partial, srgp->variant, exe_name, run_base, report_path, full_report_path, srgp->user_spelling, srpp->spelling, NULL /* mirror_dir */, utf8_mode); //if (cr_serialize_unlock(&serve_state) < 0) return -1; if (tst == &tn) { sarray_free(tst->start_env); tst->start_env = 0; sarray_free(tst->super); tst->super = 0; } } if (srgp->reply_report_dir && srgp->reply_report_dir[0]) { snprintf(full_report_dir, sizeof(full_report_dir), "%s", srgp->reply_report_dir); } else { snprintf(full_report_dir, sizeof(full_report_dir), "%s/%06d/report", global->run_dir, srgp->contest_id); } if (srgp->reply_spool_dir && srgp->reply_spool_dir[0]) { snprintf(full_status_dir, sizeof(full_status_dir), "%s", srgp->reply_spool_dir); } else { snprintf(full_status_dir, sizeof(full_status_dir), "%s/%06d/status", global->run_dir, srgp->contest_id); } if (srgp->reply_full_archive_dir && srgp->reply_full_archive_dir[0]) { snprintf(full_full_dir, sizeof(full_full_dir), "%s", srgp->reply_full_archive_dir); } else { snprintf(full_full_dir, sizeof(full_full_dir), "%s/%06d/output", global->run_dir, srgp->contest_id); } if (generic_copy_file(0, NULL, report_path, "", 0, full_report_dir, run_base, "") < 0) return -1; #if defined CONF_HAS_LIBZIP if (full_report_path[0] && generic_copy_file(0, NULL, full_report_path, "", 0, full_full_dir, run_base, ".zip") < 0) return -1; #else if (full_report_path[0] && generic_copy_file(0, NULL, full_report_path, "", 0, full_full_dir, run_base, "") < 0) return -1; #endif //run_reply_packet_dump(&reply_pkt); if (run_reply_packet_write(&reply_pkt, &reply_pkt_buf_size, &reply_pkt_buf) < 0) { /* FIXME: do something, if this is possible. * However, unability to generate a reply packet only * means that invalid data passed, which should be reported * immediately as internal error! */ abort(); } if (generic_write_file(reply_pkt_buf, reply_pkt_buf_size, SAFE, full_status_dir, run_base, "") < 0) { xfree(reply_pkt_buf); reply_pkt_buf = 0; return -1; } xfree(reply_pkt_buf); reply_pkt_buf = 0; clear_directory(global->run_work_dir); last_activity_time = time(0); continue; report_check_failed_and_continue:; memset(&reply_pkt, 0, sizeof(reply_pkt)); reply_pkt.judge_id = srgp->judge_id; reply_pkt.contest_id = srgp->contest_id; reply_pkt.run_id = srgp->run_id; reply_pkt.user_status = -1; reply_pkt.user_tests_passed = -1; reply_pkt.user_score = -1; reply_pkt.ts1 = srgp->ts1; reply_pkt.ts1_us = srgp->ts1_us; reply_pkt.ts2 = srgp->ts2; reply_pkt.ts2_us = srgp->ts2_us; reply_pkt.ts3 = srgp->ts3; reply_pkt.ts3_us = srgp->ts3_us; reply_pkt.ts4 = srgp->ts4; reply_pkt.ts4_us = srgp->ts4_us; get_current_time(&reply_pkt.ts5, &reply_pkt.ts5_us); reply_pkt.ts6 = reply_pkt.ts5; reply_pkt.ts6_us = reply_pkt.ts5_us; reply_pkt.ts7 = reply_pkt.ts5; reply_pkt.ts7_us = reply_pkt.ts5_us; reply_pkt.status = RUN_CHECK_FAILED; reply_pkt.failed_test = 0; reply_pkt.score = -1; if (run_reply_packet_write(&reply_pkt, &reply_pkt_buf_size, &reply_pkt_buf) < 0) { // oops :( abort(); } if (generic_write_file(errmsg, strlen(errmsg), 0, full_report_dir, run_base, "") < 0 || generic_write_file(reply_pkt_buf, reply_pkt_buf_size, SAFE, full_status_dir, run_base, "") < 0) { err("error writing check failed packet"); } clear_directory(global->run_work_dir); } srp = super_run_in_packet_free(srp); xfree(srp_b); srp_b = NULL; srp_z = 0; return 0; }
static CamelFolderInfo * scan_dir (CamelStore *store, GHashTable *visited, CamelFolderInfo *parent, const gchar *root, const gchar *name, guint32 flags, GError **error) { CamelFolderInfo *folders, *tail, *fi; GHashTable *folder_hash; const gchar *dent; GDir *dir; tail = folders = NULL; if (!(dir = g_dir_open (root, 0, NULL))) return NULL; folder_hash = g_hash_table_new (g_str_hash, g_str_equal); /* FIXME: it would be better if we queue'd up the recursive * scans till the end so that we can limit the number of * directory descriptors open at any given time... */ while ((dent = g_dir_read_name (dir))) { gchar *short_name, *full_name, *path, *ext; struct stat st; if (dent[0] == '.') continue; if (ignore_file (dent, FALSE)) continue; path = g_strdup_printf ("%s/%s", root, dent); if (g_stat (path, &st) == -1) { g_free (path); continue; } #ifndef G_OS_WIN32 if (S_ISDIR (st.st_mode)) { struct _inode in = { st.st_dev, st.st_ino }; if (g_hash_table_lookup (visited, &in)) { g_free (path); continue; } } #endif short_name = g_strdup (dent); if ((ext = strrchr (short_name, '.')) && !strcmp (ext, ".sbd")) *ext = '\0'; if (name != NULL) full_name = g_strdup_printf ("%s/%s", name, short_name); else full_name = g_strdup (short_name); if ((fi = g_hash_table_lookup (folder_hash, short_name)) != NULL) { g_free (short_name); g_free (full_name); if (S_ISDIR (st.st_mode)) { fi->flags = (fi->flags & ~CAMEL_FOLDER_NOCHILDREN) | CAMEL_FOLDER_CHILDREN; } else { fi->flags &= ~CAMEL_FOLDER_NOSELECT; } } else { fi = camel_folder_info_new (); fi->parent = parent; fi->full_name = full_name; fi->display_name = short_name; fi->unread = -1; fi->total = -1; if (S_ISDIR (st.st_mode)) fi->flags = CAMEL_FOLDER_NOSELECT; else fi->flags = CAMEL_FOLDER_NOCHILDREN; if (tail == NULL) folders = fi; else tail->next = fi; tail = fi; g_hash_table_insert (folder_hash, fi->display_name, fi); } if (!S_ISDIR (st.st_mode)) { fill_fi (store, fi, flags); } else if ((flags & CAMEL_STORE_FOLDER_INFO_RECURSIVE)) { struct _inode in = { st.st_dev, st.st_ino }; if (g_hash_table_lookup (visited, &in) == NULL) { #ifndef G_OS_WIN32 struct _inode *inew = g_new (struct _inode, 1); *inew = in; g_hash_table_insert (visited, inew, inew); #endif if ((fi->child = scan_dir (store, visited, fi, path, fi->full_name, flags, error))) fi->flags |= CAMEL_FOLDER_CHILDREN; else fi->flags = (fi->flags & ~CAMEL_FOLDER_CHILDREN) | CAMEL_FOLDER_NOCHILDREN; } } g_free (path); } g_dir_close (dir); g_hash_table_destroy (folder_hash); return folders; }
/* Main function */ int main(int argc, char **argv) { int rc = -1, local_brightness = -1; int exit_status = EXIT_SUCCESS; unsigned seed; char *annfile = NULL; char cfgpath[PATH_MAX]; char current_wallpaper[PATH_MAX] = "\0"; char dbfile[PATH_MAX]; char wallpaper_path[PATH_MAX] = "\0"; struct arguments arguments; struct fann *ann = NULL; GSettings *settings = NULL; sqlite3 *db = NULL; /* Default argument values */ arguments.brightness = -1; arguments.interactive = 0; arguments.latitude = -1; arguments.longitude = -1; arguments.recursion = 0; arguments.scan = 0; arguments.time = 0; arguments.verbose = 0; /* Parse arguments; every option seen by parse_opt will be reflected in arguments. */ argp_parse(&argp, argc, argv, 0, 0, &arguments); /* Define the wallpaper state */ struct wallpaper_state wallpaper = { arguments.args[0], current_wallpaper, wallpaper_path }; if ( !g_file_test(wallpaper.dir, G_FILE_TEST_IS_DIR) ) { fprintf(stderr, "Cannot access directory %s\n", wallpaper.dir); exit_status = EXIT_FAILURE; goto Return; } /* Set the user specific data storage folder. The folder is automatically created if it doesn't already exist. */ get_user_data_folder(cfgpath, sizeof cfgpath, "nextwall"); if (cfgpath[0] == 0) { fprintf(stderr, "Error: Unable to set the data storage folder.\n"); exit_status = EXIT_FAILURE; goto Return; } /* Set the database file path */ strcpy(dbfile, cfgpath); strcat(dbfile, "nextwall.db"); /* Find the location of the ANN file */ if (arguments.scan) { int i, ann_found; char *annfiles[3]; if (asprintf(&annfile, "%snextwall.net", cfgpath) == -1) { fprintf(stderr, "asprintf() failed: %s\n", strerror(errno)); exit_status = EXIT_FAILURE; goto Return; } annfiles[0] = annfile; annfiles[1] = "/usr/local/share/nextwall/nextwall.net"; annfiles[2] = "/usr/share/nextwall/nextwall.net"; for (i = 0; i < 3; i++) { if ( (ann_found = g_file_test(annfiles[i], G_FILE_TEST_IS_REGULAR)) ) { eprintf("Using ANN %s\n", annfiles[i]); /* Initialize the ANN */ ann = fann_create_from_file(annfiles[i]); break; } } if (!ann_found) { fprintf(stderr, "Error: Could not find ANN file nextwall.net\n"); exit_status = EXIT_FAILURE; goto Return; } } /* Create the database if it doesn't exist */ if ( !g_file_test(dbfile, G_FILE_TEST_IS_REGULAR) ) { eprintf("Creating database... "); if ( (rc = sqlite3_open(dbfile, &db)) == SQLITE_OK && \ create_database(db) == 0 ) { eprintf("Done\n"); } else { eprintf("Failed\n"); fprintf(stderr, "Error: Creating database failed.\n"); exit_status = EXIT_FAILURE; goto Return; } } /* Open database connection */ if ( rc != SQLITE_OK ) { if ( sqlite3_open(dbfile, &db) != SQLITE_OK ) { fprintf(stderr, "Error: Can't open database: %s\n", sqlite3_errmsg(db)); exit_status = EXIT_FAILURE; goto Return; } } /* Search directory for wallpapers */ if (arguments.scan) { int found; fprintf(stderr, "Scanning for new wallpapers..."); found = scan_dir(db, wallpaper.dir, ann, arguments.recursion); fann_destroy(ann); fprintf(stderr, " Done\n"); fprintf(stderr, "Found %d new wallpapers\n", found); goto Return; } /* Get local brightness */ if (arguments.time) { if (arguments.brightness == -1) local_brightness = get_local_brightness(arguments.latitude, arguments.longitude); else local_brightness = arguments.brightness; switch (local_brightness) { case 0: eprintf("Selecting wallpaper for night.\n"); break; case 1: eprintf("Selecting wallpapers for twilight.\n"); break; case 2: eprintf("Selecting wallpaper for day.\n"); break; default: fprintf(stderr, "Error: Could not determine the local " \ "brightness value.\n"); exit_status = EXIT_FAILURE; goto Return; } } /* Set the seed for the random number generator */ if ( read(open("/dev/urandom", O_RDONLY), &seed, sizeof seed) == -1 ) { exit_status = EXIT_FAILURE; goto Return; } srand(seed); /* Set the wallpaper path */ if ( (nextwall(db, wallpaper.dir, local_brightness, wallpaper.path)) == -1 ) { fprintf(stderr, "No wallpapers found for directory %s. Try the " \ "--scan option or remove the --time option.\n", wallpaper.dir); goto Return; } /* Create a GSettings object for the desktop background */ settings = g_settings_new("org.gnome.desktop.background"); if (arguments.interactive) { char* input, shell_prompt[100]; fprintf(stderr, "Nextwall %s\n" \ "License: GNU GPL version 3 or later " \ "<http://gnu.org/licenses/gpl.html>\n" \ "Type 'help' for more information.\n", PACKAGE_VERSION); // Configure readline to auto-complete paths when the tab key is hit. rl_bind_key('\t', rl_complete); // Set the prompt text. snprintf(shell_prompt, sizeof(shell_prompt), "nextwall> "); for(;;) { // Display prompt and read input. input = readline(shell_prompt); // Check for EOF. if (!input) { fprintf(stderr, "\n"); break; } // If the line has any text in it, save it on the history. if (input && *input) add_history(input); // Check if the directory still exists. if ( !g_file_test(wallpaper.dir, G_FILE_TEST_IS_DIR) ) { fprintf(stderr, "Cannot access directory %s\n", wallpaper.dir); exit_status = EXIT_FAILURE; goto Return; } if (strcmp(input, "d") == 0) { get_background_uri(settings, wallpaper.current); fprintf(stderr, "Move wallpaper %s to trash? (y/N) ", wallpaper.current); if ( (input = readline("")) && strcmp(input, "y") == 0 && \ remove_wallpaper(db, wallpaper.current) == 0 ) { fprintf(stderr, "Wallpaper removed\n"); if ( set_wallpaper(settings, db, local_brightness, &wallpaper) == -1) goto Return; } } else if (strcmp(input, "") == 0 || strcmp(input, "n") == 0) { if (set_wallpaper(settings, db, local_brightness, &wallpaper) == -1) goto Return; } else if (strcmp(input, "o") == 0) { get_background_uri(settings, wallpaper.current); open_image(wallpaper.current); } else if (strcmp(input, "help") == 0) { fprintf(stderr, "Nextwall is now running in interactive mode. The " \ "following commands are available:\n" \ "'d'\tDelete the current wallpaper\n" \ "'n'\tNext wallpaper (default)\n" \ "'o'\tOpen the current wallpaper\n" \ "'q'\tExit nextwall\n"); } else if (strcmp(input, "q") == 0) { goto Return; } else { fprintf(stderr, "Unknown command. Type 'help' to see the " \ "available commands.\n"); } // Free input. free(input); } } else { set_wallpaper(settings, db, local_brightness, &wallpaper); } goto Return; Return: if (annfile) free(annfile); if (settings) g_object_unref(settings); if (db) sqlite3_close(db); return exit_status; }
int main(int argc,char* argv[]) {//argv[1]为要扫描的文件路径 scan_dir(argv[1],1); return 0; }
int getevent_main(int argc, char *argv[]) { int c; int i; int res; int get_time = 0; int print_device = 0; char *newline = "\n"; uint16_t get_switch = 0; struct input_event event; int print_flags = 0; int print_flags_set = 0; int dont_block = -1; int event_count = 0; int sync_rate = 0; int64_t last_sync_time = 0; const char *device = NULL; const char *device_path = "/dev/input"; opterr = 0; do { c = getopt(argc, argv, "tns:Sv::dpilqc:rh"); if (c == EOF) break; switch (c) { case 't': get_time = 1; break; case 'n': newline = ""; break; case 's': get_switch = strtoul(optarg, NULL, 0); if(dont_block == -1) dont_block = 1; break; case 'S': get_switch = ~0; if(dont_block == -1) dont_block = 1; break; case 'v': if(optarg) print_flags |= strtoul(optarg, NULL, 0); else print_flags |= PRINT_DEVICE | PRINT_DEVICE_NAME | PRINT_DEVICE_INFO | PRINT_VERSION; print_flags_set = 1; break; case 'd': print_flags |= PRINT_HID_DESCRIPTOR; break; case 'p': print_flags |= PRINT_DEVICE_ERRORS | PRINT_DEVICE | PRINT_DEVICE_NAME | PRINT_POSSIBLE_EVENTS | PRINT_INPUT_PROPS; print_flags_set = 1; if(dont_block == -1) dont_block = 1; break; case 'i': print_flags |= PRINT_ALL_INFO; print_flags_set = 1; if(dont_block == -1) dont_block = 1; break; case 'l': print_flags |= PRINT_LABELS; break; case 'q': print_flags_set = 1; break; case 'c': event_count = atoi(optarg); dont_block = 0; break; case 'r': sync_rate = 1; break; case '?': fprintf(stderr, "%s: invalid option -%c\n", argv[0], optopt); case 'h': usage(argv[0]); exit(1); } } while (1); if(dont_block == -1) dont_block = 0; if (optind + 1 == argc) { device = argv[optind]; optind++; } if (optind != argc) { usage(argv[0]); exit(1); } nfds = 1; ufds = calloc(1, sizeof(ufds[0])); ufds[0].fd = inotify_init(); ufds[0].events = POLLIN; if(device) { if(!print_flags_set) print_flags |= PRINT_DEVICE_ERRORS; res = open_device(device, print_flags); if(res < 0) { return 1; } } else { if(!print_flags_set) print_flags |= PRINT_DEVICE_ERRORS | PRINT_DEVICE | PRINT_DEVICE_NAME; print_device = 1; res = inotify_add_watch(ufds[0].fd, device_path, IN_DELETE | IN_CREATE); if(res < 0) { fprintf(stderr, "could not add watch for %s, %s\n", device_path, strerror(errno)); return 1; } res = scan_dir(device_path, print_flags); if(res < 0) { fprintf(stderr, "scan dir failed for %s\n", device_path); return 1; } } if(get_switch) { for(i = 1; i < nfds; i++) { uint16_t sw; res = ioctl(ufds[i].fd, EVIOCGSW(1), &sw); if(res < 0) { fprintf(stderr, "could not get switch state, %s\n", strerror(errno)); return 1; } sw &= get_switch; printf("%04x%s", sw, newline); } } if(dont_block) return 0; while(1) { //int pollres = poll(ufds, nfds, -1); //printf("poll %d, returned %d\n", nfds, pollres); if(ufds[0].revents & POLLIN) { read_notify(device_path, ufds[0].fd, print_flags); } for(i = 1; i < nfds; i++) { if(ufds[i].revents) { if(ufds[i].revents & POLLIN) { res = read(ufds[i].fd, &event, sizeof(event)); if(res < (int)sizeof(event)) { fprintf(stderr, "could not get event\n"); return 1; } if(get_time) { printf("[%8ld.%06ld] ", event.time.tv_sec, event.time.tv_usec); } if(print_device) printf("%s: ", device_names[i]); print_event(event.type, event.code, event.value, print_flags); if(sync_rate && event.type == 0 && event.code == 0) { int64_t now = event.time.tv_sec * 1000000LL + event.time.tv_usec; if(last_sync_time) printf(" rate %lld", 1000000LL / (now - last_sync_time)); last_sync_time = now; } printf("%s", newline); if(event_count && --event_count == 0) return 0; } } } } return 0; }
int main(int argc, char *argv[]) { // read options char *dir = NULL; short badarg = 0; int opt; while ((opt = getopt(argc, argv, "d:")) != -1) { if (opt == 'd') dir = optarg; else badarg = 1; } if (badarg) { print_usage(); return 1; } // change dir dir = flon_path(argv[0], dir); if (chdir(dir) != 0) { fgaj_r("couldn't chdir to %s", dir); return 1; } fgaj_i("-d %s", dir); // load configuration if (flon_configure(".") != 0) { fgaj_r("couldn't read %s/etc/flon.json, cannot start", dir); return 1; } free(dir); // set up logging flon_setup_logging("dispatcher"); // scan once scan_dir(); // load timers flon_load_timers(); // then, ev... struct ev_loop *l = ev_default_loop(0); // watch var/spool/dis/ ev_stat est; ev_stat_init(&est, spool_cb, "var/spool/dis/", 0.); ev_stat_start(l, &est); // check from time to time too ev_periodic epe; ev_periodic_init(&epe, trigger_cb, 0., .35, trigger_reschedule_cb); ev_periodic_start(l, &epe); //ev_timer eti; //ev_timer_init(&eti, do_something_when_loop_ready_cb, 0., 0.); //ev_timer_start(l, &eti); ev_signal esi; ev_signal_init(&esi, sighup_cb, SIGHUP); ev_signal_start(l, &esi); // loop //fgaj_i("about to ev_loop..."); ev_loop(l, 0); fgaj_r("something went wrong"); }
std::vector<Dimension> MrsidReader::getDefaultDimensions() { std::vector<Dimension> output; Dimension x("X", dimension::Float, 8); x.setUUID("8c54ff0c-234f-43a2-8959-d9681ad1dea3"); x.setNamespace(s_getName()); output.push_back(x); Dimension y("Y", dimension::Float, 8); y.setUUID("9cee971b-2505-40cd-b7e9-f32c399afac7"); y.setNamespace(s_getName()); output.push_back(y); Dimension z("Z", dimension::Float, 8); z.setUUID("89dc4e36-6166-4bc8-bf95-5660657b0ea6"); z.setNamespace(s_getName()); output.push_back(z); Dimension t("Time", dimension::Float, 8); t.setUUID("3aea2826-4a6e-4c1b-ae27-7b2f24763ce1"); t.setNamespace(s_getName()); output.push_back(t); Dimension blue("Blue", dimension::UnsignedInteger, 2); blue.setUUID("f69977e3-23e8-4483-91b6-14cad981e9fd"); blue.setNamespace(s_getName()); output.push_back(blue); Dimension red("Red", dimension::UnsignedInteger, 2); red.setUUID("40a02a80-c399-42f0-a587-a286635b446e"); red.setNamespace(s_getName()); output.push_back(red); Dimension green("Green", dimension::UnsignedInteger, 2); green.setUUID("b329df2d-44f1-4f35-8993-d183dacaa1ff"); green.setNamespace(s_getName()); output.push_back(green); Dimension cls("Classification", dimension::UnsignedInteger, 1); cls.setUUID("ba1e2af8-6dfd-46a7-972a-ecc00f68914d"); cls.setNamespace(s_getName()); output.push_back(cls); Dimension edge("EdgeOfFlightLine", dimension::UnsignedInteger, 1); edge.setUUID("daed3bfc-650d-4265-93a7-d8093cbd75a0"); edge.setNamespace(s_getName()); output.push_back(edge); Dimension intensity("Intensity", dimension::UnsignedInteger, 2); intensity.setUUID("a43332a8-26b3-4609-a2b1-ddfda30e0565"); intensity.setNamespace(s_getName()); output.push_back(intensity); Dimension num_returns("NumberOfReturns", dimension::UnsignedInteger, 1); num_returns.setUUID("fa7c5d56-fb2b-4f81-9126-f183000c3cd8"); num_returns.setNamespace(s_getName()); output.push_back(num_returns); Dimension return_no("ReturnNumber", dimension::UnsignedInteger, 1); return_no.setUUID("e38cc121-8d26-482a-8920-c5599b2cdd19"); return_no.setNamespace(s_getName()); output.push_back(return_no); Dimension scan_angle("ScanAngleRank", dimension::UnsignedInteger, 1); scan_angle.setUUID("5d816875-10a5-4048-ad9d-fd3b8d065a6a"); scan_angle.setNamespace(s_getName()); output.push_back(scan_angle); Dimension scan_dir("ScanDirectionFlag", dimension::UnsignedInteger, 1); scan_dir.setUUID("d1054379-8bf6-4685-abfc-1f0ec37aa819"); scan_dir.setNamespace(s_getName()); output.push_back(scan_dir); Dimension ptsource("PointSourceId", dimension::UnsignedInteger, 2); ptsource.setUUID("be6e71af-b2f7-4107-a902-96e2fb71343f"); ptsource.setNamespace(s_getName()); output.push_back(ptsource); Dimension userdata("UserData", dimension::UnsignedInteger, 1); userdata.setUUID("551ca4be-cb6e-47a4-93a9-e403e9a06a8a"); userdata.setNamespace(s_getName()); output.push_back(userdata); return output; }
uint16_t scan_dir(char* path, char mkdb, uint32_t this_dir_tgt) { DIR dir; FILINFO fno; FRESULT res; uint8_t len; unsigned char* fn; static unsigned char depth = 0; static uint16_t crc; static uint32_t db_tgt; static uint32_t next_subdir_tgt; static uint32_t parent_tgt; static uint32_t dir_end = 0; static uint8_t was_empty = 0; uint32_t dir_tgt; uint16_t numentries; uint32_t dirsize; uint8_t pass = 0; dir_tgt = this_dir_tgt; if(depth==0) { crc = 0; db_tgt = SRAM_DB_ADDR+0x10; dir_tgt = SRAM_DIR_ADDR; next_subdir_tgt = SRAM_DIR_ADDR; this_dir_tgt = SRAM_DIR_ADDR; parent_tgt = 0; dprintf("root dir @%lx\n", dir_tgt); } fno.lfn = file_lfn; numentries=0; for(pass = 0; pass < 2; pass++) { if(pass) { dirsize = 4*(numentries); // dir_tgt_next = dir_tgt + dirsize + 4; // number of entries + end marker next_subdir_tgt += dirsize + 4; if(parent_tgt) next_subdir_tgt += 4; if(next_subdir_tgt > dir_end) { dir_end = next_subdir_tgt; } dprintf("path=%s depth=%d ptr=%lx entries=%d parent=%lx next subdir @%lx\n", path, depth, db_tgt, numentries, parent_tgt, next_subdir_tgt /*dir_tgt_next*/); // _delay_ms(50); if(mkdb) { dprintf("d=%d Saving %lX to Address %lX [end]\n", depth, 0L, next_subdir_tgt - 4); // _delay_ms(50); sram_writelong(0L, next_subdir_tgt - 4); } } res = f_opendir(&dir, (unsigned char*)path); if (res == FR_OK) { if(pass && parent_tgt && mkdb) { // write backlink to parent dir // switch to next bank if record does not fit in current bank if((db_tgt&0xffff) > ((0x10000-(sizeof(next_subdir_tgt)+sizeof(len)+4))&0xffff)) { dprintf("switch! old=%lx ", db_tgt); db_tgt &= 0xffff0000; db_tgt += 0x00010000; dprintf("new=%lx\n", db_tgt); } sram_writelong((parent_tgt-SRAM_MENU_ADDR), db_tgt); sram_writebyte(0, db_tgt+sizeof(next_subdir_tgt)); sram_writeblock("../\0", db_tgt+sizeof(next_subdir_tgt)+sizeof(len), 4); sram_writelong((db_tgt-SRAM_MENU_ADDR)|((uint32_t)0x80<<24), dir_tgt); db_tgt += sizeof(next_subdir_tgt)+sizeof(len)+4; dir_tgt += 4; } len = strlen((char*)path); for (;;) { toggle_busy_led(); res = f_readdir(&dir, &fno); if (res != FR_OK || fno.fname[0] == 0) { if(pass) { if(!numentries) was_empty=1; } break; } fn = *fno.lfn ? fno.lfn : fno.fname; // dprintf("%s\n", fn); // _delay_ms(100); if (*fn == '.') continue; if (fno.fattrib & AM_DIR) { numentries++; if(pass) { path[len]='/'; strncpy(path+len+1, (char*)fn, sizeof(fs_path)-len); depth++; if(mkdb) { uint16_t pathlen = strlen(path); // write element pointer to current dir structure dprintf("d=%d Saving %lX to Address %lX [dir]\n", depth, db_tgt, dir_tgt); // _delay_ms(50); sram_writelong((db_tgt-SRAM_MENU_ADDR)|((uint32_t)0x80<<24), dir_tgt); // sram_writeblock((uint8_t*)&db_tgt, dir_tgt_save, sizeof(dir_tgt_save)); // save element: // - path name // - pointer to sub dir structure if((db_tgt&0xffff) > ((0x10000-(sizeof(next_subdir_tgt) + sizeof(len) + pathlen + 2))&0xffff)) { dprintf("switch! old=%lx ", db_tgt); db_tgt &= 0xffff0000; db_tgt += 0x00010000; dprintf("new=%lx\n", db_tgt); } dprintf(" Saving dir descriptor to %lX, tgt=%lX, path=%s\n", db_tgt, next_subdir_tgt, path); // _delay_ms(100); sram_writelong((next_subdir_tgt-SRAM_MENU_ADDR), db_tgt); sram_writebyte(len+1, db_tgt+sizeof(next_subdir_tgt)); sram_writeblock(path, db_tgt+sizeof(next_subdir_tgt)+sizeof(len), pathlen); sram_writeblock("/\0", db_tgt + sizeof(next_subdir_tgt) + sizeof(len) + pathlen, 2); // sram_writeblock((uint8_t*)&dir_tgt, db_tgt+256, sizeof(dir_tgt)); db_tgt += sizeof(next_subdir_tgt) + sizeof(len) + pathlen + 2; } parent_tgt = this_dir_tgt; scan_dir(path, mkdb, next_subdir_tgt); dir_tgt += 4; // if(was_empty)dir_tgt_next += 4; was_empty = 0; depth--; path[len]=0; } } else { SNES_FTYPE type = determine_filetype((char*)fn); if(type != TYPE_UNKNOWN) { numentries++; if(pass) { if(mkdb) { snes_romprops_t romprops; path[len]='/'; strncpy(path+len+1, (char*)fn, sizeof(fs_path)-len); uint16_t pathlen = strlen(path); switch(type) { case TYPE_SMC: // XXX file_open_by_filinfo(&fno); // XXX if(file_res){ // XXX dprintf("ZOMG NOOOO %d\n", file_res); // XXX _delay_ms(30); // XXX } // XXX smc_id(&romprops); // XXX file_close(); // _delay_ms(30); // write element pointer to current dir structure // dprintf("d=%d Saving %lX to Address %lX [file]\n", depth, db_tgt, dir_tgt); // _delay_ms(50); if((db_tgt&0xffff) > ((0x10000-(sizeof(romprops) + sizeof(len) + pathlen + 1))&0xffff)) { dprintf("switch! old=%lx ", db_tgt); db_tgt &= 0xffff0000; db_tgt += 0x00010000; dprintf("new=%lx\n", db_tgt); } sram_writelong((db_tgt-SRAM_MENU_ADDR), dir_tgt); // sram_writeblock((uint8_t*)&db_tgt, dir_tgt, sizeof(db_tgt)); dir_tgt += 4; // save element: // - SNES header information // - file name sram_writeblock((uint8_t*)&romprops, db_tgt, sizeof(romprops)); sram_writebyte(len+1, db_tgt + sizeof(romprops)); sram_writeblock(path, db_tgt + sizeof(romprops) + sizeof(len), pathlen + 1); db_tgt += sizeof(romprops) + sizeof(len) + pathlen + 1; break; case TYPE_UNKNOWN: default: break; } path[len]=0; // dprintf("%s ", path); // _delay_ms(30); } } else { unsigned char* sfn = fno.fname; while(*sfn != 0) { crc += crc16_update(crc, sfn++, 1); } } } // dprintf("%s/%s\n", path, fn); // _delay_ms(50); } } } else uart_putc(0x30+res); } // dprintf("%x\n", crc); // _delay_ms(50); sram_writelong(db_tgt, SRAM_DB_ADDR+4); sram_writelong(dir_end, SRAM_DB_ADDR+8); return crc; }