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

Last change on this file since 596 was 596, checked in by alain, 5 years ago

Fix a big bug in ksh: wrong handling of illegal command, blocking ksh.

File size: 31.9 KB
Line 
1/////////////////////////////////////////////////////////////////////////////////////////
2// File   :  ksh.c
3// Date   :  October 2017
4// Author :  Alain Greiner
5/////////////////////////////////////////////////////////////////////////////////////////
6// This application implements a minimal shell for ALMOS-MKH.
7//
8// This user KSH process contains two POSIX threads:
9// - the "main" thread contains the infinite loop implementing
10//   the children processes termination monitoring, using the wait() syscall.
11// - the "interactive" thread contains the infinite loop implementing the command
12//   interpreter attached to the TXT terminal, and handling one KSH command
13//   per iteration.
14//
15// The children processes are created by the <load> command, and are
16// attached to the same TXT terminal as the KSH process itself.
17// A child process can be lauched in foreground or in background:
18// . when the child process is running in foreground, the KSH process loses
19//   the TXT terminal ownership, that is transfered to the child process.
20// . when the child process is running in background: the KSH process keeps
21//   the TXT terminal ownership.
22//
23// We use a semaphore to synchronize the two KSH threads. At each iteration,
24// the interactive thread check the semaphore (with a sem_wait). It blocks
25// and deschedules, if the KSH process loosed the TXT ownership (after a load,
26// or for any other cause. It unblocks with the following policy:
27// . if the command is "not a load", the semaphore is incremented by the
28//   cmd_***() function when the command is completed, to allow the KSH interactive()
29//   function to get the next command in the while loop.   
30// . if the command is a "load without &", the TXT is given to the NEW process by the
31//   execve() syscall, and is released to the KSH process when NEW process terminates.
32//   The KSH process is notified and the KSH main() function increments the semahore
33//   to allow the KSH interactive() function to handle commands.
34// . if the command is a "load with &", the cmd_load() function returns the TXT
35//   to the KSH process and increment the semaphore, when the parent KSH process
36//   returns from the fork() syscall.
37/////////////////////////////////////////////////////////////////////////////////////////
38
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <sys/wait.h>
43#include <signal.h>
44#include <unistd.h>
45#include <almosmkh.h>
46#include <semaphore.h>
47#include <hal_macros.h>
48#include <sys/stat.h>
49#include <sys/mman.h>
50#include <fcntl.h>
51
52#define CMD_MAX_SIZE   (256)    // max number of characters in one command
53#define LOG_DEPTH      (32)     // max number of registered commands
54#define MAX_ARGS           (32)     // max number of arguments in a command
55
56#define MAIN_DEBUG          0
57#define CMD_LOAD_DEBUG      0
58#define CMD_CAT_DEBUG       1
59
60//////////////////////////////////////////////////////////////////////////////////////////
61//         Structures
62//////////////////////////////////////////////////////////////////////////////////////////
63
64// one entry in the registered commands array
65typedef struct log_entry_s
66{
67        char          buf[CMD_MAX_SIZE];
68        unsigned int  count;
69}
70log_entry_t;
71
72// one entry in the supported command types array
73typedef struct ksh_cmd_s
74{
75        char * name;
76        char * desc;
77        void   (*fn)( int , char ** );
78}
79ksh_cmd_t;
80
81
82//////////////////////////////////////////////////////////////////////////////////////////
83//         Global Variables
84//////////////////////////////////////////////////////////////////////////////////////////
85
86ksh_cmd_t       cmd[];                    // array of supported commands
87
88log_entry_t     log_entries[LOG_DEPTH];   // array of registered commands
89
90unsigned int    ptw;                      // write pointer in log_entries[]
91unsigned int    ptr;                      // read pointer in log_entries[]
92
93pthread_attr_t  attr;                     // interactive thread attributes
94
95sem_t           semaphore;                // block interactive thread when zero
96
97//////////////////////////////////////////////////////////////////////////////////////////
98//         Shell  Commands
99//////////////////////////////////////////////////////////////////////////////////////////
100
101/////////////////////////////////////////////
102static void cmd_cat( int argc , char **argv )
103{
104        char         * path;
105    stat_t         st;      // stat structure
106    int            fd;
107    int            size;
108    char         * buf;
109
110        if (argc != 2) 
111    {
112        fd   = -1;
113        buf  = NULL;
114        size = 0;
115                printf("  usage: cat pathname\n");
116        goto exit;
117    }
118
119    path = argv[1];
120
121    // open the file
122    fd = open( path , O_RDONLY , 0 );
123    if (fd < 0) 
124    {
125        buf  = NULL;
126        size = 0;
127            printf("  error: cannot open %s\n", path);
128            goto exit;
129    }
130
131#if CMD_CAT_DEBUG
132long long unsigned cycle;
133get_cycle( &cycle );
134printf("\n[%s] file %s open / cycle %d\n",
135__FUNCTION__ , path , (int)cycle );
136#endif
137
138    // get file stats
139    if ( stat( path , &st ) == -1)
140    {
141        buf  = NULL;
142        size = 0;
143            printf("  error: cannot stat %s\n", path);
144            goto exit;
145    }
146
147        if ( S_ISDIR(st.st_mode) )
148    {
149        buf  = NULL;
150        size = 0;
151            printf("  error: %s is a directory\n", path);
152            goto exit;
153    }
154
155    // get file size
156    size = st.st_size;
157
158#if CMD_CAT_DEBUG
159get_cycle( &cycle );
160printf("\n[%s] get size %d / cycle %d\n",
161__FUNCTION__ , size , (int)cycle );
162#endif
163
164    // MAP_FILE is default type when MAP_ANON and MAP_REMOTE are not specified
165    buf = mmap( NULL , size , PROT_READ|PROT_WRITE , MAP_PRIVATE , fd , 0 );
166
167    if ( buf == NULL )
168    {
169            printf("  error: cannot map %s\n", path );
170            goto exit;
171    }
172
173#if CMD_CAT_DEBUG
174get_cycle( &cycle );
175printf("\n[%s] map file %d to buffer %x / cycle %d\n",
176__FUNCTION__ , fd , buf , (int)cycle );
177display_vmm( 0 , getpid() );
178#endif
179
180    // display the file content on TXT terminal
181    write( 1 , buf , size );
182
183    // release semaphore to get next command
184    sem_post( &semaphore );
185
186    return;
187
188exit:
189
190        if (buf != NULL) munmap(buf, size);
191        if (fd >= 0) close(fd);
192
193    // release semaphore to get next command
194    sem_post( &semaphore );
195
196}   // end cmd_cat()
197
198////////////////////////////////////////////
199static void cmd_cd( int argc , char **argv )
200{
201        char * path;
202
203        if (argc != 2)
204    {
205                printf("  usage: cd pathname\n");
206        }
207    else
208    {
209            path = argv[1];
210
211        printf("  error: not implemented yet\n" );
212    }
213
214    // release semaphore to get next command
215    sem_post( &semaphore );
216
217}   // end cmd_cd()
218
219/////////////////////////////////////////
220static void cmd_cp(int argc, char **argv)
221{
222        int    src_fd;
223    int    dst_fd;
224        char * srcpath;
225    char * dstpath;
226        int    size;          // source file size
227        int    bytes;         // number of transfered bytes
228        char   buf[1024];
229        stat_t st;
230
231        if (argc != 3) 
232    {
233        src_fd = -1;
234        dst_fd = -1;
235                printf("  usage: cp src_pathname dst_pathname\n");
236        goto exit;
237        }
238
239    srcpath = argv[1];
240    dstpath = argv[2];
241
242    // open the src file
243    src_fd = open( srcpath , O_RDONLY , 0 );
244
245    if ( src_fd < 0 ) 
246    {
247        dst_fd = -1;
248            printf("  error: cannot open %s\n", srcpath );
249            goto exit;
250    }
251
252    // get file stats
253    if ( stat( srcpath , &st ) )
254    {
255        dst_fd = -1;
256            printf("  error: cannot stat %s\n", srcpath);
257            goto exit;
258    }
259
260        if ( S_ISDIR(st.st_mode) )
261    {
262        dst_fd = -1;
263                printf("  error: %s is a directory\n", srcpath);
264                goto exit;
265        }
266
267    // get src file size
268        size = st.st_size;
269
270        // open the dst file
271        dst_fd = open( dstpath , O_CREAT|O_TRUNC|O_RDWR , 0 );
272
273        if ( dst_fd < 0 ) 
274    {
275                printf("  error: cannot open %s\n", dstpath );
276                goto exit;
277        }
278
279        if ( stat( dstpath , &st ) )
280    {
281                printf("  error: cannot stat %s\n", dstpath );
282                goto exit;
283        }
284
285        if ( S_ISDIR(st.st_mode ) ) 
286    {
287                printf("  error: %s is a directory\n", dstpath );
288                goto exit;
289        }
290
291        bytes = 0;
292
293        while (bytes < size)
294        {
295                int rlen = ((size - bytes) < 1024) ? (size - bytes) : 1024;
296                int wlen;
297                int ret;
298
299                // read the source
300                ret = read( src_fd , buf , rlen );
301                if (ret == -1) 
302        {
303                        printf("  error: cannot read from file %s\n", srcpath);
304                        goto exit;
305                }
306
307                rlen = (int)ret;
308
309                // write to the destination
310                ret = write( dst_fd , buf , rlen );
311                if (ret == -1)
312        {
313                        printf("  error: cannot write to file %s\n", dstpath);
314                        goto exit;
315                }
316
317                wlen = (int)ret;
318
319                // check
320                if (wlen != rlen) 
321        {
322                        printf("  error: cannot write on device\n");
323                        goto exit;
324                }
325
326                bytes += rlen;
327        }
328
329exit:
330
331        if (src_fd >= 0) close(src_fd);
332        if (dst_fd >= 0) close(dst_fd);
333
334    // release semaphore to get next command
335    sem_post( &semaphore );
336
337}   // end cmd_cp()
338
339/////////////////////////////////////////////////
340static void cmd_display( int argc , char **argv )
341{
342    if( argc < 2 )
343    {
344        printf("  usage: display  vmm      cxy  pid   \n"
345               "         display  sched    cxy  lid   \n"             
346               "         display  process  cxy        \n"             
347               "         display  txt      txtid      \n"             
348               "         display  vfs                 \n"             
349               "         display  chdev               \n"             
350               "         display  dqdt                \n"             
351               "         display  locks    pid  trdid \n");
352    }
353    ////////////////////////////////////
354    else if( strcmp( argv[1] , "vmm" ) == 0 )
355    {
356        if( argc != 4 )
357        {
358                    printf("  usage: display vmm cxy pid\n");
359            }
360        else
361        {
362                unsigned int cxy = atoi(argv[2]);
363                unsigned int pid = atoi(argv[3]);
364
365            if( display_vmm( cxy , pid ) )
366            {
367                printf("  error: no process %x in cluster %x\n", pid , cxy );
368            }
369        }
370    }
371    ///////////////////////////////////////////
372    else if( strcmp( argv[1] , "sched" ) == 0 )
373    {
374        if( argc != 4 )
375        {
376                    printf("  usage: display sched cxy lid\n");
377            }
378        else
379        {
380                unsigned int cxy = atoi(argv[2]);
381                unsigned int lid = atoi(argv[3]);
382
383            if( display_sched( cxy , lid ) )
384            {
385                printf("  error: illegal arguments cxy = %x / lid = %d\n", cxy, lid );
386            }
387        }
388    }
389    /////////////////////////////////////////////
390    else if( strcmp( argv[1] , "process" ) == 0 )
391    {
392        if( argc != 3 )
393        {
394                    printf("  usage: display process cxy\n");
395            }
396        else
397        {
398                unsigned int cxy = atoi(argv[2]);
399
400            if( display_cluster_processes( cxy , 0 ) )
401            {
402                printf("  error: illegal argument cxy = %x\n", cxy );
403            }
404        }
405    }
406    /////////////////////////////////////////
407    else if( strcmp( argv[1] , "txt" ) == 0 )
408    {
409        if( argc != 3 )
410        {
411                    printf("  usage: display txt txt_id\n");
412            }
413        else
414        {
415                unsigned int txtid = atoi(argv[2]);
416
417            if( display_txt_processes( txtid ) )
418            {
419                printf("  error: illegal argument txtid = %d\n", txtid );
420            }
421        }
422    }
423    /////////////////////////////////////////
424    else if( strcmp( argv[1] , "vfs" ) == 0 )
425    {
426        if( argc != 2 )
427        {
428                    printf("  usage: display vfs\n");
429            }
430        else
431        {
432            display_vfs();
433        }
434    }
435    //////////////////////////////////////////
436    else if( strcmp( argv[1] , "chdev" ) == 0 )
437    {
438        if( argc != 2 )
439        {
440                    printf("  usage: display chdev\n");
441            }
442        else
443        {
444            display_chdev();
445        }
446    }
447    //////////////////////////////////////////
448    else if( strcmp( argv[1] , "dqdt" ) == 0 )
449    {
450        if( argc != 2 )
451        {
452                    printf("  usage: display dqdt\n");
453            }
454        else
455        {
456            display_dqdt();
457        }
458    }
459    ///////////////////////////////////////////
460    else if( strcmp( argv[1] , "locks" ) == 0 )
461    {
462        if( argc != 4 )
463        {
464                    printf("  usage: display locks pid trdid\n");
465            }
466        else
467        {
468                unsigned int pid   = atoi(argv[2]);
469            unsigned int trdid = atoi(argv[3]);
470
471            if( display_busylocks( pid , trdid ) )
472            {
473                printf("  error: illegal arguments pid = %x / trdid = %x\n", pid, trdid );
474            }
475        }
476    }
477    else
478    {
479        printf("  error: undefined display request : %s\n", argv[1] ); 
480    }       
481
482    // release semaphore to get next command
483    sem_post( &semaphore );
484
485} // end cmd_display()
486
487/////////////////////////////////////////
488static void cmd_fg(int argc, char **argv)
489{
490        unsigned int pid;
491
492        if (argc != 2) 
493    {
494                printf("  usage: %s pid\n", argv[0]);
495        }
496    else
497    {
498        pid = atoi( argv[1] );   
499
500        if( pid == 0 )
501        { 
502                    printf("  error: PID cannot be 0\n" );
503            }
504        else if( fg( pid ) )
505        {
506                    printf("  error: cannot find process %x\n", pid );
507            }
508    }
509
510    // release semaphore to get next command
511    sem_post( &semaphore );
512
513}  // end cmd_fg()
514
515//////////////////////////////////////////////
516static void cmd_help( int argc , char **argv )
517{
518        unsigned int i;
519
520        if (argc != 1) 
521    {
522                printf("  usage: %s\n", argv[0]);
523        }
524    else
525    {
526            printf("available commands:\n");
527            for (i = 0 ; cmd[i].name ; i++) 
528        {
529                    printf("\t%s\t : %s\n", cmd[i].name , cmd[i].desc);
530            }
531    }
532
533    // release semaphore to get next command
534    sem_post( &semaphore );
535
536}   // end cmd_help()
537
538//////////////////////////////////////////////
539static void cmd_kill( int argc , char **argv )
540{
541        unsigned int pid;
542
543        if (argc != 2) 
544    {
545                printf("  usage: %s pid\n", argv[0]);
546        }
547    else
548    {
549            pid = atoi( argv[1] );
550
551        if( pid == 0 )
552        {
553                    printf("  error: kernel process 0 cannot be killed\n" );
554            }
555
556            else if( kill( pid , SIGKILL ) )
557        {
558                    printf("  error: process %x cannot be killed\n", pid );
559            }
560    }
561
562    // release semaphore to get next command
563    sem_post( &semaphore );
564
565}   // end cmd_kill()
566
567//////////////////////////////////////////////
568static void cmd_load( int argc , char **argv )
569{
570        int                  ret_fork;           // return value from fork
571        int                  ret_exec;           // return value from exec
572    unsigned int         ksh_pid;            // KSH process PID
573        char               * pathname;           // path to .elf file
574    unsigned int         background;         // background execution if non zero
575    unsigned int         placement;          // placement specified if non zero
576    unsigned int         cxy;                // target cluster if placement specified
577
578        if( (argc < 2) || (argc > 4) ) 
579    {
580                printf("  usage: %s pathname [cxy] [&]\n", argv[0] );
581        }
582    else
583    {
584            pathname = argv[1];
585
586        if( argc == 2 )
587        {
588            background = 0;
589            placement  = 0;
590            cxy        = 0;
591        }
592        else if( argc == 3 )
593        {
594            if( (argv[2][0] == '&') && (argv[2][1] == 0) )
595            {
596                background = 1;
597                placement  = 0;
598                cxy        = 0;
599            }
600            else 
601            {
602                background = 0;
603                placement  = 1;
604                cxy        = atoi( argv[2] );
605            }
606        }
607        else  // argc == 4
608        { 
609            background = ( (argv[3][0] == '&') && (argv[3][1] == 0) );
610            placement  = 1;
611            cxy        = atoi( argv[2] );
612        }
613
614        // get KSH process PID
615        ksh_pid = getpid();
616
617#if CMD_LOAD_DEBUG
618long long unsigned cycle;
619get_cycle( &cycle );
620printf("\n[KSH] %s : ksh_pid %x / path %s / bg %d / place %d (%x) / cycle %d\n",
621__FUNCTION__, ksh_pid, argv[1], background, placement, cxy, (int)cycle );
622#endif
623
624        // set target cluster if required
625        if( placement ) place_fork( cxy );
626
627        // KSH process fork CHILD process
628            ret_fork = fork();
629
630        if ( ret_fork < 0 )     // it is a failure reported to KSH
631        {
632            printf("  error: ksh process unable to fork\n");
633        }
634        else if (ret_fork == 0) // it is the CHILD process
635        {
636
637#if CMD_LOAD_DEBUG
638get_cycle( &cycle );
639printf("\n[KSH] %s : child_pid %x after fork, before exec / cycle %d\n",
640__FUNCTION__ , getpid(), (int)cycle );
641#endif
642
643            // CHILD process exec NEW process
644            ret_exec = execve( pathname , NULL , NULL );
645
646#if CMD_LOAD_DEBUG
647get_cycle( &cycle );
648printf("\n[KSH] %s : child_pid %x after exec / ret_exec %d / cycle %d\n",
649__FUNCTION__ , getpid(), ret_exec, (int)cycle );
650#endif
651
652            // this is only executed in case of exec failure
653            if( ret_exec )
654            {
655                printf("  error: child process unable to exec <%s>\n", pathname );
656                exit( 0 );
657            }   
658            } 
659        else                    // it is the KSH process : ret_fork is the new process PID
660        {
661
662#if CMD_LOAD_DEBUG
663get_cycle( &cycle );
664printf("\n[KSH] %s : ksh_pid %x after fork / ret_fork %x / cycle %d\n",
665__FUNCTION__, getpid(), ret_fork, (int)cycle );
666#endif
667
668            if( background )    // child in background =>  KSH must keep TXT ownership
669            {
670                fg( ksh_pid );
671            }
672        }
673    }
674
675    // release semaphore to get next command
676    sem_post( &semaphore );
677   
678}   // end cmd_load
679
680/////////////////////////////////////////////
681static void cmd_log( int argc , char **argv )
682{
683        unsigned int i;
684
685        if (argc != 1)
686    {
687                printf("  usage: %s\n", argv[0], argc ); 
688        }
689    else
690    {
691            printf("--- registered commands ---\n");
692            for (i = 0; i < LOG_DEPTH; i++) 
693        {
694                    printf(" - %d\t: %s\n", i, &log_entries[i].buf);
695            }
696    }
697
698    // release semaphore to get next command
699    sem_post( &semaphore );
700
701} // end cmd_log()
702
703
704////////////////////////////////////////////
705static void cmd_ls( int argc , char **argv )
706{
707        char  * path;
708
709//  struct dirent * file;
710//  DIR *dir;
711
712        if (argc > 2 )
713    {
714                printf("  usage: ls [path]\n");
715        }
716    else
717    {
718        if ( argc == 1 ) path = ".";
719        else             path = argv[1];
720
721        printf("  error: not implemented yet\n");
722/*
723        dir = opendir( path );
724        while ((file = readdir(dir)) != NULL)
725        {
726                printf(" %s\n", file->d_name);
727        }
728        closedir(dir);
729*/
730    }
731
732    // release semaphore to get next command
733    sem_post( &semaphore );
734
735} // end cmd_ls()
736
737///////////////////////////////////////////////
738static void cmd_mkdir( int argc , char **argv )
739{
740        char * pathname;
741
742        if (argc != 2)
743    {
744                printf("  usage: mkdir pathname\n");
745        }
746    else
747    {
748        pathname = argv[1];
749
750        printf("  error: not implemented yet\n");
751    }
752
753    // release semaphore to get next command
754    sem_post( &semaphore );
755
756} // end cmd_mkdir()
757
758////////////////////////////////////////////
759static void cmd_mv( int argc , char **argv )
760{
761
762        if (argc < 3)
763        {
764                printf("  usage : mv src_pathname dst_pathname\n");
765        }
766    else
767    {
768        printf("  error: not implemented yet\n");
769    }
770   
771    // release semaphore to get next command
772    sem_post( &semaphore );
773
774}  // end cmd_mv
775
776
777////////////////////////////////////////////
778static void cmd_ps( int argc , char **argv )
779{
780    unsigned int x_size;
781    unsigned int y_size;
782    unsigned int ncores;
783    unsigned int x;
784    unsigned int y;
785
786        if (argc != 1)
787    {
788                printf("  usage: %s\n", argv[0]);
789        }
790    else
791    {
792        // get platform config
793        get_config( &x_size , &y_size , &ncores );
794
795        // scan all clusters
796        for( x = 0 ; x < x_size ; x++ )
797        {
798            for( y = 0 ; y < y_size ; y++ )
799            {
800                // display only owned processes
801                display_cluster_processes( HAL_CXY_FROM_XY(x,y), 1 ); 
802            }
803        }
804    }
805
806    // release semaphore to get next command
807    sem_post( &semaphore );
808
809}  // end cmd_ps()
810
811/////////////////////////////////////////////
812static void cmd_pwd( int argc , char **argv )
813{
814        char buf[1024];
815
816        if (argc != 1)
817    {
818                printf("  usage: %s\n", argv[0]);
819        }
820    else 
821    {
822        if ( getcwd( buf , 1024 ) ) 
823        {
824                    printf("  error: unable to get current directory\n");
825            }
826        else 
827        {
828                    printf("%s\n", buf);
829            }
830    }
831
832    // release semaphore to get next command
833    sem_post( &semaphore );
834
835}  // end cmd_pwd()
836
837////////////////////////////////////////////
838static void cmd_rm( int argc , char **argv )
839{
840        char * pathname;
841
842        if (argc != 2)
843    {
844                printf("  usage: %s pathname\n", argv[0]);
845        }
846    else
847    {
848            pathname = argv[1];
849
850        printf("  error: not implemented yet\n");
851    }
852
853    // release semaphore to get next command
854    sem_post( &semaphore );
855
856}  // end_cmd_rm()
857
858///////////////////////////////////////////////
859static void cmd_rmdir( int argc , char **argv )
860{
861    // same as cmd_rm()
862        cmd_rm(argc, argv);
863}
864
865///////////////////////////////////////////////
866static void cmd_trace( int argc , char **argv )
867{
868    unsigned int cxy;
869    unsigned int lid;
870
871        if (argc != 3)
872    {
873                printf("  usage: trace cxy lid \n");
874        }
875    else
876    {
877        cxy = atoi(argv[1]);
878        lid = atoi(argv[2]);
879
880        if( trace( 1 , cxy , lid ) )
881        {
882            printf("  error: core[%x,%d] not found\n", cxy, lid );
883        }
884    }
885
886    // release semaphore to get next command
887    sem_post( &semaphore );
888
889}  // end cmd_trace
890
891///////////////////////////////////////////////
892static void cmd_untrace( int argc , char **argv )
893{
894    unsigned int cxy;
895    unsigned int lid;
896
897        if (argc != 3)
898    {
899                printf("  usage: untrace cxy lid \n");
900        }
901    else
902    {
903        cxy = atoi(argv[1]);
904        lid = atoi(argv[2]);
905
906        if( trace( 0 , cxy , lid ) )
907        {
908            printf("  error: core[%x,%d] not found\n", cxy, lid );
909        }
910    }
911
912    // release semaphore to get next command
913    sem_post( &semaphore );
914
915}  // end cmd_untrace()
916
917///////////////////////////////////////////////////////////////////////////////////
918// Array of commands
919///////////////////////////////////////////////////////////////////////////////////
920
921ksh_cmd_t cmd[] =
922{
923        { "cat",     "display file content",                            cmd_cat     },
924        { "cd",      "change current directory",                        cmd_cd      },
925        { "cp",      "replicate a file in file system",                 cmd_cp      },
926    { "fg",      "put a process in foreground",                     cmd_fg      },
927    { "display", "display vmm/sched/process/vfs/chdev/txt",         cmd_display },
928        { "load",    "load an user application",                        cmd_load    },
929        { "help",    "list available commands",                         cmd_help    },
930        { "kill",    "kill a process (all threads)",                    cmd_kill    },
931        { "log",     "list registered commands",                        cmd_log     },
932        { "ls",      "list directory entries",                          cmd_ls      },
933        { "mkdir",   "create a new directory",                          cmd_mkdir   },
934        { "mv",      "move a file in file system",                      cmd_mv      },
935        { "pwd",     "print current working directory",                 cmd_pwd     },
936        { "ps",      "display all processes",                           cmd_ps      },
937        { "rm",      "remove a file from file system",                  cmd_rm      },
938        { "rmdir",   "remove a directory from file system",             cmd_rmdir   },
939        { "trace",   "activate trace for a given core",                 cmd_trace   },
940        { "untrace", "desactivate trace for a given core",              cmd_untrace },
941        { NULL,      NULL,                                                                              NULL        }
942};
943
944////////////////////////////////////////////////////////////////////////////////////
945// This function analyses one command (with arguments), executes it, and returns.
946////////////////////////////////////////////////////////////////////////////////////
947static void __attribute__ ((noinline)) parse( char * buf )
948{
949        int argc = 0;
950        char *argv[MAX_ARGS];
951        int i;
952        int len = strlen(buf);
953
954        // build argc/argv
955        for (i = 0; i < len; i++) 
956    {
957                if (buf[i] == ' ') 
958        {
959                        buf[i] = '\0';
960                }
961        else if (i == 0 || buf[i - 1] == '\0') 
962        {
963                        if (argc < MAX_ARGS) 
964            {
965                                argv[argc] = &buf[i];
966                                argc++;
967                        }
968                }
969        }
970
971    // analyse command type
972        if (argc > 0)
973    {
974                int found = 0;
975
976                argv[argc] = NULL;
977
978                // try to match typed command
979                for (i = 0 ; cmd[i].name ; i++)
980        {
981                        if (strcmp(argv[0], cmd[i].name) == 0)
982            {
983                                cmd[i].fn(argc, argv);
984                                found = 1;
985                                break;
986                        }
987                }
988
989                if (!found)  // undefined command
990        {
991                        printf("  error : undefined command <%s>\n", argv[0]);
992
993            // release semaphore to get next command
994            sem_post( &semaphore );
995                }
996        }
997}  // end parse()
998
999///////////////////////////////
1000static void interactive( void )
1001{
1002        char           c;                                               // read character
1003        char           buf[CMD_MAX_SIZE];               // buffer for one command
1004    unsigned int   end_command;             // last character found in a command
1005        unsigned int   count;                   // pointer in command buffer
1006        unsigned int   i;                                               // index for loops
1007        unsigned int   state;                   // escape sequence state
1008
1009
1010/* To lauch one application without interactive mode
1011   
1012if( sem_wait( &semaphore ) )
1013{
1014    printf("\n[ksh error] cannot found semafore\n" );
1015    exit( 1 );
1016}
1017else
1018{
1019    printf("\n[ksh] for fft\n");
1020}
1021
1022strcpy( buf , "load /bin/user/fft.elf" );
1023parse( buf );
1024
1025*/
1026
1027        enum fsm_states
1028    {
1029                NORMAL = 0,
1030                ESCAPE = 1,
1031                BRAKET = 2,
1032        };
1033
1034        // This lexical analyser writes one command line in the command buffer.
1035        // It is implemented as a 3 states FSM to handle the following escape sequences:
1036        // - ESC [ A : up arrow
1037        // - ESC [ B : down arrow
1038        // - ESC [ C : right arrow
1039        // - ESC [ D : left arrow
1040        // The three states have the following semantic:
1041        // - NORMAL : no (ESC) character has been found
1042        // - ESCAPE : the character (ESC) has been found
1043        // - BRAKET : the wo characters (ESC,[) have been found
1044
1045    // external loop on the commands
1046    // the in teractive thread should not exit this loop
1047        while (1)
1048        {
1049            // initialize command buffer
1050            memset( buf, 0x20 , sizeof(buf) );   // TODO useful ?
1051            count = 0;
1052            state = NORMAL;
1053
1054        // decrement semaphore, and block if the KSH process is not the TXT owner
1055        if ( sem_wait( &semaphore ) )
1056        {
1057            printf("\n[ksh error] cannot found semafore\n" );
1058            exit( 1 );
1059        }
1060
1061        // display prompt on a new line
1062        printf("\n[ksh] ");
1063 
1064        end_command = 0;
1065
1066        // internal loop on characters in one command
1067        while( end_command == 0 )
1068        {
1069            // get one character from TXT_RX
1070                c = (char)getchar();
1071
1072            if( c == 0 ) continue;
1073
1074                    if( state == NORMAL )  // we are not in an escape sequence
1075                    {
1076                                if ((c == '\b') || (c == 0x7F))  // backspace => remove one character
1077                                {
1078                                    if (count > 0)
1079                    {
1080                                        printf("\b \b");
1081                                        count--;
1082                                    }
1083                                }
1084                                else if (c == '\n')                  // new line => end of command
1085                                {
1086                                    if (count > 0)               // analyse & execute command
1087                                    {
1088                                            // complete command with NUL character
1089                                            buf[count] = 0;
1090                        count++;
1091
1092                                        // register command in log arrays
1093                                            strcpy(log_entries[ptw].buf, buf);
1094                                            log_entries[ptw].count = count;
1095                                            ptw = (ptw + 1) % LOG_DEPTH;
1096                                            ptr = ptw;
1097
1098                        // echo character
1099                        putchar( c );
1100
1101                                            // call parser to analyse and execute command
1102                                            parse( buf );
1103                                    }
1104                    else                         // no command registered
1105                    {
1106                        // release semaphore to get next command
1107                        sem_post( &semaphore );
1108                    }
1109
1110                    // exit internal loop on characters
1111                    end_command = 1;
1112                }
1113                            else if (c == '\t')             // tabulation => do nothing
1114                                {
1115                            }
1116                            else if (c == (char)0x1B)       // ESC => start an escape sequence
1117                            {
1118                    state = ESCAPE;
1119                            }
1120                            else                                               // normal character
1121                                {
1122                                    if (count < sizeof(buf) - 1)
1123                                    {
1124                        // register character in command buffer
1125                                            buf[count] = c;
1126                                            count++;
1127
1128                        // echo character
1129                        putchar( c );
1130                                        }
1131                                }
1132                        }
1133                        else if( state == ESCAPE ) 
1134                        {
1135                                if (c == '[')           //  valid sequence => continue
1136                                {
1137                                        state = BRAKET;
1138                                }
1139                                else                               // invalid sequence => do nothing
1140                                {
1141                                        state = NORMAL;
1142                                }
1143                        }
1144                        else if( state == BRAKET )
1145                        {
1146                                if (c == 'D')   // valid  LEFT sequence => move buf pointer left
1147                                {
1148                                        if (count > 0)
1149                                        {
1150                                                printf("\b");
1151                                                count--;
1152                                        }
1153
1154                                        // get next user char
1155                                        state = NORMAL;
1156                                }
1157                                else if (c == 'C')   // valid  RIGHT sequence => move buf pointer right
1158                                {
1159                                        if (count < sizeof(buf) - 1)
1160                                        {
1161                                                printf("%c", buf[count]);
1162                                                count++;
1163                                        }
1164
1165                                        // get next user char
1166                                        state = NORMAL;
1167                                }
1168                                else if (c == 'A')   // valid  UP sequence => move log pointer backward
1169                                {
1170                                        // cancel current command
1171                                        for (i = 0; i < count; i++) printf("\b \b");
1172                                        count = 0;
1173
1174                                        // copy log command into buf
1175                                        ptr = (ptr - 1) % LOG_DEPTH;
1176                                        strcpy(buf, log_entries[ptr].buf);
1177                                        count = log_entries[ptr].count - 1;
1178
1179                                        // display log command
1180                                        printf("%s", buf);
1181
1182                                        // get next user char
1183                                        state = NORMAL;
1184                                }
1185                                else if (c == 'B')   // valid  DOWN sequence => move log pointer forward
1186                                {
1187                                        // cancel current command
1188                                        for (i = 0 ; i < count; i++) printf("\b \b");
1189                                        count = 0;
1190
1191                                        // copy log command into buf
1192                                        ptr = (ptr + 1) % LOG_DEPTH;
1193                                        strcpy(buf, log_entries[ptr].buf);
1194                                        count = log_entries[ptr].count;
1195
1196                                        // display log command
1197                                        printf("%s", buf);
1198
1199                                        // get next user char
1200                                        state = NORMAL;
1201                                }
1202                                else                               // other character => do nothing
1203                                {
1204                                        // get next user char
1205                                        state = NORMAL;
1206                                }
1207                        }
1208                }  // end internal while loop on characters
1209        }  // end external while loop on commands
1210}  // end interactive()
1211
1212////////////////
1213int main( void )
1214{
1215    unsigned int cxy;             // owner cluster identifier for this KSH process
1216    unsigned int lid;             // core identifier for this KSH main thread
1217    int          status;          // child process termination status
1218    int          child_pid;       // child process identifier
1219    int          parent_pid;      // parent process identifier (i.e. this process)
1220    pthread_t    trdid;           // interactive thread identifier (unused)
1221    unsigned int is_owner;        // non-zero if KSH process is TXT owner
1222
1223    // initialize log buffer
1224        memset( &log_entries , 0, sizeof(log_entries));
1225        ptw   = 0;
1226        ptr   = 0;
1227
1228    // get KSH process pid and core
1229    parent_pid = getpid();
1230    get_core( &cxy , &lid );
1231
1232#if MAIN_DEBUG
1233printf("\n[ksh] main started on core[%x,%d]\n", cxy , lid ); 
1234#endif
1235   
1236    // initializes the semaphore used to synchronize with interactive thread
1237    if ( sem_init( &semaphore , 0 , 1 ) )
1238    {
1239        printf("\n[KSH ERROR] cannot initialize semaphore\n" );
1240        exit( 1 ); 
1241    }
1242
1243#if MAIN_DEBUG
1244printf("\n[ksh] main initialized semaphore\n" ); 
1245#endif
1246   
1247    // initialize interactive thread attributes
1248    attr.attributes = PT_ATTR_DETACH | PT_ATTR_CLUSTER_DEFINED;
1249    attr.cxy        = cxy;
1250
1251    // lauch the interactive thread
1252    pthread_create( &trdid,
1253                    &attr,
1254                    &interactive,   // entry function
1255                    NULL ); 
1256#if MAIN_DEBUG
1257printf("\n[ksh] main launched interactive thread => wait children termination\n" ); 
1258#endif
1259
1260    // signal INIT process
1261    kill( 1 , SIGCONT );
1262   
1263    // enter infinite loop monitoring children processes termination
1264    while( 1 )
1265    {
1266        // wait children termination
1267        child_pid = wait( &status );
1268
1269#if MAIN_DEBUG
1270if( WIFEXITED  (status) ) printf("\n[ksh] child process %x exit\n"   , child_pid );
1271if( WIFSIGNALED(status) ) printf("\n[ksh] child process %x killed\n" , child_pid );
1272if( WIFSTOPPED (status) ) printf("\n[ksh] child process %x stopped\n", child_pid );
1273#endif
1274
1275        // release semaphore if KSH process is TXT owner, to unblock interactive thread
1276        is_fg( parent_pid , &is_owner );
1277        if( is_owner ) sem_post( &semaphore );
1278
1279    }
1280}  // end main()
1281
1282
Note: See TracBrowser for help on using the repository browser.