int main(int argc, char** argv) { int showhelp = 0; unsigned int channels = 1; int window_size = 1024; int shift = 256; int rate = 8000; snd_pcm_format_t format = SND_PCM_FORMAT_UNKNOWN; int opt; while ((opt = getopt(argc, argv, "hw:s:r:f:")) != -1) { switch (opt) { case 'h': showhelp = 1; break; case 'w': window_size = atoi(optarg); break; case 's': shift = atoi(optarg); break; case 'r': rate = atoi(optarg); break; case 'f': format = snd_pcm_format_value(optarg); break; default: /* '?' */ showhelp = 1; break; } } if (showhelp || argc - optind < 1) { fprintf(stderr, "Usage: %s [-w window_size] [-s shift] " "[-r sampling rate] [-f format] <inputFile>\n", argv[0]); exit(EXIT_SUCCESS); } if (format == SND_PCM_FORMAT_UNKNOWN) { fprintf(stderr, "Unknown format\n"); exit(EXIT_FAILURE); } FILE* input = fopen(argv[optind], "r"); if (input == NULL) { fprintf(stderr, "Cannot Open File %s : %s\n", argv[optind], strerror(errno)); exit(EXIT_FAILURE); } // Load Audio File double** data; unsigned long int count = pcm_size(input, channels, format); count = read_file(input, count, channels, format, &data); fprintf(stderr, "%lu samples read\n", count); fclose(input); // Transform int nos = number_of_spectrum(count, window_size, shift); TimeFreq* tf = alloc_tf(window_size, nos); stft(data[0], count, window_size, shift, tf); printf("set style line 11 lc rgb '#808080' lt 1\n" "set border 3 front ls 11\n" "set tics nomirror out scale 0.75\n" "unset key\n" "unset colorbox\n" "set palette defined (0 '#000090', 1 '#000fff', 2 '#0090ff', 3 '#0fffee', 4 '#90ff70', 5 '#ffee00', 6 '#ff7000', 7 '#ee0000', 8 '#7f0000')\n" "set xlabel 'Time (s)'\n" "set ylabel 'Frequency (Hz)'\n"); printf("set yrange [0:%g]\n", (double) rate / 2.0); printf("set xrange [0:%g]\n", (double) count / rate); printf("plot '-' matrix using (($2 + 0.5) * %g) : (($1 + 0.5) * %g) : (log($3))" " with image\n", (double) shift / rate, (double) rate / window_size); int i, j; for (i = 0; i < nos; i++) { Spectra s = get_spectra(tf, i); for (j = 0; j < window_size / 2 + 1; j++) { printf("%g ", get_magnitude(s, j)); } printf("\n"); } printf("e\n"); // Free memory free_data(data, channels); free_tf(tf); exit(EXIT_SUCCESS); }
int contact_tracker(bt_args_t *bt_args) { printf("Please wait ...\nConnecting with tracker.\n"); char *new_file; long long leng; new_file = read_file(bt_args->torrent_file, &leng); if (!new_file) return 1; char *inf = strstr(strstr(new_file, "info"), "d"); // length on ubuntu 14.04 torrent should be 44478 long long len = be_len(inf); memset(bt_args->info_hash, '\0', BT_INFO_HASH_SIZE); memset(bt_args->bt_peer_id, '\0', BT_INFO_HASH_SIZE); SHA1((unsigned char const *) inf, (size_t) len, (unsigned char *) bt_args->info_hash); char *request_to_send = malloc(FILE_NAME_MAX); request_to_send = malloc(FILE_NAME_MAX); memset(request_to_send, '\0', FILE_NAME_MAX); memcpy(bt_args->bt_peer_id, generate_peer_id(), 20); //Port number this peer is listening on. //Common behavior is for a downloader to try to listen on //port 6881 and if that port is taken try 6882, then 6883, etc. and give up after 6889. uint16_t port = INIT_PORT; bt_args->bt_info->num_pieces = bt_args->bt_info->length / bt_args->bt_info->piece_length; sprintf(request_to_send, "%s?info_hash=%s&peer_id=%s&port=%hu&uploaded=0" "&downloaded=0&left=%d&event=started&compact=1", bt_args->bt_info->announce, url_encode(bt_args->info_hash), url_encode(bt_args->bt_peer_id), port, bt_args->bt_info->length); // correct request to send on ubuntu torrent // http://torrent.ubuntu.com:6969/announce? // info_hash=%B4%15%C9%13d%3E%5F%F4%9F%E3%7D0K%BB%5En%11%ADQ%01 // announce?info_hash=%b4%15%c9%13d%3e_%f4%9f%e3%7d0K%bb%5en%11%adQ%01 // &peer_id=TueFeb32137332015RRR&port=6681&event=started&uploaded=0 // &downloaded=0&left=1162936320&compact=1 if (bt_args->verbose) printf("Request URL for tracker: %s\n", request_to_send); char *result = _send_http_request(request_to_send); if (result) { be_node *node = be_decoden(result, (long long int) be_len); if (bt_args->verbose) be_dump(node); bt_peer *peer = malloc(sizeof(bt_peer)); // parse_info(peer, node); _fill_peer_info(peer, node, 0, ""); int num_peers = 0; char *peer_num = strstr(result, "peers"); if (peer_num == NULL) { printf("Something went wrong in parsing received data!\n"); free(result); return 1; } int i = 0; peer_num += 5; char buff[20]; memset(buff, 0, 20); for (; *peer_num != ':'; peer_num++, i++) buff[i] = *peer_num; char *endptr; num_peers = (int) strtol(buff, &endptr, 10) / 6; if (num_peers == 0) { free(result); return 1; } int count = 0; pthread_t *thread = malloc(num_peers * sizeof(pthread_t)); printf("Connecting with peers.\n"); for (i = 0; i < num_peers; i++) { uint32_t ip = *(uint32_t *) (peer->peer_hashes + count); count = (int) (count + sizeof(uint32_t)); port = *(uint16_t *) (peer->peer_hashes + count); count = (int) (count + sizeof(uint16_t)); peer_t *my_peer_t = malloc(sizeof(peer_t)); my_peer_t->interested = -1; my_peer_t->choked = -1; //IP to string struct in_addr ip_addr; ip_addr.s_addr = ip; char *id = malloc(21); memset(id, 0, 21); calc_id(inet_ntoa(ip_addr), port, id); memset(my_peer_t->id, 0, ID_SIZE); strcpy((char *) my_peer_t->id, id); init_peer(my_peer_t, id, inet_ntoa(ip_addr), htons(port)); add_peer(my_peer_t, bt_args, inet_ntoa(ip_addr), port); thdata *data = malloc(sizeof(thdata)); data->th_num = i; data->bt_args = bt_args; data->bt_peer_t = my_peer_t; pthread_create (&thread[i], NULL, (void *) &_connect_function, (void *) data); } for (i = 0; i < num_peers; i++); pthread_join(thread[i], NULL); } else { printf("Something went wrong!\n"); return 1; } return 0; }
int SSL_CTX_use_certificate_file(SSL_CTX* ctx, const char* file, int format) { return read_file(ctx, file, format, Cert); }
string HighlightCutoffEffect::output_fragment_shader() { return read_file("highlight_cutoff_effect.frag"); }
int main(int argc, char **argv) { init_buf(); if (argc > 1) strncpy(file_name, argv[1], BUFSIZ); else strcpy(file_name, "untitled.txt"); read_file(file_name); initscr(); cbreak(); noecho(); if (has_colors()) { int white; start_color(); if (COLORS > 255) white = 231; else if (COLORS > 87) white = 79; else white = 15; init_pair(1, white, 0); minibuf_attrs = COLOR_PAIR(1); } else { minibuf_attrs = A_BOLD; } while (TRUE) { int ch; // Redisplay drop_until(getmaxy(stdscr) / 2); print_queue(); mbuf_display(); refresh(); // Wait for input switch ((ch = getch())) { case EOF: case '\x04': // ^D quit(); case '\x08': // ^H case '\x7f': // DEL del_buf(buf.i - 1); break; case '\x17': // ^W del_buf(buf.wbeg); break; case '\x15': // ^U reset_buf(""); break; case '\x1b': // ESC mbuf_msg("Press CTRL+D to quit"); break; case '\r': case '\n': append_buf('\n'); break; default: mbuf_msg(file_name); if (ch > '\x1f') append_buf(ch); } } return 0; }
string SaturationEffect::output_fragment_shader() { return read_file("saturation_effect.frag"); }
int main(int argc, char *argv[]) { HTNODE ht[MAX]; HTNODE hs[MAX]; Char_code *head; Char_code *p; CODE *code; CODE *q; char data[MAX][MAX]; char data1[MAX][MAX]; int i; int j; int count = 0; int pch = 0; int qch = 0; int ii, jj; head = read_file(head, "a.png"); count = get_len(head); Creat_Huffman(ht, head, count); Get_Code(ht, data1, count); write_import(ht, data1, count , "c.txt"); code = get_tree(code, "c.txt"); count = get_count(code); Creat_Huffman_file(hs, code, count); Get_Code_file(hs, data, count, code); p = head->next; q = code->next; /* while (p && q) { if (p->ch == 0) { pch++; } if (q->ch == 0) { qch++; } p = p->next; q = q->next; } */ while (p && q) { if (p->ch != q->ch ) { printf("ch butong\n"); printf("p->ch %c %d q->ch %c \n", p->ch,p->ch, q->ch); printf("p->count %d, q->count %d\n", p->count, q->count); getchar(); // getchar(); } if (p->count != q->count) { printf("count butong\n"); printf("%d %d", p->count, q->count); // getchar(); } p = p->next; q = q->next; } if (p || q) { printf("ollllll\n"); getchar(); } trans_to_code(code, "a.png", "data.txt"); Get_Language(hs, count, "data.txt", "b.png"); ii = get_count(code); jj = get_len(head); printf("ii = %d, jj = %d\n", ii, jj); return EXIT_SUCCESS; }
static int read_input_file ( const char *filename, struct input_file *input ) { return read_file ( filename, &input->buf, &input->len ); }
int main(int argc, char *argv[]) { int err; cl_platform_id platform; cl_device_id device; cl_command_queue command_queue; cl_program program; cl_kernel kernel; cl_context context; //##############################// //########OpenCL Stuff##########// //##############################// // find platform and device to use if (!connect_to_device(CL_DEVICE_TYPE_GPU, &platform, &device)) { printf ("Unable to find suitable OpenCL device!\n"); return 1; } char buffer[512]; clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof (buffer), buffer, NULL); printf ("Using device: %s\n", buffer); context = clCreateContext(0, 1, &device, NULL, NULL, &err); if (!context || err != CL_SUCCESS) { printf("ERROR: Failed to create a compute context! %s\n", get_ocl_error(err)); return EXIT_FAILURE; } cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE; command_queue = clCreateCommandQueue (context, device, properties, &err); if (!command_queue || err != CL_SUCCESS) { printf("ERROR: Failed to create a command commands! %s\n", get_ocl_error(err)); return EXIT_FAILURE; } const char *strings[] = {NULL, NULL}; strings[0] = read_file(KERNEL_FILE); if (strings[0] == NULL) { fprintf(stderr, "Unable to find \"%s\"", KERNEL_FILE); return 1; } program = clCreateProgramWithSource(context, 1, (const char **) & strings[0], NULL, &err); if (!program || err != CL_SUCCESS) { printf("ERROR: Failed to create compute program! %s\n", get_ocl_error(err)); return EXIT_FAILURE; } err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (err != CL_SUCCESS) { size_t len; char buffer[2048]; printf("ERROR: Failed to build program executable! %s\n", get_ocl_error(err)); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); return EXIT_FAILURE; } kernel = clCreateKernel(program, KERNEL_FUNC, &err); if (!kernel || err != CL_SUCCESS) { printf("ERROR: Failed to create compute kernel! %s\n", get_ocl_error(err)); exit(1); } edizinami **all_histograms = malloc(0 * sizeof(edizinami*)); if(all_histograms == NULL) { printf("Cannot allocate memory!"); return -1; } // Get all weak classifiers and dataset we'll use read_all_histograms(&all_histograms); for(int i = 0; i < current_size; i++) { int total = 0; //printf("Hallelujah! %s\n", all_histograms[i]->filename); // Initial weights all_histograms[i]->weight = 1 / current_size; } for(int i = 0; i < current_size; i++) { free(all_histograms[i]->filename); free(all_histograms[i]->data); free(all_histograms[i]); } free(all_histograms); clReleaseCommandQueue(command_queue); clReleaseKernel(kernel); clReleaseContext(context); clReleaseProgram(program); return 0; }
int main(int argc, char *argv[]) { int test_num; int task_num; int len; int num_cpus; int migrate = 0; /* For task migration*/ char mygroup[FILENAME_MAX], mytaskfile[FILENAME_MAX]; char mysharesfile[FILENAME_MAX], ch; /* Following variables are to capture parameters from script*/ char *group_num_p, *mygroup_p, *script_pid_p, *num_cpus_p; char *test_num_p, *task_num_p; pid_t pid; gid_t mygroup_num; /* A number attached with a group*/ int fd; /* to open a fifo to synchronize*/ int counter = 0; /* To take n number of readings*/ double total_cpu_time; /* Accumulated cpu time*/ double delta_cpu_time; /* Time the task could run on cpu(s)*/ double prev_cpu_time = 0; double exp_cpu_time; /* Exp time in % by shares calculation*/ struct rusage cpu_usage; time_t current_time, prev_time, delta_time; unsigned int fmyshares, num_tasks; struct sigaction newaction, oldaction; mygroup_num = -1; num_cpus = 0; task_num = 0; test_num = 0; /* Signal handling for alarm*/ sigemptyset(&newaction.sa_mask); newaction.sa_handler = signal_handler_alarm; newaction.sa_flags = 0; sigaction(SIGALRM, &newaction, &oldaction); /* Collect the parameters passed by the script */ group_num_p = getenv("GROUP_NUM"); mygroup_p = getenv("MYGROUP"); script_pid_p = getenv("SCRIPT_PID"); num_cpus_p = getenv("NUM_CPUS"); test_num_p = getenv("TEST_NUM"); task_num_p = getenv("TASK_NUM"); /* Check if all of them are valid */ if ((test_num_p != NULL) && (((test_num = atoi(test_num_p)) == 4) || \ ((test_num = atoi(test_num_p)) == 5))) { if ((group_num_p != NULL) && (mygroup_p != NULL) && \ (script_pid_p != NULL) && (num_cpus_p != NULL) && \ (task_num_p != NULL)) { mygroup_num = atoi(group_num_p); scriptpid = atoi(script_pid_p); num_cpus = atoi(num_cpus_p); task_num = atoi(task_num_p); sprintf(mygroup, "%s", mygroup_p); } else { tst_brkm(TBROK, cleanup, "Invalid other input parameters\n"); } } else { tst_brkm(TBROK, cleanup, "Invalid test number passed\n"); } sprintf(mytaskfile, "%s", mygroup); sprintf(mysharesfile, "%s", mygroup); strcat(mytaskfile, "/tasks"); strcat(mysharesfile, "/cpu.shares"); pid = getpid(); write_to_file(mytaskfile, "a", pid); /* Assign task to it's group*/ fd = open("./myfifo", 0); if (fd == -1) tst_brkm(TBROK, cleanup, "Could not open fifo for synchronization"); read(fd, &ch, 1); /* Block task here to synchronize */ /* * We now calculate the expected % cpu time of this task by getting * it's group's shares, the total shares of all the groups and the * number of tasks in this group. */ FLAG = 0; total_shares = 0; shares_pointer = &total_shares; len = strlen(path); if (!strncpy(fullpath, path, len)) tst_brkm(TBROK, cleanup, "Could not copy directory path %s ", path); if (scan_shares_files(shares_pointer) != 0) tst_brkm(TBROK, cleanup, "From function scan_shares_files in %s ", fullpath); /* return val -1 in case of function error, else 2 is min share value */ if ((fmyshares = read_shares_file(mysharesfile)) < 2) tst_brkm(TBROK, cleanup, "in reading shares files %s ", mysharesfile); if ((read_file(mytaskfile, GET_TASKS, &num_tasks)) < 0) tst_brkm(TBROK, cleanup, "in reading tasks files %s ", mytaskfile); exp_cpu_time = (double)(fmyshares * 100) / (total_shares * num_tasks); prev_time = time(NULL); /* Note down the time*/ while (1) { /* * Need to run some cpu intensive task, which also * frequently checks the timer value */ double f = 274.345, mytime; /*just a float number for sqrt*/ alarm(TIME_INTERVAL); timer_expired = 0; /* * Let the task run on cpu for TIME_INTERVAL. Time of this * operation should not be high otherwise we can exceed the * TIME_INTERVAL to measure cpu usage */ while (!timer_expired) f = sqrt(f * f); current_time = time(NULL); /* Duration in case its not exact TIME_INTERVAL*/ delta_time = current_time - prev_time; getrusage(0, &cpu_usage); /* total_cpu_time = total user time + total sys time */ total_cpu_time = (cpu_usage.ru_utime.tv_sec + cpu_usage.ru_utime.tv_usec * 1e-6 + cpu_usage.ru_stime.tv_sec + cpu_usage.ru_stime.tv_usec * 1e-6) ; delta_cpu_time = total_cpu_time - prev_cpu_time; prev_cpu_time = total_cpu_time; prev_time = current_time; /* calculate % cpu time each task gets */ if (delta_time > TIME_INTERVAL) mytime = (delta_cpu_time * 100) / (delta_time * num_cpus); else mytime = (delta_cpu_time * 100) / (TIME_INTERVAL * num_cpus); fprintf(stdout, "Grp:-%3dDEF task-%3d: CPU TIME{calc:-%6.2f(s)" "i.e. %6.2f(%%)exp:-%6.2f(%%)} with %u(shares) in %lu" " (s)\n", mygroup_num, task_num, delta_cpu_time, mytime, exp_cpu_time, fmyshares, delta_time); counter++; if (counter >= NUM_INTERVALS) { switch (test_num) { case 4: /* Test04 */ exit(0); /* This task is done its job*/ break; case 5: /* Test 05 */ if (migrate == 0) { counter = 0; migrate = 1; } else { exit(0); } break; default: tst_brkm(TBROK, cleanup, "Invalid test number passed\n"); break; } /* end switch*/ } } /* end while*/ } /* end main*/
void filter_calcs(void) { //External variables extern char filtersinput[FILEPATH_LENGTH]; extern char galssedinput[FILEPATH_LENGTH]; extern char starssedinput[FILEPATH_LENGTH]; //Internal variables long *N,ii; long sedlength = 0; long regridfactor; long filterlength[Nfilter]; double *pnorm; double *filtlamb,*filtthru; //Allocate temporary variables N = (long *)malloc(sizeof(long)); pnorm = (double *)malloc(sizeof(double)); //How many filters? get_num_files(filtersinput, N); Nfilter = *N; if (Nfilter<2) { printf("Need more than 1 filter\n"); return; } printf("\n\nFound %ld Filters\n",Nfilter); //Read in the number of star/galaxy SEDs get_num_files(starssedinput, N); Nstartemplate = *N; get_num_files(galssedinput, N); Ngaltemplate = *N; //Find the finest SED amongst the bunch for (ii=0;ii<Nstartemplate;ii++) { get_filelength(ii,starssedinput,N); if (*N * 2 > sedlength) sedlength = *N * 2; } for (ii=0;ii<Ngaltemplate;ii++) { get_filelength(ii,galssedinput,N); if (*N * 2 > sedlength) sedlength = *N * 2; } //Allocate final filter arrays, which are globals filter_lgth_fine = (long *)malloc(Nfilter*sizeof(long)); filter_lamb_fine = malloc(Nfilter*sizeof(double*)); filter_thru_fine = malloc(Nfilter*sizeof(double*)); norm = (double *)malloc(Nfilter*sizeof(double)); //Loop over the filters in the file for (ii=0;ii<Nfilter;ii++) { //get length get_filelength(ii,filtersinput, N); filterlength[ii] = *N; regridfactor = round((float)sedlength / (float)*N); filter_lgth_fine[ii] = *N * regridfactor; //alloc filter arrays filtlamb = (double *)malloc(*N * sizeof(double)); filtthru = (double *)malloc(*N * sizeof(double)); filter_lamb_fine[ii] = (double *)malloc(regridfactor * *N * sizeof(double)); filter_thru_fine[ii] = (double *)malloc(regridfactor * *N * sizeof(double)); //read in the 2 column ascii filter file read_file(ii,filtersinput,filtlamb,filtthru); //regrid the filter to user spec, using gsl spline interpolation regrid_filter(filtlamb,filtthru,filterlength[ii],filter_lgth_fine[ii], \ filter_lamb_fine[ii],filter_thru_fine[ii]); //calculate the flux zeropoint calc_normalization(filter_lamb_fine[ii],filter_thru_fine[ii], \ filter_lgth_fine[ii],pnorm); norm[ii] = *pnorm; printf("Filter %ld has (AB) zeropoint flux normalization: %g\n",ii,norm[ii]); free(filtlamb); free(filtthru); } free(pnorm); free(N); }
void get_serial_info(hd_data_t *hd_data) { char buf[64]; unsigned u0, u1, u2; #if !defined(__PPC__) unsigned u3; #endif int i; str_list_t *sl, *sl0, **sll; serial_t *ser; #if !defined(__PPC__) /* * Max. 44 serial lines at the moment; the serial proc interface is * somewhat buggy at the moment (2.2.13), hence the explicit 44 lines * limit. That may be dropped later. */ sl0 = read_file(PROC_DRIVER_SERIAL, 1, 44); sll = &sl0; while(*sll) sll = &(*sll)->next; // append Agere modem devices *sll = read_file("/proc/tty/driver/agrserial", 1, 17); // ########## FIX !!!!!!!! ######## if(sl0) { for(sl = sl0; sl; sl = sl->next) { i = 0; if( sscanf(sl->str, "%u: uart:%31s port:%x irq:%u baud:%u", &u0, buf, &u1, &u2, &u3) == 5 || (i = 1, sscanf(sl->str, "%u: uart:%31s port:%x irq:%u tx:%u", &u0, buf, &u1, &u2, &u3) == 5) ) { /* * The 'baud' or 'tx' entries are only present for real interfaces. */ ser = add_serial_entry(&hd_data->serial, new_mem(sizeof *ser)); ser->line = u0; if(u1 >= 0x100) ser->port = u1; // Agere modem does not use real port numbers ser->irq = u2; if(!i) ser->baud = u3; ser->name = new_str(buf); } } if((hd_data->debug & HD_DEB_SERIAL)) { /* log just the first 16 entries */ ADD2LOG("----- "PROC_DRIVER_SERIAL" -----\n"); for(sl = sl0, i = 16; sl && i--; sl = sl->next) { ADD2LOG(" %s", sl->str); } ADD2LOG("----- "PROC_DRIVER_SERIAL" end -----\n"); } } #endif /* !defined(__PPC__) */ #if defined(__PPC__) sl0 = read_file(PROC_DRIVER_MACSERIAL, 1, 0); if(sl0) { for(sl = sl0; sl; sl = sl->next) { if( (i = sscanf(sl->str, "%u: port:%x irq:%u con:%63[^\n]", &u0, &u1, &u2, buf)) >= 3 ) { ser = add_serial_entry(&hd_data->serial, new_mem(sizeof *ser)); ser->line = u0; ser->port = u1; ser->irq = u2; ser->name = new_str("SCC"); if(i == 4) ser->device = new_str(buf); } } if((hd_data->debug & HD_DEB_SERIAL)) { /* log just the first 16 entries */ ADD2LOG("----- "PROC_DRIVER_MACSERIAL" -----\n"); for(sl = sl0, i = 16; sl && i--; sl = sl->next) { ADD2LOG(" %s", sl->str); } ADD2LOG("----- "PROC_DRIVER_MACSERIAL" end -----\n"); } } #endif /* defined(__PPC__) */ free_str_list(sl0); }
static int read_directory(const char * dname) { int ret = 0; solist_t files; solist_t dirs; strobj_t sobj; //d_dbg("%s: dname = '%s'\n",__func__,dname); do { files = solist_new(); dirs = solist_new(); if (!files || !dirs) { ret = -1; verbose("solist_new() return error!\n"); break; } ret = read_file_list(dname, files, dirs); if (ret < 0) { verbose("error reading file list @ '%s' !\n", dname); break; } /* handle files first */ ret = 0; while ((sobj=solist_get_next(files)) != NULL) { ret = read_file(sobj_get_string(sobj)); if (ret < 0) { verbose("error handling file - '%s'\n",sobj_get_string(sobj)); break; } } if (ret < 0) break; /* handle diretories if recursive. */ if (o_recursive) { ret = 0; while ((sobj=solist_get_next(dirs)) != NULL) { ret = read_directory(sobj_get_string(sobj)); if (ret < 0) { verbose("error handling directory - '%s'\n",sobj_get_string(sobj)); break; } } if (ret < 0) break; } } while (0); if (files) solist_del(files); if (dirs) solist_del(dirs); return ret; }
int main (int argc, char **argv) { char *text; GtkWidget *window; GtkWidget *scrollwin; GtkWidget *vbox, *hbox; GtkWidget *frame; GtkWidget *checkbutton; gtk_init (&argc, &argv); if (argc != 2) { fprintf (stderr, "Usage: %s FILE\n", g_get_prgname ()); exit(1); } /* Create the list of paragraphs from the supplied file */ text = read_file (argv[1]); if (!text) exit(1); context = pango_win32_get_context (); paragraphs = split_paragraphs (text); pango_context_set_language (context, pango_language_from_string ("en_US")); pango_context_set_base_dir (context, PANGO_DIRECTION_LTR); font_description = pango_font_description_new (); pango_font_description_set_family(font_description, "sans"); pango_font_description_set_size(font_description, 16 * PANGO_SCALE); #if 0 /* default init ok? */ font_description.style = PANGO_STYLE_NORMAL; font_description.variant = PANGO_VARIANT_NORMAL; font_description.weight = 500; font_description.stretch = PANGO_STRETCH_NORMAL; #endif pango_context_set_font_description (context, font_description); /* Create the user interface */ window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size (GTK_WINDOW (window), 400, 400); gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_main_quit), NULL); vbox = gtk_vbox_new (FALSE, 4); gtk_container_add (GTK_CONTAINER (window), vbox); hbox = make_font_selector (); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); scrollwin = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrollwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_box_pack_start (GTK_BOX (vbox), scrollwin, TRUE, TRUE, 0); layout = gtk_layout_new (NULL, NULL); gtk_widget_set_events (layout, GDK_BUTTON_PRESS_MASK); gtk_widget_set_app_paintable (layout, TRUE); gtk_signal_connect (GTK_OBJECT (layout), "size_allocate", GTK_SIGNAL_FUNC (size_allocate), paragraphs); gtk_signal_connect (GTK_OBJECT (layout), "expose_event", GTK_SIGNAL_FUNC (expose), paragraphs); gtk_signal_connect (GTK_OBJECT (layout), "draw", GTK_SIGNAL_FUNC (draw), paragraphs); gtk_signal_connect (GTK_OBJECT (layout), "button_press_event", GTK_SIGNAL_FUNC (button_press), paragraphs); #if GTK_CHECK_VERSION (1,3,2) gtk_widget_set_double_buffered (layout, FALSE); #endif gtk_container_add (GTK_CONTAINER (scrollwin), layout); frame = gtk_frame_new (NULL); gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN); gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0); message_label = gtk_label_new ("Current char:"); gtk_misc_set_padding (GTK_MISC (message_label), 1, 1); gtk_misc_set_alignment (GTK_MISC (message_label), 0.0, 0.5); gtk_container_add (GTK_CONTAINER (frame), message_label); checkbutton = gtk_check_button_new_with_label ("Use RTL global direction"); gtk_signal_connect (GTK_OBJECT (checkbutton), "toggled", GTK_SIGNAL_FUNC (checkbutton_toggled), NULL); gtk_box_pack_start (GTK_BOX (vbox), checkbutton, FALSE, FALSE, 0); gtk_widget_show_all (window); gtk_main (); return 0; }
int main(int ac, char *av[]) { int f_usage = 0, f_list = 0, f_showscore = 0; int f_printpath = 0; const char *file = NULL; char *name, *ptr, *seed; struct sigaction sa; gid_t gid; #ifdef BSD struct itimerval itv; #endif open_score_file(); /* revoke privs */ gid = getgid(); setresgid(gid, gid, gid); start_time = time(0); makenoise = 1; seed = NULL; name = *av++; while (*av) { #ifndef SAVEDASH if (**av == '-') ++*av; else break; #endif ptr = *av++; while (*ptr) { switch (*ptr) { case '?': case 'u': f_usage++; break; case 'l': f_list++; break; case 's': case 't': f_showscore++; break; case 'p': f_printpath++; break; case 'q': makenoise = 0; break; case 'r': seed = *av; av++; break; case 'f': case 'g': file = *av; av++; break; default: warnx("unknown option '%c'", *ptr); f_usage++; break; } ptr++; } } if (seed != NULL) srandom(atol(seed)); else srandomdev(); if (f_usage) fprintf(stderr, "usage: %s [-lpqstu?] [-f game] [-g game] [-r seed]\n", name); if (f_showscore) log_score(1); if (f_list) list_games(); if (f_printpath) { size_t len; char buf[256]; strlcpy(buf, _PATH_GAMES, sizeof buf); len = strlen(buf); if (len != 0 && buf[len - 1] == '/') buf[len - 1] = '\0'; puts(buf); } if (f_usage || f_showscore || f_list || f_printpath) exit(0); if (file == NULL) file = default_game(); else file = okay_game(file); if (file == NULL || read_file(file) < 0) exit(1); setup_screen(sp); addplane(); signal(SIGINT, quit); signal(SIGQUIT, quit); #ifdef BSD signal(SIGTSTP, SIG_IGN); signal(SIGSTOP, SIG_IGN); #endif signal(SIGHUP, log_score_quit); signal(SIGTERM, log_score_quit); tcgetattr(fileno(stdin), &tty_start); tty_new = tty_start; tty_new.c_lflag &= ~(ICANON|ECHO); tty_new.c_iflag |= ICRNL; tty_new.c_cc[VMIN] = 1; tty_new.c_cc[VTIME] = 0; tcsetattr(fileno(stdin), TCSADRAIN, &tty_new); memset(&sa, 0, sizeof sa); sa.sa_handler = update; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGALRM); sigaddset(&sa.sa_mask, SIGINT); sa.sa_flags = 0; sigaction(SIGALRM, &sa, (struct sigaction *)0); #ifdef BSD itv.it_value.tv_sec = 0; itv.it_value.tv_usec = 1; itv.it_interval.tv_sec = sp->update_secs; itv.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); #endif #ifdef SYSV alarm(sp->update_secs); #endif for (;;) { if (getcommand() != 1) planewin(); else { #ifdef BSD itv.it_value.tv_sec = 0; itv.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); #endif #ifdef SYSV alarm(0); #endif update(0); #ifdef BSD itv.it_value.tv_sec = sp->update_secs; itv.it_value.tv_usec = 0; itv.it_interval.tv_sec = sp->update_secs; itv.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &itv, NULL); #endif #ifdef SYSV alarm(sp->update_secs); #endif } } }
Trace * off_read_trace (Dbptr db, double tstart, double tend) { char fname[1024]; char dtype[8]; char segtype[8]; long foff, nsamp; void *data; Trace *trace; double time, endtime, samprate; double calib, calper; int isamp, jsamp, size, nbytec; int ret; dbgetv (db, 0, "time", &time, "endtime", &endtime, "samprate", &samprate, "nsamp", &nsamp, "datatype", dtype, "segtype", segtype, "foff", &foff, "calib", &calib, "calper", &calper, NULL); switch (dtype[0]) { default: break; case 'c': nbytec = nsamp; nsamp = (endtime - time)*samprate + 1.5; break; } isamp = (tstart - time)*samprate - 1.5; jsamp = (tend - time)*samprate + 1.5; if (isamp < 0) isamp = 0; if (jsamp > nsamp-1) jsamp = nsamp-1; nsamp = jsamp+1; size = atoi(&dtype[strlen(dtype)-1]); nsamp -= isamp; time += isamp/samprate; if (nsamp < 0) nsamp = 0; data = NULL; if (nsamp > 0) { if (dbfilename (db, fname) < 1) { fprintf (stderr, "read_trace: Unable to find input file '%s'\n", fname); nsamp = 0; data = NULL; } else { switch (dtype[0]) { default: foff += isamp*size; if (!read_file (fname, foff, dtype, &nsamp, &data)) { fprintf (stderr, "read_trace: Unable to read input file '%s'\n", fname); return (NULL); } break; case 'c': data = malloc (nsamp*size); if (data == NULL) { fprintf (stderr, "read_trace: malloc() error.\n"); return (NULL); } dtype[0] = 's'; ret = wf_read_idacompress (fname, foff, nbytec, isamp, nsamp, size, data); if (ret < 0) { fprintf (stderr, "read_trace: wf_read_idacompress() error.\n"); free (data); return (NULL); } if (ret < nsamp) nsamp = ret; break; } } } trace = (Trace *) malloc (sizeof(Trace)); if (trace == NULL) { fprintf (stderr, "read_trace: Malloc error on Trace structure.\n"); free (data); return (NULL); } trace->tstart = time; trace->dt = 1.0/samprate; trace->nsamps = nsamp; trace->calib = calib; trace->calper = calper; strcpy (trace->rawdata_format, dtype); strcpy (trace->rawdata_type, segtype); trace->data = NULL; trace->data_free = NULL; trace->data_malloc = 0; trace->raw_data = data; trace->rawdata_free = data; if (data) trace->rawdata_malloc = nsamp*size; else trace->rawdata_malloc = 0; trace->prev = NULL; trace->next = NULL; if (data) trace = (Trace *) SCV_trace_fixgaps (trace, "segment"); return (trace); }
int main(int argc, char *argv[]) { char *file_name = " Usage: -f filename"; CALC_MODE mode = CM_OVERLAP; // 計算する方式 int is_chaged = 1; // 計算方法に変更があったか ACTION act; // 操作を選択 int threshold = 2; // 計算に用いる出現頻度の最小値 int i; init(); // 要素の確保 // コマンドライン引数の読み込み for (i = 0; i < argc; i++) { if (strcmp(argv[i], "-f") == 0 && i + 1 < argc) // 次の文字列があれば file_name = argv[i + 1]; // 開くファイルを読み込む } read_file(file_name); // ファイル読み込み printf("\nFinished Reading File\n"); printf("Total number of documents read = %d\n", n_docs); printf("Total number of words in the index = %d\n", n_words); fflush(stdout); printf("\nCurrent Indicator Type: %s\n", mode_string[mode]); while (1) { if (is_chaged) // 変更があった場合 { free_results(); // 前回の結果の消去 // 次回の計算用 results = (RESULTS **)malloc(sizeof(RESULTS *) * n_results_max); if (results == NULL) { fprintf(stderr, "Memory Allocation Error\n"); exit(1); } calc_indicator(mode, threshold); // 強度の計算 printf("\nCalculation Finished\n"); fflush(stdout); sort_results(); // 結果のソート printf("\nSort Finished\n"); fflush(stdout); } printf("\nCurrent Indicator Type: %s, Threshold: %d\n", mode_string[mode], threshold); printf("Choose Action (-1:Quit)\n"); printf("0:Show Results 1:Change Indicator \n"); printf("2:Change Precision 3:Write to Csv \n> "); act = read_input_as_int(); // 操作を選択 switch (act) { case A_QUIT: // 終了 free_all(); printf("Quit\n"); return 0; case A_SHOW_RESULTS: show_results_in_range(); // 結果の表示 is_chaged = 0; break; case A_CHANGE_INDICATOR: // 計算方法の変更 is_chaged = change_mode(&mode); break; case A_CHANGE_PRECISION: is_chaged = change_threshold(&threshold); // 計算に用いるときの閾値(頻度)の変更 break; case A_WRITE_CSV: write_to_csv_in_range(); // CSV形式で書き出し is_chaged = 0; break; default: break; } } return 0; }
/** * information about the cache: level, associativity... */ int generic_cache_info(int cpu, int id, char* output, size_t len) { char tmp[_HW_DETECT_MAX_OUTPUT], tmp2[_HW_DETECT_MAX_OUTPUT]; char tmppath[_HW_DETECT_MAX_OUTPUT]; struct stat statbuf; if (cpu == -1) cpu = get_cpu(); if (cpu == -1) return -1; snprintf(path,sizeof(path), "/sys/devices/system/cpu/cpu%i/cache/index%i/", cpu, id); memset(output, 0, len); if(stat(path, &statbuf)) //path doesn't exist return -1; strncpy(tmppath, path, _HW_DETECT_MAX_OUTPUT); strncat(tmppath, "level", (_HW_DETECT_MAX_OUTPUT-strlen(tmppath))-1); if(read_file(tmppath, tmp, _HW_DETECT_MAX_OUTPUT)) { snprintf(tmp2,_HW_DETECT_MAX_OUTPUT-1, "Level %s", tmp); strncat(output, tmp2, (len-strlen(output))-1); } strncpy(tmppath, path, _HW_DETECT_MAX_OUTPUT); strncat(tmppath, "type", (_HW_DETECT_MAX_OUTPUT-strlen(tmppath))-1); if(read_file(tmppath, tmp, _HW_DETECT_MAX_OUTPUT)) { if(!strcmp(tmp, "Unified")) { strncpy(tmp2, output,_HW_DETECT_MAX_OUTPUT-1); snprintf(output, len, "%s ", tmp); strncat(output, tmp2, (len-strlen(output))-1); } else { strncat(output, " ", (len-strlen(output))-1); strncat(output, tmp, (len-strlen(output))-1); } } strncat(output, " Cache,", (len-strlen(output))-1); strncpy(tmppath, path, _HW_DETECT_MAX_OUTPUT); strncat(tmppath, "size", (_HW_DETECT_MAX_OUTPUT-strlen(tmppath))-1); if(read_file(tmppath, tmp, _HW_DETECT_MAX_OUTPUT)) { strncat(output, " ", (len-strlen(output))-1); strncat(output, tmp, (len-strlen(output))-1); } strncpy(tmppath, path, _HW_DETECT_MAX_OUTPUT); strncat(tmppath, "ways_of_associativity", (_HW_DETECT_MAX_OUTPUT-strlen(tmppath))-1); if(read_file(tmppath, tmp, _HW_DETECT_MAX_OUTPUT)) { strncat(output, ", ", (len-strlen(output))-1); strncat(output, tmp, (len-strlen(output))-1); strncat(output, "-way set associative", (len-strlen(output))-1); } strncpy(tmppath, path,_HW_DETECT_MAX_OUTPUT); strncat(tmppath, "coherency_line_size", (_HW_DETECT_MAX_OUTPUT-strlen(tmppath))-1); if(read_file(tmppath, tmp, _HW_DETECT_MAX_OUTPUT)) { strncat(output, ", ", (len-strlen(output))-1); strncat(output, tmp, (len-strlen(output))-1); strncat(output, " Byte cachelines", (len-strlen(output))-1); } strncpy(tmppath, path,_HW_DETECT_MAX_OUTPUT); strncat(tmppath, "shared_cpu_map",(_HW_DETECT_MAX_OUTPUT-strlen(tmppath))-1); if(read_file(tmppath, tmp, _HW_DETECT_MAX_OUTPUT)) { cpu_map_to_list(tmp, tmp2, _HW_DETECT_MAX_OUTPUT); snprintf(tmppath,_HW_DETECT_MAX_OUTPUT, "cpu%i ", cpu); if(!strcmp(tmp2, tmppath)) { strncat(output, ", exclusive for ", (len-strlen(output))-1); strncat(output, tmppath, (len-strlen(output))-1); } else { strncat(output, ", shared among ", (len-strlen(output))-1); strncat(output, tmp2, (len-strlen(output))-1); } } return 0; }
int main(int argc, char **argv){ cl_context context = get_platform(CL_DEVICE_TYPE_GPU); cl_device_id device = 0; cl_command_queue queue = get_first_device(context, &device); char *prog_src = read_file(CL_PROGRAM("convolution.cl"), NULL); cl_program program = build_program(prog_src, context, device, NULL); free(prog_src); cl_int err = CL_SUCCESS; cl_kernel kernel = clCreateKernel(program, "convolve", &err); check_cl_err(err, "failed to create kernel"); //Setup our input signal and mask cl_uint in_signal[IN_DIM][IN_DIM] = { { 3, 1, 1, 4, 8, 2, 1, 3 }, { 4, 2, 1, 1, 2, 1, 2, 3 }, { 4, 4, 4, 4, 3, 2, 2, 2 }, { 9, 8, 3, 8, 9, 0, 0, 0 }, { 9, 3, 3, 9, 0, 0, 0, 0 }, { 0, 9, 0, 8, 0, 0, 0, 0 }, { 3, 0, 8, 8, 9, 4, 4, 4 }, { 5, 9, 8, 1, 8, 1, 1, 1 } }; cl_uint mask[MASK_DIM][MASK_DIM] = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } }; //0 is input, 1 is mask, 2 is output cl_mem mem_objs[3]; mem_objs[0] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint) * IN_DIM * IN_DIM, in_signal, &err); mem_objs[1] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint) * MASK_DIM * MASK_DIM, mask, &err); mem_objs[2] = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(cl_uint) * OUT_DIM * OUT_DIM, NULL, &err); check_cl_err(err, "failed to create buffers"); for (int i = 0; i < 3; ++i){ err = clSetKernelArg(kernel, i, sizeof(cl_mem), &mem_objs[i]); check_cl_err(err, "failed to set kernel argument"); } size_t in_dim = IN_DIM, mask_dim = MASK_DIM; err = clSetKernelArg(kernel, 3, sizeof(unsigned), &in_dim); err = clSetKernelArg(kernel, 4, sizeof(unsigned), &mask_dim); check_cl_err(err, "failed to set kernel argument"); size_t global_size[2] = { OUT_DIM, OUT_DIM }; size_t local_size[2] = { 2, 2 }; err = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global_size, local_size, 0, NULL, NULL); check_cl_err(err, "failed to enqueue ND range kernel"); cl_uint* out = clEnqueueMapBuffer(queue, mem_objs[2], CL_TRUE, CL_MAP_READ, 0, sizeof(cl_uint) * OUT_DIM * OUT_DIM, 0, NULL, NULL, &err); check_cl_err(err, "failed to map result"); printf("Result:\n"); for (int i = 0; i < OUT_DIM; ++i){ for (int j = 0; j < OUT_DIM; ++j){ printf("%d ", out[i * OUT_DIM + j]); } printf("\n"); } printf("\n"); clEnqueueUnmapMemObject(queue, mem_objs[2], out, 0, 0, NULL); for (int i = 0; i < 3; ++i){ clReleaseMemObject(mem_objs[i]); } clReleaseKernel(kernel); clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context); return 0; }
SourceFile::SourceFile(const wchar_t* filename) { file_name_ = std::wstring(filename); read_file(filename); }
int main(int argc, char** argv) { char c; unsigned width_override = 0; unsigned height_override = 0; unsigned window_width = 512; unsigned window_height = 512; unsigned long time_generations = 0; view.fullscreen = true; DEBUG("Initializing GLUT\n"); glutInit (&argc, argv); glutInitDisplayMode (GLUT_RGBA); while ((c = getopt_long(argc, argv, "w:s:hft:", longopts, NULL)) != -1) { switch (c) { case 's': sscanf(optarg, "%ux%u\n", &width_override, &height_override); break; case 'w': sscanf(optarg, "%ux%u\n", &window_width, &window_height); break; case 'f': view.fullscreen = true; break; case 't': time_generations = strtoul(optarg, NULL, 10); break; case 'h': default: usage(argv[0]); } } argc -= optind; argv += optind; atexit(cleanup); init_parallel_component(); compute_params.generations_per_redraw = 0.05; create_window(window_width, window_height); uint8_t* data = NULL; unsigned width = width_override ? width_override : 128; unsigned height = height_override ? height_override : 128; if (argc >= 1) { const char* filename = argv[0]; DEBUG("Filename argument \"%s\" given\n", filename); unsigned __width, __height; data = read_file(filename, &__width, &__height, width_override, height_override); if (data != NULL) { width = __width; height = __height; } } create_grid(width, height, data); if (time_generations) { struct timeval t1, t2; gettimeofday(&t1, NULL); DEBUG("Timing how long it takes to advance %lu generations\n", time_generations); advance_generations(time_generations); gettimeofday(&t2, NULL); unsigned long us_elapsed = (t2.tv_sec * 1000000 + t2.tv_usec) - (t1.tv_sec * 1000000 + t1.tv_usec); printf("%lu milliseconds elapsed\n", us_elapsed / 1000); } else { reset_view(); glutMainLoop(); } return 0; }
int expose_hook(t_env *e) { read_file(e); return (0); }
/// Creates difference images, returns the number that have a 0 metric. /// If outputDir.isEmpty(), don't write out diff files. static void create_diff_images (DiffMetricProc dmp, const int colorThreshold, RecordArray* differences, const SkString& baseDir, const SkString& comparisonDir, const SkString& outputDir, const StringArray& matchSubstrings, const StringArray& nomatchSubstrings, bool recurseIntoSubdirs, bool getBounds, bool verbose, DiffSummary* summary) { SkASSERT(!baseDir.isEmpty()); SkASSERT(!comparisonDir.isEmpty()); FileArray baseFiles; FileArray comparisonFiles; get_file_list(baseDir, matchSubstrings, nomatchSubstrings, recurseIntoSubdirs, &baseFiles); get_file_list(comparisonDir, matchSubstrings, nomatchSubstrings, recurseIntoSubdirs, &comparisonFiles); if (!baseFiles.isEmpty()) { qsort(baseFiles.begin(), baseFiles.count(), sizeof(SkString*), SkCastForQSort(compare_file_name_metrics)); } if (!comparisonFiles.isEmpty()) { qsort(comparisonFiles.begin(), comparisonFiles.count(), sizeof(SkString*), SkCastForQSort(compare_file_name_metrics)); } int i = 0; int j = 0; while (i < baseFiles.count() && j < comparisonFiles.count()) { SkString basePath(baseDir); SkString comparisonPath(comparisonDir); DiffRecord *drp = new DiffRecord; int v = strcmp(baseFiles[i]->c_str(), comparisonFiles[j]->c_str()); if (v < 0) { // in baseDir, but not in comparisonDir drp->fResult = DiffRecord::kCouldNotCompare_Result; basePath.append(*baseFiles[i]); comparisonPath.append(*baseFiles[i]); drp->fBase.fFilename = *baseFiles[i]; drp->fBase.fFullPath = basePath; drp->fBase.fStatus = DiffResource::kExists_Status; drp->fComparison.fFilename = *baseFiles[i]; drp->fComparison.fFullPath = comparisonPath; drp->fComparison.fStatus = DiffResource::kDoesNotExist_Status; VERBOSE_STATUS("MISSING", ANSI_COLOR_YELLOW, baseFiles[i]); ++i; } else if (v > 0) { // in comparisonDir, but not in baseDir drp->fResult = DiffRecord::kCouldNotCompare_Result; basePath.append(*comparisonFiles[j]); comparisonPath.append(*comparisonFiles[j]); drp->fBase.fFilename = *comparisonFiles[j]; drp->fBase.fFullPath = basePath; drp->fBase.fStatus = DiffResource::kDoesNotExist_Status; drp->fComparison.fFilename = *comparisonFiles[j]; drp->fComparison.fFullPath = comparisonPath; drp->fComparison.fStatus = DiffResource::kExists_Status; VERBOSE_STATUS("MISSING", ANSI_COLOR_YELLOW, comparisonFiles[j]); ++j; } else { // Found the same filename in both baseDir and comparisonDir. SkASSERT(DiffRecord::kUnknown_Result == drp->fResult); basePath.append(*baseFiles[i]); comparisonPath.append(*comparisonFiles[j]); drp->fBase.fFilename = *baseFiles[i]; drp->fBase.fFullPath = basePath; drp->fBase.fStatus = DiffResource::kExists_Status; drp->fComparison.fFilename = *comparisonFiles[j]; drp->fComparison.fFullPath = comparisonPath; drp->fComparison.fStatus = DiffResource::kExists_Status; SkAutoDataUnref baseFileBits(read_file(drp->fBase.fFullPath.c_str())); if (NULL != baseFileBits) { drp->fBase.fStatus = DiffResource::kRead_Status; } SkAutoDataUnref comparisonFileBits(read_file(drp->fComparison.fFullPath.c_str())); if (NULL != comparisonFileBits) { drp->fComparison.fStatus = DiffResource::kRead_Status; } if (NULL == baseFileBits || NULL == comparisonFileBits) { if (NULL == baseFileBits) { drp->fBase.fStatus = DiffResource::kCouldNotRead_Status; VERBOSE_STATUS("READ FAIL", ANSI_COLOR_RED, baseFiles[i]); } if (NULL == comparisonFileBits) { drp->fComparison.fStatus = DiffResource::kCouldNotRead_Status; VERBOSE_STATUS("READ FAIL", ANSI_COLOR_RED, comparisonFiles[j]); } drp->fResult = DiffRecord::kCouldNotCompare_Result; } else if (are_buffers_equal(baseFileBits, comparisonFileBits)) { drp->fResult = DiffRecord::kEqualBits_Result; VERBOSE_STATUS("MATCH", ANSI_COLOR_GREEN, baseFiles[i]); } else { AutoReleasePixels arp(drp); get_bitmap(baseFileBits, drp->fBase, SkImageDecoder::kDecodePixels_Mode); get_bitmap(comparisonFileBits, drp->fComparison, SkImageDecoder::kDecodePixels_Mode); VERBOSE_STATUS("DIFFERENT", ANSI_COLOR_RED, baseFiles[i]); if (DiffResource::kDecoded_Status == drp->fBase.fStatus && DiffResource::kDecoded_Status == drp->fComparison.fStatus) { create_and_write_diff_image(drp, dmp, colorThreshold, outputDir, drp->fBase.fFilename); } else { drp->fResult = DiffRecord::kCouldNotCompare_Result; } } ++i; ++j; } if (getBounds) { get_bounds(*drp); } SkASSERT(DiffRecord::kUnknown_Result != drp->fResult); differences->push(drp); summary->add(drp); } for (; i < baseFiles.count(); ++i) { // files only in baseDir DiffRecord *drp = new DiffRecord(); drp->fBase.fFilename = *baseFiles[i]; drp->fBase.fFullPath = baseDir; drp->fBase.fFullPath.append(drp->fBase.fFilename); drp->fBase.fStatus = DiffResource::kExists_Status; drp->fComparison.fFilename = *baseFiles[i]; drp->fComparison.fFullPath = comparisonDir; drp->fComparison.fFullPath.append(drp->fComparison.fFilename); drp->fComparison.fStatus = DiffResource::kDoesNotExist_Status; drp->fResult = DiffRecord::kCouldNotCompare_Result; if (getBounds) { get_bounds(*drp); } differences->push(drp); summary->add(drp); } for (; j < comparisonFiles.count(); ++j) { // files only in comparisonDir DiffRecord *drp = new DiffRecord(); drp->fBase.fFilename = *comparisonFiles[j]; drp->fBase.fFullPath = baseDir; drp->fBase.fFullPath.append(drp->fBase.fFilename); drp->fBase.fStatus = DiffResource::kDoesNotExist_Status; drp->fComparison.fFilename = *comparisonFiles[j]; drp->fComparison.fFullPath = comparisonDir; drp->fComparison.fFullPath.append(drp->fComparison.fFilename); drp->fComparison.fStatus = DiffResource::kExists_Status; drp->fResult = DiffRecord::kCouldNotCompare_Result; if (getBounds) { get_bounds(*drp); } differences->push(drp); summary->add(drp); } release_file_list(&baseFiles); release_file_list(&comparisonFiles); }
int main( int argc, char **argv ) { libspectrum_snap *snap; libspectrum_id_t type; libspectrum_class_t class; unsigned char *buffer; size_t length; libspectrum_creator *creator; int flags; int compress = 0; int fix = 0; FILE *f; int error = 0; int c; struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'V' }, { 0, 0, 0, 0 } }; progname = argv[0]; while( ( c = getopt_long( argc, argv, "cnfhV", long_options, NULL ) ) != -1 ) { switch( c ) { case 'c': compress = LIBSPECTRUM_FLAG_SNAPSHOT_ALWAYS_COMPRESS; break; case 'n': compress = LIBSPECTRUM_FLAG_SNAPSHOT_NO_COMPRESSION; break; case 'f': fix = 1; break; case 'h': show_help(); return 0; case 'V': show_version(); return 0; case '?': /* getopt prints an error message to stderr */ error = 1; break; default: error = 1; fprintf( stderr, "%s: unknown option `%c'\n", progname, (char) c ); break; } } argc -= optind; argv += optind; if( error ) { fprintf( stderr, "Try `%s --help' for more information.\n", progname ); return error; } if( argc < 2 ) { fprintf( stderr, "%s: usage: %s [-c] [-n] [-f] <infile> <outfile>\n", progname, progname ); fprintf( stderr, "Try `%s --help' for more information.\n", progname ); return 1; } error = init_libspectrum(); if( error ) return error; snap = libspectrum_snap_alloc(); if( read_file( argv[0], &buffer, &length ) ) { libspectrum_snap_free( snap ); return 1; } error = libspectrum_snap_read( snap, buffer, length, LIBSPECTRUM_ID_UNKNOWN, argv[0] ); if( error ) { libspectrum_snap_free( snap ); free( buffer ); return error; } free( buffer ); if( fix ) fix_snapshot( snap ); error = libspectrum_identify_file_with_class( &type, &class, argv[1], NULL, 0 ); if( error ) { libspectrum_snap_free( snap ); return error; } if( class != LIBSPECTRUM_CLASS_SNAPSHOT ) { fprintf( stderr, "%s: '%s' is not a snapshot file\n", progname, argv[1] ); libspectrum_snap_free( snap ); return 1; } error = get_creator( &creator, "snapconv" ); if( error ) { libspectrum_snap_free( snap ); return error; } length = 0; error = libspectrum_snap_write( &buffer, &length, &flags, snap, type, creator, compress ); if( error ) { libspectrum_creator_free( creator ); libspectrum_snap_free( snap ); return error; } if( flags & LIBSPECTRUM_FLAG_SNAPSHOT_MAJOR_INFO_LOSS ) { fprintf( stderr, "%s: warning: major information loss during conversion\n", progname ); } else if( flags & LIBSPECTRUM_FLAG_SNAPSHOT_MINOR_INFO_LOSS ) { fprintf( stderr, "%s: warning: minor information loss during conversion\n", progname ); } error = libspectrum_creator_free( creator ); if( error ) { free( buffer ); libspectrum_snap_free( snap ); return error; } error = libspectrum_snap_free( snap ); if( error ) { free( buffer ); return error; } f = fopen( argv[1], "wb" ); if( !f ) { fprintf( stderr, "%s: couldn't open '%s': %s\n", progname, argv[1], strerror( errno ) ); free( buffer ); return 1; } if( fwrite( buffer, 1, length, f ) != length ) { fprintf( stderr, "%s: error writing to '%s'\n", progname, argv[1] ); free( buffer ); fclose( f ); return 1; } free( buffer ); fclose( f ); return 0; }
/* * Send a file via the TFTP data session. */ void tftp_send(int peer, uint16_t *block, struct tftp_stats *ts) { struct tftphdr *rp; int size, n_data, n_ack, try; uint16_t oldblock; char sendbuffer[MAXPKTSIZE]; char recvbuffer[MAXPKTSIZE]; rp = (struct tftphdr *)recvbuffer; *block = 1; ts->amount = 0; do { if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Sending block %d", *block); size = read_file(sendbuffer, segsize); if (size < 0) { tftp_log(LOG_ERR, "read_file returned %d", size); send_error(peer, errno + 100); goto abort; } for (try = 0; ; try++) { n_data = send_data(peer, *block, sendbuffer, size); if (n_data > 0) { if (try == maxtimeouts) { tftp_log(LOG_ERR, "Cannot send DATA packet #%d, " "giving up", *block); return; } tftp_log(LOG_ERR, "Cannot send DATA packet #%d, trying again", *block); continue; } n_ack = receive_packet(peer, recvbuffer, MAXPKTSIZE, NULL, timeoutpacket); if (n_ack < 0) { if (n_ack == RP_TIMEOUT) { if (try == maxtimeouts) { tftp_log(LOG_ERR, "Timeout #%d send ACK %d " "giving up", try, *block); return; } tftp_log(LOG_WARNING, "Timeout #%d on ACK %d", try, *block); continue; } /* Either read failure or ERROR packet */ if (debug&DEBUG_SIMPLE) tftp_log(LOG_ERR, "Aborting: %s", rp_strerror(n_ack)); goto abort; } if (rp->th_opcode == ACK) { ts->blocks++; if (rp->th_block == *block) { ts->amount += size; break; } /* Re-synchronize with the other side */ (void) synchnet(peer); if (rp->th_block == (*block - 1)) { ts->retries++; continue; } } } oldblock = *block; (*block)++; if (oldblock > *block) { if (options[OPT_ROLLOVER].o_request == NULL) { /* * "rollover" option not specified in * tftp client. Default to rolling block * counter to 0. */ *block = 0; } else { *block = atoi(options[OPT_ROLLOVER].o_request); } ts->rollovers++; } gettimeofday(&(ts->tstop), NULL); } while (size == segsize); abort: return; } /* * Receive a file via the TFTP data session. * * - It could be that the first block has already arrived while * trying to figure out if we were receiving options or not. In * that case it is passed to this function. */ void tftp_receive(int peer, uint16_t *block, struct tftp_stats *ts, struct tftphdr *firstblock, size_t fb_size) { struct tftphdr *rp; uint16_t oldblock; int n_data, n_ack, writesize, i, retry; char recvbuffer[MAXPKTSIZE]; ts->amount = 0; if (firstblock != NULL) { writesize = write_file(firstblock->th_data, fb_size); ts->amount += writesize; for (i = 0; ; i++) { n_ack = send_ack(peer, *block); if (n_ack > 0) { if (i == maxtimeouts) { tftp_log(LOG_ERR, "Cannot send ACK packet #%d, " "giving up", *block); return; } tftp_log(LOG_ERR, "Cannot send ACK packet #%d, trying again", *block); continue; } break; } if (fb_size != segsize) { gettimeofday(&(ts->tstop), NULL); return; } } rp = (struct tftphdr *)recvbuffer; do { oldblock = *block; (*block)++; if (oldblock > *block) { if (options[OPT_ROLLOVER].o_request == NULL) { /* * "rollover" option not specified in * tftp client. Default to rolling block * counter to 0. */ *block = 0; } else { *block = atoi(options[OPT_ROLLOVER].o_request); } ts->rollovers++; } for (retry = 0; ; retry++) { if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Receiving DATA block %d", *block); n_data = receive_packet(peer, recvbuffer, MAXPKTSIZE, NULL, timeoutpacket); if (n_data < 0) { if (retry == maxtimeouts) { tftp_log(LOG_ERR, "Timeout #%d on DATA block %d, " "giving up", retry, *block); return; } if (n_data == RP_TIMEOUT) { tftp_log(LOG_WARNING, "Timeout #%d on DATA block %d", retry, *block); send_ack(peer, oldblock); continue; } /* Either read failure or ERROR packet */ if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Aborting: %s", rp_strerror(n_data)); goto abort; } if (rp->th_opcode == DATA) { ts->blocks++; if (rp->th_block == *block) break; tftp_log(LOG_WARNING, "Expected DATA block %d, got block %d", *block, rp->th_block); /* Re-synchronize with the other side */ (void) synchnet(peer); if (rp->th_block == (*block-1)) { tftp_log(LOG_INFO, "Trying to sync"); *block = oldblock; ts->retries++; goto send_ack; /* rexmit */ } } else { tftp_log(LOG_WARNING, "Expected DATA block, got %s block", packettype(rp->th_opcode)); } } if (n_data > 0) { writesize = write_file(rp->th_data, n_data); ts->amount += writesize; if (writesize <= 0) { tftp_log(LOG_ERR, "write_file returned %d", writesize); if (writesize < 0) send_error(peer, errno + 100); else send_error(peer, ENOSPACE); goto abort; } } send_ack: for (i = 0; ; i++) { n_ack = send_ack(peer, *block); if (n_ack > 0) { if (i == maxtimeouts) { tftp_log(LOG_ERR, "Cannot send ACK packet #%d, " "giving up", *block); return; } tftp_log(LOG_ERR, "Cannot send ACK packet #%d, trying again", *block); continue; } break; } gettimeofday(&(ts->tstop), NULL); } while (n_data == segsize); /* Don't do late packet management for the client implementation */ if (acting_as_client) return; for (i = 0; ; i++) { n_data = receive_packet(peer, (char *)rp, pktsize, NULL, timeoutpacket); if (n_data <= 0) break; if (n_data > 0 && rp->th_opcode == DATA && /* and got a data block */ *block == rp->th_block) /* then my last ack was lost */ send_ack(peer, *block); /* resend final ack */ } abort: return; }
bool LoadMDX(const char *mdx_name, char *title, int title_len) { u8 *mdx_buf = 0, *pdx_buf = 0; int mdx_size = 0, pdx_size = 0; // Load MDX file if (!read_file(mdx_name, &mdx_size, &mdx_buf, MAGIC_OFFSET)) { fprintf(stderr, "Cannot open/read %s.\n", mdx_name); return false; } // Skip title. int pos = MAGIC_OFFSET; { char *ptitle = title; while (pos < mdx_size && --title_len > 0) { *ptitle++ = mdx_buf[pos]; if (mdx_buf[pos] == 0x0d && mdx_buf[pos + 1] == 0x0a) break; pos++; } *ptitle = 0; } while (pos < mdx_size) { u8 c = mdx_buf[pos++]; if (c == 0x1a) break; } char *pdx_name = (char*) mdx_buf + pos; while (pos < mdx_size) { u8 c = mdx_buf[pos++]; if (c == 0) break; } if (pos >= mdx_size) return false; // Get mdx path. if (*pdx_name) { char pdx_path[FILENAME_MAX]; strncpy(pdx_path, mdx_name, sizeof(pdx_path)); int pdx_name_start = 0; for (int i = strlen(pdx_path) - 1; i > 0; i--) { if (pdx_path[i - 1] == '/') { pdx_name_start = i; break; } } if (pdx_name_start + strlen(pdx_path) + 4 >= sizeof(pdx_path)) { return false; } // remove .pdx from pdx_name { int pdx_name_len = strlen(pdx_name); if (pdx_name_len > 4) { if (pdx_name[pdx_name_len - 4] == '.') { pdx_name[pdx_name_len - 4] = 0; } } } // Make pdx path. for (int i = 0; i < 3 * 2; i++) { strcpy_cnv(pdx_path + pdx_name_start, pdx_name, i % 3); strcpy_cnv(pdx_path + pdx_name_start + strlen(pdx_name), ".pdx", i / 3); if (verbose) { fprintf(stderr, "try to open pdx:%s\n", pdx_path); } if (read_file(pdx_path, &pdx_size, &pdx_buf, MAGIC_OFFSET)) { break; } } } // Convert mdx to MXDRVG readable structure. int mdx_body_pos = pos; if (verbose) { fprintf(stderr, "mdx body pos :0x%x\n", mdx_body_pos - MAGIC_OFFSET); fprintf(stderr, "mdx body size :0x%x\n", mdx_size - mdx_body_pos - MAGIC_OFFSET); } u8 *mdx_head = mdx_buf + mdx_body_pos - MAGIC_OFFSET; mdx_head[0] = 0x00; mdx_head[1] = 0x00; mdx_head[2] = (pdx_buf ? 0 : 0xff); mdx_head[3] = (pdx_buf ? 0 : 0xff); mdx_head[4] = 0; mdx_head[5] = 0x0a; mdx_head[6] = 0x00; mdx_head[7] = 0x08; mdx_head[8] = 0x00; mdx_head[9] = 0x00; if (pdx_buf) { pdx_buf[0] = 0x00; pdx_buf[1] = 0x00; pdx_buf[2] = 0x00; pdx_buf[3] = 0x00; pdx_buf[4] = 0x00; pdx_buf[5] = 0x0a; pdx_buf[6] = 0x00; pdx_buf[7] = 0x02; pdx_buf[8] = 0x00; pdx_buf[9] = 0x00; } if (verbose) { fprintf(stderr, "instrument pos:0x%x\n", mdx_body_pos - 10 + (mdx_head[10] << 8) + mdx_head[11]); } MXDRVG_SetData(mdx_head, mdx_size, pdx_buf, pdx_size); delete []mdx_buf; delete []pdx_buf; return true; }
int main (int argc, char *argv[]) { double *a, *b, *c; if (argc != 3) { fprintf(stderr, "Usage: %s size_of_vector num_adds\n", argv[0]); abort(); } const cl_long N = (cl_long) atol(argv[1]); const int num_adds = atoi(argv[2]); cl_context ctx; cl_command_queue queue; create_context_on(CHOOSE_INTERACTIVELY, CHOOSE_INTERACTIVELY, 0, &ctx, &queue, 0); print_device_info_from_queue(queue); // -------------------------------------------------------------------------- // load kernels // -------------------------------------------------------------------------- char *knl_text = read_file("vec-add-kernel.cl"); cl_kernel knl = kernel_from_string(ctx, knl_text, "sum", NULL); free(knl_text); // -------------------------------------------------------------------------- // allocate and initialize CPU memory // -------------------------------------------------------------------------- posix_memalign((void**)&a, 32, N*sizeof(double)); if (!a) { fprintf(stderr, "alloc a"); abort(); } posix_memalign((void**)&b, 32, N*sizeof(double)); if (!b) { fprintf(stderr, "alloc b"); abort(); } posix_memalign((void**)&c, 32, N*sizeof(double)); if (!c) { fprintf(stderr, "alloc c"); abort(); } for(cl_long n = 0; n < N; ++n) { a[n] = n; b[n] = 2*n; } // -------------------------------------------------------------------------- // allocate device memory // -------------------------------------------------------------------------- cl_int status; cl_mem buf_a = clCreateBuffer(ctx, CL_MEM_READ_WRITE, sizeof(double) * N, 0, &status); CHECK_CL_ERROR(status, "clCreateBuffer"); cl_mem buf_b = clCreateBuffer(ctx, CL_MEM_READ_WRITE, sizeof(double) * N, 0, &status); CHECK_CL_ERROR(status, "clCreateBuffer"); cl_mem buf_c = clCreateBuffer(ctx, CL_MEM_READ_WRITE, sizeof(double) * N, 0, &status); CHECK_CL_ERROR(status, "clCreateBuffer"); // -------------------------------------------------------------------------- // transfer to device // -------------------------------------------------------------------------- CALL_CL_SAFE(clEnqueueWriteBuffer( queue, buf_a, /*blocking*/ CL_TRUE, /*offset*/ 0, N * sizeof(double), a, 0, NULL, NULL)); CALL_CL_SAFE(clEnqueueWriteBuffer( queue, buf_b, /*blocking*/ CL_TRUE, /*offset*/ 0, N * sizeof(double), b, 0, NULL, NULL)); // -------------------------------------------------------------------------- // run code on device // -------------------------------------------------------------------------- CALL_CL_SAFE(clFinish(queue)); timestamp_type tic, toc; get_timestamp(&tic); for(int add = 0; add < num_adds; ++add) { SET_4_KERNEL_ARGS(knl, N, buf_a, buf_b, buf_c); size_t local_size[] = { 128 }; size_t global_size[] = { ((N + local_size[0] - 1)/local_size[0])* local_size[0] }; CALL_CL_SAFE(clEnqueueNDRangeKernel(queue, knl, 1, NULL, global_size, local_size, 0, NULL, NULL)); } CALL_CL_SAFE(clFinish(queue)); get_timestamp(&toc); double elapsed = timestamp_diff_in_seconds(tic,toc)/num_adds; printf("%f s\n", elapsed); printf("%f GB/s\n", 3*N*sizeof(double)/1e9/elapsed); // -------------------------------------------------------------------------- // transfer back & check // -------------------------------------------------------------------------- CALL_CL_SAFE(clEnqueueReadBuffer( queue, buf_c, /*blocking*/ CL_TRUE, /*offset*/ 0, N * sizeof(double), c, 0, NULL, NULL)); for(cl_long i = 0; i < N; ++i) if(c[i] != 3*i) { printf("BAD %ld\n", (long)i); abort(); } printf("GOOD\n"); // -------------------------------------------------------------------------- // clean up // -------------------------------------------------------------------------- CALL_CL_SAFE(clReleaseMemObject(buf_a)); CALL_CL_SAFE(clReleaseMemObject(buf_b)); CALL_CL_SAFE(clReleaseMemObject(buf_c)); CALL_CL_SAFE(clReleaseKernel(knl)); CALL_CL_SAFE(clReleaseCommandQueue(queue)); CALL_CL_SAFE(clReleaseContext(ctx)); free(a); free(b); free(c); return 0; }
static int sc_pkcs15emu_openpgp_init(sc_pkcs15_card_t *p15card) { sc_card_t *card = p15card->card; sc_context_t *ctx = card->ctx; char string[256]; u8 buffer[256]; size_t length; int r, i; set_string(&p15card->label, "OpenPGP Card"); set_string(&p15card->manufacturer_id, "OpenPGP project"); if ((r = read_file(card, "004f", buffer, sizeof(buffer))) < 0) goto failed; sc_bin_to_hex(buffer, (size_t)r, string, sizeof(string), 0); set_string(&p15card->serial_number, string); p15card->version = (buffer[6] << 8) | buffer[7]; p15card->flags = SC_PKCS15_CARD_FLAG_LOGIN_REQUIRED | SC_PKCS15_CARD_FLAG_PRN_GENERATION | SC_PKCS15_CARD_FLAG_EID_COMPLIANT; /* Extract preferred language */ r = read_file(card, "00655f2d", string, sizeof(string)-1); if (r < 0) goto failed; string[r] = '\0'; set_string(&p15card->preferred_language, string); /* Get Application Related Data (006E) */ if ((r = sc_get_data(card, 0x006E, buffer, sizeof(buffer))) < 0) goto failed; length = r; /* TBD: extract algorithm info */ /* Get CHV status bytes: * 00: ?? * 01-03: max length of pins 1-3 * 04-07: tries left for pins 1-3 */ if ((r = read_file(card, "006E007300C4", buffer, sizeof(buffer))) < 0) goto failed; if (r != 7) { sc_error(ctx, "CHV status bytes have unexpected length " "(expected 7, got %d)\n", r); return SC_ERROR_OBJECT_NOT_VALID; } for (i = 0; i < 3; i++) { unsigned int flags; struct sc_pkcs15_pin_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED | SC_PKCS15_PIN_FLAG_LOCAL; if (i == 2) { flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED | SC_PKCS15_PIN_FLAG_SO_PIN; } pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = i + 1; pin_info.reference = i + 1; pin_info.flags = flags; pin_info.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.min_length = 0; pin_info.stored_length = buffer[1+i]; pin_info.max_length = buffer[1+i]; pin_info.pad_char = '\0'; sc_format_path("3F00", &pin_info.path); pin_info.tries_left = buffer[4+i]; strlcpy(pin_obj.label, pgp_pin_name[i], sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } for (i = 0; i < 3; i++) { static int prkey_pin[3] = { 1, 2, 2 }; static int prkey_usage[3] = { SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER | SC_PKCS15_PRKEY_USAGE_NONREPUDIATION, SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION }; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = i + 1; prkey_info.usage = prkey_usage[i]; prkey_info.native = 1; prkey_info.key_reference = i; prkey_info.modulus_length= 1024; strlcpy(prkey_obj.label, pgp_key_name[i], sizeof(prkey_obj.label)); prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE | SC_PKCS15_CO_FLAG_MODIFIABLE; prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } for (i = 0; i < 3; i++) { static int pubkey_usage[3] = { SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER, SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_WRAP, SC_PKCS15_PRKEY_USAGE_VERIFY }; struct sc_pkcs15_pubkey_info pubkey_info; struct sc_pkcs15_object pubkey_obj; memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); pubkey_info.id.len = 1; pubkey_info.id.value[0] = i +1; pubkey_info.modulus_length = 1024; pubkey_info.usage = pubkey_usage[i]; sc_format_path(pgp_pubkey_path[i], &pubkey_info.path); strlcpy(pubkey_obj.label, pgp_key_name[i], sizeof(pubkey_obj.label)); pubkey_obj.auth_id.len = 1; pubkey_obj.auth_id.value[0] = 3; pubkey_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return 0; failed: sc_error(card->ctx, "Failed to initialize OpenPGP emulation: %s\n", sc_strerror(r)); return r; }
int SSL_CTX_use_PrivateKey_file(SSL_CTX* ctx, const char* file, int format) { return read_file(ctx, file, format, PrivateKey); }
/* * Read kernel log info. Combine with /var/log/boot.msg. */ void _read_klog(hd_data_t *hd_data) { char buf[0x2000 + 1], *s; int i, j, len, n; str_list_t *sl, *sl1, *sl2, *sl_last, **ssl, *sl_next; /* some clean-up */ hd_data->klog = free_str_list(hd_data->klog); sl1 = read_file(KLOG_BOOT, 0, 0); sl2 = NULL; /* * remove non-canonical lines (not starting with <[0-9]>) at the start and * at the end */ /* note: the implementations assumes that at least *one* line is ok */ for(sl_last = NULL, sl = sl1; sl; sl = (sl_last = sl)->next) { if(str_ok(sl)) { if(sl_last) { sl_last->next = NULL; free_str_list(sl1); sl1 = sl; } break; } } for(sl_last = NULL, sl = sl1; sl; sl = (sl_last = sl)->next) { if(!str_ok(sl)) { if(sl_last) { sl_last->next = NULL; free_str_list(sl); } break; } } n = klogctl(3, buf, sizeof buf - 1); if(n <= 0) { hd_data->klog = sl1; return; } if(n > (int) sizeof buf - 1) n = sizeof buf - 1; buf[n] = 0; for(i = j = 0; i < n; i++) { if(buf[i] == '\n') { len = i - j + 1; s = new_mem(len + 1); memcpy(s, buf + j, len); add_str_list(&sl2, s); s = free_mem(s); j = i + 1; } } /* the 1st line may be incomplete */ if(sl2 && !str_ok(sl2)) { sl_next = sl2->next; sl2->next = NULL; free_str_list(sl2); sl2 = sl_next; } if(!sl1) { hd_data->klog = sl2; return; } if(sl1 && !sl2) { hd_data->klog = sl1; return; } /* now, try to join sl1 & sl2 */ for(sl_last = NULL, sl = sl1; sl; sl = (sl_last = sl)->next) { if(!str_list_cmp(sl, sl2)) { free_str_list(sl); if(sl_last) sl_last->next = NULL; else sl1 = NULL; break; } } /* append sl2 to sl1 */ for(ssl = &sl1; *ssl; ssl = &(*ssl)->next); *ssl = sl2; hd_data->klog = sl1; }