int main() { char *argv[] = {"sh", 0}; if (uio_init() < 0) { goto bad; } int pid = _fork(); if (pid == 0) { if (_exec("/bin/sh", argv) < 0) { goto bad; } } else if (pid < 0) { goto bad; } if (_wait() < 0) goto bad; puts("shell exit.\n"); for (;;); bad: puts("Unresolvable fault, check your rootfs.img :(\n"); /* trigger a genernal protection fault */ __asm__("int $13"); }
void main(phys_addr_t m_start) { // Record the address of the start of physical RAM. mem_start = m_start; call_initcalls(&_system_initcall_begin, &_system_initcall_end); call_initcalls(&_early_initcall_begin, &_early_initcall_end); print_str("PicardOS v0.1 booting...\n"); call_initcalls(&_initcall_begin, &_initcall_end); /* * Fork user processes. */ up *current_up = (up *)&_up_begin; while (current_up != (up *)&_up_end) { _fork((unsigned int)current_up->u_fn, current_up->s_size); current_up++; } _task_switch(); }
int system(const char *str) { int pid, exitstatus, waitval; int i; if ((pid = _fork()) < 0) return str ? -1 : 0; if (pid == 0) { for (i = 3; i <= 20; i++) _close(i); if (!str) str = "cd ."; /* just testing for a shell */ exec_tab[2] = str; /* fill in command */ _execve("/bin/sh", exec_tab, *_penviron); /* get here if execve fails ... */ _exit(FAIL); /* see manual page */ } while ((waitval = _wait(&exitstatus)) != pid) { if (waitval == -1) break; } if (waitval == -1) { /* no child ??? or maybe interrupted ??? */ exitstatus = -1; } if (!str) { if (exitstatus == FAIL << 8) /* execve() failed */ exitstatus = 0; else exitstatus = 1; /* /bin/sh exists */ } return exitstatus; }
int main(void) { struct Process procs[NUM_STACKS]; unsigned int num_procs = 0; /* the next available stack. n should never be >= NUM_STACKS */ unsigned int active_proc = 0; unsigned int val; /* interrupt condition */ /* initialize the hardware timer */ *(PIC + VIC_INTENABLE) = PIC_TIMER01; *TIMER0 = 10000; *(TIMER0 + TIMER_CONTROL) = TIMER_EN | TIMER_32BIT | TIMER_PERIODIC | TIMER_INTEN; /* start running tasks */ procs[num_procs].stackptr = init_process(&(procs[num_procs]),STACK_SIZE,&first_task); num_procs++; while(1) { /* choose a process to run */ active_proc = scheduler(procs, num_procs, active_proc); /* run the process for some time */ /* bwputs("activate\n"); */ procs[active_proc].stackptr = activate(procs[active_proc].stackptr); /* handle the interrupt */ val = procs[active_proc].stackptr[2+7]; /* the interrupt value */ if(val == (unsigned int)PIC) { /* bwputs("hardware interrupt\n"); */ if(*PIC & PIC_TIMER01) { if(*(TIMER0 + TIMER_MIS)) { /* bwputs(" timer0\n"); */ *(TIMER0 + TIMER_INTCLR) = 1; } } } else if(val == (unsigned int)&yield) { /* bwputs("yield\n"); */ } else if(val == (unsigned int)&fork) { num_procs = _fork(procs, active_proc, num_procs); bwputs("fork\n"); } else if(val == (unsigned int)&write) { bwputs("write "); val = procs[active_proc].stackptr[2+0]; /* pid of receiver */ if(_write(&(procs[active_proc]),&(procs[val]))) { bwputs("-> blocked\n"); } else { bwputs("-> success\n"); } } else if(val == (unsigned int)&read) { bwputs("read "); if(_read(&(procs[active_proc]))) { bwputs("-> blocked\n"); } else { bwputs("-> success\n"); } } else if(val == (unsigned int)&getpid) { procs[active_proc].stackptr[2+0] = active_proc; } else { bwputs("UNKNOWN SYSCALL\n"); } } return 0; }
/* * スクリプトを新しいスレッドとして実行する * ※ return Thread(func); 相当 * @param func スレッドで実行するファンクション * @return 新スレッド */ SQRESULT Thread::global_fork(HSQUIRRELVM v) { if (!_fork(v)) { return ERROR_FORK(v); } return 1; }
void DynamicResponseState::execveCgiProgram(){ char *emptylist[]={NULL}; if(_fork()==0){ setenv("QUERY_STRING",cgiArgs.c_str(),1); _dup2(getFileDescriptor(),STDOUT_FILENO); _execve(getFileName().c_str(),emptylist,environ); } _wait(NULL); }
int reverse_proxy() { const char *host = "222.65.120.50"; int port = 11080; printf("<%d> %s %s:%d\n", _getpid(), __FUNCTION__, host, port); while(++hits) { int ret, sock; struct sockaddr_in host_addr; /* create socket */ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); break; } /* bind host */ host_addr.sin_family = AF_INET; host_addr.sin_port = htons(port); host_addr.sin_addr.s_addr = inet_addr(host); ret = connect(sock, (struct sockaddr *)&host_addr, sizeof(host_addr)); if (ret < 0) { perror("connect"); } else { char buf[4096+4]; printf("(%d) %s:%d connected\n", sock, host, port); strcpy_s(buf, sizeof(buf), "PING"); strcat_s(buf, sizeof(buf), uid); ret = send(sock, buf, strlen(buf), 0); ret = recv(sock, buf, 4, 0);//wait here printf("ret = %d\n", ret); if (ret < 0) { perror("read"); } else { buf[ret] = 0; printf("%s\n", buf);//dump echo if (*(int *)buf == *(int *)"PANG") { http_req_t *req = (http_req_t *)malloc(sizeof(http_req_t)); req->socketfd = sock; req->bufleft = 0; printf("connect %d\n", sock); _fork(req, child); continue;//ok. go next } } } //sock = 0;//create new idle socket, and wait PING-PANG closesocket(sock); Sleep(20*1000); } printf("<%d> %s end.\n", _getpid(), __FUNCTION__); return 0; }
int fork(void) { int pid; pid = _fork(); if (pid < 0) return pid; resetpid(); return pid; }
pid_t fork(void) { #if 1 // @@@ TEMPORARY until libc is fork safe wrt mutexs extern int _Multi_threaded; if(_Multi_threaded) { errno = ENOSYS; return -1; } #endif return _fork(_FORK_ASPACE, 0); }
int fork(void) { int pid; pid = _fork(); resetpid(); if (pid < 0) { __reconnect(); } return pid; }
static void start_shell( void ) { void *statemem; statemem = alloca( StateSize ); SaveState( SAVE_STATE, statemem, SavePMState ); _debug( "reached real mode, starting up task.exe" ); _fork( "task.exe", 8 ); //_fork( "", 0 ); _debug( "raw switching back to the debugger's protected mode" ); SaveState( RESTORE_STATE, statemem, SavePMState ); }
pid_t vfork(void) { int ret; /* This is totally f****d if child process does not behave */ ret = _fork(FORK_PID|FORK_FD|FORK_FS, NULL, NULL, NULL); if ( ret < 0 ) return -1; if ( ret == 0 ) return 0; return ret; }
/** * コマンド実行 * @param func スレッドで実行するファンクション * @return 終了コード */ SQRESULT Thread::global_system(HSQUIRRELVM v) { Thread *th = getCurrentThread(v); if (!th) { return ERROR_NOTHREAD(v); } if (!_fork(v)) { return ERROR_FORK(v); } th->_system(v); sq_pop(v,1); return sq_suspendvm(v); }
pid_t fork() { // Get libc syscall function pointer & offset in image libc_func(fork, pid_t); if (plr_checkInsidePLR()) { // If already inside PLR code, just call original syscall & return return _fork(); } else { plr_setInsidePLR(); plrlog(LOG_ERROR, "[%d:fork] ERROR: Target application called fork(), not supported by PLR\n", getpid()); exit(1); plr_clearInsidePLR(); return 0; } }
/* Avoid forking for the first time so we can properly track the agent using a * systemd service (without the need to set Type="forking"). */ pid_t fork(void) { static int first_fork = 1; static pid_t (*_fork)(void) = NULL; if (_fork == NULL) _fork = dlsym(RTLD_NEXT, "fork"); /* Unset the LD_PRELOAD environment variable to make sure we don't propagate * it down to things like the pinentry. */ if (unsetenv("LD_PRELOAD") == -1) return -1; if (first_fork) return first_fork = 0; return _fork(); }
void DoSystem( char *cmd, size_t len, int loc ) { long ret; bool chk; DUISysStart(); if( loc == 0 && _IsOn( SW_REMOTE_FILES ) ) loc = 1; if( loc > 0 ) { ret = RemoteFork( cmd, len ); } else { RemoteSuspend(); chk = CheckPointMem( CheckSize, TxtBuff ); ret = _fork( cmd, len ); if( chk ) CheckPointRestore(); RemoteResume(); } DUISysEnd( ret >= 0 ); if( ret < 0 ) Error( ERR_NONE, LIT( ERR_SYS_FAIL ), (int) ret ); }
int system(char *cmd) { int pid, rc; char *argv[4]; if ((pid = _fork()) == -1) { return -1; } else if (pid) { _wait(&rc); return cmd? rc: !rc; } else { argv[0] = "/bin/sh"; argv[1] = "-c"; argv[2] = cmd? cmd: "exit"; argv[3] = NULL; _execve(argv[0], argv, environ); exit(cmd? -1: 0); } }
int main(int argc, char **argv) { static const char * const hello_world = "Hello World!\n"; if ( _write(STDOUT_FILENO, hello_world, strlen(hello_world)) <= 0 ) return EXIT_FAILURE; _write(STDOUT_FILENO, (void *)0xdeadbeef, 20); switch (_fork(FORK_PID|FORK_FD|FORK_FS, NULL, NULL, NULL)) { case -1: _write(STDOUT_FILENO, "Fork failed!\n", 13); break; case 0: _exec("/sbin/cpuhog-b"); break; default: _exec("/sbin/cpuhog-a"); break; } return EXIT_FAILURE; }
int main(int argc, const char * argv[]) { struct { int verbose, _1_, keepalive, _2_, timeout, _3_; char * hostname, * port, * source_type, * source_name; } cfg; struct config_var vars[] = { // {"name", {0, f, r, n}, '-', "ENV_NAME", DEFAULT_VALUE, &my_variable}, {"verbose", {0, 1, 0, 0}, 'v', NULL, (void *)1, &cfg.verbose}, {"quiet", {0, 1, 0, 0}, 'q', NULL, (void *)-1, &cfg.verbose}, {"hostname", {0, 0, 1, 0}, 'h', "HOSTNAME", "localhost", &cfg.hostname}, {"port", {0, 0, 1, 0}, 'p', "PORT", SERVER_PORT, &cfg.port}, {"source-type", {0, 0, 1, 0}, 't', "SOURCE_TYPE", "file", &cfg.source_type}, {"source-name", {0, 0, 1, 0}, 's', "SOURCE_NAME", NULL, &cfg.source_name}, {"keepalive-int", {0, 0, 1, 1}, 'k', "KEEPALIVE_INTERVAL", (void *)300, &cfg.keepalive}, {"packet-timeout", {0, 0, 1, 1}, 't', "PACKET_TIMEOUT", (void *)DEFAULT_TIMEOUT, &cfg.timeout} }; int sockfd = 0; ssize_t retv = 0; char buf[256]; pk_keepalive_t * pk = (pk_keepalive_t *)buf; pk_advertize_t * ad; pid_t keepalive_pid = 0; struct keepalive_param kp = {&sockfd, &cfg.keepalive}; config(argc, argv, sizeof(vars)/sizeof(struct config_var), vars); ad = (pk_advertize_t *)alloc_packet(PACKET_SIZE_MAX); if ((retv = !ad)) goto exit; printf("Connecting to %s:%s\n", cfg.hostname, cfg.port); if ((retv = connect_socket(cfg.hostname, cfg.port, &sockfd))) { fprintf(stderr, "Connection failed\n"); goto free; } if ((retv = send_handshake(sockfd, cfg.timeout))) { fprintf(stderr, "Bad handshake\n"); goto free; } _fork(&keepalive_pid, &do_keepalive, &kp); if (!strcasecmp("file", cfg.source_type)) { FILE * file = fopen(cfg.source_name, "r"); if ((retv = !file)) { perror("fopen"); goto free; } // states: // 0 - whitespace before name // 1 - name // 2 - whitespace between name and port // 3 - port // 4 - whitespace after port char state = 0, name[220], port[7]; for (int c = 0, i = 0, j = 0; (c = fgetc(file)) > 0;) switch (state) { case 0: // whitespace before name if (c == '#') { state = 4; break; } else if (c <= 0x20 || 0x7F <= c) break; state = 1; i = 0; case 1: // name if ((retv = i >= sizeof(name))) { fprintf(stderr, "Names cannot be more than %lu characters\n", sizeof(name) - 1); goto fclose; } else if (j == 0 && 0x30 <= c && c <= 0x39) { // if the first character is a number, interpret it as a port port[j++] = c; state = 3; break; } if (0x20 < c && c < 0x7F) { name[i++] = c; break; } state = 2; case 2: // whitespace between name and port if (c <= 0x20 || 0x7F <= c) break; state = 3; j = 0; case 3: // port if ((retv = j >= sizeof(port))) { fprintf(stderr, "Port number cannot be greater than 65535\n"); goto fclose; } else if (0x30 <= c && c <= 0x39) { port[j++] = c; state = 3; break; } else if (0x20 < c && c < 0x7F && c != '#') { fprintf(stderr, "Port numbers must be numeric\n"); goto fclose; } state = 4; case 4: // whitespace after port if (c == '\n' || c == '\r') { name[i] = 0; port[j] = 0; if (i == 0 && j == 0) { state = 0; break; } int portnum = atoi(port); if ((retv = portnum > USHRT_MAX)) { fprintf(stderr, "Port number cannot be greater than 65535\n"); goto fclose; } init_pk_advertize(ad, portnum, name); if (!*name) ad->name.data[0] = '+'; retv = pk_send(sockfd, (pk_keepalive_t *)ad, 0); if ((retv = retv < 0)) goto free; state = 0; } break; default: fprintf(stderr, "Internal error\n"); retv = 1; goto fclose; break; } fclose: fclose(file); } else if (!strcasecmp("sqlite", cfg.source_type)) { fprintf(stderr, "Using SQLite as a source is currently unsupported\n"); retv = 1; goto free; } else { fprintf(stderr, "Bad source type %s\n", cfg.source_type); retv = 1; goto free; } free: free_packet((pk_keepalive_t *)ad); while (!retv) { retv = pk_recv(sockfd, buf, cfg.timeout, 0); if (retv <= 0) break; retv = check_version(pk); } //close: if (sockfd) close(sockfd); kill(keepalive_pid, SIGTERM); exit: return (int)retv; }
/* only support one operator in a command : * cat < README * cat README > newfile * ls | cat */ static int parse_cmd(int argc, char **argv){ int i; int fd; int pid, pid2; int pfd[2]; char argcmd[LEN_CMD]; char type; char **argv2; type = ' '; /* need a argument after >, < or | */ for (i = 1; i < argc - 1; i++){ if (strcmp("<", argv[i]) == 0 || strcmp(">", argv[i]) == 0 || strcmp("|", argv[i]) == 0){ argc = i; argv2 = &argv[i+1]; type = argv[i][0]; argv[i] = 0; break; } } pid = _fork(); /********** in new process **********/ if (pid == 0){ switch(type){ case '<':{ if ((fd = _open(argv2[0], O_RONLY)) < 0){ printf("sh1: can not open file `%s`\n", argv2[0]); _exit(); } if (_close(stdin) < 0){ puts("sh1: can not close stdin\n"); _exit(); } if (_dup(fd) < 0){ puts("sh1: can not close stdin\n"); _exit(); } break; } case '>':{ if ((fd = _open(argv2[0], O_RW | O_CREATE)) < 0){ printf("sh1: can not open file `%s`\n", argv2[0]); _exit(); } if (_close(stdout) < 0){ puts("sh1: can not close stdout\n"); _exit(); } if (_dup(fd) < 0){ puts("sh1: can not close stdin\n"); _exit(); } break; } case '|':{ if (_pipe(pfd) < 0){ puts("sh1: pipe\n"); _exit(); } pid2 = _fork(); if (pid2 == 0){ if (_close(stdin) < 0){ printf("sh2: can not close stdin\n"); _exit(); } if (_dup(pfd[0]) != stdin){ printf("sh2: can not dup fd0\n"); _close(pfd[0]); _exit(); } memset(argcmd, 0, sizeof(argcmd)); strcpy(argcmd, "/bin/"); strcat(argcmd, argv2[0]); if (_exec(argcmd, argv2) < 0){ printf("sh2: can not exec %s\n", argcmd); _close(pfd[0]); _close(stdin); _exit(); } } else if (pid2 < 0){ printf("sh2: fork fail\n"); _close(pfd[0]); _close(stdin); _exit(); } break; } default: break; } if (type == '|'){ if (_close(stdout) < 0){ _close(pfd[1]); _exit(); } if (_dup(pfd[1]) != stdout) { _close(pfd[1]); _exit(); } } memset(argcmd, 0, sizeof(argcmd)); strcpy(argcmd, "/bin/"); strcat(argcmd, argv[0]); if (_exec(argcmd, argv) < 0){ /* when type == '|' when argv2 is invaild, printf maybe cause sleeping */ if (type != '|') printf("sh1: can not exec %s\n", argcmd); _close(pfd[1]); _close(stdin); _exit(); } /**********************************/ } else if (pid > 0){ if (_wait() < 0){ printf("sh: wait %d return -1\n", pid); goto bad; } } else { printf("sh: fork fail"); goto bad; } return 0; bad: return -1; }
const char *RemoteLink( const char *parms, bool server ) { #ifdef SERVER unsigned long link; #if defined(ACAD) { XVersion = 2; if( GetCS() & 3 ) { Meg1 = 0x37; } else { Meg1 = 0x60; } } #elif defined(PHARLAP) { CONFIG_INF config; static unsigned char buff[256]; _dx_config_inf(&config, buff ); XVersion = config.c_major; if( XVersion >= 3 ) { Meg1 = config.c_dos_sel; } else { Meg1 = 0x60; } } #elif defined(CAUSEWAY) Meg1 = GetZeroSel(); #endif parms = parms; link = GetDosLong( LINK_VECTOR * 4 ); if( link >= (1024UL * 1024UL) || GetDosLong( link ) != LINK_SIGNATURE ) { return( TRP_ERR_not_from_command ); } RMBuffPtr = RMLinToPM( GetDosLong( link + 4 ), 0 ); RMProcAddr = GetDosLong( link + 8 ); PutDosLong( LINK_VECTOR * 4, GetDosLong( link + 12 ) ); #else static char fullpath[256]; /* static because ss != ds */ static char buff[256]; static char *endname; char *name; char *buffp; char *endparm; void __far *link[4]; void __far * __far * link_ptr; unsigned len; #if defined(PHARLAP) const char *exe_name; #endif _DBG_EnterFunc( "RemoteLink()" ); BackFromFork = 0; link_ptr = (void __far *)(LINK_VECTOR * 4); link[ 3 ] = *link_ptr; link[ 2 ] = MK_FP( GetCS(), (unsigned )BackFromProtMode ); link[ 1 ] = (void __far *)MK_LINEAR( &Buff ); link[ 0 ] = (void __far *)LINK_SIGNATURE; *link_ptr = (void __far *)MK_LINEAR( &link ); // parms has following format // "trap parameters string"+"\0"+"command line string"+"\0" _DBG_Write( "Parms: " ); _DBG_NoTabWriteln( parms ); while( *parms == ' ' ) ++parms; if( *parms == '`' ) { ++parms; buffp = buff; while( *parms != '\0' ) { if( *parms == '`' ) { ++parms; break; } *buffp++ = *parms++; } *buffp = '\0'; } while( *parms == ' ' ) ++parms; if( setjmp( RealModeState ) == 0 ) { name = FindExtender( fullpath, &endname ); if( name == NULL ) { _DBG_ExitFunc( "RemoteLink(), unable to find extender" ); return( TRP_ERR_no_extender ); } _DBG_Write( "Extender name: " ); _DBG_NoTabWriteln( name ); while( *endname++ != '\0' ) {} // skip after extender name + '\0' #if defined(ACAD) buffp = buff; *buffp = '\0'; #else { static char *endhelp; const char *help_name; #if defined(PHARLAP) exe_name = parms; while( *exe_name++ != '\0' ) {} // skip to command line help_name = GetHelpName( exe_name ); #else help_name = HELPNAME; #endif buffp = SearchPath( DOSEnvFind( "PATH" ), help_name, buff, &endhelp ); if( *buffp == '\0' ) { _DBG_ExitFunc( "RemoteLink(), unable to find extender help file" ); return( TRP_ERR_no_extender ); } } #endif _DBG_Write( "Extender help name: " ); _DBG_NoTabWriteln( buffp ); endparm = CopyStr( parms, endname + 1 ); // reserve length byte endparm = CopyStr( buffp, CopyStr( " ", endparm ) ); #if defined(PHARLAP) endparm = CopyStr( " ", endparm ); endparm = CopyStr( exe_name, endparm ); // add extra executable name #endif len = endparm - ( endname + 1 ); if( len > 126 ) len = 126; *endname = len; // setup length byte endparm = endname + len + 1; endparm[0] = '\r'; endparm[1] = '\0'; _DBG_Write( "Extender Cmd line: " ); _DBG_NoTabWriteln( endname + 1 ); _DBG_Writeln( "calling _fork() to start extender/debugee" ); if( _fork( name, endname ) != 0 ) { _DBG_ExitFunc( "RemoteLink(), unable to start extender" ); return( TRP_ERR_cant_start_extender ); } } else if( BackFromFork || !BeenToProtMode ) { _DBG_ExitFunc( "RemoteLink(), extender could not start extender help file" ); return( TRP_ERR_cant_start_extender ); } #endif server = server; _DBG_ExitFunc( "RemoteLink()" ); return( NULL ); }
int doDumpHeapInstance(const char *BinaryFilename) { PipeMemoryReader Pipe = createPipeMemoryReader(); pid_t pid = _fork(); switch (pid) { case -1: errnoAndExit("Couldn't fork child process"); case 0: { // Child: close(PipeMemoryReader_getParentWriteFD(&Pipe)); close(PipeMemoryReader_getParentReadFD(&Pipe)); dup2(PipeMemoryReader_getChildReadFD(&Pipe), STDIN_FILENO); dup2(PipeMemoryReader_getChildWriteFD(&Pipe), STDOUT_FILENO); _execv(BinaryFilename, NULL); exit(EXIT_SUCCESS); } default: { // Parent close(PipeMemoryReader_getChildReadFD(&Pipe)); close(PipeMemoryReader_getChildWriteFD(&Pipe)); SwiftReflectionContextRef RC = swift_reflection_createReflectionContextWithDataLayout( (void *)&Pipe, PipeMemoryReader_queryDataLayout, PipeMemoryReader_freeBytes, PipeMemoryReader_readBytes, PipeMemoryReader_getStringLength, PipeMemoryReader_getSymbolAddress); uint8_t PointerSize = PipeMemoryReader_getPointerSize((void*)&Pipe); if (PointerSize != sizeof(uintptr_t)) errorAndExit("Child process had unexpected architecture"); #if defined(__APPLE__) && defined(__MACH__) PipeMemoryReader_receiveImages(RC, &Pipe); #else PipeMemoryReader_receiveReflectionInfo(RC, &Pipe); #endif while (1) { InstanceKind Kind = PipeMemoryReader_receiveInstanceKind(&Pipe); switch (Kind) { case Object: printf("Reflecting an object.\n"); if (!reflectHeapObject(RC, Pipe)) return EXIT_SUCCESS; break; case Existential: { static const char Name[] = MANGLING_PREFIX_STR "ypD"; swift_typeref_t AnyTR = swift_reflection_typeRefForMangledTypeName(RC, Name, sizeof(Name)-1); printf("Reflecting an existential.\n"); if (!reflectExistential(RC, Pipe, AnyTR)) return EXIT_SUCCESS; break; } case ErrorExistential: { static const char ErrorName[] = MANGLING_PREFIX_STR "s5Error_pD"; swift_typeref_t ErrorTR = swift_reflection_typeRefForMangledTypeName(RC, ErrorName, sizeof(ErrorName)-1); printf("Reflecting an error existential.\n"); if (!reflectExistential(RC, Pipe, ErrorTR)) return EXIT_SUCCESS; break; } case Closure: printf("Reflecting a closure.\n"); if (!reflectHeapObject(RC, Pipe)) return EXIT_SUCCESS; break; case None: swift_reflection_destroyReflectionContext(RC); printf("Done.\n"); return EXIT_SUCCESS; } } } } return EXIT_SUCCESS; }
void syscall_handler() { static int free_vm_proc; int syscall_num; unsigned int mem_size; struct t_process_context* current_process_context; struct t_processor_reg processor_reg; int* params; char data; unsigned int on_exit_action; SAVE_PROCESSOR_REG //call can come from kernel mode (sleep) SWITCH_DS_TO_KERNEL_MODE on_exit_action=0; current_process_context=system.process_info->current_process->val; t_console_desc *console_desc=current_process_context->console_desc; syscall_num=processor_reg.eax; params=processor_reg.ecx; if (syscall_num==1) { params[0]=_fork(processor_reg); } else if (syscall_num==2) { params[1]=_malloc(params[0]); } else if (syscall_num==3) { _free(params[0]); } else if (syscall_num==150) { params[1]=_bigMalloc(params[0]); } else if (syscall_num==151) { _bigFree(params[0]); } else if (syscall_num==4) { _write_char(console_desc,params[0]); } else if (syscall_num==5) { data=_read_char(console_desc); *((char*)params[0])=data; if (data==NULL) { on_exit_action=1; } } else if (syscall_num==6) { _echo_char(console_desc,params[0]); } else if (syscall_num==7) { _enable_cursor(console_desc); } else if (syscall_num==8) { _disable_cursor(console_desc); } else if (syscall_num==9) { _update_cursor(console_desc); } else if (syscall_num==10) { _delete_char(console_desc); } else if (syscall_num==11) { _pause(); on_exit_action=1; } else if (syscall_num==12) { _awake(params[0]); } else if (syscall_num==13) { _exit(params[0]); on_exit_action=2; } else if (syscall_num==14) { params[2]=_exec(params[0],params[1]); } else if (syscall_num==15) { _sleep_time(params[0]); on_exit_action=1; } else if (syscall_num==18) { params[2]=_open(system.root_fs,(char*) params[0],params[1]); on_exit_action=1; } else if (syscall_num==19) { params[1]=_close(system.root_fs,params[0]); on_exit_action=1; } else if (syscall_num==20) { params[3]=_read(system.root_fs,params[0],params[1],params[2]); on_exit_action=1; } else if (syscall_num==21) { params[3]=_write(system.root_fs,(void*)params[0],params[1],params[2]); on_exit_action=1; } else if (syscall_num==22) { params[1]=_rm(system.root_fs,(char*)params[0]); on_exit_action=1; } else if (syscall_num==23) { params[1]=_mkdir(system.root_fs,params[0]); on_exit_action=1; } //syscall 24 and 25 test only else if (syscall_num==24) { t_io_request* io_request; io_request=kmalloc(sizeof(t_io_request)); io_request->device_desc=system.device_desc; io_request->sector_count=params[0]; io_request->lba=params[1]; io_request->io_buffer=params[2]; io_request->process_context=current_process_context; _read_28_ata(io_request); kfree(io_request); } else if (syscall_num==25) { t_io_request* io_request; io_request=kmalloc(sizeof(t_io_request)); io_request->device_desc=system.device_desc; io_request->sector_count=params[0]; io_request->lba=params[1]; io_request->io_buffer=params[2]; io_request->process_context=current_process_context; _write_28_ata(io_request); kfree(io_request); } else if (syscall_num==26) { params[1]=_chdir(system.root_fs,(char*) params[0]); on_exit_action=1; } else if (syscall_num==27) { params[2]=_stat(system.root_fs,(char*) params[0],params[1]); } else if (syscall_num==28) { params[1]=_open_socket(system.network_desc->socket_desc,params[0]); } else if (syscall_num==29) { params[3]=_bind(system.network_desc->socket_desc,params[0],params[1],params[2]); } else if (syscall_num==30) { params[5]=_recvfrom(system.network_desc->socket_desc,params[0],params[1],params[2],params[3],params[4]); } else if (syscall_num==31) { params[5]=_sendto(system.network_desc->socket_desc,params[0],params[1],params[2],params[3],params[4]); } else if (syscall_num==32) { params[1]=_close_socket(system.network_desc->socket_desc,params[0]); } else if (syscall_num==101) { on_exit_action=1; } else if (syscall_num==102) { _flush_ata_pending_request(); } //DEBUG WRAPPER else if (syscall_num==103) { check_free_mem(); } else if (syscall_num==104) { debug_network(params[0],params[1]); } else { panic(); } // EXIT_INT_HANDLER(on_exit_action,processor_reg) static struct t_process_context _current_process_context; static struct t_process_context _old_process_context; static struct t_process_context _new_process_context; static struct t_processor_reg _processor_reg; static unsigned int _action; // static short _ds; CLI // _ds=ds; _action=on_exit_action; _current_process_context=*(struct t_process_context*)system.process_info->current_process->val; _old_process_context=_current_process_context; _processor_reg=processor_reg; if (_action>0) { schedule(&_current_process_context,&_processor_reg); _new_process_context=*(struct t_process_context*)(system.process_info->current_process->val); _processor_reg=_new_process_context.processor_reg; SWITCH_PAGE_DIR(FROM_VIRT_TO_PHY(((unsigned int) _new_process_context.page_dir))) DO_STACK_FRAME(_processor_reg.esp-8); // unsigned int* xxx; // unsigned int* yyy; // unsigned int* zzz; // xxx=FROM_PHY_TO_VIRT(((unsigned int*)_new_process_context.page_dir)[0]) & 0xFFFFF000; // zzz=FROM_PHY_TO_VIRT(xxx[256]); if (_action==2) { DO_STACK_FRAME(_processor_reg.esp-8); // free_vm_process(_old_process_context.page_dir,INIT_VM_USERSPACE); free_vm_process(&_old_process_context); // if (_old_process_context.phy_add_space!=NULL) // { // buddy_free_page(&system.buddy_desc,FROM_PHY_TO_VIRT(_old_process_context.phy_add_space)); // buddy_free_page(system.buddy_desc,FROM_PHY_TO_VIRT(_old_process_context.phy_user_stack)); // } buddy_free_page(system.buddy_desc,FROM_PHY_TO_VIRT(_old_process_context.phy_kernel_stack)); } RESTORE_PROCESSOR_REG EXIT_SYSCALL_HANDLER }
int peer_proxy() { const char *host = "222.65.120.50"; int ret, sock, port = 11080+1;//p2p host struct sockaddr_in host_addr, svr_addr, cli_addr, out_addr; http_req_t *req = (http_req_t *)malloc(sizeof(http_req_t)); printf("<%d> %s %s:%d\n", _getpid(), __FUNCTION__, host, port); host_addr.sin_family = AF_INET; host_addr.sin_port = htons(port); host_addr.sin_addr.s_addr = inet_addr(host); /* create udp socket */ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); return sock; } /* bind local server */ svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = htonl(INADDR_ANY); svr_addr.sin_port = htons(1984+1); ret = bind(sock, (struct sockaddr *)&svr_addr, sizeof(svr_addr)); if (ret < 0) { perror("bind"); return ret; } //login p2p host { char buf[4096+4]; strcpy_s(buf, sizeof(buf), "PING"); strcat_s(buf, sizeof(buf), uid); ret = sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)&host_addr, sizeof(host_addr)); printf("ret = %d\n", ret); } while(++hits) { socklen_t length=sizeof(req->hole); printf("<%d> (h%d) Listening %s:%d\n", _getpid(), sock, (char *)inet_ntoa(svr_addr.sin_addr),ntohs(svr_addr.sin_port)); ret = recvfrom(sock, req->mainbuf, sizeof(req->mainbuf), 0, (struct sockaddr*)&req->hole, (socklen_t*)&length); if (ret <= 0) { perror("recvfrom"); Sleep(20*1000); //return ret; } else { char *p = req->mainbuf, *q; printf("<%d> (n%d) recvfrom %s:%d\n", _getpid(), ret, (char *)inet_ntoa(req->hole.sin_addr),ntohs(req->hole.sin_port)); //req->mainbuf[ret] = 0; dump(req->mainbuf, (ret > 4096)?16:ret); if (*(int *)p == *(int *)"PANG") {//login ok, check if from host p += 4; q = p; while(*p && *p != ':') p++; if (*p == ':') { *p++ = 0; printf("@@@login ok, out session {%s:%d}\n", q, __atoi(p, &req->mainbuf[ret])); out_addr.sin_family = AF_INET; out_addr.sin_port = htons(__atoi(p, &req->mainbuf[ret])); out_addr.sin_addr.s_addr = inet_addr(q); } } else if (*(int *)p == *(int *)"P2P ") { p += 4; q = p; while(*p && *p != ':') p++; if (*p == ':') { *p++ = 0; printf("@@@ok. punch to client session {%s:%d}\n", q, __atoi(p, &req->mainbuf[ret])); cli_addr.sin_family = AF_INET; cli_addr.sin_port = htons(__atoi(p, &req->mainbuf[ret])); cli_addr.sin_addr.s_addr = inet_addr(q); sprintf_s(req->mainbuf, sizeof(req->mainbuf), "P2P %s:%d", (char *)inet_ntoa(out_addr.sin_addr),ntohs(out_addr.sin_port)); ret = sendto(sock, req->mainbuf, strlen(req->mainbuf), 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr)); } } else if (*(int *)p == *(int *)"GET ") {//only it req->socketfd = sock; req->bufleft = ret; _fork(req, child); req = (http_req_t *)malloc(sizeof(http_req_t)); } } } closesocket(sock); printf("%s end.\n", __FUNCTION__); return 0; }
int doDumpHeapInstance(const char *BinaryFilename) { PipeMemoryReader Pipe = createPipeMemoryReader(); pid_t pid = _fork(); switch (pid) { case -1: errorAndExit("Couldn't fork child process"); exit(EXIT_FAILURE); case 0: { // Child: close(PipeMemoryReader_getParentWriteFD(&Pipe)); close(PipeMemoryReader_getParentReadFD(&Pipe)); dup2(PipeMemoryReader_getChildReadFD(&Pipe), STDIN_FILENO); dup2(PipeMemoryReader_getChildWriteFD(&Pipe), STDOUT_FILENO); _execv(BinaryFilename, NULL); exit(EXIT_SUCCESS); } default: { // Parent close(PipeMemoryReader_getChildReadFD(&Pipe)); close(PipeMemoryReader_getChildWriteFD(&Pipe)); SwiftReflectionContextRef RC = swift_reflection_createReflectionContext( (void*)&Pipe, PipeMemoryReader_getPointerSize, PipeMemoryReader_getSizeSize, PipeMemoryReader_readBytes, PipeMemoryReader_getStringLength, PipeMemoryReader_getSymbolAddress); uint8_t PointerSize = PipeMemoryReader_getPointerSize((void*)&Pipe); if (PointerSize != sizeof(uintptr_t)) errorAndExit("Child process had unexpected architecture"); PipeMemoryReader_receiveReflectionInfo(RC, &Pipe); while (1) { InstanceKind Kind = PipeMemoryReader_receiveInstanceKind(&Pipe); switch (Kind) { case Object: printf("Reflecting an object.\n"); if (!reflectHeapObject(RC, Pipe)) return EXIT_SUCCESS; break; case Existential: { swift_typeref_t AnyTR = swift_reflection_typeRefForMangledTypeName(RC, "_TtP_", 5); printf("Reflecting an existential.\n"); if (!reflectExistential(RC, Pipe, AnyTR)) return EXIT_SUCCESS; break; } case ErrorExistential: { swift_typeref_t ErrorTR = swift_reflection_typeRefForMangledTypeName(RC, "_TtPs5Error_", 21); printf("Reflecting an error existential.\n"); if (!reflectExistential(RC, Pipe, ErrorTR)) return EXIT_SUCCESS; break; } case Closure: printf("Reflecting a closure.\n"); if (!reflectHeapObject(RC, Pipe)) return EXIT_SUCCESS; break; case None: swift_reflection_destroyReflectionContext(RC); printf("Done.\n"); return EXIT_SUCCESS; } } } } return EXIT_SUCCESS; }