source: trunk/user/ksh/ksh.c @ 418

Last change on this file since 418 was 418, checked in by alain, 6 years ago

Fix a bug in hal_kentry.S : the "uzone" pointer in the thread descriptor
must not be modified in case of interrupt.

File size: 15.1 KB
Line 
1///////////////////////////////////////////////////////////////////////////////
2// File   :  ksh.c
3// Date   :  October 2017
4// Author :  Alain Greiner
5///////////////////////////////////////////////////////////////////////////////
6// This single thread application implement a simple shell for ALMOS-MKH.
7///////////////////////////////////////////////////////////////////////////////
8
9#include <nostdio.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13#include <shared_syscalls.h>
14
15#define CMD_MAX_SIZE   (256)    // max number of characters in one command
16#define LOG_DEPTH      (256)    // max number of registered commands
17#define MAX_ARGS           (32)     // max number of arguments in a command
18#define FIFO_SIZE      (1024)   // FIFO depth for recursive ls
19
20////////////////////////////////////////////////////////////////////////////////
21//         Structures
22////////////////////////////////////////////////////////////////////////////////
23
24// one entry in the registered commands array
25typedef struct log_entry_s
26{
27        char          buf[CMD_MAX_SIZE];
28        unsigned int  count;
29}
30log_entry_t;
31
32// one entry in the supported command types array
33typedef struct ksh_cmd_s
34{
35        char * name;
36        char * desc;
37        void   (*fn)( int , char ** );
38}
39ksh_cmd_t;
40
41
42////////////////////////////////////////////////////////////////////////////////
43//         Global Variables
44////////////////////////////////////////////////////////////////////////////////
45
46ksh_cmd_t       cmd[];                    // array of supported commands
47
48log_entry_t     log_entries[LOG_DEPTH];   // array of registered commands
49
50unsigned int    ptw;                      // write pointer in log_entries[]
51unsigned int    ptr;                      // read pointer in log_entries[]
52
53////////////////////////////////////////////////////////////////////////////////
54//         Shell  Commands
55////////////////////////////////////////////////////////////////////////////////
56
57/////////////////////////////////////////////
58static void cmd_cat( int argc , char **argv )
59{
60        char         * path;
61
62        if (argc != 2) 
63    {
64                printf("  usage: cat pathname\n");
65                return;
66        }
67
68        path = argv[1];
69
70    printf("  error: not implemented yet\n");
71
72/*
73        // open the file
74        fd = open( path , O_RDONLY , 0 );
75        if (fd < 0)
76    {
77                printf("  error: cannot open %s\n", path);
78                goto exit;
79        }
80
81        // get file size
82        if (stat(path, &st) == -1)
83    {
84                printf("  error: cannot stat %s\n", path);
85                goto exit;
86        }
87        if (S_ISDIR(st.st_mode)) {
88                printf("  error: %s is a directory\n", path);
89                goto exit;
90        }
91        size = st.st_size;
92
93        // mmap the file
94        buf = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
95        if (buf == NULL || buf == (char *)-1) {
96                printf("  error: cannot map %s\n", path);
97                goto exit;
98        }
99
100        // set terminating '0' XXX
101        buf[size-1] = 0;
102
103        // display the file content
104        printf("%s", buf);
105
106exit:
107        if (buf != NULL) munmap(buf, size);
108        if (fd >= 0) close(fd);
109*/
110
111}   // end cmd_cat()
112
113////////////////////////////////////////////
114static void cmd_cd( int argc , char **argv )
115{
116        char * path;
117
118        if (argc != 2)
119    {
120                printf("  usage: cd pathname\n");
121                return;
122        }
123
124        path = argv[1];
125
126    printf("  error: not implemented yet\n");
127/*
128        path = argv[1];
129
130        if (chdir(path) == -1)
131    {
132                printf("  error: cannot cd to %s\n", path);
133        }
134*/
135
136}   // end cmd_cd()
137
138/////////////////////////////////////////
139static void cmd_cp(int argc, char **argv)
140{
141//      int src_fd = -1, dst_fd = -1;
142//      char *srcpath, *dstpath;
143//      struct stat st;
144//      size_t size, i;
145//      char buf[1024];
146
147        if (argc != 3) 
148    {
149                printf("  usage: cp src_pathname dst_pathname\n");
150                return;
151        }
152
153    printf("  error: not implemented yet\n");
154
155/*
156        srcpath = argv[1];
157        dstpath = argv[2];
158
159        // open the src file
160        src_fd = open(srcpath, O_RDONLY, 0);
161        if (src_fd < 0) {
162                printf("  error: cannot open %s / err = %d\n", srcpath, errno);
163                goto exit;
164        }
165
166        // get file size
167        if (stat(srcpath, &st) == -1) {
168                printf("  error: cannot stat %s\n", srcpath);
169                goto exit;
170        }
171        if (S_ISDIR(st.st_mode)) {
172                printf("  error: %s is a directory\n", srcpath);
173                goto exit;
174        }
175        size = st.st_size;
176
177        // open the dst file
178        dst_fd = open(dstpath, O_CREAT|O_TRUNC|O_RDWR, 0);
179        if (dst_fd < 0) {
180                printf("  error: cannot open %s / err = %d\n", dstpath, errno);
181                goto exit;
182        }
183        if (stat(dstpath, &st) == -1) {
184                printf("  error: cannot stat %s\n", dstpath);
185                goto exit;
186        }
187        if (S_ISDIR(st.st_mode)) {
188                printf("  error: %s is a directory\n", dstpath);
189                goto exit;
190        }
191
192        i = 0;
193        while (i < size)
194        {
195                size_t rlen = (size - i < 1024 ? size - i : 1024);
196                size_t wlen;
197                ssize_t ret;
198
199                // read the source
200                ret = read(src_fd, buf, rlen);
201                if (ret == -1) {
202                        printf("  error: cannot read from file %s\n", srcpath);
203                        goto exit;
204                }
205                rlen = (size_t)ret;
206
207                // write to the destination
208                ret = write(dst_fd, buf, rlen);
209                if (ret == -1) {
210                        printf("  error: cannot write to file %s\n", dstpath);
211                        goto exit;
212                }
213                wlen = (size_t)ret;
214
215                // check
216                if (wlen != rlen) {
217                        printf("  error: cannot write on device\n");
218                        goto exit;
219                }
220
221                i += rlen;
222        }
223
224exit:
225        if (src_fd >= 0) close(src_fd);
226        if (dst_fd >= 0) close(dst_fd);
227*/
228
229}   // end cmd_cp()
230
231//////////////////////////////////////////////
232static void cmd_help( int argc , char **argv )
233{
234        unsigned int i;
235
236        if (argc != 1) 
237    {
238                printf("  usage: %s\n", argv[0]);
239                return;
240        }
241
242        printf("available commands:\n");
243        for (i = 0 ; cmd[i].name ; i++) 
244    {
245                printf("\t%s\t : %s\n", cmd[i].name , cmd[i].desc);
246        }
247}   // end cmd_help()
248
249//////////////////////////////////////////////
250static void cmd_kill( int argc , char **argv )
251{
252        unsigned int pid;
253
254        if (argc != 2) 
255    {
256                printf("  usage: %s pid\n", argv[0]);
257                return;
258        }
259
260        pid = atoi(argv[1]);
261
262        if( kill( pid , SIGKILL ) )
263    {
264                printf("  error: unable to kill process %x\n", pid );
265        }
266
267    printf("\n   ...  done\n" );
268
269}   // end cmd_kill()
270
271//////////////////////////////////////////////
272static void cmd_load( int argc , char **argv )
273{
274        unsigned int         pid;
275    unsigned int         error;
276        char               * pathname;
277
278        if (argc != 2) 
279    {
280                printf("  usage: %s pathname \n", argv[0] );
281                return;
282        }
283
284        pathname = argv[1];
285
286    // fork system call
287        pid = fork();
288
289    if (pid == 0)  // it is the child process
290    {
291        // exec system call
292        error = exec( pathname , NULL , NULL );
293
294        if( error )
295        {
296            printf("  error: new process unable to exec <%s>\n", pathname );
297            exit(0);
298        }
299        } 
300    else if ( pid < 0 )  // it is a failure reported to parent
301    {
302        printf("  error: unable to fork\n");
303    }
304}   // end cmd_load
305
306/////////////////////////////////////////////
307static void cmd_log( int argc , char **argv )
308{
309        unsigned int i;
310
311        printf("--- registered commands ---\n");
312        for (i = 0; i < LOG_DEPTH; i++) 
313    {
314                printf(" - %zu\t: %s\n", i, &log_entries[i].buf);
315        }
316}
317
318////////////////////////////////////////////
319static void cmd_ls( int argc , char **argv )
320{
321        char  * path;
322
323//  struct dirent * file;
324//  DIR *dir;
325
326        if (argc == 1)
327    {
328                path = ".";
329        }
330    else if (argc == 2) 
331    {
332                path = argv[1];
333        } 
334    else 
335    {
336                printf("  usage: ls [path]\n");
337                return;
338        }
339
340    printf("  error: not implemented yet\n");
341/*
342        dir = opendir( path );
343        while ((file = readdir(dir)) != NULL)
344        {
345                printf(" %s\n", file->d_name);
346        }
347        closedir(dir);
348*/
349}
350
351///////////////////////////////////////////////
352static void cmd_mkdir( int argc , char **argv )
353{
354        char * pathname;
355
356        if (argc != 2)
357    {
358                printf("  usage: mkdir pathname\n");
359                return;
360        }
361
362    pathname = argv[1];
363
364    printf("  error: not implemented yet\n");
365/*
366        if ( mkdir( path, 0x700) == -1 )
367    {
368                printf("  error: cannot create directory %s\n", path);
369        }
370*/
371}
372
373////////////////////////////////////////////
374static void cmd_mv( int argc , char **argv )
375{
376
377        if (argc < 3)
378        {
379                printf("  usage : %s src_pathname dst_pathname\n", argv[0]);
380                return;
381        }
382
383    printf("  error: not implemented yet\n");
384   
385/*
386        int ret = giet_fat_rename(argv[1], argv[2]);
387        if (ret < 0)
388        {
389                printf("  error : cannot move %s to %s / err = %d\n", argv[1], argv[2], ret );
390        }
391*/
392
393}
394
395/////////////////////////////////////////////
396static void cmd_pwd( int argc , char **argv )
397{
398        char buf[1024];
399
400        if (argc != 1)
401    {
402                printf("  usage: pwd\n");
403                return;
404        }
405
406        if ( getcwd( buf , 1024 ) ) 
407    {
408                printf("  error: unable to get current directory\n");
409        }
410    else 
411    {
412                printf("%s\n", buf);
413        }
414}
415
416////////////////////////////////////////////
417static void cmd_rm( int argc , char **argv )
418{
419        char * pathname;
420
421        if (argc != 2)
422    {
423                printf("  usage: rm pathname\n");
424                return;
425        }
426
427        pathname = argv[1];
428
429    printf("  error: not implemented yet\n");
430/*
431        if (remove(path) == -1)
432    {
433                printf("  error: cannot remove %s\n", path);
434        }
435*/
436
437}
438
439///////////////////////////////////////////////
440static void cmd_rmdir( int argc , char **argv )
441{
442        cmd_rm(argc, argv);
443}
444
445///////////////////////////////////////////////
446static void cmd_sched( int argc , char **argv )
447{
448    unsigned int cxy;
449    unsigned int lid;
450
451        if (argc != 3)
452    {
453                printf("  usage: sched cxy lid\n");
454                return;
455        }
456
457        cxy = atoi(argv[1]);
458        lid = atoi(argv[2]);
459
460    if( get_sched( cxy , lid ) )
461    {
462        printf("  error: illegal arguments\n");
463    }
464}
465
466//////////////////////////////////////////////////////////////////
467// Array of commands
468//////////////////////////////////////////////////////////////////
469
470ksh_cmd_t cmd[] =
471{
472        { "cat",    "display file content",                cmd_cat   },
473        { "cd",     "change current directory",            cmd_cd    },
474        { "cp",     "replicate a file in file system",     cmd_cp    },
475        { "load",   "load an user application",            cmd_load  },
476        { "help",   "list available commands",             cmd_help  },
477        { "kill",   "kill an application (all threads)",   cmd_kill  },
478        { "log",    "list registered commands",            cmd_log   },
479        { "ls",     "list directory entries",              cmd_ls    },
480        { "mkdir",  "create a new directory",              cmd_mkdir },
481        { "mv",     "move a file in file system",          cmd_mv    },
482        { "pwd",    "print current working directory",     cmd_pwd   },
483        { "rm",     "remove a file from file system",      cmd_rm    },
484        { "rmdir",  "remove a directory from file system", cmd_rmdir },
485    { "sched",  "display scheduler state",             cmd_sched },
486        { NULL,     NULL,                                                                  NULL      }
487};
488
489////////////////////////////////////////////////////////////////////////////////////
490// This function analyses one command (with arguments), execute it, and return.
491////////////////////////////////////////////////////////////////////////////////////
492static void parse(char *buf)
493{
494        int argc = 0;
495        char *argv[MAX_ARGS];
496        int i;
497        int len = strlen(buf);
498
499        // build argc/argv
500        for (i = 0; i < len; i++) 
501    {
502                if (buf[i] == ' ') 
503        {
504                        buf[i] = '\0';
505                }
506        else if (i == 0 || buf[i - 1] == '\0') 
507        {
508                        if (argc < MAX_ARGS) 
509            {
510                                argv[argc] = &buf[i];
511                                argc++;
512                        }
513                }
514        }
515
516        if (argc > 0)
517    {
518                int found = 0;
519
520                argv[argc] = NULL;
521
522                // try to match typed command
523                for (i = 0; cmd[i].name; i++)
524        {
525                        if (strcmp(argv[0], cmd[i].name) == 0)
526            {
527                                cmd[i].fn(argc, argv);
528                                found = 1;
529                                break;
530                        }
531                }
532
533                if (!found)
534        {
535                        printf("\n  undefined command %s\n", argv[0]);
536                }
537        }
538}
539
540///////////////////////////////////
541int main( int argc , char *argv[] )
542{
543        char         c;                                           // read character
544        char         buf[CMD_MAX_SIZE];           // buffer for one command
545        unsigned int count = 0;                           // pointer in buf
546        unsigned int i;                                           // index for loops
547
548        enum fsm_states
549    {
550                NORMAL,
551                ESCAPE,
552                BRAKET,
553        };
554
555    // log buffer initialisation
556        memset( &log_entries , 0, sizeof(log_entries));
557        ptw   = 0;
558        ptr   = 0;
559
560        printf( "~~~ shell ~~~\n\n" );
561
562        // command buffer initialisation
563        memset( buf, 0x20 , sizeof(buf) );
564        count = 0;
565
566        // display first prompt
567        printf("# ");
568
569        // This lexical analyser writes one command line in the buf buffer.
570        // It is implemented as a 3 states FSM to handle the following sequences:
571        // - ESC [ A : up arrow
572        // - ESC [ B : down arrow
573        // - ESC [ C : right arrow
574        // - ESC [ D : left arrow
575        // The three states have the following semantic:
576        // - NORMAL : no (ESC) character has been found
577        // - ESCAPE : the character (ESC) has been found
578        // - BRAKET : the wo characters (ESC,[) have been found
579        unsigned int state = NORMAL;
580
581
582// @@@
583// parse("load /bin/user/sort.elf");
584// @@@
585
586   
587        while (1)
588        {
589                c = (char)getchar();
590
591        if( c == 0 ) continue;
592
593                switch (state)
594                {
595                        case NORMAL:
596                        {
597                                if ((c == '\b') || (c == 0x7F))  // backspace => remove one character
598                                {
599                                        if (count > 0) {
600                                                printf("\b \b");
601                                                count--;
602                                        }
603                                }
604                                else if (c == '\n')      // new line => call parser to execute command
605                                {
606                                        if (count > 0)
607                                        {
608                                                // complete command
609                                                buf[count] = '\0';
610
611                                                // register command in log arrays
612                                                strcpy(log_entries[ptw].buf, buf);
613                                                log_entries[ptw].count = count;
614                                                ptw = (ptw + 1) % LOG_DEPTH;
615                                                ptr = ptw;
616
617                                                // execute command
618                                                printf("\n");
619                                                parse((char *)&buf);
620
621                                                // reinitialise buffer and display prompt
622                                                for ( i = 0 ; i < sizeof(buf) ; i++ ) buf[i] = 0x20;
623                                                count = 0;
624                                                printf("# ");
625                                        }
626                                }
627                                else if (c == '\t')     // tabulation => do nothing
628                                {
629                                }
630                                else if (c == 0x1B)     // ESC => start an escape sequence
631                                {
632                                        state = ESCAPE;
633                                }
634                                else if (c == 0x03)     // ^C  => cancel current command
635                                {
636                                        for (i = 0; i < count; i++) printf("\b \b");
637                                        for (i = 0; i < sizeof(buf); i++) buf[i] = 0x20;
638                                        count = 0;
639                                }
640                                else                                     // register character in command buffer
641                                {
642                                        if (count < sizeof(buf) - 1)
643                                        {
644                                                putchar( c );
645                                                buf[count] = c;
646                                                count++;
647                                        }
648                                }
649                                break;
650                        }
651                        case ESCAPE:
652                        {
653                                if (c == '[')           //  valid sequence => continue
654                                {
655                                        state = BRAKET;
656                                }
657                                else                               // invalid sequence => do nothing
658                                {
659                                        state = NORMAL;
660                                }
661                                break;
662                        }
663                        case BRAKET:
664                        {
665                                if (c == 'D')   // valid  LEFT sequence => move buf pointer left
666                                {
667                                        if (count > 0)
668                                        {
669                                                printf("\b");
670                                                count--;
671                                        }
672
673                                        // get next user char
674                                        state = NORMAL;
675                                }
676                                else if (c == 'C')   // valid  RIGHT sequence => move buf pointer right
677                                {
678                                        if (count < sizeof(buf) - 1)
679                                        {
680                                                printf("%c", buf[count]);
681                                                count++;
682                                        }
683
684                                        // get next user char
685                                        state = NORMAL;
686                                }
687                                else if (c == 'A')   // valid  UP sequence => move log pointer backward
688                                {
689                                        // cancel current command
690                                        for (i = 0; i < count; i++) printf("\b \b");
691                                        count = 0;
692
693                                        // copy log command into buf
694                                        ptr = (ptr - 1) % LOG_DEPTH;
695                                        strcpy(buf, log_entries[ptr].buf);
696                                        count = log_entries[ptr].count;
697
698                                        // display log command
699                                        printf("%s", buf);
700
701                                        // get next user char
702                                        state = NORMAL;
703                                }
704                                else if (c == 'B')   // valid  DOWN sequence => move log pointer forward
705                                {
706                                        // cancel current command
707                                        for (i = 0 ; i < count; i++) printf("\b \b");
708                                        count = 0;
709
710                                        // copy log command into buf
711                                        ptr = (ptr + 1) % LOG_DEPTH;
712                                        strcpy(buf, log_entries[ptr].buf);
713                                        count = log_entries[ptr].count;
714
715                                        // display log command
716                                        printf("%s", buf);
717
718                                        // get next user char
719                                        state = NORMAL;
720                                }
721                                else                               // other character => do nothing
722                                {
723                                        // get next user char
724                                        state = NORMAL;
725                                }
726                                break;
727                        }
728                }
729        }
730}
731
Note: See TracBrowser for help on using the repository browser.