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

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