546095612b70875b86a9ff91eb6fc267ebbd7f43
[tpg/acess2.git] / AcessNative / ld-acess_src / syscalls.c
1 /*
2  */
3 #define DONT_INCLUDE_SYSCALL_NAMES 1
4 #include "../../Usermode/include/acess/sys.h"
5 #include "common.h"
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdint.h>
9 #include <stdarg.h>
10 #include <string.h>
11 #include <stddef.h>
12 #include "request.h"
13 #include "../syscalls.h"
14
15 #define DEBUG(str, x...)        Debug(str, x)
16
17 #define NATIVE_FILE_MASK        0x40000000
18 #define MAX_FPS 16
19
20 // === Types ===
21
22 // === IMPORTS ===
23 extern int      giSyscall_ClientID;     // Needed for execve
24
25 // === GLOBALS ===
26 FILE    *gaSyscall_LocalFPs[MAX_FPS];
27
28 // === CODE ===
29 const char *ReadEntry(tRequestValue *Dest, void *DataDest, void **PtrDest, const char *ArgTypes, va_list *Args)
30 {
31         uint64_t        val64;
32         uint32_t        val32;
33          int    direction = 0;  // 0: Invalid, 1: Out, 2: In, 3: Out
34         char    *str;
35          int    len;
36         
37         // Eat whitespace
38         while(*ArgTypes && *ArgTypes == ' ')    ArgTypes ++;
39         if( *ArgTypes == '\0' ) return ArgTypes;
40         
41         // Get direction
42         switch(*ArgTypes)
43         {
44         default:        // Defaults to output
45         case '>':       direction = 1;  break;
46         case '<':       direction = 2;  break;
47         case '?':       direction = 3;  break;
48         }
49         ArgTypes ++;
50         
51         // Eat whitespace
52         while(*ArgTypes && *ArgTypes == ' ')    ArgTypes ++;
53         if( *ArgTypes == '\0' ) return ArgTypes;
54         
55         // Get type
56         switch(*ArgTypes)
57         {
58         // 32-bit integer
59         case 'i':
60                 
61                 if( direction != 1 ) {
62                         Warning("ReadEntry: Recieving an integer is not defined");
63                         return NULL;
64                 }
65                 
66                 val32 = va_arg(*Args, uint32_t);
67                 
68                 Dest->Type = ARG_TYPE_INT32;
69                 Dest->Length = sizeof(uint32_t);
70                 Dest->Flags = 0;
71                 
72                 if( DataDest )
73                         *(uint32_t*)DataDest = val32;
74                 break;
75         // 64-bit integer
76         case 'I':
77                 
78                 if( direction != 1 ) {
79                         fprintf(stderr, "ReadEntry: Recieving an integer is not defined\n");
80                         return NULL;
81                 }
82                 
83                 val64 = va_arg(*Args, uint64_t);
84                 
85                 Dest->Type = ARG_TYPE_INT64;
86                 Dest->Length = sizeof(uint64_t);
87                 Dest->Flags = 0;
88                 if( DataDest )
89                         *(uint64_t*)DataDest = val64;
90                 break;
91         // String
92         case 's':
93                 // Input string makes no sense!
94                 if( direction != 1 ) {
95                         fprintf(stderr, "ReadEntry: Recieving a string is not defined\n");
96                         return NULL;
97                 }
98                 
99                 str = va_arg(*Args, char*);
100                 
101                 Dest->Type = ARG_TYPE_STRING;
102                 Dest->Length = strlen(str) + 1;
103                 Dest->Flags = 0;
104                 
105                 if( DataDest )
106                 {
107                         memcpy(DataDest, str, Dest->Length);
108                 }
109                 break;
110         // Data (special handling)
111         case 'd':
112                 len = va_arg(*Args, int);
113                 str = va_arg(*Args, char*);
114                 
115                 // Save the pointer for later
116                 if( PtrDest )   *PtrDest = str;
117                 
118                 // Create parameter block
119                 Dest->Type = ARG_TYPE_DATA;
120                 Dest->Length = len;
121                 Dest->Flags = 0;
122                 if( direction & 2 )
123                         Dest->Flags |= ARG_FLAG_RETURN;
124                 
125                 // Has data?
126                 if( direction & 1 )
127                 {
128                         if( DataDest )
129                                 memcpy(DataDest, str, len);
130                 }
131                 else
132                         Dest->Flags |= ARG_FLAG_ZEROED;
133                 break;
134         
135         default:
136                 return NULL;
137         }
138         ArgTypes ++;
139         
140         return ArgTypes;
141 }
142
143 /**
144  * \param ArgTypes
145  *
146  * Whitespace is ignored
147  * >i:  Input Integer (32-bits)
148  * >I:  Input Long Integer (64-bits)
149  * >s:  Input String
150  * >d:  Input Buffer (Preceded by valid size)
151  * <I:  Output long integer
152  * <d:  Output Buffer (Preceded by valid size)
153  * ?d:  Bi-directional buffer (Preceded by valid size), buffer contents
154  *      are returned
155  */
156 uint64_t _Syscall(int SyscallID, const char *ArgTypes, ...)
157 {
158         va_list args;
159          int    paramCount, dataLength;
160          int    retCount = 1, retLength = sizeof(uint64_t);
161         void    **retPtrs;      // Pointers to return buffers
162         const char      *str;
163         tRequestHeader  *req;
164         void    *dataPtr;
165         uint64_t        retValue;
166          int    i;
167         
168         // DEBUG!
169 //      printf("&tRequestHeader->Params = %i\n", offsetof(tRequestHeader, Params));
170 //      printf("&tRequestValue->Flags = %i\n", offsetof(tRequestValue, Flags));
171 //      printf("&tRequestValue->Length = %i\n", offsetof(tRequestValue, Length));
172         
173         // Get data size
174         va_start(args, ArgTypes);
175         str = ArgTypes;
176         paramCount = 0;
177         dataLength = 0;
178         while(*str)
179         {
180                 tRequestValue   tmpVal;
181                 
182                 str = ReadEntry(&tmpVal, NULL, NULL, str, &args);
183                 if( !str ) {
184                         fprintf(stderr, "syscalls.c: ReadEntry failed (SyscallID = %i)\n", SyscallID);
185                         exit(127);
186                 }
187                 paramCount ++;
188                 if( !(tmpVal.Flags & ARG_FLAG_ZEROED) )
189                         dataLength += tmpVal.Length;
190                 
191                 if( tmpVal.Flags & ARG_FLAG_RETURN ) {
192                         retLength += tmpVal.Length;
193                         retCount ++;
194                 }
195         }
196         va_end(args);
197         
198         dataLength += sizeof(tRequestHeader) + paramCount*sizeof(tRequestValue);
199         retLength += sizeof(tRequestHeader) + retCount*sizeof(tRequestValue);
200         
201         // Allocate buffers
202         retPtrs = malloc( sizeof(void*) * (retCount+1) );
203         if( dataLength > retLength)
204                 req = malloc( dataLength );
205         else
206                 req = malloc( retLength );
207         req->ClientID = 0;      //< Filled later
208         req->CallID = SyscallID;
209         req->NParams = paramCount;
210         dataPtr = &req->Params[paramCount];
211         
212         // Fill `output` and `input`
213         va_start(args, ArgTypes);
214         str = ArgTypes;
215         // - re-zero so they can be used as indicies
216         paramCount = 0;
217         retCount = 0;
218         while(*str)
219         {               
220                 str = ReadEntry(&req->Params[paramCount], dataPtr, &retPtrs[retCount], str, &args);
221                 if( !str )      break;
222                 
223                 if( !(req->Params[paramCount].Flags & ARG_FLAG_ZEROED) )
224                         dataPtr += req->Params[paramCount].Length;
225                 if( req->Params[paramCount].Flags & ARG_FLAG_RETURN )
226                         retCount ++;
227                 
228                 paramCount ++;
229         }
230         va_end(args);
231         
232         // Send syscall request
233         if( SendRequest(req, dataLength, retLength) < 0 ) {
234                 fprintf(stderr, "syscalls.c: SendRequest failed (SyscallID = %i)\n", SyscallID);
235                 exit(127);
236         }
237         
238         // Parse return value
239         dataPtr = &req->Params[req->NParams];
240         retValue = 0;
241         if( req->NParams >= 1 )
242         {
243                 switch(req->Params[0].Type)
244                 {
245                 case ARG_TYPE_INT64:
246                         retValue = *(uint64_t*)dataPtr;
247                         dataPtr += req->Params[0].Length;
248                         break;
249                 case ARG_TYPE_INT32:
250                         retValue = *(uint32_t*)dataPtr;
251                         dataPtr += req->Params[0].Length;
252                         break;
253                 }       
254         }
255         
256         // Write changes to buffers
257         retCount = 0;
258         for( i = 1; i < req->NParams; i ++ )
259         {
260                 #if 0
261                  int     j;
262                 printf("Return Data %i: (%i)", i, req->Params[i].Length);
263                 for( j = 0; j < req->Params[i].Length; j ++ )
264                         printf(" %02x", ((uint8_t*)dataPtr)[j]);
265                 printf("\n");
266                 #endif
267                 memcpy( retPtrs[retCount++], dataPtr, req->Params[i].Length );
268                 dataPtr += req->Params[i].Length;
269         }
270         
271         free( req );
272         free( retPtrs );
273         
274         DEBUG(": %llx", retValue);
275         
276         return retValue;
277 }
278
279 // --- VFS Calls
280 int acess_chdir(const char *Path)
281 {
282         return _Syscall(SYS_CHDIR, ">s", Path);
283 }
284
285 int acess_open(const char *Path, int Flags)
286 {
287         if( strncmp(Path, "$$$$", 4) == 0 )
288         {
289                  int    ret;
290                 for(ret = 0; ret < MAX_FPS && gaSyscall_LocalFPs[ret]; ret ++ ) ;
291                 if(ret == MAX_FPS)      return -1;
292                 // TODO: Handle directories
293                 gaSyscall_LocalFPs[ret] = fopen(&Path[4], "r+");
294                 if(!gaSyscall_LocalFPs[ret])    return -1;
295                 return ret|NATIVE_FILE_MASK;
296         }
297         DEBUG("open(\"%s\", 0x%x)", Path, Flags);
298         return _Syscall(SYS_OPEN, ">s >i", Path, Flags);
299 }
300
301 void acess_close(int FD) {
302         if(FD & NATIVE_FILE_MASK) {
303                 fclose( gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
304                 gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] = NULL;
305                 return ;
306         }
307         DEBUG("close(%i)", FD);
308         _Syscall(SYS_CLOSE, ">i", FD);
309 }
310
311 int acess_reopen(int FD, const char *Path, int Flags) {
312         DEBUG("reopen(0x%x, \"%s\", 0x%x)", FD, Path, Flags);
313         return _Syscall(SYS_REOPEN, ">i >s >i", FD, Path, Flags);
314 }
315
316 size_t acess_read(int FD, size_t Bytes, void *Dest) {
317         if(FD & NATIVE_FILE_MASK)
318                 return fread( Dest, Bytes, 1, gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
319         DEBUG("read(0x%x, 0x%x, *%p)", FD, Bytes, Dest);
320         return _Syscall(SYS_READ, ">i >i <d", FD, Bytes, Bytes, Dest);
321 }
322
323 size_t acess_write(int FD, size_t Bytes, void *Src) {
324         if(FD & NATIVE_FILE_MASK)
325                 return fwrite( Src, Bytes, 1, gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
326         DEBUG("write(0x%x, 0x%x, %p\"%.*s\")", FD, Bytes, Src, Bytes, (char*)Src);
327         return _Syscall(SYS_WRITE, ">i >i >d", FD, Bytes, Bytes, Src);
328 }
329
330 int acess_seek(int FD, int64_t Ofs, int Dir) {
331         if(FD & NATIVE_FILE_MASK) {
332                 switch(Dir) {
333                 case ACESS_SEEK_SET:    Dir = SEEK_SET; break;
334                 default:
335                 case ACESS_SEEK_CUR:    Dir = SEEK_CUR; break;
336                 case ACESS_SEEK_END:    Dir = SEEK_END; break;
337                 }
338                 return fseek( gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)], Ofs, Dir );
339         }
340         DEBUG("seek(0x%x, 0x%llx, %i)", FD, Ofs, Dir);
341         return _Syscall(SYS_SEEK, ">i >I >i", FD, Ofs, Dir);
342 }
343
344 uint64_t acess_tell(int FD) {
345         if(FD & NATIVE_FILE_MASK)
346                 return ftell( gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
347         return _Syscall(SYS_TELL, ">i", FD);
348 }
349
350 int acess_ioctl(int fd, int id, void *data) {
351         // NOTE: 1024 byte size is a hack
352         DEBUG("ioctl(%i, %i, %p)", fd, id, data);
353         return _Syscall(SYS_IOCTL, ">i >i ?d", fd, id, 1024, data);
354 }
355 int acess_finfo(int fd, t_sysFInfo *info, int maxacls) {
356         return _Syscall(SYS_FINFO, ">i <d >i",
357                 fd,
358                 sizeof(t_sysFInfo)+maxacls*sizeof(t_sysACL), info,
359                 maxacls);
360 }
361
362 int acess_readdir(int fd, char *dest) {
363         DEBUG("readdir(%i, %p)", fd, dest);
364         return _Syscall(SYS_READDIR, ">i <d", fd, 256, dest);
365 }
366
367 int acess_select(int nfds, fd_set *read, fd_set *write, fd_set *error, time_t *timeout)
368 {
369         DEBUG("select(%i, %p, %p, %p, %p)", nfds, read, write, error, timeout);
370         return _Syscall(SYS_SELECT, ">i ?d ?d ?d >d", nfds,
371                 read ? (nfds+7)/8 : 0, read,
372                 write ? (nfds+7)/8 : 0, write,
373                 error ? (nfds+7)/8 : 0, error,
374                 sizeof(*timeout), timeout
375                 );
376 }
377
378 int acess__SysOpenChild(int fd, char *name, int flags) {
379         return _Syscall(SYS_OPENCHILD, ">i >s >i", fd, name, flags);
380 }
381
382 int acess__SysGetACL(int fd, t_sysACL *dest) {
383         return _Syscall(SYS_GETACL, "<i >i <d", fd, sizeof(t_sysACL), dest);
384 }
385
386 int acess__SysMount(const char *Device, const char *Directory, const char *Type, const char *Options) {
387         return _Syscall(SYS_MOUNT, ">s >s >s >s", Device, Directory, Type, Options);
388 }
389
390
391 // --- Error Handler
392 int     acess__SysSetFaultHandler(int (*Handler)(int)) {
393         printf("TODO: Set fault handler (asked to set to %p)\n", Handler);
394         return 0;
395 }
396
397 // --- Memory Management ---
398 uint64_t acess__SysAllocate(uint vaddr)
399 {
400         if( AllocateMemory(vaddr, 0x1000) == -1 )       // Allocate a page
401                 return 0;
402                 
403         return vaddr;   // Just ignore the need for paddrs :)
404 }
405
406 // --- Process Management ---
407 int acess_clone(int flags, void *stack)
408 {
409         extern int fork(void);
410         if(flags & CLONE_VM) {
411                  int    ret, newID, kernel_tid=0;
412                 printf("fork()");
413                 
414                 newID = _Syscall(SYS_FORK, "<d", sizeof(int), &kernel_tid);
415                 ret = fork();
416                 if(ret < 0)     return ret;
417                 
418                 if(ret == 0)
419                 {
420                         giSyscall_ClientID = newID;
421                         return 0;
422                 }
423                 
424                 // Return the acess TID instead
425                 return kernel_tid;
426         }
427         else
428         {
429                 fprintf(stderr, "ERROR: Threads currently unsupported\n");
430                 exit(-1);
431         }
432 }
433
434 int acess_execve(char *path, char **argv, char **envp)
435 {
436          int    i, argc;
437         
438         DEBUG("acess_execve: (path='%s', argv=%p, envp=%p)", path, argv, envp);
439         
440         // Get argument count
441         for( argc = 0; argv[argc]; argc ++ ) ;
442         DEBUG(" acess_execve: argc = %i", argc);
443         
444         char    *new_argv[5+argc+1];
445         char    key[11];
446         sprintf(key, "%i", giSyscall_ClientID);
447         new_argv[0] = "ld-acess";       // TODO: Get path to ld-acess executable
448         new_argv[1] = "--key";  // Set socket/client ID for Request.c
449         new_argv[2] = key;
450         new_argv[3] = "--binary";       // Set the binary path (instead of using argv[0])
451         new_argv[4] = path;
452         for( i = 0; i < argc; i ++ )    new_argv[5+i] = argv[i];
453         new_argv[5+i] = NULL;
454         
455         #if 1
456         argc += 5;
457         for( i = 0; i < argc; i ++ )
458                 printf("\"%s\" ", new_argv[i]);
459         printf("\n");
460         #endif
461         
462         // Call actual execve
463         return execve("./ld-acess", new_argv, envp);
464 }
465
466 void acess_sleep(void)
467 {
468         _Syscall(SYS_SLEEP, "");
469 }
470
471 int acess_waittid(int TID, int *ExitStatus)
472 {
473         return _Syscall(SYS_WAITTID, ">i <d", TID, sizeof(int), &ExitStatus);
474 }
475
476 int acess_setuid(int ID)
477 {
478         return _Syscall(SYS_SETUID, ">i", ID);
479 }
480
481 int acess_setgid(int ID)
482 {
483         return _Syscall(SYS_SETGID, ">i", ID);
484 }
485
486 int acess_SysSendMessage(int DestTID, int Length, void *Data)
487 {
488         return _Syscall(SYS_SENDMSG, ">i >d", DestTID, Length, Data);
489 }
490
491 int acess_SysGetMessage(int *SourceTID, void *Data)
492 {
493         return _Syscall(SYS_GETMSG, "<d <d",
494                 SourceTID ? sizeof(int) : 0, SourceTID,
495                 Data ? 4096 : 0, Data
496                 );
497 }
498
499 // --- Logging
500 void acess__SysDebug(const char *Format, ...)
501 {
502         va_list args;
503         
504         va_start(args, Format);
505         
506         printf("[_SysDebug %i]", giSyscall_ClientID);
507         vprintf(Format, args);
508         printf("\n");
509         
510         va_end(args);
511 }
512
513 void acess__exit(int Status)
514 {
515         DEBUG("_exit(%i)", Status);
516         _Syscall(SYS_EXIT, ">i", Status);
517         exit(Status);
518 }
519
520
521 // === Symbol List ===
522 #define DEFSYM(name)    {#name, acess_##name}
523 const tSym      caBuiltinSymbols[] = {
524         DEFSYM(_exit),
525         
526         DEFSYM(chdir),
527         DEFSYM(open),
528         DEFSYM(close),
529         DEFSYM(reopen),
530         DEFSYM(read),
531         DEFSYM(write),
532         DEFSYM(seek),
533         DEFSYM(tell),
534         DEFSYM(ioctl),
535         DEFSYM(finfo),
536         DEFSYM(readdir),
537         DEFSYM(select),
538         DEFSYM(_SysOpenChild),
539         DEFSYM(_SysGetACL),
540         DEFSYM(_SysMount),
541         
542         DEFSYM(clone),
543         DEFSYM(execve),
544         DEFSYM(sleep),
545         
546         DEFSYM(waittid),
547         DEFSYM(setuid),
548         DEFSYM(setgid),
549
550         DEFSYM(SysSendMessage),
551         DEFSYM(SysGetMessage),
552         
553         DEFSYM(_SysAllocate),
554         DEFSYM(_SysDebug),
555         DEFSYM(_SysSetFaultHandler)
556 };
557
558 const int       ciNumBuiltinSymbols = sizeof(caBuiltinSymbols)/sizeof(caBuiltinSymbols[0]);
559

UCC git Repository :: git.ucc.asn.au