43dfe26e5f32c03710cb27fc660636ad6ad0358f
[tpg/acess2.git] / AcessNative / ld-acess_src / syscalls.c
1 /*
2  */
3 #define DONT_INCLUDE_SYSCALL_NAMES 1
4 #include "common.h"
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdint.h>
8 #include <stdarg.h>
9 #include <string.h>
10 #include <stddef.h>
11 #include <unistd.h>
12 #ifndef __WIN32__
13 # include <spawn.h>     // posix_spawn
14 #endif
15 #include "request.h"
16
17 #define assert(cnd) do{ \
18         if( !(cnd) ) { \
19                 fprintf(stderr, "%s:%i - assert failed - " #cnd"\n", __FILE__, __LINE__);\
20                 exit(-1); \
21         } \
22 }while(0)
23
24 #define MAX_FPS 16
25
26 // === Types ===
27
28 // === IMPORTS ===
29 extern int      gbSyscallDebugEnabled;
30
31 // === GLOBALS ===
32 FILE    *gaSyscall_LocalFPs[MAX_FPS];
33
34 // === CODE ===
35 const char *ReadEntry(tRequestValue *Dest, void *DataDest, void **PtrDest, const char *ArgTypes, va_list *Args)
36 {
37         uint64_t        val64;
38         uint32_t        val32;
39          int    direction = 0;  // 0: Invalid, 1: Out, 2: In, 3: Out
40         char    *str;
41          int    len;
42
43         // Eat whitespace
44         while(*ArgTypes && *ArgTypes == ' ')    ArgTypes ++;
45         if( *ArgTypes == '\0' ) return ArgTypes;
46         
47 //      DEBUG("ArgTypes = '%s'", ArgTypes);
48         
49         // Get direction
50         switch(*ArgTypes)
51         {
52         default:        // Defaults to output
53         case '>':       direction = 1;  break;
54         case '<':       direction = 2;  break;
55         case '?':       direction = 3;  break;
56         }
57         ArgTypes ++;
58         
59         // Eat whitespace
60         while(*ArgTypes && *ArgTypes == ' ')    ArgTypes ++;
61         if( *ArgTypes == '\0' ) return ArgTypes;
62         
63         // Get type
64         switch(*ArgTypes)
65         {
66         // 32-bit integer
67         case 'i':
68                 
69                 if( direction != 1 ) {
70                         Warning("ReadEntry: Recieving an integer is not defined");
71                         return NULL;
72                 }
73                 
74                 val32 = va_arg(*Args, uint32_t);
75                 
76                 Dest->Type = ARG_TYPE_INT32;
77                 Dest->Length = sizeof(uint32_t);
78                 Dest->Flags = 0;
79                 
80                 if( DataDest )
81                         *(uint32_t*)DataDest = val32;
82                 break;
83         // 64-bit integer
84         case 'I':
85                 
86                 if( direction != 1 ) {
87                         fprintf(stderr, "ReadEntry: Recieving an integer is not defined\n");
88                         return NULL;
89                 }
90                 
91                 val64 = va_arg(*Args, uint64_t);
92                 
93                 Dest->Type = ARG_TYPE_INT64;
94                 Dest->Length = sizeof(uint64_t);
95                 Dest->Flags = 0;
96                 if( DataDest )
97                         *(uint64_t*)DataDest = val64;
98                 break;
99         // String
100         case 's':
101                 // Input string makes no sense!
102                 if( direction != 1 ) {
103                         fprintf(stderr, "ReadEntry: Recieving a string is not defined\n");
104                         return NULL;
105                 }
106                 
107                 str = va_arg(*Args, char*);
108                 
109                 Dest->Type = ARG_TYPE_STRING;
110                 Dest->Length = strlen(str) + 1;
111                 Dest->Flags = 0;
112                 
113                 if( DataDest )
114                 {
115                         memcpy(DataDest, str, Dest->Length);
116                 }
117                 break;
118         // Data (special handling)
119         case 'd':
120                 len = va_arg(*Args, size_t);
121                 str = va_arg(*Args, char*);
122                 
123                 // Save the pointer for later
124                 if( PtrDest )   *PtrDest = str;
125                 
126                 // Create parameter block
127                 Dest->Type = ARG_TYPE_DATA;
128                 Dest->Length = str ? len : 0;
129                 Dest->Flags = 0;
130                 if( direction & 2 )
131                         Dest->Flags |= ARG_FLAG_RETURN;
132                 
133                 // Has data?
134                 if( direction & 1 )
135                 {
136                         if( DataDest && str )
137                                 memcpy(DataDest, str, len);
138                 }
139                 else
140                         Dest->Flags |= ARG_FLAG_ZEROED;
141                 break;
142         
143         default:
144                 return NULL;
145         }
146         ArgTypes ++;
147         
148         return ArgTypes;
149 }
150
151 /**
152  * \param ArgTypes
153  *
154  * Whitespace is ignored
155  * >i:  Input Integer (32-bits)
156  * >I:  Input Long Integer (64-bits)
157  * >s:  Input String
158  * >d:  Input Buffer (Preceded by valid size)
159  * <I:  Output long integer
160  * <d:  Output Buffer (Preceded by valid size)
161  * ?d:  Bi-directional buffer (Preceded by valid size), buffer contents
162  *      are returned
163  */
164 uint64_t _Syscall(int SyscallID, const char *ArgTypes, ...)
165 {
166         va_list args;
167          int    paramCount, dataLength;
168          int    retCount = 2, retLength = sizeof(uint64_t) + sizeof(uint32_t);
169         void    **retPtrs;      // Pointers to return buffers
170         const char      *str;
171         tRequestHeader  *req;
172         void    *dataPtr;
173         uint64_t        retValue;
174          int    i;
175         
176         // DEBUG!
177 //      printf("&tRequestHeader->Params = %i\n", offsetof(tRequestHeader, Params));
178 //      printf("&tRequestValue->Flags = %i\n", offsetof(tRequestValue, Flags));
179 //      printf("&tRequestValue->Length = %i\n", offsetof(tRequestValue, Length));
180         
181         // Get data size
182         va_start(args, ArgTypes);
183         str = ArgTypes;
184         paramCount = 0;
185         dataLength = 0;
186         while(*str)
187         {
188                 tRequestValue   tmpVal;
189                 
190                 str = ReadEntry(&tmpVal, NULL, NULL, str, &args);
191                 if( !str ) {
192                         fprintf(stderr, "syscalls.c: ReadEntry failed (SyscallID = %i)\n", SyscallID);
193                         exit(127);
194                 }
195                 paramCount ++;
196                 if( !(tmpVal.Flags & ARG_FLAG_ZEROED) )
197                         dataLength += tmpVal.Length;
198                 
199                 if( tmpVal.Flags & ARG_FLAG_RETURN ) {
200                         retLength += tmpVal.Length;
201                         retCount ++;
202                 }
203         }
204         va_end(args);
205         
206         dataLength += sizeof(tRequestHeader) + paramCount*sizeof(tRequestValue);
207         retLength += sizeof(tRequestHeader) + retCount*sizeof(tRequestValue);
208         
209         // Allocate buffers
210         retPtrs = malloc( sizeof(void*) * (retCount+1) );
211         if( dataLength > retLength)
212                 req = malloc( dataLength );
213         else
214                 req = malloc( retLength );
215         req->ClientID = 0;      //< Filled later
216         req->CallID = SyscallID;
217         req->NParams = paramCount;
218         req->MessageLength = dataLength;
219         dataPtr = &req->Params[paramCount];
220         
221         // Fill `output` and `input`
222         va_start(args, ArgTypes);
223         str = ArgTypes;
224         // - re-zero so they can be used as indicies
225         paramCount = 0;
226         retCount = 0;
227         while(*str)
228         {               
229                 str = ReadEntry(&req->Params[paramCount], dataPtr, &retPtrs[retCount], str, &args);
230                 if( !str )      break;
231                 
232                 if( !(req->Params[paramCount].Flags & ARG_FLAG_ZEROED) )
233                         dataPtr += req->Params[paramCount].Length;
234                 if( req->Params[paramCount].Flags & ARG_FLAG_RETURN )
235                         retCount ++;
236                 
237                 paramCount ++;
238         }
239         va_end(args);
240         
241         // --- Send syscall request
242         if( SendRequest(req, dataLength, retLength) < 0 ) {
243                 fprintf(stderr, "syscalls.c: SendRequest failed (SyscallID = %i)\n", SyscallID);
244                 exit(127);
245         }
246         
247         dataPtr = (void*)&req->Params[req->NParams];
248         assert(req->NParams >= 2);
249         // return
250         assert(req->Params[0].Type == ARG_TYPE_INT64);
251         assert(req->Params[0].Length == sizeof(uint64_t));
252         retValue = *(uint64_t*)dataPtr;
253         dataPtr += sizeof(uint64_t);
254         // errno
255         assert(req->Params[1].Type == ARG_TYPE_INT32);
256         assert(req->Params[1].Length == sizeof(uint32_t));
257         acess__errno = *(uint32_t*)dataPtr;
258         dataPtr += sizeof(uint32_t);
259         
260         // Write changes to buffers
261         if( req->NParams - 2 != retCount ) {
262                 fprintf(stderr, "syscalls.c: Return count inbalance (%i - 1 != exp %i) [Call %i]\n",
263                         req->NParams, retCount, SyscallID);
264                 exit(127);
265         }
266         retCount = 0;
267         for( i = 2; i < req->NParams; i ++ )
268         {
269                 #if 0
270                  int     j;
271                 printf("Return Data %i: (%i)", i, req->Params[i].Length);
272                 for( j = 0; j < req->Params[i].Length; j ++ )
273                         printf(" %02x", ((uint8_t*)dataPtr)[j]);
274                 printf("\n");
275                 #endif
276                 assert( req->Params[i].Type == ARG_TYPE_DATA );
277                 memcpy( retPtrs[retCount++], dataPtr, req->Params[i].Length );
278                 dataPtr += req->Params[i].Length;
279         }
280         
281         free( req );
282         free( retPtrs );
283         
284         if( gbSyscallDebugEnabled ) {
285                 SYSTRACE(": %i 0x%llx", SyscallID, retValue);
286         }
287         
288         return retValue;
289 }
290
291
292 int native_open(const char *Path, int Flags)
293 {
294         int     ret;
295        for(ret = 0; ret < MAX_FPS && gaSyscall_LocalFPs[ret]; ret ++ )  ;
296        if(ret == MAX_FPS)       return -1;
297        // TODO: Handle directories
298        gaSyscall_LocalFPs[ret] = fopen(&Path[4], "r+");
299        if(!gaSyscall_LocalFPs[ret])     return -1;
300        return ret;
301 }
302
303 void native_close(int FD)
304 {
305         fclose( gaSyscall_LocalFPs[FD] );
306         gaSyscall_LocalFPs[FD] = NULL;
307 }
308
309 size_t native_read(int FD, void *Dest, size_t Bytes)
310 {
311         return fread( Dest, Bytes, 1, gaSyscall_LocalFPs[FD] );
312 }
313
314 size_t native_write(int FD, const void *Src, size_t Bytes)
315 {
316         return fwrite( Src, Bytes, 1, gaSyscall_LocalFPs[FD] );
317 }
318
319 int native_seek(int FD, int64_t Ofs, int Dir)
320 {
321         if(Dir == 0)
322                 return fseek( gaSyscall_LocalFPs[FD], Ofs, SEEK_CUR );
323         else if(Dir > 0)
324                 return fseek( gaSyscall_LocalFPs[FD], Ofs, SEEK_SET );
325         else
326                 return fseek( gaSyscall_LocalFPs[FD], Ofs, SEEK_END );
327 }
328
329 uint64_t native_tell(int FD)
330 {
331         return ftell( gaSyscall_LocalFPs[FD] );
332 }
333
334 int native_execve(const char *filename, const char *const argv[], const char *const envp[])
335 {
336         int ret;
337         ret = execve(filename, (void*)argv, (void*)envp);
338         perror("native_execve");
339         return ret;
340 }
341
342 int native_spawn(const char *filename, const char *const argv[], const char *const envp[])
343 {
344         int rv;
345         
346         #if __WIN32__
347         rv = _spawnve(_P_NOWAIT, filename, argv, envp);
348         #else
349         rv = posix_spawn(NULL, filename, NULL, NULL, (void*)argv, (void*)envp);
350         #endif
351         
352         return rv;
353 }

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