AcessNative - Hexdump sycall, stub shm
[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         
175         // DEBUG!
176 //      printf("&tRequestHeader->Params = %i\n", offsetof(tRequestHeader, Params));
177 //      printf("&tRequestValue->Flags = %i\n", offsetof(tRequestValue, Flags));
178 //      printf("&tRequestValue->Length = %i\n", offsetof(tRequestValue, Length));
179         
180         // Get data size
181         va_start(args, ArgTypes);
182         str = ArgTypes;
183         paramCount = 0;
184         dataLength = 0;
185         while(*str)
186         {
187                 tRequestValue   tmpVal;
188                 
189                 str = ReadEntry(&tmpVal, NULL, NULL, str, &args);
190                 if( !str ) {
191                         fprintf(stderr, "syscalls.c: ReadEntry failed (SyscallID = %i)\n", SyscallID);
192                         exit(127);
193                 }
194                 paramCount ++;
195                 if( !(tmpVal.Flags & ARG_FLAG_ZEROED) )
196                         dataLength += tmpVal.Length;
197                 
198                 if( tmpVal.Flags & ARG_FLAG_RETURN ) {
199                         retLength += tmpVal.Length;
200                         retCount ++;
201                 }
202         }
203         va_end(args);
204         
205         dataLength += sizeof(tRequestHeader) + paramCount*sizeof(tRequestValue);
206         retLength += sizeof(tRequestHeader) + retCount*sizeof(tRequestValue);
207         
208         // Allocate buffers
209         retPtrs = malloc( sizeof(void*) * (retCount+1) );
210         if( dataLength > retLength)
211                 req = malloc( dataLength );
212         else
213                 req = malloc( retLength );
214         req->ClientID = 0;      //< Filled later
215         req->CallID = SyscallID;
216         req->NParams = paramCount;
217         req->MessageLength = dataLength;
218         dataPtr = &req->Params[paramCount];
219         
220         // Fill `output` and `input`
221         va_start(args, ArgTypes);
222         str = ArgTypes;
223         // - re-zero so they can be used as indicies
224         paramCount = 0;
225         retCount = 0;
226         while(*str)
227         {               
228                 str = ReadEntry(&req->Params[paramCount], dataPtr, &retPtrs[retCount], str, &args);
229                 if( !str )      break;
230                 
231                 if( !(req->Params[paramCount].Flags & ARG_FLAG_ZEROED) )
232                         dataPtr += req->Params[paramCount].Length;
233                 if( req->Params[paramCount].Flags & ARG_FLAG_RETURN )
234                         retCount ++;
235                 
236                 paramCount ++;
237         }
238         va_end(args);
239         
240         // --- Send syscall request
241         if( SendRequest(req, dataLength, retLength) < 0 ) {
242                 fprintf(stderr, "syscalls.c: SendRequest failed (SyscallID = %i)\n", SyscallID);
243                 exit(127);
244         }
245         
246         if( !(req->NParams >= 2) ) {
247                 fprintf(stderr, "syscalls.c: Too few return params (%i)", req->NParams);
248                 exit(127);
249         }
250         dataPtr = (void*)&req->Params[req->NParams];
251         // return
252         assert(req->Params[0].Type == ARG_TYPE_INT64);
253         assert(req->Params[0].Length == sizeof(uint64_t));
254         retValue = *(uint64_t*)dataPtr;
255         dataPtr += sizeof(uint64_t);
256         // errno
257         assert(req->Params[1].Type == ARG_TYPE_INT32);
258         assert(req->Params[1].Length == sizeof(uint32_t));
259         acess__errno = *(uint32_t*)dataPtr;
260         dataPtr += sizeof(uint32_t);
261         
262         // Write changes to buffers
263         if( req->NParams - 2 != retCount ) {
264                 fprintf(stderr, "syscalls.c: Return count inbalance (%i - 1 != exp %i) [Call %i]\n",
265                         req->NParams, retCount, SyscallID);
266                 exit(127);
267         }
268         retCount = 0;
269         for( unsigned int i = 2; i < req->NParams; i ++ )
270         {
271                 #if 0
272                  int     j;
273                 printf("Return Data %i: (%i)", i, req->Params[i].Length);
274                 for( j = 0; j < req->Params[i].Length; j ++ )
275                         printf(" %02x", ((uint8_t*)dataPtr)[j]);
276                 printf("\n");
277                 #endif
278                 assert( req->Params[i].Type == ARG_TYPE_DATA );
279                 memcpy( retPtrs[retCount++], dataPtr, req->Params[i].Length );
280                 dataPtr += req->Params[i].Length;
281         }
282         
283         free( req );
284         free( retPtrs );
285         
286         if( gbSyscallDebugEnabled ) {
287                 SYSTRACE(": %i 0x%llx", SyscallID, retValue);
288         }
289         
290         return retValue;
291 }
292
293 int native_int_getfd(void)
294 {
295         for(int ret = 0; ret < MAX_FPS; ret ++ )
296                 if( gaSyscall_LocalFPs[ret] == NULL )
297                         return ret;
298         return -1;
299 }
300
301 int native_open(const char *Path, int Flags)
302 {
303         int     ret = native_int_getfd();
304         if(ret == -1)   return -1;
305        // TODO: Handle directories
306        gaSyscall_LocalFPs[ret] = fopen(Path, "r+");
307        if(!gaSyscall_LocalFPs[ret])     return -1;
308        return ret;
309 }
310
311 int native_shm(const char *Tag, int Flags)
312 {
313         // int ret = native_int_getfd();
314         //if(ret == -1) return -1;
315         //if( strcmp(Tag, "anon") == 0 )
316         //      path = "/AcessNative/anon/RAND";
317         //      FD = shm_open(path, O_RDWD);
318         //shm_unlink(path);
319         //else
320         //      path = "/Acessnative/named/<TAG>";
321         // int FD = shm_open(path, O_RDWD);
322         //shm_unlink(path);
323         //gaSyscall_LocalFPs[ret] = 
324         return -1;
325 }
326
327 void native_close(int FD)
328 {
329         fclose( gaSyscall_LocalFPs[FD] );
330         gaSyscall_LocalFPs[FD] = NULL;
331 }
332
333 size_t native_read(int FD, void *Dest, size_t Bytes)
334 {
335         return fread( Dest, Bytes, 1, gaSyscall_LocalFPs[FD] );
336 }
337
338 size_t native_write(int FD, const void *Src, size_t Bytes)
339 {
340         return fwrite( Src, Bytes, 1, gaSyscall_LocalFPs[FD] );
341 }
342
343 int native_seek(int FD, int64_t Ofs, int Dir)
344 {
345         if(Dir == 0)
346                 return fseek( gaSyscall_LocalFPs[FD], Ofs, SEEK_CUR );
347         else if(Dir > 0)
348                 return fseek( gaSyscall_LocalFPs[FD], Ofs, SEEK_SET );
349         else
350                 return fseek( gaSyscall_LocalFPs[FD], Ofs, SEEK_END );
351 }
352
353 uint64_t native_tell(int FD)
354 {
355         return ftell( gaSyscall_LocalFPs[FD] );
356 }
357
358 int native_execve(const char *filename, const char *const argv[], const char *const envp[])
359 {
360         int ret;
361         ret = execve(filename, (void*)argv, (void*)envp);
362         perror("native_execve");
363         return ret;
364 }
365
366 int native_spawn(const char *filename, const char *const argv[], const char *const envp[])
367 {
368         int rv;
369
370         fprintf(stderr, "native_spawn('%s')\n", filename);
371
372         #if __WIN32__
373         rv = _spawnve(_P_NOWAIT, filename, argv, envp);
374         #else
375         rv = posix_spawn(NULL, filename, NULL, NULL, (void*)argv, (void*)envp);
376         #endif
377         
378         if( rv == 0 ) {
379                 perror("native_spawn");
380         }
381         
382         return rv;
383 }

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