static int xv_alloc_frame( void ) { int size; uint8_t *alloc; size = input_width * input_height * 2; if( use_shm ) { alloc = create_shm( size ); } else { alloc = malloc( input_width * input_height * 2 ); } if( alloc ) { /* Initialize the input image to black. */ blit_colour_packed422_scanline( alloc, input_width * input_height, 16, 128, 128 ); if( use_shm ) { image = XvShmCreateImage( display, xv_port, FOURCC_YUY2, (char *) alloc, input_width, input_height, &shminfo ); } else { image = XvCreateImage( display, xv_port, FOURCC_YUY2, (char *) alloc, input_width, input_height ); } image_data = alloc; return 1; } return 0; }
int product() { char buf[128]; if (!create_shm()) { fprintf(stderr, "create_shm failed\n"); return -1; } printf("write some data:\n"); fgets(buf, sizeof(buf), stdin); if (!write_data(buf)) { fprintf(stderr, "write_data failed\n"); return -1; } sleep(10); if (shmctl(shmid, IPC_RMID, NULL) == -1) { perror("shmctl"); return -1; } return 1; }
int main(int argc, char *argv[]){ int iter = 0; /* identifiant du segment de memoire partage */ int shmid; if(argc != 2){ printf("Error :\t ./v4 nber_iteration\n"); exit(EXIT_FAILURE); } iter = atoi(argv[1]); /* creation zone memoire */ shmid = create_shm(100,"key",1); /* creation des processus */ switch(fork()){ case -1 : error("Creation fils", ERR_CREAT_FILS); case 0 : /* on est dans le fils */ incremente(iter, shmid); default : break; } decremente(iter, shmid); /*on attends la fin des processus */ printf("Le pere attend la mort de son fils\n") ; wait(0); printf("Bon, faisons le menage et supprimons le segment partagee\n") ; /*destruction du segment de memoire */ delete_shm(shmid); printf("Le pere se suicide\n") ; return 0; }
static int dosdetector_post_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { void *user_data; apr_pool_userdata_get(&user_data, USER_DATA_KEY, s->process->pool); if (user_data == NULL) { apr_pool_userdata_set((const void *)(1), USER_DATA_KEY, apr_pool_cleanup_null, s->process->pool); return OK; } apr_status_t rv = create_shm(s, p); if(rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, "failed to create shared memory"); return HTTP_INTERNAL_SERVER_ERROR; } apr_pool_cleanup_register(p, NULL, cleanup_shm, apr_pool_cleanup_null); rv = ap_global_mutex_create(&lock, NULL, mutex_id, NULL, s, p, 0); if(rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, "failed to create global mutex"); return HTTP_INTERNAL_SERVER_ERROR; } #ifdef _DEBUG const char *mutex_name = apr_global_mutex_name(lock); DEBUGLOG("mutex name is %s", mutex_name); const char *mutex_filename = apr_global_mutex_lockfile(lock); DEBUGLOG("mutex filename is %s", mutex_filename); #endif apr_pool_cleanup_register(p, NULL, cleanup_mutex, apr_pool_cleanup_null); return OK; }
int setup_shm() { /* set up shared Memory */ printf("Setting up shared Memory ..."); /* create REF File, if it not exists */ remove(REF_FILE); create_if_missing(REF_FILE, S_IRUSR | S_IWUSR); /*create shm 'unique' key */ key_t shm_key = ftok(REF_FILE, 1); if (shm_key < 0) { handle_error(-1, "ftok failed", NO_EXIT); } create_shm(shm_key, "create", "shmget failed", IPC_CREAT | IPC_EXCL); shm_id = create_shm(shm_key, "create", "shmget failed", 0); return 1; }
int main() { int _size=4096; int shm_id=create_shm(_size); char* mem=(char*)attach(shm_id); int index=0; while(1) { mem[index++]='A'; mem[index+1]='\0'; index++; sleep(1); } detach(mem); return 0; }
int worker(int num) { char *local, *remote; //int id; int k; fprintf(stderr, "\tbind process %d to cpu %ld\n", num, cpu_num - num - 1); if (bind_to_cpu(cpu_num - num - 1) < 0) { //(*total_e)++; kill(0, SIGUSR1); exit(-1); } local = (char *)create_shm(key[num], shm_size); if (local == NULL) { kill(0, SIGUSR1); exit(-1); } k = (num % 2 == 0 ? num + 1 : num - 1); remote = (char *)wait_remote_shm(key[k], shm_size); if (remote == NULL) { kill(0, SIGUSR1); exit(-1); } while (1) { sem_wait(sem[num]); fill_mem(local, data, shm_size); sem_wait(write_lock); (*total_w)++; sem_post(write_lock); sem_post(sem[num]); sem_wait(sem[k]); if (read_mem(remote, data, shm_size) < 0) { sem_post(sem[k]); (*total_e)++; kill(0, SIGUSR1); exit(-1); } sem_wait(read_lock); (*total_r)++; sem_post(read_lock); sem_post(sem[k]); } }
static int initialize_module(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { //DEBUGLOG("initialize_module is called"); ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, MODULE_NAME " " MODULE_VERSION " started."); void *user_data; apr_pool_userdata_get(&user_data, USER_DATA_KEY, s->process->pool); if (user_data == NULL) { apr_pool_userdata_set((const void *)(1), USER_DATA_KEY, apr_pool_cleanup_null, s->process->pool); return OK; } create_shm(s, p); apr_pool_cleanup_register(p, NULL, cleanup_shm, apr_pool_cleanup_null); return OK; }
void loop(void *arg){ RT_HEAP sampling_heap; Matrix outputMatrix=empty_matrix(1,1); long* current_period; int create; //This works as a global variable current_period=(long*) create_shm(&sampling_heap,"tickPeriod",sizeof(long),&create); *current_period=gs->sampling_period*1000; if(*current_period<SAFEZONE) *current_period=SAFEZONE; rt_task_set_periodic(NULL, TM_NOW,*current_period); while(running){ rt_task_wait_period(NULL); debug_get_start_time(); //XL forces this block to have inputs, //so we force the count to zero to ignore it io.input_num = 0; debug_store_inputs(); write_output_queues(&outputMatrix); debug_write_queue(); outputMatrix.matrix[0][0]++; //Change period if changed in GUI if(*current_period!=gs->sampling_period*1000){ *current_period=gs->sampling_period*1000; if(*current_period<SAFEZONE) *current_period=SAFEZONE; rt_task_set_periodic(NULL, TM_NOW,*current_period); } } delete_shm(&sampling_heap,current_period); }
int main(int argc, char *argv[]) { if(argc != 2){ printf("Please enter a file name\n"); exit(1); } printf("This programm use semaphore and shared memory, please cleanup after testing\n"); int sem_id = create_sem("create semaphore", "semget failed"); semid_for_cleanup = sem_id; int i; for(i = 0; i < 250; i++){ int retcode = semctl(sem_id, i, SETVAL , 1); if(retcode < 0){ printf("Init semaphore %d\n", i); handle_error(retcode, "Could not initialize semaphore to 1"); } } int shm_id = create_shm("create shared memory", "shmget failed"); struct data *shm_data = (struct data *) shmat(shm_id, NULL, 0); show_shm_ctl(shm_id, "Show shared memory information:"); shmid_for_cleanup = shm_id; printf("Start reading\n"); readFile(argv[1], shm_data, sem_id); printf("Reading finished\n"); printResult(shm_data); printf("Detach the shared memory\n"); shmdt(shm_data); //cleanup(); exit(0); }
int task_communate() { int shm_id; char msg[10]; /* create shared memory. */ shm_id = create_shm(); /* receive the message. If "yes" continu,"no" wait... */ rcv_shm(shm_id, msg); while( strcmp(msg,"yes")!=0 ) { sleep(1); rcv_shm(shm_id, msg); } /* send message "no" */ snd_shm(shm_id,"no"); /* return shm_id for next. */ return shm_id; }
int main(int argc, char **argv) { int permission = 0644; int opt; size_t size = 0; int nsems = 0; int ask_shm = 0, ask_msg = 0, ask_sem = 0; static const struct option longopts[] = { {"shmem", required_argument, NULL, 'M'}, {"semaphore", required_argument, NULL, 'S'}, {"queue", no_argument, NULL, 'Q'}, {"mode", required_argument, NULL, 'p'}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); atexit(close_stdout); while((opt = getopt_long(argc, argv, "hM:QS:p:Vh", longopts, NULL)) != -1) { switch(opt) { case 'M': size = strtosize_or_err(optarg, _("failed to parse size")); ask_shm = 1; break; case 'Q': ask_msg = 1; break; case 'S': nsems = strtos32_or_err(optarg, _("failed to parse elements")); ask_sem = 1; break; case 'p': permission = strtoul(optarg, NULL, 8); break; case 'h': usage(stdout); break; case 'V': printf(UTIL_LINUX_VERSION); return EXIT_SUCCESS; default: errtryhelp(EXIT_FAILURE); } } if(!ask_shm && !ask_msg && !ask_sem) usage(stderr); if (ask_shm) { int shmid; if (-1 == (shmid = create_shm(size, permission))) err(EXIT_FAILURE, _("create share memory failed")); else printf(_("Shared memory id: %d\n"), shmid); } if (ask_msg) { int msgid; if (-1 == (msgid = create_msg(permission))) err(EXIT_FAILURE, _("create message queue failed")); else printf(_("Message queue id: %d\n"), msgid); } if (ask_sem) { int semid; if (-1 == (semid = create_sem(nsems, permission))) err(EXIT_FAILURE, _("create semaphore failed")); else printf(_("Semaphore id: %d\n"), semid); } return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { int ret = EXIT_SUCCESS; int childstatus; pid_t pid; const char taskname[13]="trinity-main"; outputstd("Trinity " VERSION " Dave Jones <*****@*****.**>\n"); progname = argv[0]; initpid = getpid(); page_size = getpagesize(); num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN); max_children = num_online_cpus; /* possibly overridden in params. */ if (init_random() == FALSE) exit(EXIT_FAILURE); set_seed(0); select_syscall_tables(); create_shm(); /* We do this before the parse_args because --fds will need to * operate on it when implemented. */ setup_fd_providers(); parse_args(argc, argv); init_uids(); change_tmp_dir(); init_logging(); init_shm(); kernel_taint_initial = check_tainted(); if (kernel_taint_initial != 0) output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n"); if (munge_tables() == FALSE) { ret = EXIT_FAILURE; goto out; } if (show_syscall_list == TRUE) { dump_syscall_tables(); goto out; } init_syscalls(); if (show_ioctl_list == TRUE) { dump_ioctls(); goto out; } do_uid0_check(); if (do_specific_domain == TRUE) find_specific_domain(specific_domain_optarg); setup_initial_mappings(); parse_devices(); pids_init(); setup_main_signals(); /* check if we ctrl'c or something went wrong during init. */ if (shm->exit_reason != STILL_RUNNING) goto cleanup_fds; init_watchdog(); /* do an extra fork so that the watchdog and the children don't share a common parent */ fflush(stdout); pid = fork(); if (pid == 0) { shm->mainpid = getpid(); setup_main_signals(); no_bind_to_cpu = RAND_BOOL(); output(0, "Main thread is alive.\n"); prctl(PR_SET_NAME, (unsigned long) &taskname); set_seed(0); if (open_fds() == FALSE) { if (shm->exit_reason != STILL_RUNNING) panic(EXIT_FD_INIT_FAILURE); // FIXME: Later, push this down to multiple EXIT's. exit_main_fail(); } if (dropprivs == TRUE) //FIXME: Push down into child processes later. drop_privs(); main_loop(); shm->mainpid = 0; _exit(EXIT_SUCCESS); } /* wait for main loop process to exit. */ (void)waitpid(pid, &childstatus, 0); /* wait for watchdog to exit. */ waitpid(watchdog_pid, &childstatus, 0); output(0, "Ran %ld syscalls. Successes: %ld Failures: %ld\n", shm->stats.total_syscalls_done - 1, shm->stats.successes, shm->stats.failures); cleanup_fds: close_sockets(); destroy_initial_mappings(); shutdown_logging(); ret = set_exit_code(shm->exit_reason); out: exit(ret); }
int main(int argc, char* argv[]) { int ret = EXIT_SUCCESS; int childstatus; unsigned int i; outputstd("Trinity v" __stringify(VERSION) " Dave Jones <*****@*****.**>\n"); progname = argv[0]; initpid = getpid(); page_size = getpagesize(); num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN); select_syscall_tables(); if (create_shm()) exit(EXIT_FAILURE); parse_args(argc, argv); outputstd("Done parsing arguments.\n"); if (kernel_taint_mask != (int)0xFFFFFFFF) { outputstd("Custom kernel taint mask has been specified: 0x%08x (%d).\n", kernel_taint_mask, kernel_taint_mask); } if (user_specified_children != 0) max_children = user_specified_children; else max_children = sysconf(_SC_NPROCESSORS_ONLN); if (max_children > MAX_NR_CHILDREN) { outputerr("Increase MAX_NR_CHILDREN!\n"); exit(EXIT_FAILURE); } setup_shm_postargs(); if (logging == TRUE) open_logfiles(); if (munge_tables() == FALSE) { ret = EXIT_FAILURE; goto out; } if (show_syscall_list == TRUE) { dump_syscall_tables(); goto out; } init_syscalls(); if (show_ioctl_list == TRUE) { dump_ioctls(); goto out; } if (getuid() == 0) { if (dangerous == TRUE) { outputstd("DANGER: RUNNING AS ROOT.\n"); outputstd("Unless you are running in a virtual machine, this could cause serious problems such as overwriting CMOS\n"); outputstd("or similar which could potentially make this machine unbootable without a firmware reset.\n\n"); outputstd("ctrl-c now unless you really know what you are doing.\n"); for (i = 10; i > 0; i--) { outputstd("Continuing in %d seconds.\r", i); (void)fflush(stdout); sleep(1); } } else { outputstd("Don't run as root (or pass --dangerous if you know what you are doing).\n"); exit(EXIT_FAILURE); } } if (do_specific_proto == TRUE) find_specific_proto(specific_proto_optarg); init_buffers(); parse_devices(); pids_init(); setup_main_signals(); kernel_taint_initial = check_tainted(); if (kernel_taint_initial != 0) { output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n"); } change_tmp_dir(); /* check if we ctrl'c or something went wrong during init. */ if (shm->exit_reason != STILL_RUNNING) goto cleanup_fds; init_watchdog(); do_main_loop(); /* Shutting down. */ waitpid(watchdog_pid, &childstatus, 0); output(0, "\nRan %ld syscalls. Successes: %ld Failures: %ld\n", shm->total_syscalls_done - 1, shm->successes, shm->failures); ret = EXIT_SUCCESS; cleanup_fds: close_sockets(); destroy_global_mappings(); if (logging == TRUE) close_logfiles(); out: exit(ret); }
int main( int argc, char *argv[] ) { CONFIGURATION conf; int shm_fd; RINGBUFFER rb; char *logs; /* NETWORK Socket */ int sockfd; ssize_t n; socklen_t len; struct sockaddr_in cliaddr; char msg[NET_BUF_SIZE]; char clientip[IP_STRLEN]; /* Other variables */ int c; erase_conf_struct( &conf ); /* Analyze command line arguments */ opterr = 0; while ((c = getopt (argc, argv, AVAILABLE_ARGUMENTS)) != -1) switch(c) { case 'd': conf.debug = YES; break; case 'f': break; case 'n': conf.nb_bytes = atoll(optarg); break; case 'h': help(0); break; case '?': if ( (optopt == 'f') || (optopt == 'n') ) fprintf(stderr, "-%c: missing arguments\n", optopt); else if (isprint(optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); help(1); break; default: help(1); } /* * Init phase */ /* Configuration initialisation */ init_configuration( &conf ); if (conf.debug == YES) print_configuration( &conf ); /* SHM setup */ if ((shm_fd = create_shm(SHM_PATH, conf.nb_bytes)) < 0) MANAGE_ERROR("can't create shm", TRUE, EXIT_FAILURE); if ((logs = mmap(NULL, conf.nb_bytes, (PROT_READ | PROT_WRITE), MAP_SHARED, shm_fd, 0)) == MAP_FAILED) MANAGE_ERROR("mmap", TRUE, EXIT_FAILURE); /* ring buffer */ rb_init(&rb, logs, conf.nb_bytes); //rb_info(&rb); /* main listening daemon */ udp_daemon_setup(&sockfd, 1514); /* Signals management */ (void) signal(SIGINT, leave); len = sizeof(cliaddr); /* * Main Loop */ while ((n = recvfrom(sockfd, msg, NET_BUF_SIZE, 0, (struct sockaddr *)&cliaddr, &len)) > 0) { /*if (memcmp(msg, "dump logs", 9) == 0) { printf("DUMP:\n"); rb_dump(&rb); continue; } if (memcmp(msg, "print logs", 10) == 0) { printf("PRINT:\n"); rb_print(&rb); continue; } */ // n - 1 to remove the remaining \n memcpy(clientip, inet_ntoa(cliaddr.sin_addr), IP_STRLEN); //rb_add_row(&rb, msg, n); rb_add_row(&rb, msg, n, clientip); memset(msg, '\0', NET_BUF_SIZE); } printf("\n"); unlink_shm(SHM_PATH); return EXIT_SUCCESS; }
void *thrFunc(void * args) { char fifo_name[MAX_SIZE]; //Gerar o nome do fifo strcpy(fifo_name,"/tmp/fb_"); char str_pid[MAX_SIZE]; sprintf(str_pid, "%d", getpid()); strcat(fifo_name, str_pid); mkfifo(fifo_name, 0660); //Criar o fifo com o nome gerado anteriormente Shared_memory * shm; if( (shm = create_shm(((ArgsToSend *)args)->name,((ArgsToSend *)args)->mytime)) == NULL ) { //Caso tenha falhado em criar uma memoria partilhada printf("Shared memory could not be created\n"); exit(EXIT_FAILURE); } printf("Store was created at %s", ctime(&shm->mytime)); printf("Desk number %d\n", shm->sum); int desk_number = shm->sum; //Salvar numero de balcao porque a memoria partilhada vai ser alterada signal(SIGALRM, alarmhandler); alarm(((ArgsToSend *)args)->mytime); time_t opening_time = time(NULL); //Receber o tempo de abertura de balcao para controlar o tempo em que ele esta aberto fd1 = open(fifo_name, O_RDONLY); int fd2 = open(fifo_name, O_WRONLY); //Abrir um fifo de escrita e de leitura ao mesmo tempo para originar espera bloqueante if (fd1 < 0 && !alarmflag) { perror("FIFO open()"); exit(EXIT_FAILURE); } putchar('\n'); char str[100]; pthread_t thread_array[5000]; int size = 0; while(opening_time - shm->mytime < ((ArgsToSend *)args)->mytime){ //Enquanto o tempo nao passar if(readline(fd1,str)) //Se houver alguma coisa a ler (espera bloqueante porque ha um fifo de leitura e escrita abertos ao mesmo tempo, portanto so passa desta linha quando houver uma mensagem a receber do lado do cliente) { Treatment_args * t_args = malloc(sizeof(Treatment_args)); t_args->shm = shm; t_args->desk_number = desk_number; strcpy(t_args->str, str); pthread_t treatment_thread; pthread_create(&treatment_thread, NULL, treatment_thr, t_args); //Cria uma thread de atendimento thread_array[size] = treatment_thread; size++; } opening_time = time(NULL); //Atualizar o tempo } //Depois de receber while(size >= 0) { //Espera que todas as threads criadas anteriormente terminem pthread_join(thread_array[size], NULL); size--; } close(fd1); //fecha os fifos close(fd2); shm->table[desk_number - 1][DURATION] = ((ArgsToSend *)args)->mytime; //Atualizar duracao na tabela quando o balcao fecha, valor diferente de -1 if(shm->table[shm->sum - 1][RECEPTIONED] > 0) shm->table[desk_number - 1][AVERAGE_TIME] = time_sum / shm->table[shm->sum - 1][RECEPTIONED]; print_on_log(desk_number, "fecha_balcao"); if(shm->running == 1) //Significa que este e o ultimo balcao em execucao, tem por isso que libertar a memoria partilhada { for(; shm->sum > 0; shm->sum--) { printf("Desk num: %d, opened at: %d, with duration of: %d, with pid of %d, with %d clients in reception, with %d receptioned clients, with %d seconds of average time\n", shm->table[shm->sum - 1][DESK_NUM], shm->table[shm->sum - 1][TIME], shm->table[shm->sum - 1][DURATION], shm->table[shm->sum - 1][PID], shm->table[shm->sum - 1][IN_RECEPTION], shm->table[shm->sum - 1][RECEPTIONED], shm->table[shm->sum - 1][AVERAGE_TIME]); } print_on_log(desk_number, "fecha_loja"); destroy_shm(shm,((ArgsToSend *)args)->name); }else{ shm->running--; } close(log_file); free(args); //liberta memoria alocada anteriormente pthread_exit(NULL); }
int main(int argc, char *argv[]) { time_t t_start = time(NULL); if (is_help_requested(argc, argv)) { usage(argv[0], ""); } if (argc > 2) { usage(argv[0], "too many arguments"); } int retcode = 0; create_if_missing(REF_FILE, S_IRUSR | S_IWUSR); key_t shm_key = ftok(REF_FILE, 1); if (shm_key < 0) { handle_error(-1, "ftok failed", PROCESS_EXIT); } key_t sem_key = ftok(REF_FILE, 2); if (sem_key < 0) { handle_error(-1, "ftok failed", PROCESS_EXIT); } if (argc == 2 && strcmp(argv[1], "-s") == 0) { printf("setting up IPC\n"); int shm_id = create_shm(shm_key, "create", "shmget failed", IPC_CREAT); shmid_for_cleanup = shm_id; int semaphore_id = create_sem(sem_key, SEM_SIZE, "create", "semget (data) failed", IPC_CREAT); semid_for_cleanup = semaphore_id; show_sem_ctl(semaphore_id, 0, "semaphore before setup"); setup_sem(semaphore_id, "semaphore setup failed"); show_sem_ctl(semaphore_id, 0, "semaphore after setup"); printf("done\n"); exit(0); } int shm_id = create_shm(shm_key, "create", "shmget failed", 0); shmid_for_cleanup = shm_id; int semaphore_id = create_sem(sem_key, SEM_SIZE, "create", "semget failed", 0); semid_for_cleanup = semaphore_id; if (argc == 2 && strcmp(argv[1], "-c") == 0) { printf("cleaning up IPC\n"); cleanup(); exit(0); } char *name = ""; if (argc == 2) { name = argv[1]; } struct data *shm_data = (struct data *) shmat(shm_id, NULL, 0); time_t total_data_semops_wait = 0; char buffer[BUF_SIZE]; long *counter = shm_data->counter; while (TRUE) { ssize_t size_read = read(STDIN_FILENO, buffer, BUF_SIZE); if (size_read == 0) { /* end of file */ break; } handle_error(size_read, "error while reading stdin", PROCESS_EXIT); int i; for (i = 0; i < size_read; i++) { unsigned char c = buffer[i]; unsigned int ck = c % SEM_SIZE; struct sembuf semops_write; semops_write.sem_num = ck; semops_write.sem_op = -SEM_LIMIT; semops_write.sem_flg = SEM_UNDO; time_t t0 = time(NULL); // show_sem_ctl(semaphore_id, ck, "reserving write semaphore"); retcode = semop(semaphore_id, &semops_write, 1); handle_error(retcode, "error while getting write-semaphore", PROCESS_EXIT); // show_sem_ctl(semaphore_id, ck, "write semaphore reserved"); time_t dt = time(NULL) - t0; total_data_semops_wait += dt; counter[c]++; semops_write.sem_num = ck; semops_write.sem_op = SEM_LIMIT; semops_write.sem_flg = SEM_UNDO; // show_sem_ctl(semaphore_id, ck, "freeing write semaphore"); retcode = semop(semaphore_id, &semops_write, 1); handle_error(retcode, "error while releasing write-semaphore", PROCESS_EXIT); // show_sem_ctl(semaphore_id, ck, "write semaphore freed"); } } time_t total_duration = time(NULL) - t_start; unsigned int i; char output_buffer[16384]; char *output_ptr = output_buffer; int n; int m = 0; n = sprintf(output_ptr, "------------------------------------------------------------\n"); output_ptr += n; m += n; n = sprintf(output_ptr, "%s: pid=%ld\n", name, (long) getpid()); output_ptr += n; m += n; n = sprintf(output_ptr, "total wait for data: ~ %ld sec; total duration: ~ %ld\n", (long) total_data_semops_wait, (long) total_duration); output_ptr += n; m += n; n = sprintf(output_ptr, "------------------------------------------------------------\n"); output_ptr += n; m += n; for (i = 0; i < ALPHA_SIZE; i++) { struct sembuf semops_read; unsigned int ck = (i % SEM_SIZE); semops_read.sem_num = ck; semops_read.sem_op = -1; semops_read.sem_flg = SEM_UNDO; retcode = semop(semaphore_id, &semops_read, 1); handle_error(retcode, "error while getting read-semaphore", PROCESS_EXIT); long *counter = shm_data->counter; long val = counter[i]; semops_read.sem_op = 1; retcode = semop(semaphore_id, &semops_read, 1); handle_error(retcode, "error while releasing read-semaphore", PROCESS_EXIT); if (! (i & 007)) { n = sprintf(output_ptr, "\n"); output_ptr += n; m += n; } if ((i & 0177) < 32 || i == 127) { n = sprintf(output_ptr, "\\%03o: %10ld ", i, val); output_ptr += n; m += n; } else { n = sprintf(output_ptr, "%4c: %10ld ", (char) i, val); output_ptr += n; m += n; } } n = sprintf(output_ptr, "\n\n"); output_ptr += n; m += n; n = sprintf(output_ptr, "------------------------------------------------------------\n\n"); output_ptr += n; m += n; write(STDOUT_FILENO, output_buffer, (size_t) m); exit(0); }
// Create a shared memory segment for a child process // // This function takes a pointer to a ProcessInfo structure // creates a shared memory segment for it. A default size // of SHM_SIZE is used // // @param[in,out] pi A pointer to a ProcessInfo structure void MathildaFork::create_shm(ProcessInfo *pi) { create_shm(pi, SHM_SIZE); }
int main(int argc, char **argv){ char c; char *cores = NULL; char *nodes = NULL; int shuffle = 0; struct shared_state s = {}; while ((c = getopt(argc, argv, "+vVsc:n:SN")) != -1) { switch (c) { case 'c': if(cores) { fprintf(stderr, "-c or -n already used !\n"); exit(EXIT_FAILURE); } cores = strdup(optarg); break; case 'n': if(nodes || cores) { fprintf(stderr, "-c or -n already used !\n"); exit(EXIT_FAILURE); } nodes = strdup(optarg); break; case 'N': s.per_node = 1; break; case 's': shuffle = 1; break; case 'S': s.server = 1; break; case 'v': s.verbose = 1; break; case 'V': s.verbose = 1; s.verbose_err = 1; break; default: usage(argv[0]); } } if(!cores && !nodes) cores = build_default_affinity_string(shuffle); if(optind == argc) usage(argv[0]); argv += optind; char *lib = get_lib_path(); setenv("LD_PRELOAD", lib, 1); free(lib); int *cores_array; if(cores) { parse_cores(cores, &cores_array, &s.nr_entries_in_cores, 0); } else { parse_cores(nodes, &cores_array, &s.nr_entries_in_cores, 1); } char *uniq_shm_name = NULL; assert(asprintf(&uniq_shm_name, "%s_%d", "/tmp/shm", gettid())); assert(create_shm(uniq_shm_name, &s, cores_array)); setenv("PINTHREADS_SHMID", uniq_shm_name, 1); setenv("PINTHREADS_SHMSIZE", get_shm_size(), 1); free(uniq_shm_name); execvp(argv[0], argv); perror("execvp"); fprintf(stderr,"failed to execute %s\n", argv[0]); cleanup_shm(uniq_shm_name); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int retcode; /* SIG Handler */ signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); /* SHM & SEM */ FILE *fptr; fptr = fopen(REF_FILE, "rb+"); if (fptr == NULL) { fptr = fopen(REF_FILE, "wb"); } shmkey = ftok(REF_FILE, 9); handle_error(semkey, "ftok():"); shmid = create_shm(shmkey); handle_error(shmid, "create_shm():"); nodes = (struct datei *) shmat(shmid, NULL, 0); semkey = ftok(REF_FILE, 2); handle_error(semkey, "ftok():"); semid = create_sem(semkey, 20, IPC_CREAT); handle_error(semid, "create_sem():"); struct sembuf sem_one, sem_all, sem_one_reset, sem_all_reset; sem_one.sem_num = 0; sem_one.sem_op = -1; sem_one.sem_flg = SEM_UNDO; sem_one_reset.sem_num = 0; sem_one_reset.sem_op = 1; sem_one_reset.sem_flg = SEM_UNDO; sem_all.sem_num = 0; sem_all.sem_op = -20; sem_all.sem_flg = SEM_UNDO; sem_all_reset.sem_num = 0; sem_all_reset.sem_op = 20; sem_all_reset.sem_flg = SEM_UNDO; /* SOCKET */ int clntLen, portno; char buffer[256]; struct sockaddr_in server_addr, clnt_addr; server_sock = socket(AF_INET, SOCK_STREAM, 0); handle_error(server_sock, "socket():"); bzero((char *) &server_addr, sizeof(server_addr)); portno = 15000; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(portno); retcode = bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)); handle_error(retcode, "bind():"); retcode = listen(server_sock, 100); handle_error(semid, "listen():"); clntLen = sizeof(clnt_addr); while (1) { client_sock = accept(server_sock, (struct sockaddr *) &clnt_addr, &clntLen); handle_error(semid, "accept():"); int pid; pid = fork(); if (pid < 0) { close(client_sock); perror("ERROR ACCEPTING CONNECTION!\n"); exit(1); } else if (pid > 0) { continue; } else { /* CHILD */ while (1) { int result = read(client_sock, buffer, 255); handle_error(result, "write()"); char delimiter[] = " ,;:\n"; char *cmd = strtok(buffer, delimiter); char *name = strtok(NULL, delimiter); char *size = strtok(NULL, delimiter); /* LIST */ if (strcmp(cmd, "LIST") == 0) { int i = 0; int c = 0; char *temp; char message[5000]; temp = (char*) malloc(sizeof(nodes)); while ((int) strlen(nodes[i].name) != 0) { if (strcmp(nodes[i].name, "DELETED") == 0) { i++; } else { strcat(temp, nodes[i].name); strcat(temp, "\n"); c++; i++; } } sprintf(message, "ACK %d\n%s", c, temp); result = write(client_sock, message, strlen(message)); handle_error(result, "write()"); temp[0] = '\0'; message[0] = '\0'; } else /* CREATE */ if (strcmp(cmd, "CREATE") == 0 && name != NULL && size != NULL) { int i = 0; int status = 0; char *message; message = "FILEEXISTS\n"; while ((int) strlen(nodes[i].name) != 0) { if (strcmp(nodes[i].name, name) != 0) { i++; } else { status = 1; break; } } if (status != 1) { i = 0; while ((int) strlen(nodes[i].name) != 0) { if (strcmp(nodes[i].name, "DELETED") == 0) { break; } i++; } nodes[i].semval[0] = (short) 10; strcpy(nodes[i].name, name); nodes[i].size = atoi(size); result = write(client_sock, "CONTENT:\n", 10); handle_error(result, "write()"); result = read(client_sock, buffer, 255); handle_error(result, "read()"); strcpy(nodes[i].content, buffer); message = "FILECREATED\n"; } result = write(client_sock, message, strlen(message)); handle_error(result, "write()"); } else /* READ */ if (strcmp(cmd, "READ") == 0 && name != NULL) { int i = 0; char message[256]; sprintf(message, "NOSUCHFILE\n"); while ((int) strlen(nodes[i].name) != 0) { if (strcmp(nodes[i].name, name) == 0) { result = semctl(semid, 0, SETALL, &nodes[i].semval[0]); handle_error(result, "semctl()"); result = semop(semid, &sem_one, 1); handle_error(result, "semop()"); nodes[i].semval[0] = semctl(semid, 0, GETVAL, 0); sprintf(message, "FILECONTENT %s %d\n%s\n", nodes[i].name, nodes[i].size, nodes[i].content); result = semop(semid, &sem_one_reset, 1); handle_error(result, "semop()"); nodes[i].semval[0] = semctl(semid, 0, GETVAL, 0); break; } i++; } result = write(client_sock, message, strlen(message)); message[0] = '\0'; handle_error(result, "write()"); } else /* UPDATE */ if (strcmp(cmd, "UPDATE") == 0 && name != NULL && size != NULL) { int i = 0; char *message; message = "NOSUCHFILE\n"; while ((int) strlen(nodes[i].name) != 0) { if (strcmp(nodes[i].name, name) == 0) { result = semctl(semid, 0, SETALL, &nodes[i].semval[0]); handle_error(result, "semctl()"); nodes[i].size = atoi(size); strcpy(nodes[i].content, ""); message = "CONTENT:\n"; result = semop(semid, &sem_all, 1); handle_error(result, "semop()"); nodes[i].semval[0] = semctl(semid, 0, GETVAL, 0); result = read(client_sock, buffer, 256); handle_error(result, "write()"); strcpy(nodes[i].content, buffer); result = write(client_sock, "UPDATED\n", 9); handle_error(result, "write()"); result = semop(semid, &sem_all_reset, 1); handle_error(result, "semop()"); nodes[i].semval[0] = semctl(semid, 0, GETVAL, 0); break; } i++; } result = write(client_sock, message, strlen(message)); handle_error(result, "write()"); } else /* DELETE */ if (strcmp(cmd, "DELETE") == 0 && name != NULL) { int i = 0; char *message; message = "NOSUCHFILE\n"; while ((int) strlen(nodes[i].name) != 0) { if (strcmp(nodes[i].name, name) == 0) { result = semctl(semid, 0, SETALL, &nodes[i].semval[0]); handle_error(result, "write()"); if (semop(semid, &sem_all, 1) < 0) { printf("ERROR SEMOP FOR FILE\n"); } nodes[i].semval[0] = semctl(semid, 0, GETVAL, 0); strcpy(nodes[i].name, "DELETED"); strcpy(nodes[i].content, ""); nodes[i].size = 0; message = "DELETED\n"; result = semop(semid, &sem_all_reset, 1); handle_error(result, "semop()"); nodes[i].semval[0] = semctl(semid, 0, GETVAL, 0); break; } i++; } result = write(client_sock, message, strlen(message)); handle_error(result, "write()"); } /* CMDUNKNOWN */ else { retcode = write(client_sock, "CMDUNKNOWN\n", 19); handle_error(result, "write()"); } } } } }
int main(int argc, char* argv[]) { int ret = EXIT_SUCCESS; const char taskname[13]="trinity-main"; outputstd("Trinity " VERSION " Dave Jones <*****@*****.**>\n"); progname = argv[0]; mainpid = getpid(); page_size = getpagesize(); num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN); max_children = num_online_cpus; /* possibly overridden in params. */ if (init_random() == FALSE) exit(EXIT_FAILURE); select_syscall_tables(); create_shm(); /* We do this before the parse_args because --fds will need to * operate on the providers list when implemented. */ setup_fd_providers(); parse_args(argc, argv); init_uids(); change_tmp_dir(); init_logging(); init_shm(); kernel_taint_initial = check_tainted(); if (kernel_taint_initial != 0) output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n"); if (munge_tables() == FALSE) { ret = EXIT_FAILURE; goto out; } if (show_syscall_list == TRUE) { dump_syscall_tables(); goto out; } if (show_ioctl_list == TRUE) { dump_ioctls(); goto out; } if (show_unannotated == TRUE) { show_unannotated_args(); goto out; } init_syscalls(); do_uid0_check(); if (do_specific_domain == TRUE) find_specific_domain(specific_domain_optarg); pids_init(); init_object_lists(OBJ_GLOBAL); setup_initial_mappings(); parse_devices(); /* FIXME: Some better object construction method needed. */ create_futexes(); create_sysv_shms(); setup_main_signals(); no_bind_to_cpu = RAND_BOOL(); prctl(PR_SET_NAME, (unsigned long) &taskname); if (open_fds() == FALSE) { if (shm->exit_reason != STILL_RUNNING) panic(EXIT_FD_INIT_FAILURE); // FIXME: Later, push this down to multiple EXIT's. _exit(EXIT_FAILURE); } if (dropprivs == TRUE) //FIXME: Push down into child processes later. drop_privs(); main_loop(); destroy_global_objects(); output(0, "Ran %ld syscalls. Successes: %ld Failures: %ld\n", shm->stats.total_syscalls_done - 1, shm->stats.successes, shm->stats.failures); shutdown_logging(); ret = set_exit_code(shm->exit_reason); out: exit(ret); }
int main(int argc, char* argv[]) { int ret; unsigned int i; printf("Trinity v" __stringify(VERSION) " Dave Jones <*****@*****.**> 2012\n"); #ifdef __x86_64__ syscalls = syscalls_x86_64; max_nr_syscalls = NR_X86_64_SYSCALLS; #elif __i386__ syscalls = syscalls_i386; max_nr_syscalls = NR_I386_SYSCALLS; #elif __powerpc__ syscalls = syscalls_ppc; #elif __ia64__ syscalls = syscalls_ia64; #elif __sparc__ syscalls = syscalls_sparc; #else syscalls = syscalls_i386; #endif progname = argv[0]; parse_args(argc, argv); if (getuid() == 0) { if (dangerous == 1) { printf("DANGER: RUNNING AS ROOT.\n"); printf("Unless you are running in a virtual machine, this could cause serious problems such as overwriting CMOS\n"); printf("or similar which could potentially make this machine unbootable without a firmware reset.\n\n"); printf("ctrl-c now unless you really know what you are doing.\n"); for (i = 10; i > 0; i--) { printf("Continuing in %d seconds.\r", i); (void)fflush(stdout); sleep(1); } } else { printf("Don't run as root (or pass --dangerous if you know what you are doing).\n"); exit(EXIT_FAILURE); } } if (create_shm()) exit(EXIT_FAILURE); if (logging != 0) open_logfiles(); max_nr_syscalls = NR_SYSCALLS; for (i = 0; i < max_nr_syscalls; i++) syscalls[i].entry->number = i; if (desired_group == GROUP_VM) { struct syscalltable *newsyscalls; int count = 0, j = 0; for (i = 0; i < max_nr_syscalls; i++) { if (syscalls[i].entry->group == GROUP_VM) count++; } newsyscalls = malloc(count * sizeof(struct syscalltable)); if (newsyscalls == NULL) exit(EXIT_FAILURE); for (i = 0; i < max_nr_syscalls; i++) { if (syscalls[i].entry->group == GROUP_VM) newsyscalls[j++].entry = syscalls[i].entry; } max_nr_syscalls = count; syscalls = newsyscalls; } if (!do_specific_syscall) output("Fuzzing %d syscalls.\n", max_nr_syscalls); if (do_specific_syscall == 1) find_specific_syscall(); if (do_specific_proto == 1) find_specific_proto(); if (show_syscall_list == 1) { syscall_list(); exit(EXIT_SUCCESS); } page_size = getpagesize(); if (!seed) seed_from_tod(); else output("[%d] Random seed: %u (0x%x)\n", getpid(), seed, seed); init_buffers(); mask_signals(); setup_fds(); if (check_tainted() != 0) { output("Kernel was tainted on startup. Will keep running if trinity causes an oops.\n"); do_check_tainted = 1; } /* just in case we're not using the test.sh harness. */ chmod("tmp/", 0755); ret = chdir("tmp/"); if (!ret) { /* nothing right now */ } main_loop(); printf("\nRan %ld syscalls (%ld retries). Successes: %ld Failures: %ld\n", shm->execcount - 1, shm->retries, shm->successes, shm->failures); shmdt(shm); destroy_maps(); for (i = 0; i < socks; i++) close(socket_fds[i]); if (logging != 0) close_logfiles(); exit(EXIT_SUCCESS); }
int main(int argc, char* argv[]) { int ret = EXIT_SUCCESS; unsigned int i; printf("Trinity v" __stringify(VERSION) " Dave Jones <*****@*****.**> 2012\n"); progname = argv[0]; setup_syscall_tables(); parse_args(argc, argv); /* If we didn't pass -c or -x, mark all syscalls active. */ if ((do_specific_syscall == FALSE) && (do_exclude_syscall == FALSE)) mark_all_syscalls_active(); if (getuid() == 0) { if (dangerous == TRUE) { printf("DANGER: RUNNING AS ROOT.\n"); printf("Unless you are running in a virtual machine, this could cause serious problems such as overwriting CMOS\n"); printf("or similar which could potentially make this machine unbootable without a firmware reset.\n\n"); printf("ctrl-c now unless you really know what you are doing.\n"); for (i = 10; i > 0; i--) { printf("Continuing in %d seconds.\r", i); (void)fflush(stdout); sleep(1); } } else { printf("Don't run as root (or pass --dangerous if you know what you are doing).\n"); exit(EXIT_FAILURE); } } if (create_shm()) exit(EXIT_FAILURE); /* Set seed in parent thread*/ set_seed(0); if (desired_group != GROUP_NONE) { ret = setup_syscall_group(desired_group); if (ret == FALSE) { ret = EXIT_FAILURE; goto cleanup_shm; } } if (show_syscall_list == TRUE) { dump_syscall_tables(); goto cleanup_shm; } if (validate_syscall_tables() == FALSE) { printf("No syscalls were enabled!\n"); printf("Use 32bit:%d 64bit:%d\n", use_32bit, use_64bit); goto cleanup_shm; } sanity_check_tables(); if (logging == TRUE) open_logfiles(); if (do_specific_syscall == FALSE) { if (biarch == TRUE) output(0, "Fuzzing %d 32-bit syscalls & %d 64-bit syscalls.\n", max_nr_32bit_syscalls, max_nr_64bit_syscalls); else output(0, "Fuzzing %d syscalls.\n", max_nr_syscalls); } if (do_specific_proto == TRUE) find_specific_proto(specific_proto_optarg); page_size = getpagesize(); init_buffers(); mask_signals(); if (check_tainted() != 0) { output(0, "Kernel was tainted on startup. Will keep running if trinity causes an oops.\n"); do_check_tainted = TRUE; } /* just in case we're not using the test.sh harness. */ chmod("tmp/", 0755); ret = chdir("tmp/"); if (!ret) { /* nothing right now */ } if (shm->exit_reason != STILL_RUNNING) goto cleanup_fds; init_watchdog(); do_main_loop(); printf("\nRan %ld syscalls. Successes: %ld Failures: %ld\n", shm->total_syscalls_done - 1, shm->successes, shm->failures); ret = EXIT_SUCCESS; cleanup_fds: for (i = 0; i < nr_sockets; i++) { struct linger ling; ling.l_onoff = FALSE; /* linger active */ setsockopt(shm->socket_fds[i], SOL_SOCKET, SO_LINGER, &ling, sizeof(struct linger)); shutdown(shm->socket_fds[i], SHUT_RDWR); close(shm->socket_fds[i]); } destroy_maps(); if (logging == TRUE) close_logfiles(); cleanup_shm: if (shm != NULL) munmap(shm, sizeof(struct shm_s)); exit(ret); }
int main(int argc, char **argv) { int i; char *logfile_name=NULL; unsigned int seed=0; int sample_rate,paranoid,kernel_watchdog; FILE *fff; struct utsname uname_info; char cpuinfo[BUFSIZ]; int seed_specified=0; int c,j,missing=0; time_t timer; char buffer[26]; struct tm* tm_info; struct timeval current_time; long long interval_start=0; double rate; /*********************************/ /* Parse command line parameters */ /*********************************/ while ((c=getopt(argc, argv,"hvl:r:s:t:"))!=-1) { switch(c) { case 'h': /* help */ usage(argv[0],1); exit(0); break; case 'v': /* version */ usage(argv[0],0); exit(0); break; case 'l': /* log */ logging=TYPE_ALL; logfile_name=strdup(optarg); break; case 'r': /* seed */ seed=atoi(optarg); seed_specified=1; printf("Using user-specified random seed of %d\n",seed); break; case 's': /* stop */ stop_after=atoi(optarg); break; case 't': /* type */ type=0; for(j=0;j<strlen(optarg);j++) { switch(optarg[j]) { case 'O': type|=TYPE_OPEN; break; case 'C': type|=TYPE_CLOSE; break; case 'I': type|=TYPE_IOCTL; break; case 'R': type|=TYPE_READ; break; case 'M': type|=TYPE_MMAP; break; case 'F': type|=TYPE_FORK; break; case 'Q': type|=TYPE_TRASH_MMAP; break; case 'W': type|=TYPE_WRITE; break; case 'P': type|=TYPE_PRCTL; break; case 'p': type|=TYPE_POLL; break; case 'A': type|=TYPE_ACCESS; break; case 'o': type|=TYPE_OVERFLOW; break; case 'i': type|=TYPE_MILLION; break; default: printf("Unknown type %c\n", optarg[j]); } } break; default: usage(argv[0],1); exit(1); break; } } /****************/ /* Open logfile */ /****************/ if (logging) { if (!strcmp(logfile_name,"-")) { log_fd=1; /* stdout */ } else { log_fd=open(logfile_name,O_WRONLY|O_CREAT,0660); if (log_fd<0) { fprintf(stderr,"Error opening %s: %s\n", logfile_name,strerror(errno)); exit(1); } fprintf(stderr,"Warning! Using a named log file might disrupt determinism due to the extra file descriptor created. Consider logging to stdout instead\n\n"); } } /****************/ /* Print banner */ /****************/ printf("\n*** perf_fuzzer %s *** by Vince Weaver\n\n",VERSION); /*****************/ /* Print OS info */ /*****************/ uname(&uname_info); printf("\t%s version %s %s\n", uname_info.sysname,uname_info.release,uname_info.machine); /*****************/ /* Print cpuinfo */ /*****************/ get_cpuinfo(cpuinfo); printf("\tProcessor: %s\n",cpuinfo); /*****************/ /* Print options */ /*****************/ if (stop_after) printf("\tStopping after %d\n",stop_after); /* TODO: Make these configurable */ printf("\tWatchdog enabled with timeout %ds\n",WATCHDOG_TIMEOUT); printf("\tWill auto-exit if signal storm detected\n"); /**********************/ /* Print logging info */ /**********************/ if (logging) { printf("\tLogging to file: %s\n",logfile_name); printf("\tLogging perf_event_open() failures: %s\n", LOG_FAILURES?"yes":"no"); printf("\tRunning fsync after every syscall: %s\n", FSYNC_EVERY?"yes":"no"); } /************************************/ /* Seed the random number generator */ /************************************/ /* should read /dev/urandom instead? */ if (!seed) { seed=time(NULL); printf("\tSeeding RNG from time %d\n",seed); } else { printf("\tSeeding RNG with supplied seed %d\n",seed); } srand(seed); /* Write seed to disk so we can find it later */ fff=fopen("last.seed","w"); if (fff!=NULL) { fprintf(fff,"%d\n",seed); fclose(fff); } if (logging) { sprintf(log_buffer,"S %d\n",seed); write(log_fd,log_buffer,strlen(log_buffer)); } /************************/ /* setup watchdog timer */ /************************/ /* FIXME: make optional */ struct sigaction watchdog; memset(&watchdog, 0, sizeof(struct sigaction)); watchdog.sa_sigaction = alarm_handler; watchdog.sa_flags = SA_SIGINFO | SA_RESTART; if (sigaction( SIGALRM, &watchdog, NULL) < 0) { printf("Error setting up alarm handler\n"); } alarm(WATCHDOG_TIMEOUT); /******************************/ /* Initialize data structures */ /******************************/ /* Clear errnos count */ for(i=0;i<MAX_ERRNOS;i++) { stats.open_errno_count[i]=0; stats.fork_errno_count[i]=0; } /* Clear type counts */ for(i=0;i<MAX_OPEN_TYPE;i++) { stats.open_type_success[i]=0; stats.open_type_fail[i]=0; } /* Save our pid so we can re-map on replay */ if (logging) { sprintf(log_buffer,"G %d\n",getpid()); write(log_fd,log_buffer,strlen(log_buffer)); } /* Save the content of /proc/sys/kernel/perf_event_max_sample_rate */ /* If it has been changed, a replay might not be perfect */ sample_rate=get_sample_rate(); if (logging) { sprintf(log_buffer,"r %d\n",sample_rate); write(log_fd,log_buffer,strlen(log_buffer)); } /* Check kernel watchdog */ kernel_watchdog=get_kernel_watchdog_value(); /* Check paranoid setting */ paranoid=get_paranoid_value(); /*******************************/ /* Print reproduce information */ /*******************************/ printf("\n\tTo reproduce, try:\n"); printf("\t\techo %d > /proc/sys/kernel/nmi_watchdog\n", kernel_watchdog); printf("\t\techo %d > /proc/sys/kernel/perf_event_paranoid\n", paranoid); printf("\t\techo %d > /proc/sys/kernel/perf_event_max_sample_rate\n", sample_rate); printf("\t\t"); for(i=0;i<argc;i++) { printf("%s ",argv[i]); } if (!seed_specified) printf("-r %d",seed); printf("\n\n"); /* Print what we are actually fuzzing */ /* Sometimes I comment out code and forget */ missing=0; printf("\tFuzzing the following syscalls: "); if (type&TYPE_MMAP) printf("mmap "); else missing++; if (type&TYPE_OPEN) printf("perf_event_open "); else missing++; if (type&TYPE_CLOSE) printf("close "); else missing++; if (type&TYPE_READ) printf("read "); else missing++; if (type&TYPE_WRITE) printf("write "); else missing++; if (type&TYPE_IOCTL) printf("ioctl "); else missing++; if (type&TYPE_FORK) printf("fork "); else missing++; if (type&TYPE_PRCTL) printf("prctl "); else missing++; if (type&TYPE_POLL) printf("poll "); else missing++; printf("\n"); if (missing) { printf("\t*NOT* Fuzzing the following syscalls: "); if (!(type&TYPE_MMAP)) printf("mmap "); if (!(type&TYPE_OPEN)) printf("perf_event_open "); if (!(type&TYPE_CLOSE)) printf("close "); if (!(type&TYPE_READ)) printf("read "); if (!(type&TYPE_WRITE)) printf("write "); if (!(type&TYPE_IOCTL)) printf("ioctl "); if (!(type&TYPE_FORK)) printf("fork "); if (!(type&TYPE_PRCTL)) printf("prctl "); if (!(type&TYPE_POLL)) printf("poll "); printf("\n"); } missing=0; printf("\tAlso attempting the following: "); if (type&TYPE_OVERFLOW) printf("signal-handler-on-overflow "); else missing++; if (type&TYPE_MILLION) printf("busy-instruction-loop "); else missing++; if (type&TYPE_ACCESS) printf("accessing-perf-proc-and-sys-files "); else missing++; if (type&TYPE_TRASH_MMAP) printf("trashing-the-mmap-page "); else missing++; printf("\n"); if (missing) { printf("\t*NOT* attempting the following: "); if (!(type&TYPE_OVERFLOW)) printf("signal-handler-on-overflow "); if (!(type&TYPE_MILLION)) printf("busy-instruction-loop "); if (!(type&TYPE_ACCESS)) printf("accessing-perf-proc-and-sys-files "); if (!(type&TYPE_TRASH_MMAP)) printf("trashing-the-mmap-page "); printf("\n"); } if (attempt_determinism) { printf("\n\tAttempting more deterministic results by:\n\t"); printf("waitpid-after-killing-child "); printf("disabling-overflow-signal-handler "); printf("\n"); /* Disable overflows if trying for determinism */ if (attempt_determinism) { type&=~TYPE_OVERFLOW; } } /******************************************/ /* Set up to match trinity setup, vaguely */ /******************************************/ page_size=getpagesize(); //printf("Page size=%d\n",page_size); num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN); create_shm(); create_shm_arrays(); init_shm(); // init_shared_pages(); syscall_perf_event_open.init(); /* Initialize PMU names if possible */ /* This depends on trinity exporting the values */ if (pmus!=NULL) { for(i=0;i<num_pmus;i++) { if (pmus[i].type<MAX_OPEN_TYPE) { stats_set_pmu_name(pmus[i].type,pmus[i].name); } } } /************************/ /* Set up SIGIO handler */ /************************/ /* In theory we shouldn't get SIGIO as we set up SIGRT for overflow */ /* But if the RT queue overflows we will get a SIGIO */ memset(&sigio, 0, sizeof(struct sigaction)); sigio.sa_sigaction = sigio_handler; sigio.sa_flags = SA_SIGINFO; if (sigaction( SIGIO, &sigio, NULL) < 0) { printf("Error setting up SIGIO signal handler\n"); } /* Set up SIGQUIT handler */ memset(&sigquit, 0, sizeof(struct sigaction)); sigquit.sa_sigaction = sigquit_handler; sigquit.sa_flags = SA_SIGINFO; if (sigaction( SIGQUIT, &sigquit, NULL) < 0) { printf("Error setting up SIGQUIT signal handler\n"); } /* Initialize Event Structure */ for(i=0;i<NUM_EVENTS;i++) { event_data[i].active=0; event_data[i].fd=0; event_data[i].read_size=rand(); } /* Sleep to make it easier to ftrace/ptrace */ printf("\n\tPid=%d, sleeping 1s\n\n",getpid()); sleep(1); /* Print start time */ time(&timer); tm_info = localtime(&timer); strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info); printf("==================================================\n"); printf("Starting fuzzing at %s\n",buffer); printf("==================================================\n"); gettimeofday(¤t_time,NULL); interval_start=current_time.tv_sec; /****************/ /* MAIN LOOP */ /****************/ while(1) { switch(rand()%11) { case 0: if (type&TYPE_OPEN) { open_random_event(type&TYPE_MMAP, type&TYPE_OVERFLOW); } break; case 1: if (type&TYPE_CLOSE) { // if (rand()%3==0) close_random_event(); } break; case 2: if (type&TYPE_IOCTL) { ioctl_random_event(); } break; case 3: if (type&TYPE_PRCTL) { prctl_random_event(); } break; case 4: if (type&TYPE_READ) { read_random_event(); } break; case 5: if (type&TYPE_WRITE) { write_random_event(); } break; case 6: if (type&TYPE_ACCESS) { access_random_file(); } break; case 7: if (type&TYPE_FORK) { fork_random_event(); } break; case 8: if (type&TYPE_POLL) { poll_random_event(); } break; case 9:if (type&TYPE_MMAP) { mmap_random_event(type); } break; default: if (type&TYPE_MILLION) { run_a_million_instructions(); } break; } #if FSYNC_EVERY if (logging) fsync(log_fd); #endif if (throttle_close_event) { printf("Closing stuck event %d\n", throttle_close_event); close_event(throttle_close_event,1); throttle_close_event=0; } next_overflow_refresh=rand()%2; next_refresh=rand_refresh(); stats.total_iterations++; watchdog_counter++; if ((stop_after) && (stats.total_iterations>=stop_after)) { long long end_count; end_count=stats.total_iterations% STATUS_UPDATE_INTERVAL; if ((end_count==0) && (stats.total_iterations>0)) { end_count=STATUS_UPDATE_INTERVAL; } gettimeofday(¤t_time,NULL); rate=((double)(end_count))/ (current_time.tv_sec-interval_start); dump_summary(stderr,1,rate); /* Kill child, doesn't happen automatically? */ if (already_forked) { int status; kill(forked_pid,SIGKILL); waitpid(forked_pid, &status, 0); } return 0; } /* Print status update every 10000 iterations */ /* Don't print if logging to stdout as it clutters */ /* up the trace file. */ if (stats.total_iterations%STATUS_UPDATE_INTERVAL==0) { gettimeofday(¤t_time,NULL); rate=((double)STATUS_UPDATE_INTERVAL)/ (current_time.tv_sec-interval_start); if (log_fd!=1) { dump_summary(stderr,1,rate); } else { dump_summary(stderr,0,rate); } interval_start=current_time.tv_sec; } // fsync(log_fd); } return 0; }
int main(int argc, char* argv[]) { int ret = EXIT_SUCCESS; int childstatus; unsigned int i; printf("Trinity v" __stringify(VERSION) " Dave Jones <*****@*****.**>\n"); progname = argv[0]; page_size = getpagesize(); select_syscall_tables(); if (create_shm()) exit(EXIT_FAILURE); parse_args(argc, argv); printf("Done parsing arguments.\n"); setup_shm_postargs(); if (logging == TRUE) open_logfiles(); if (munge_tables() == FALSE) { ret = EXIT_FAILURE; goto out; } if (show_syscall_list == TRUE) { dump_syscall_tables(); goto out; } if (show_ioctl_list == TRUE) { dump_ioctls(); goto out; } if (getuid() == 0) { if (dangerous == TRUE) { printf("DANGER: RUNNING AS ROOT.\n"); printf("Unless you are running in a virtual machine, this could cause serious problems such as overwriting CMOS\n"); printf("or similar which could potentially make this machine unbootable without a firmware reset.\n\n"); printf("ctrl-c now unless you really know what you are doing.\n"); for (i = 10; i > 0; i--) { printf("Continuing in %d seconds.\r", i); (void)fflush(stdout); sleep(1); } } else { printf("Don't run as root (or pass --dangerous if you know what you are doing).\n"); exit(EXIT_FAILURE); } } if (do_specific_proto == TRUE) find_specific_proto(specific_proto_optarg); init_buffers(); parse_devices(); pids_init(); setup_main_signals(); if (check_tainted() != 0) { output(0, "Kernel was tainted on startup. Will keep running if trinity causes an oops.\n"); ignore_tainted = TRUE; } /* just in case we're not using the test.sh harness. */ chmod("tmp/", 0755); ret = chdir("tmp/"); if (!ret) { /* nothing right now */ } if (shm->exit_reason != STILL_RUNNING) goto cleanup_fds; init_watchdog(); do_main_loop(); waitpid(shm->watchdog_pid, &childstatus, 0); printf("\nRan %ld syscalls. Successes: %ld Failures: %ld\n", shm->total_syscalls_done - 1, shm->successes, shm->failures); ret = EXIT_SUCCESS; cleanup_fds: for (i = 0; i < nr_sockets; i++) { struct linger ling; ling.l_onoff = FALSE; /* linger active */ setsockopt(shm->socket_fds[i], SOL_SOCKET, SO_LINGER, &ling, sizeof(struct linger)); shutdown(shm->socket_fds[i], SHUT_RDWR); close(shm->socket_fds[i]); } destroy_maps(); if (logging == TRUE) close_logfiles(); out: exit(ret); }
int main(int argc, char *argv[]) { time_t t0 = time(NULL); if (argc > 2) { printf("Usage\n\n"); printf("%s -c\ncleanup ipc\n\n", argv[0]); printf("%s -s\nsetup ipc\n\n", argv[0]); printf("%s < inputfile\ncout file, show accumulated output\n\n", argv[0]); printf("%s name < inputfile\ncout file, show output with name\n\n", argv[0]); exit(1); } int retcode = 0; create_if_missing(REF_FILE, S_IRUSR | S_IWUSR); key_t shm_key = ftok(REF_FILE, 1); if (shm_key < 0) { handle_error(-1, "ftok failed", PROCESS_EXIT); } if (argc == 2 && strcmp(argv[1], "-s") == 0) { printf("setting up IPC\n"); create_shm(shm_key, "create", "shmget failed", IPC_CREAT | IPC_EXCL); create_sem(1, "sem_open failed", O_CREAT | O_EXCL); printf("done\n"); exit(0); } int shm_id = create_shm(shm_key, "create", "shmget failed", 0); sem_t *sem_ptr = create_sem(1, "semget failed", 0); if (argc == 2 && strcmp(argv[1], "-c") == 0) { printf("cleaning up IPC\n"); cleanup(shm_id, sem_ptr); exit(0); } char *name = ""; if (argc == 2) { name = argv[1]; } struct data *shm_data = (struct data *) shmat(shm_id, NULL, 0); char buffer[BUF_SIZE]; struct data local_data; long *counter = local_data.counter; for (int i = 0; i < ALPHA_SIZE; i++) { counter[i] = 0L; } while (TRUE) { ssize_t size_read = read(STDIN_FILENO, buffer, BUF_SIZE); if (size_read == 0) { /* end of file */ break; } handle_error(size_read, "error while reading stdin", PROCESS_EXIT); int i; for (i = 0; i < size_read; i++) { unsigned char c = buffer[i]; counter[c]++; } } unsigned int i; time_t t1 = time(NULL); retcode = sem_wait(sem_ptr); handle_error(retcode, "error while getting semaphore", PROCESS_EXIT); time_t dt = time(NULL) - t1; for (int i = 0; i < ALPHA_SIZE; i++) { long *tcounter = shm_data->counter; long *scounter = local_data.counter; tcounter[i] += scounter[i]; } time_t total = time(NULL) - t0; printf("------------------------------------------------------------\n"); printf("%s: pid=%ld\n", name, (long) getpid()); printf("total time for calculation: ~ %ld sec; total wait for semaphore: ~ %ld sec\n", (long) total, (long) dt); printf("------------------------------------------------------------\n"); for (i = 0; i < ALPHA_SIZE; i++) { long *counter = shm_data->counter; long val = counter[i]; if (! (i & 007)) { printf("\n"); fflush(stdout); } if ((i & 0177) < 32 || i == 127) { printf("\\%03o: %10ld ", i, val); } else { printf("%4c: %10ld ", (char) i, val); } } printf("\n\n"); printf("------------------------------------------------------------\n\n"); fflush(stdout); retcode = sem_post(sem_ptr); handle_error(retcode, "error while releasing semaphore", PROCESS_EXIT); retcode = sem_close(sem_ptr); handle_error(retcode, "error while closing semaphore", PROCESS_EXIT); retcode = shmdt(shm_data); handle_error(retcode, "error while detaching shared memory", PROCESS_EXIT); /* cleanup(); */ printf("done\n"); exit(0); }
// Main Function int main(int argc, char *argv[]) { signal(SIGINT, sighandler); int retcode; // Startparameter überprüfen if (argc !=2) { usage(); } // Ref-File überprüfen und ggf erstellen FILE *ref_file_ptr; ref_file_ptr = fopen(REF_FILE, "r+"); if (ref_file_ptr == NULL){ ref_file_ptr = fopen(REF_FILE, "w+"); if (ref_file_ptr == 0){ perror("Datei konnte nicht erstellt werden"); } } retcode = fclose(ref_file_ptr); handle_error(retcode,"fclose() Fehlgeschlagen", NO_EXIT); // Shared Memory für Kontrollstruktur erstellen shm_fh_key = ftok(REF_FILE, 1); shm_fh_id = create_shm(shm_fh_key, (MAX_FILES * (MAX_FILESIZE+270)), "create", "create_shm() failed"); printf("shm_id %d\n", shm_fh_id); fh = (struct fileheader *) shmat(shm_fh_id, NULL, 0); // Semaphor erstellen, Vorbereitungen sem_fh_key = ftok(REF_FILE, 1); sem_fh_id = create_sem(sem_fh_key, MAX_FILES+1, "erstelle Semaphor", "Semaphor fehlgeschlagen"); semun_lock.val = 0; semun_unlock.val = 1; // Initialisiere die Dateistruktur "Formatieren". MAX_FILES + 1 ist der Semaphor für die Kontrollstruktur for (int i = 0; i < (MAX_FILES +1); i++){ fh[i].filelength = 0; fh[i].filename[0] = '\0'; retcode = semctl(sem_fh_id,i,SETVAL, semun_unlock); handle_error(retcode, "init sem", PROCESS_EXIT); //fh[i].shm_key = 0; Vorgesehen für Variante 2 gemäss Seminarbericht fh[i].content[0] = '\0'; } // Welcome Screen printf("*************************\n"); printf("Multi-User Fileserver\n"); printf("*************************\n"); // Server initialisieren //int server_socket; /* Socketdeskriptor für Server*/ //int client_socket; /* Socketdeskriptor für Client*/ struct sockaddr_in server_addr; /* IP-Adresse des lokalen Servers */ struct sockaddr_in client_addr; /* IP-Adresse des Clients */ unsigned short server_port; /* Port des Servers für IP-Verbindungen */ unsigned int client_addr_len; server_port = atoi(argv[1]); //printf("server_port %d\n", server_port); server_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); handle_error(server_socket,"socket failed", NO_EXIT); //printf("serv_sock: %d\n",serv_sock); /* Adress-Struktur */ memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; /* Internet Address Family */ server_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ server_addr.sin_port = htons(server_port); /* local server port */ /* binding */ retcode = bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)); handle_error(retcode, "binding failed", NO_EXIT); /* make socket listening to incoming connections */ retcode = listen(server_socket,MAX_PEND); handle_error(retcode, "listen failed", NO_EXIT); while (true) { client_addr_len = sizeof(client_addr); client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &client_addr_len); handle_error(client_socket, "accept failed", NO_EXIT); int pid; pid = fork(); if (pid < 0) { perror("fork() Fehler beim Erstellen von Child-Prozess"); exit(1); } else if (pid > 0) { continue; } else { /* This is the client process */ close(server_socket); handle_request(client_socket); exit(0); } } return 0; }