AcessNative - Fixes mostly, still not yet complete
[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(x...)     printf(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                         fprintf(stderr, "ReadEntry: Recieving an integer is not defined\n");
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\n", retValue);
275         
276         return retValue;
277 }
278
279 // --- VFS Calls
280 int acess_open(const char *Path, int Flags)
281 {
282         if( strncmp(Path, "$$$$", 4) == 0 )
283         {
284                  int    ret;
285                 for(ret = 0; ret < MAX_FPS && gaSyscall_LocalFPs[ret]; ret ++ ) ;
286                 if(ret == MAX_FPS)      return -1;
287                 // TODO: Handle directories
288                 gaSyscall_LocalFPs[ret] = fopen(&Path[4], "r+");
289                 if(!gaSyscall_LocalFPs[ret])    return -1;
290                 return ret|NATIVE_FILE_MASK;
291         }
292         DEBUG("open(\"%s\", 0x%x)", Path, Flags);
293         return _Syscall(SYS_OPEN, ">s >i", Path, Flags);
294 }
295
296 void acess_close(int FD) {
297         if(FD & NATIVE_FILE_MASK) {
298                 fclose( gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
299                 gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] = NULL;
300                 return ;
301         }
302         DEBUG("close(%i)", FD);
303         _Syscall(SYS_CLOSE, ">i", FD);
304 }
305
306 int acess_reopen(int FD, const char *Path, int Flags) {
307         DEBUG("reopen(0x%x, \"%s\", 0x%x)", FD, Path, Flags);
308         return _Syscall(SYS_REOPEN, ">i >s >i", FD, Path, Flags);
309 }
310
311 size_t acess_read(int FD, size_t Bytes, void *Dest) {
312         if(FD & NATIVE_FILE_MASK)
313                 return fread( Dest, Bytes, 1, gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
314         DEBUG("read(0x%x, 0x%x, *%p)", FD, Bytes, Dest);
315         return _Syscall(SYS_READ, ">i >i <d", FD, Bytes, Bytes, Dest);
316 }
317
318 size_t acess_write(int FD, size_t Bytes, void *Src) {
319         if(FD & NATIVE_FILE_MASK)
320                 return fwrite( Src, Bytes, 1, gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
321         DEBUG("write(0x%x, 0x%x, %p\"%.*s\")", FD, Bytes, Src, Bytes, (char*)Src);
322         return _Syscall(SYS_WRITE, ">i >i >d", FD, Bytes, Bytes, Src);
323 }
324
325 int acess_seek(int FD, int64_t Ofs, int Dir) {
326         if(FD & NATIVE_FILE_MASK) {
327                 switch(Dir) {
328                 case ACESS_SEEK_SET:    Dir = SEEK_SET; break;
329                 default:
330                 case ACESS_SEEK_CUR:    Dir = SEEK_CUR; break;
331                 case ACESS_SEEK_END:    Dir = SEEK_END; break;
332                 }
333                 return fseek( gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)], Ofs, Dir );
334         }
335         DEBUG("seek(0x%x, 0x%llx, %i)", FD, Ofs, Dir);
336         return _Syscall(SYS_SEEK, ">i >I >i", FD, Ofs, Dir);
337 }
338
339 uint64_t acess_tell(int FD) {
340         if(FD & NATIVE_FILE_MASK)
341                 return ftell( gaSyscall_LocalFPs[FD & (NATIVE_FILE_MASK-1)] );
342         return _Syscall(SYS_TELL, ">i", FD);
343 }
344
345 int acess_ioctl(int fd, int id, void *data) {
346         // NOTE: 1024 byte size is a hack
347         return _Syscall(SYS_IOCTL, ">i >i ?d", fd, id, 1024, data);
348 }
349 int acess_finfo(int fd, t_sysFInfo *info, int maxacls) {
350         return _Syscall(SYS_FINFO, ">i <d >i",
351                 fd,
352                 sizeof(t_sysFInfo)+maxacls*sizeof(t_sysACL), info,
353                 maxacls);
354 }
355
356 int acess_readdir(int fd, char *dest) {
357         return _Syscall(SYS_READDIR, ">i <d", fd, 256, dest);
358 }
359
360 int acess__SysOpenChild(int fd, char *name, int flags) {
361         return _Syscall(SYS_OPENCHILD, ">i >s >i", fd, name, flags);
362 }
363
364 int acess__SysGetACL(int fd, t_sysACL *dest) {
365         return _Syscall(SYS_GETACL, "<i >i <d", fd, sizeof(t_sysACL), dest);
366 }
367
368 int acess__SysMount(const char *Device, const char *Directory, const char *Type, const char *Options) {
369         return _Syscall(SYS_MOUNT, ">s >s >s >s", Device, Directory, Type, Options);
370 }
371
372
373 // --- Error Handler
374 int     acess__SysSetFaultHandler(int (*Handler)(int)) {
375         printf("TODO: Set fault handler (asked to set to %p)\n", Handler);
376         return 0;
377 }
378
379 // --- Memory Management ---
380 uint64_t acess__SysAllocate(uint vaddr)
381 {
382         if( AllocateMemory(vaddr, 0x1000) == -1 )       // Allocate a page
383                 return 0;
384                 
385         return vaddr;   // Just ignore the need for paddrs :)
386 }
387
388 // --- Process Management ---
389 int acess_clone(int flags, void *stack)
390 {
391         extern int fork(void);
392         if(flags & CLONE_VM) {
393                  int    ret, newID, kernel_tid=0;
394                 printf("fork()");
395                 
396                 newID = _Syscall(SYS_FORK, "<d", sizeof(int), &kernel_tid);
397                 ret = fork();
398                 if(ret < 0)     return ret;
399                 
400                 if(ret == 0)
401                 {
402                         giSyscall_ClientID = newID;
403                         return 0;
404                 }
405                 
406                 // TODO: Return the acess TID instead
407                 return kernel_tid;
408         }
409         else
410         {
411                 fprintf(stderr, "ERROR: Threads currently unsupported\n");
412                 exit(-1);
413         }
414 }
415
416 int acess_execve(char *path, char **argv, char **envp)
417 {
418          int    i, argc;
419         
420         printf("acess_execve: (path='%s', argv=%p, envp=%p)\n", path, argv, envp);
421         
422         // Get argument count
423         for( argc = 0; argv[argc]; argc ++ ) ;
424         printf(" acess_execve: argc = %i\n", argc);
425         
426         char    *new_argv[5+argc+1];
427         char    key[11];
428         sprintf(key, "%i", giSyscall_ClientID);
429         new_argv[0] = "ld-acess";       // TODO: Get path to ld-acess executable
430         new_argv[1] = "--key";  // Set socket/client ID for Request.c
431         new_argv[2] = key;
432         new_argv[3] = "--binary";       // Set the binary path (instead of using argv[0])
433         new_argv[4] = path;
434         for( i = 0; i < argc; i ++ )    new_argv[5+i] = argv[i];
435         new_argv[5+i] = NULL;
436         
437         #if 1
438         argc += 5;
439         for( i = 0; i < argc; i ++ )
440                 printf("\"%s\" ", new_argv[i]);
441         printf("\n");
442         #endif
443         
444         // Call actual execve
445         return execve("./ld-acess", new_argv, envp);
446 }
447
448 void acess_sleep(void)
449 {
450         _Syscall(SYS_SLEEP, "");
451 }
452
453 int acess_waittid(int TID, int *ExitStatus)
454 {
455         return _Syscall(SYS_WAITTID, ">i <d", TID, sizeof(int), &ExitStatus);
456 }
457
458 int acess_setuid(int ID)
459 {
460         return _Syscall(SYS_SETUID, ">i", ID);
461 }
462
463 int acess_setgid(int ID)
464 {
465         return _Syscall(SYS_SETGID, ">i", ID);
466 }
467
468 // --- Logging
469 void acess__SysDebug(const char *Format, ...)
470 {
471         va_list args;
472         
473         va_start(args, Format);
474         
475         printf("[_SysDebug] ");
476         vprintf(Format, args);
477         printf("\n");
478         
479         va_end(args);
480 }
481
482 void acess__exit(int Status)
483 {
484         _Syscall(SYS_EXIT, ">i", Status);
485         exit(Status);
486 }
487
488
489 // === Symbol List ===
490 #define DEFSYM(name)    {#name, acess_##name}
491 const tSym      caBuiltinSymbols[] = {
492         DEFSYM(_exit),
493         
494         DEFSYM(open),
495         DEFSYM(close),
496         DEFSYM(reopen),
497         DEFSYM(read),
498         DEFSYM(write),
499         DEFSYM(seek),
500         DEFSYM(tell),
501         DEFSYM(ioctl),
502         DEFSYM(finfo),
503         DEFSYM(readdir),
504         DEFSYM(_SysOpenChild),
505         DEFSYM(_SysGetACL),
506         DEFSYM(_SysMount),
507         
508         DEFSYM(clone),
509         DEFSYM(execve),
510         DEFSYM(sleep),
511         
512         DEFSYM(waittid),
513         DEFSYM(setuid),
514         DEFSYM(setgid),
515         
516         DEFSYM(_SysAllocate),
517         DEFSYM(_SysDebug),
518         DEFSYM(_SysSetFaultHandler)
519 };
520
521 const int       ciNumBuiltinSymbols = sizeof(caBuiltinSymbols)/sizeof(caBuiltinSymbols[0]);
522

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