Working on the x86 bit port (caused some changes to try and get it
[tpg/acess2.git] / Kernel / system.c
1 /*
2  * Acess 2
3  * Architecture Independent System Init
4  * system.c
5  */
6 #define DEBUG   0
7 #include <acess.h>
8
9 #define N_VARIABLES     16
10 #define N_MAX_ARGS      BITS
11
12 // === TYPES ===
13 typedef struct
14 {
15          int    TrueLine;
16          int    nParts;
17         char    **Parts;
18 }       tConfigLine;
19 typedef struct
20 {
21          int    nLines;
22         tConfigLine     Lines[];
23 }       tConfigFile;
24 typedef struct
25 {
26         char    *Name;          // Name
27          int    MinArgs;        // Minimum number of arguments
28          int    MaxArgs;        // Maximum number of arguments
29         Uint    IntArgs;        // Bitmap of arguments that should be treated as integers
30         void    *Func;          // Function pointer
31         Uint    OptDefaults[N_MAX_ARGS];        // Default values for optional arguments
32 }       tConfigCommand;
33
34 // === IMPORTS ===
35 extern void     Arch_LoadBootModules(void);
36 extern int      Modules_LoadBuiltins(void);
37 extern void     Modules_SetBuiltinParams(char *Name, char *ArgString);
38 extern void     Debug_SetKTerminal(char *File);
39
40 // === PROTOTYPES ===
41 void    System_Init(char *Commandline);
42 void    System_ParseCommandLine(char *ArgString);
43 void    System_ExecuteCommandLine(void);
44 void    System_ParseVFS(char *Arg);
45 void    System_ParseModuleArgs(char *Arg);
46 void    System_ParseSetting(char *Arg);
47 void    System_ExecuteScript(void);
48 tConfigFile     *System_Int_ParseFile(char *File);
49
50 // === CONSTANTS ===
51 const tConfigCommand    caConfigCommands[] = {
52         {"module",  1,2, 00, Module_LoadFile, {(Uint)"",0}},    // Load a module from a file
53         {"spawn",   1,1, 00, Proc_Spawn, {0}},          // Spawn a process
54         // --- VFS ---
55         {"mount",   3,4, 00, VFS_Mount, {(Uint)"",0}},          // Mount a device
56         {"symlink", 2,2, 00, VFS_Symlink, {0}}, // Create a Symbolic Link
57         {"mkdir",   1,1, 00, VFS_MkDir, {0}},           // Create a Directory
58         {"open",    1,2, 00, VFS_Open,  {VFS_OPENFLAG_READ,0}}, // Open a file
59         {"close",   1,1, 01, VFS_Close, {0}},   // Close an open file
60         {"ioctl",   3,3, 03, VFS_IOCtl, {0}},   // Call an IOCtl
61         
62         {"", 0,0, 0, NULL, {0}}
63 };
64 #define NUM_CONFIG_COMMANDS     (sizeof(caConfigCommands)/sizeof(caConfigCommands[0]))
65
66 // === GLOBALS ===
67 char    *gsConfigScript = "/Acess/Conf/BootConf.cfg";
68 char    *argv[32];
69  int    argc;
70
71 // === CODE ===
72 void System_Init(char *CommandLine)
73 {
74         // Parse Kernel's Command Line
75         System_ParseCommandLine(CommandLine);
76         
77         // Initialise modules
78         Log_Log("Config", "Initialising builtin modules...");
79         Modules_LoadBuiltins();
80         Arch_LoadBootModules();
81         
82         System_ExecuteCommandLine();
83         
84         // - Execute the Config Script
85         Log_Log("Config", "Executing config script...");
86         System_ExecuteScript();
87         
88         // Set the debug to be echoed to the terminal
89         Log_Log("Config", "Kernel now echoes to VT7 (Ctrl-Alt-F8)");
90         Debug_SetKTerminal("/Devices/VTerm/7");
91 }
92
93 /**
94  * \fn void System_ParseCommandLine(char *ArgString)
95  * \brief Parses the kernel's command line and sets the environment
96  */
97 void System_ParseCommandLine(char *ArgString)
98 {
99          int    i;
100         char    *str;
101         
102         Log_Log("Config", "Kernel Invocation (%p) \"%s\"", ArgString, ArgString);
103         Log_Log("Config", "Kernel Invocation '0x%x 0x%x'", ArgString[0], ArgString[1]);
104         
105         // --- Get Arguments ---
106         str = ArgString;
107         for( argc = 0; argc < 32; argc++ )
108         {
109                 // Eat Whitespace
110                 while(*str == ' ')      str++;
111                 // Check for the end of the string
112                 if(*str == '\0') {      argc--; break;} 
113                 argv[argc] = str;
114                 if(*str == '"') {
115                         while(*str && !(*str == '"' && str[-1] != '\\'))
116                                 str ++;
117                 }
118                 else {
119                         while(*str && *str != ' ')
120                                 str++;
121                 }
122                 if(*str == '\0')        break;  // Check for EOS
123                 *str = '\0';    // Cap off argument string
124                 str ++; // and increment the string pointer
125         }
126         if(argc < 32)
127                 argc ++;        // Count last argument
128         
129         // --- Parse Arguments (Pass 1) ---
130         for( i = 0; i < argc; i++ )
131         {
132                 switch(argv[i][0])
133                 {
134                 // --- VFS ---
135                 // Ignored on this pass
136                 case '/':
137                         break;
138                 
139                 // --- Module Paramaters ---
140                 // -VTerm:Width=640,Height=480,Scrollback=2
141                 case '-':
142                         System_ParseModuleArgs( argv[i] );
143                         break;
144                 // --- Config Options ---
145                 // SCRIPT=/Acess/Conf/BootConf.cfg
146                 default:
147                         System_ParseSetting( argv[i] );
148                         break;
149                 }
150         }
151 }
152
153 void System_ExecuteCommandLine(void)
154 {
155          int    i;
156         for( i = 0; i < argc; i++ )
157         {
158                 Log("argv[%i] = '%s'", i, argv[i]);
159                 switch(argv[i][0])
160                 {
161                 // --- VFS ---
162                 // Mount    /System=ext2:/Devices/ATA/A1
163                 // Symlink  /Acess=/System/Acess2
164                 case '/':
165                         System_ParseVFS( argv[i] );
166                         break;
167                 }
168         }
169 }
170
171 /**
172  * \fn void System_ParseVFS(char *Arg)
173  */
174 void System_ParseVFS(char *Arg)
175 {
176         char    *value;
177          int    fd;
178         
179         value = Arg;
180         // Search for the '=' token
181         while( *value && *value != '=' )
182                 value++;
183         
184         // Check if the equals was found
185         if( *value == '\0' ) {
186                 Log_Warning("Config", "Expected '=' in the string '%s'", Arg);
187                 return ;
188         }
189         
190         // Edit string
191         *value = '\0';  value ++;
192         
193         // Check assignment type
194         // - Symbolic Link <link>=<destination>
195         if(value[0] == '/')
196         {
197                 Log_Log("Config", "Symbolic link '%s' pointing to '%s'", Arg, value);
198                 VFS_Symlink(Arg, value);
199         }
200         // - Mount <mountpoint>=<fs>:<device>
201         else
202         {
203                 char    *dev = value;
204                 // Find colon
205                 while(*dev && *dev != ':')      dev++;
206                 if(*dev) {
207                         *dev = '\0';
208                         dev++;  // Eat ':'
209                 }
210                 // Create Mountpoint
211                 if( (fd = VFS_Open(Arg, 0)) == -1 ) {
212                         Log_Log("Config", "Creating directory '%s'", Arg, value);
213                         VFS_MkDir( Arg );
214                 } else {
215                         VFS_Close(fd);
216                 }
217                 // Mount
218                 Log_Log("Config", "Mounting '%s' to '%s' ('%s')", dev, Arg, value);
219                 VFS_Mount(dev, Arg, value, "");
220         }
221 }
222
223 /**
224  * \biref Parse a module argument string
225  */
226 void System_ParseModuleArgs(char *Arg)
227 {
228         char    *name, *args;
229          int    i;
230         
231         // Remove '-'   
232         name = Arg + 1;
233         
234         // Find the start of the args
235         i = strpos(name, ':');
236         if( i == -1 ) {
237                 Log_Warning("Config", "Module spec with no arguments");
238                 #if 1
239                 return ;
240                 #else
241                 i = strlen(name);
242                 args = name + i;
243                 #endif
244         }
245         else {
246                 name[i] = '\0';
247                 args = name + i + 1;
248         }
249         
250         Log_Log("Config", "Setting boot parameters for '%s' to '%s'", name, args);
251         Modules_SetBuiltinParams(name, args);
252 }
253
254 /**
255  * \fn void System_ParseSetting(char *Arg)
256  */
257 void System_ParseSetting(char *Arg)
258 {
259         char    *value;
260         value = Arg;
261
262         // Search for the '=' token
263         while( *value && *value != '=' )
264                 value++;
265         
266         // Check for boolean/flag (no '=')
267         if(*value == '\0')
268         {
269                 //if(strcmp(Arg, "") == 0) {
270                 //} else {
271                         Log_Warning("Config", "Kernel flag '%s' is not recognised", Arg);
272                 //}
273         }
274         else
275         {
276                 *value = '\0';  // Remove '='
277                 value ++;       // and eat it's position
278                 
279                 if(strcmp(Arg, "SCRIPT") == 0) {
280                         Log_Log("Config", "Config Script: '%s'", value);
281                         if(strlen(value) == 0)
282                                 gsConfigScript = NULL;
283                         else
284                                 gsConfigScript = value;
285                 } else {
286                         Log_Warning("Config", "Kernel config setting '%s' is not recognised", Arg);
287                 }
288                 
289         }
290 }
291
292 /**
293  * \fn void System_ExecuteScript()
294  * \brief Reads and parses the boot configuration script
295  */
296 void System_ExecuteScript(void)
297 {
298          int    fp;
299          int    fLen = 0;
300          int    i, j, k;
301          int    val;
302          int    result = 0;
303          int    variables[N_VARIABLES];
304          int    bReplaced[N_MAX_ARGS];
305         char    *fData;
306         char    *jmpTarget;
307         tConfigFile     *file;
308         tConfigLine     *line;
309         
310         // Open Script
311         fp = VFS_Open(gsConfigScript, VFS_OPENFLAG_READ);
312         if(fp == -1) {
313                 Log_Warning("Config", "Passed script '%s' does not exist", gsConfigScript);
314                 return;
315         }
316         
317         // Get length
318         VFS_Seek(fp, 0, SEEK_END);
319         fLen = VFS_Tell(fp);
320         VFS_Seek(fp, 0, SEEK_SET);
321         // Read into memory buffer
322         fData = malloc(fLen+1);
323         VFS_Read(fp, fLen, fData);
324         fData[fLen] = '\0';
325         VFS_Close(fp);
326         
327         
328         // Parse File
329         file = System_Int_ParseFile(fData);
330         
331         // Parse each line
332         for( i = 0; i < file->nLines; i++ )
333         {
334                 line = &file->Lines[i];
335                 if( line->nParts == 0 ) continue;       // Skip blank
336                 
337                 if(line->Parts[0][0] == ':')    continue;       // Ignore labels
338                 
339                 // Prescan and eliminate variables
340                 for( j = 1; j < line->nParts; j++ ) {
341                         Log_Debug("Config", "Arg #%i is '%s'", j, line->Parts[j]);
342                         bReplaced[j] = 0;
343                         if( line->Parts[j][0] != '$' )  continue;
344                         if( line->Parts[j][1] == '?' ) {
345                                 val = result;
346                         }
347                         else {
348                                 val = atoi( &line->Parts[j][1] );
349                                 if( val < 0 || val > N_VARIABLES )      continue;
350                                 val = variables[ val ];
351                         }
352                         Log_Debug("Config", "Replaced arg %i ('%s') with 0x%x", j, line->Parts[j], val);
353                         line->Parts[j] = malloc( BITS/8+2+1 );
354                         sprintf(line->Parts[j], "0x%x", val);
355                         bReplaced[j] = 1;
356                 }
357                 
358                 for( j = 0; j < NUM_CONFIG_COMMANDS; j++ )
359                 {
360                         Uint    args[N_MAX_ARGS];
361                         if(strcmp(line->Parts[0], caConfigCommands[j].Name) != 0)       continue;
362                         
363                         Log_Debug("Config", "Command '%s', %i args passed", line->Parts[0], line->nParts-1);
364                         
365                         if( line->nParts - 1 < caConfigCommands[j].MinArgs ) {
366                                 Log_Warning("Config",
367                                         "Configuration command '%s' requires at least %i arguments, %i given",
368                                         caConfigCommands[j].Name, caConfigCommands[j].MinArgs, line->nParts-1
369                                         );
370                                 break;
371                         }
372                         
373                         if( line->nParts - 1 > caConfigCommands[j].MaxArgs ) {
374                                 Log_Warning("Config",
375                                         "Configuration command '%s' takes at most %i arguments, %i given",
376                                         caConfigCommands[j].Name, caConfigCommands[j].MaxArgs, line->nParts-1
377                                         );
378                                 break;
379                         }
380                         
381                         for( k = caConfigCommands[j].MaxArgs-1; k > line->nParts - 1; k-- ) {
382                                 args[k] = caConfigCommands[j].OptDefaults[k];
383                         }
384                         
385                         for( k = line->nParts-1; k--; )
386                         {
387                                 if( caConfigCommands[j].IntArgs & (1 << k) ) {
388                                         args[k] = atoi(line->Parts[k+1]);
389                                 }
390                                 else {
391                                         args[k] = (Uint)line->Parts[k+1];
392                                 }
393                                 Log_Debug("Config", "args[%i] = 0x%x", k, args[k]);
394                         }
395                         result = CallWithArgArray(caConfigCommands[j].Func, caConfigCommands[j].MaxArgs, args);
396                         Log_Debug("Config", "result = %i", result);
397                         break;
398                 }
399                 if( j < NUM_CONFIG_COMMANDS )   continue;
400                         
401                 // --- State and Variables ---
402                 if(strcmp(line->Parts[0], "set") == 0)
403                 {
404                          int    to, value;
405                         if( line->nParts-1 != 2 ) {
406                                 Log_Warning("Config", "Configuration command 'set' requires 2 arguments, %i given",
407                                         line->nParts-1);
408                                 continue;
409                         }
410                         
411                         to = atoi(line->Parts[1]);
412                         value = atoi(line->Parts[2]);
413                         
414                         variables[to] = value;
415                         result = value;
416                 }
417                 // if <val1> <op> <val2> <dest>
418                 else if(strcmp(line->Parts[0], "if") == 0)
419                 {
420                         if( line->nParts-1 != 4 ) {
421                                 Log_Warning("Config", "Configuration command 'if' requires 4 arguments, %i given",
422                                         line->nParts-1);
423                         }
424                         
425                         result = atoi(line->Parts[1]);
426                         val = atoi(line->Parts[3]);
427                         
428                         jmpTarget = line->Parts[4];
429                         
430                         Log_Log("Config", "IF 0x%x %s 0x%x THEN GOTO %s",
431                                 result, line->Parts[2], val, jmpTarget);
432                         
433                         if( strcmp(line->Parts[2], "<" ) == 0 ) {
434                                 if( result < val )      goto jumpToLabel;
435                         }
436                         else if( strcmp(line->Parts[2], "<=") == 0 ) {
437                                 if( result <= val )     goto jumpToLabel;
438                         }
439                         else if( strcmp(line->Parts[2], ">" ) == 0 ) {
440                                 if (result > val )      goto jumpToLabel;
441                         }
442                         else if( strcmp(line->Parts[2], ">=") == 0 ) {
443                                 if( result >= val )     goto jumpToLabel;
444                         }
445                         else if( strcmp(line->Parts[2],  "=") == 0 ) {
446                                 if( result == val )     goto jumpToLabel;
447                         }
448                         else if( strcmp(line->Parts[2], "!=") == 0 ) {
449                                 if( result != val )     goto jumpToLabel;
450                         }
451                         else {
452                                 Log_Warning("Config", "Unknown comparision '%s' in `if`", line->Parts[2]);
453                         }
454                         
455                 }
456                 else if(strcmp(line->Parts[0], "goto") == 0) {
457                         if( line->nParts-1 != 1 ) {
458                                 Log_Warning("Config", "Configuration command 'goto' requires 1 arguments, %i given",
459                                         line->nParts-1);
460                         }
461                         jmpTarget = line->Parts[1];
462                 
463                 jumpToLabel:
464                         for( j = 0; j < file->nLines; j ++ )
465                         {
466                                 if(file->Lines[j].nParts == 0)
467                                         continue;
468                                 if(file->Lines[j].Parts[0][0] != ':')
469                                         continue;
470                                 if( strcmp(file->Lines[j].Parts[0]+1, jmpTarget) == 0)
471                                         break;
472                         }
473                         if( j == file->nLines )
474                                 Log_Warning("Config", "Unable to find label '%s'", jmpTarget);
475                         else
476                                 i = j;
477                 }
478                 else {
479                         Log_Warning("Config", "Unknown configuration command '%s' on line %i",
480                                 line->Parts[0],
481                                 line->TrueLine
482                                 );
483                 }
484         }
485         
486         // Clean up after ourselves
487         for( i = 0; i < file->nLines; i++ ) {
488                 if( file->Lines[i].nParts == 0 )        continue;       // Skip blank
489                 for( j = 0; j < file->Lines[i].nParts; j++ ) {
490                         if(IsHeap(file->Lines[i].Parts[j]))
491                                 free(file->Lines[i].Parts[j]);
492                 }
493                 free( file->Lines[i].Parts );
494         }
495         
496         // Free data
497         free( file );
498         free( fData );
499 }
500
501 /**
502  * \brief Parses a config file
503  * \param FileData      Read/Write buffer containing the config file data
504  *                  (will be modified)
505  * \return ::tConfigFile structure that represents the original contents
506  *         of \a FileData
507  */
508 tConfigFile     *System_Int_ParseFile(char *FileData)
509 {
510         char    *ptr;
511         char    *start;
512          int    nLines = 1;
513          int    i, j;
514         tConfigFile     *ret;
515         
516         ENTER("pFileData", FileData);
517         
518         // Prescan and count the number of lines
519         for(ptr = FileData; *ptr; ptr++)
520         {               
521                 if(*ptr != '\n')        continue;
522                 
523                 if(ptr == FileData) {
524                         nLines ++;
525                         continue;
526                 }
527                 
528                 // Escaped EOL
529                 if(ptr[-1] == '\\')     continue;
530                 
531                 nLines ++;
532         }
533         
534         LOG("nLines = %i", nLines);
535         
536         // Ok so we have `nLines` lines, now to allocate our return
537         ret = malloc( sizeof(tConfigFile) + sizeof(tConfigLine)*nLines );
538         ret->nLines = nLines;
539         
540         // Read the file for real
541         for(
542                 ptr = FileData, i = 0;
543                 *ptr;
544                 i++
545                 )
546         {
547                 start = ptr;
548                 
549                 ret->Lines[i].nParts = 0;
550                 
551                 // Count parts
552                 for(;;)
553                 {
554                         // Read leading whitespace
555                         while( *ptr == '\t' || *ptr == ' ' )    ptr++;
556                         
557                         // End of line/file
558                         if( *ptr == '\0' || *ptr == '\n' ) {
559                                 if(*ptr == '\n')        ptr ++;
560                                 break;
561                         }
562                         // Comment
563                         if( *ptr == '#' || *ptr == ';' ) {
564                                 while( *ptr && *ptr != '\n' )   ptr ++;
565                                 if(*ptr == '\n')        ptr ++;
566                                 break;
567                         }
568                         
569                         ret->Lines[i].nParts ++;
570                         // Quoted
571                         if( *ptr == '"' ) {
572                                 ptr ++;
573                                 while( *ptr && !(*ptr == '"' && ptr[-1] == '\\') && *ptr != '\n' )
574                                         ptr++;
575                                 continue;
576                         }
577                         // Unquoted
578                         while( *ptr && !(*ptr == '\t' || *ptr == ' ') && *ptr != '\n' )
579                                 ptr++;
580                 }
581                 
582                 LOG("ret->Lines[%i].nParts = %i", i, ret->Lines[i].nParts);
583                 
584                 if( ret->Lines[i].nParts == 0 ) {
585                         ret->Lines[i].Parts = NULL;
586                         continue;
587                 }
588                 
589                 // Allocate part list
590                 ret->Lines[i].Parts = malloc( sizeof(char*) * ret->Lines[i].nParts );
591                 
592                 // Fill list
593                 for( ptr = start, j = 0; ; j++ )
594                 {
595                         // Read leading whitespace
596                         while( *ptr == '\t' || *ptr == ' ' )    ptr++;
597                         
598                         // End of line/file
599                         if( *ptr == '\0' || *ptr == '\n' ) {
600                                 if(*ptr == '\n')        ptr ++;
601                                 break;
602                         }
603                         // Comment
604                         if( *ptr == '#' || *ptr == ';' ) {
605                                 while( *ptr && *ptr != '\n' )   ptr ++;
606                                 if(*ptr == '\n')        ptr ++;
607                                 break;
608                         }
609                         
610                         ret->Lines[i].Parts[j] = ptr;
611                         
612                         // Quoted
613                         if( *ptr == '"' ) {
614                                 ptr ++;
615                                 ret->Lines[i].Parts[j] = ptr;
616                                 while( *ptr && !(*ptr == '"' && ptr[-1] == '\\') && *ptr != '\n' )
617                                         ptr++;
618                         }
619                         // Unquoted
620                         else {
621                                 while( *ptr != '\t' && *ptr != ' ' && *ptr != '\n' )
622                                         ptr++;
623                         }
624                         
625                         // Break if we have reached NULL
626                         if( *ptr == '\0' ) {
627                                 LOG("ret->Lines[%i].Parts[%i] = '%s'", i, j, ret->Lines[i].Parts[j]);
628                                 break;
629                         }
630                         if( *ptr == '\n' ) {
631                                 *ptr = '\0';
632                                 LOG("ret->Lines[%i].Parts[%i] = '%s'", i, j, ret->Lines[i].Parts[j]);
633                                 ptr ++;
634                                 break;
635                         }
636                         *ptr = '\0';    // Cap off string
637                         LOG("ret->Lines[%i].Parts[%i] = '%s'", i, j, ret->Lines[i].Parts[j]);
638                         ptr ++; // And increment for the next round
639                 }
640         }
641         
642         LEAVE('p', ret);
643         return ret;
644 }

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