source: svn/trunk/zasc/sym/DMW_TargetShell.c @ 12

Last change on this file since 12 was 2, checked in by phkim, 11 years ago

1.phkim

  1. revision copy newcon3sk r27
File size: 23.0 KB
Line 
1/********************************************************************
2* DMW_TargetShell.c
3*  - Simple target shell
4*
5*  Copyright (c)2004 Digital STREAM Tech, Inc.
6*  All Rights Reserved
7*
8*  $Id: DMW_TargetShell.c,v 1.3 2011/11/18 04:08:33 megakiss Exp $
9*
10*********************************************************************/
11#include "stdlib.h"
12
13#include "dsthalcommon.h"
14#include "dstoslayer.h"
15
16//#include "DMW_Common.h"
17//#include "DMW_Errors.h"
18//
19#include "DMW_SymTbl.h"
20//#include "DMW_TargetShell.h"
21//#include "DMW_ChannelAPI.h"
22//#include "DMW_DebugUtil.h"//debug
23//#include "DST_Common.h"
24
25//#define _TSHELL_DEBUG_
26#ifdef UCOS
27#define TSHELL_TASK_PRIORITY DMW_TASK_PRIO_TARGET_SHELL
28#else
29#define TSHELL_TASK_PRIORITY 128
30#endif
31#define TSHELL_TASK_STACKSIZE 4096
32#define TSHELL_MAX_LENGTH       85
33
34
35#define whitespace(c) (((c)==' ') || ((c) == '\t')|| ((c) == '\n'))
36#define TSHELL_MAX_NUM_PARAM    10      // tshell¿¡¼­ ÃÖ´ë 10°³ÀÇ ÀÎÀÚ¸¦ ¹ÞÀ» ¼ö ÀÖ´Ù.
37                                                                        // µû¶ó¼­ ¾Æ·¡ÀÇ function pointer¸¦ 5°³±îÁö ¹ÞÀ» ¼ö ÀÖ°Ô ¸¸µç´Ù.
38
39// debug
40static int tsprint(char *fmt, ...);
41int g_Trace_TShell = DS_TRUE;
42        // master dbg mode ON/OFF
43
44
45// function pointer definition. ÀÎÀÚ´Â ¸ðµÎ int¸¸ Áö¿øÇÑ´Ù.
46typedef char (*FUNCPTR_10)(int,int,int,int,int,int,int,int,int,int);
47
48
49// command completion
50typedef char (*compentry_func_t)(const char *,int);
51
52
53static DS_BOOL g_TShellInitialized=DS_FALSE;
54static DS_BOOL g_TShellTerminted=DS_FALSE;
55
56OS_TASK_ID DMW_TShellTaskID=0;
57
58int quit()
59{
60    exit(0);
61        g_TShellTerminted=DS_TRUE;
62        return 0;
63
64}
65
66const char * DMW_SymbolTypeString(unsigned char type)
67{
68        if(type&0x1){//global
69                return ((type&0x1e)==SYM_TEXT?"G_TEXT":
70                                (type&0x1e)==SYM_DATA?"G_DATA":
71                                (type&0x1e)==SYM_ABS?"G_ABS":
72                                (type&0x1e)==SYM_BSS?"G_BSS":
73                                (type&0x1e)==SYM_COMM?"G_COMM":"UnKnown");
74
75        }else{//local or unde
76                return ("UNDF or LOCAL");
77        }
78
79}
80
81void help()
82{
83        tsprint("========================================\n");
84        tsprint(" TShell Help\n");
85        tsprint(" [command] : [description] \n");
86        tsprint("----------------------------------------\n");
87        tsprint(" [?]       : [print help] \n");
88        tsprint(" [/]       : [repeat command] \n");
89        tsprint("========================================\n");
90}
91/////////////////////////////////////////////////////////
92/////////////////////////////////////////////////////////
93/// string utilities..
94
95DS_BOOL isHexString(char *s)
96{
97        DS_BOOL result=DS_FALSE;
98
99  //check hex
100        if ((*s == '0' && *(s + 1) == 'X')||
101          (*s == '0' && *(s + 1) == 'x') ) {
102        result=DS_TRUE;
103        }
104
105        return result;
106}
107
108unsigned int string2unint(char *value)
109{
110        typedef struct CHexMap_T
111        {
112            char chr;
113            int value;
114        } CHexMap;
115
116  int HexMapL = 22;//16;
117  CHexMap HexMap[22] =
118  {
119    {'0', 0}, {'1', 1},
120    {'2', 2}, {'3', 3},
121    {'4', 4}, {'5', 5},
122    {'6', 6}, {'7', 7},
123    {'8', 8}, {'9', 9},
124    {'A', 10}, {'B', 11},
125    {'C', 12}, {'D', 13},
126    {'E', 14}, {'F', 15},
127    {'a', 10}, {'b', 11},
128    {'c', 12}, {'d', 13},
129    {'e', 14}, {'f', 15}
130
131  };
132
133  char *s = value;
134  int result = 0;
135  unsigned int uresult=0;
136  int i;
137        DS_BOOL firsttime = DS_TRUE;
138
139  //check hex
140  if(isHexString(s)){
141        s += 2;
142  }else{
143        printf("[Warning] It is not hexa. \n");
144        //result=atoi(s);
145        uresult=0;
146        return uresult;
147  }
148
149
150  while (*s != '\0')
151  {
152    DS_BOOL found = DS_FALSE;
153
154    for (i = 0; i < HexMapL; i++)
155    {
156      if (*s == HexMap[i].chr)
157      {
158        if (!firsttime) {
159                result <<= 4;
160                uresult <<=4;
161        }
162        result |= HexMap[i].value;
163        uresult |= HexMap[i].value;
164
165        found = DS_TRUE;
166        break;
167      }
168    }
169
170    if (!found) break;
171    s++;
172    firsttime = DS_FALSE;
173  }
174 // printf("result =%d lresult =%d,(0x%x)\n",result,uresult,uresult);
175  return uresult;
176}
177
178
179char *dupstr(char *s)
180{
181        char *r;
182        r=OS_malloc(strlen(s) +1);
183        if(r==0){
184                printf("Error! Can't allocate memory! \n");
185                return NULL;
186        }
187
188        strcpy(r,s);
189        return (r);
190}
191
192
193
194/* Look up NAME as the name of a command, and return a pointer to that
195   command.  Return a NULL pointer if NAME isn't a command name. */
196DMW_SYMBOL_T * find_command ( char *name)
197{
198#ifdef _MAKEFILE_INCLUDE_TSHELL_
199  register int i=0;
200  for (i = 0; DMW_SymbolTbl[i].name; i++)
201    if (strcmp (name, DMW_SymbolTbl[i].name) == 0)
202      return (&DMW_SymbolTbl[i]);
203#endif
204
205  return ((DMW_SYMBOL_T *)NULL);
206}
207//execute_line->DMW_ExecuteSymbol À̸§ º¯°æ. 2005.12.13
208/* Execute a command line. */
209int DMW_ExecuteSymbol (char *line)
210{
211  register int i;
212  int k=0;
213  DMW_SYMBOL_T *command;
214  char *word;
215  int nParamCnt=0;
216  char *param[TSHELL_MAX_NUM_PARAM];
217  int paramint[TSHELL_MAX_NUM_PARAM];
218  int return_value=0;
219
220
221  /* Isolate the command word. */
222  i = 0;
223  while (line[i] && whitespace (line[i]))
224    i++;
225  word = line + i;
226
227  while (line[i] && !whitespace (line[i]))
228    i++;
229
230  if (line[i])
231    line[i++] = '\0';
232
233
234
235        tsprint("[INFO] cmd: [%s] \n",word);
236
237  command = find_command (word);
238
239  if (!command){
240      fprintf (stderr, "%s: No such command for TShell.\n", word);
241      return (-1);
242    }
243
244
245
246  /* Get argument to command, if any. */
247
248  for(k=0;k<TSHELL_MAX_NUM_PARAM;k++){
249
250          if(line[i]=='\0'){
251                        break;
252          }
253
254          while (whitespace (line[i]))
255            i++;
256
257          word = line + i;
258        if(isHexString(word)){
259                paramint[k]=(int) string2unint(word);
260        }else{
261          paramint[k]=atoi(word);
262        }
263
264          param[k]=word;
265          nParamCnt++;
266
267          while (line[i] && !whitespace (line[i]))
268            i++;
269
270          if (line[i])
271            line[i++] = '\0';
272                //tsprint("[INFO] 1st param is %s \n",word);
273        }
274
275        //tsprint("[INFO] # of param=%d \n",nParamCnt);
276        tsprint("[INFO] param:");
277
278        for(k=0;k<nParamCnt;k++){
279                tsprint(" [%s]",param[k]);
280        }
281        tsprint("\n");
282
283
284        for(k=nParamCnt;k<TSHELL_MAX_NUM_PARAM;k++)
285                paramint[k]=0;
286
287  /* Call the function. */
288        if(command->type==(SYM_TEXT|SYM_GLOBAL)){//text=>function
289#ifdef _TSHELL_DEBUG_
290                tsprint("[INFO]Fucntion(%s) %s = 0x%x\n",DMW_SymbolTypeString(command->type),command->name,*(command->value));
291#endif
292
293
294                return_value=(*(FUNCPTR_10)(command->value))(paramint[0],
295                                                                                paramint[1],
296                                                                                paramint[2],
297                                                                                paramint[3],
298                                                                                paramint[4],
299                                                                                paramint[5],
300                                                                                paramint[6],
301                                                                                paramint[7],
302                                                                                paramint[8],
303                                                                                paramint[9]);
304
305                tsprint("[INFO] return of [%s] func :  %d[0x%x] \n",command->name,return_value,return_value);
306        }else{//data
307
308                if(nParamCnt>1){//set:  º¯¼ö = 1 ÀÌ·± ÇüÅÂÀÓ.
309
310                         if ((strcmp (param[0], "=") == 0) ){
311                                *(command->value)= paramint[1];
312                                tsprint("[INFO]Set Data %s = %d\n",command->name,*(command->value));
313                        }else{
314                                tsprint("[ERROR] Invalid set format:[ variable] = [decima_number] param:%s %s\n",param[0],param[1]);
315                        }
316                }else{//get
317                        tsprint("[INFO]Get Data(%s) %s = 0x%x\n",DMW_SymbolTypeString(command->type),command->name,*(command->value));
318                }
319
320        }
321
322        return 0;
323}
324
325
326
327// ÀÌ ÇÔ¼ö´Â string¿¡¼­ white space(' ', '\t')¸¦ ¾ø¾ÖÁÖ°í
328// ù¹øÂ° non-null word¸¦ °¡Á®¿Â´Ù.(¸¶Áö¸·¿¡ \0¸¦ ºÙÀδÙ.)
329/* Strip whitespace from the start and end of STRING.  Return a pointer
330   into STRING. */
331char * stripwhite(char * string)
332{
333        register char *s, *t;
334
335        for(s= string; whitespace(*s);s++);
336
337        if(*s ==0)
338                return (s);
339
340        t = s + strlen(s) -1;
341        while(t > s && whitespace(*t))
342                t--;
343        *++t = '\0';
344
345        return s;
346}
347
348#if 0
349___completion___()
350#endif
351
352//first time if state=DS_FALSE
353char * command_generator (const char *text,int state)
354{
355#ifdef _MAKEFILE_INCLUDE_TSHELL_
356        static int list_index = 0;
357        static int len = 0;
358        char *name;
359
360        // first time
361        if(!state){
362                list_index=0;
363                len=strlen(text);
364        }
365
366
367        //return the next name which partially matches from symbol table
368  while((name=DMW_SymbolTbl[list_index].name)!=NULL){
369          list_index++;
370          if(strncmp(name,text,len)==0)
371                          return (dupstr(name));
372
373  }
374#endif
375
376  //if no mateched
377  return ((char*)NULL);
378
379}
380#if 0
381/* Find the common prefix of the list of matches, and put it into
382    matches[0]. */
383static int compute_lcd_of_matches (char **match_list, int matches, const char *text)
384{
385   register int i, c1, c2, si;
386   int low;      /* Count of max-matched characters. */
387
388   /* If only one match, just use that.  Otherwise, compare each
389      member of the list with the next, finding out where they
390      stop matching. */
391   if (matches == 1){
392       match_list[0] = match_list[1];
393       match_list[1] = (char *)NULL;
394       return 1;
395   }
396
397        for (i = 1, low = 100000; i < matches; i++){
398
399                for (si = 0;
400                    (c1 = match_list[i][si]) &&
401                    (c2 = match_list[i + 1][si]);
402                    si++)
403
404                if (c1 != c2)
405                   break;
406                if (low > si)
407                        low = si;
408        }
409
410   /* If there were multiple matches, but none matched up to even the
411      first character, and the user typed something, use that as the
412      value of matches[0]. */
413   if (low == 0 && text && *text){
414       match_list[0] = (char *)OS_Malloc (strlen (text) + 1);
415       strcpy (match_list[0], text);
416
417   }else{
418       match_list[0] = (char *)OS_Malloc (low + 1);
419
420       strncpy (match_list[0], match_list[1], low);
421
422       match_list[0][low] = '\0';
423     }
424
425   return matches;
426 }
427#endif
428
429 /* Return an array of (char *) which is a list of completions for TEXT.
430     If there are no completions, return a NULL pointer.
431     The first entry in the returned array is the substitution for TEXT.
432     The remaining entries are the possible completions.
433     The array is terminated with a NULL pointer.
434
435     ENTRY_FUNCTION is a function of two args, and returns a (char *).
436       The first argument is TEXT.
437       The second is a state argument; it should be zero on the first call, and
438       non-zero on subsequent calls.  It returns a NULL pointer to the caller
439       when there are no more matches.
440   */
441
442#if 0
443char ** completion_matches(const char *text, compentry_func_t *entry_function)
444{
445
446    /* Number of slots in match_list. */
447    int match_list_size;
448
449    /* The list of matches. */
450    char **match_list;
451
452    /* Number of matches actually found. */
453    int matches;
454
455    /* Temporary string binder. */
456    char *string;
457
458    matches = 0;
459    match_list_size = 10;
460    match_list = (char **)OS_Malloc ((match_list_size + 1) * sizeof (char *));
461
462    match_list[1] = (char *)NULL;
463
464    while ((compentry_func_t *)string = (*entry_function) (text, matches)){
465        if (matches + 1 == match_list_size)
466                OS_Realloc(&match_list, 0, ((match_list_size += 10) + 1) * sizeof (char *));
467
468        match_list[++matches] = string;
469        match_list[matches + 1] = (char *)NULL;
470      }
471
472    /* If there were any matches, then look through them finding out the
473       lowest common denominator.  That then becomes match_list[0]. */
474    if (matches)
475      compute_lcd_of_matches (match_list, matches, text);
476    else              /* There were no matches. */
477      {
478        OS_Free (&match_list);
479        match_list = (char **)NULL;
480      }
481    return (match_list);
482}
483#endif
484
485void free_match_list(char **matches)
486{
487        register int i;
488        if(matches==0)
489                return;
490
491        for(i=0;matches[i];i++)
492                OS_free(&matches[i]);
493        OS_free(&matches);
494
495}
496
497#ifdef UCOS
498//read a line int s, return length
499// lim is maximum s length
500int getline(char s[], int lim)
501{
502        int c=0,i=0;
503
504        while(--lim > 0 && (c=getchar()) !=EOF && c != '\n'){
505        //while(--lim > 0 && (c=getchar()) !=EOF && c != '\n' && c != '\t'){
506                s[i++]=c;
507
508        }
509
510        if(c == '\n')
511                s[i++]=c;
512        s[i] = '\0';
513        return i;
514}
515#endif
516
517#if 0
518___TShell___()
519#endif
520//tShell Task
521void tDMW_TShellTask()
522{
523
524        char userInput[TSHELL_MAX_LENGTH];
525        char *s;
526
527        // leon 2004.08.17: #last_cmd
528        char lastuserInput[TSHELL_MAX_LENGTH];
529
530
531
532        while(1){
533
534                if(g_TShellTerminted){
535                        break;
536                }
537
538                //tshell prompt
539#if 1
540
541                printf("\r\n[tShell]# ");
542#else
543                printf("\r\n[tShell]# ");
544#endif
545                //get line
546#ifdef UCOS
547                getline(userInput,sizeof(userInput));
548#else
549                fgets(userInput,sizeof(userInput),stdin);
550#endif
551
552                //process with userInput
553                s = stripwhite(userInput);
554
555                // spetial command process!
556                if(strcmp(s,"/")==0){
557                        tsprint(" >>repeat cmd: [%s]\n",lastuserInput);
558                        memcpy(s,lastuserInput,sizeof(lastuserInput));
559                }else if(strcmp(s,"")!=0){
560                        memcpy(lastuserInput,userInput,sizeof(userInput));
561                        tsprint(" last input: [%s]\n",lastuserInput);
562                }
563
564                if(strcmp(s,"?")==0){
565                        help();
566                        continue;
567                }
568
569                if(*s){
570                        DMW_ExecuteSymbol(s);//execute_line -> DMW_ExecuteSymbol
571                }
572
573                OS_Delay(1);
574
575
576
577        }//while
578
579        tsprint("[INFO] TShell is self-deleted! \n");
580        OS_SelfDeleteTask();
581
582}
583
584#ifndef USE_CYGWIN
585void seg_dbg(void);
586#endif
587
588int DMW_TargetShellInit()
589{
590        int err=0;
591        OS_TASK_ID tid=0;
592        // target shell thread¸¦ ¸¸µç´Ù.
593        if(!g_TShellInitialized){
594                tid = OS_SpawnTask((void (*)(DS_U32))tDMW_TShellTask, "tShell", TSHELL_TASK_PRIORITY, TSHELL_TASK_STACKSIZE, 0);
595            if (tid == 0) {
596                tsprint("!!! OS_SpawnTask error! dmc_TaskID %x\n", tid);
597                return 3703;//outOfOSResourcesError;
598            }
599            *(OS_TASK_ID *)&DMW_TShellTaskID = tid;
600
601                g_TShellInitialized = DS_TRUE;
602                tsprint("[INFO] DMW Target Shell is created! tid=%d\n",tid);
603        }
604
605#ifndef USE_CYGWIN
606    //seg_dbg();
607#endif
608   
609        return err;
610}
611
612int DMW_TargetShellClose()
613{
614        int err=0;
615        //target shell thread¸¦ Á×ÀδÙ.
616        quit();
617        //¹Ù·Î Á×Áö ¾ÊÀ» ¼ö ÀÖ´Ù. ¿Ö³Ä¸é ÀԷºκп¡¼­ hold
618        // ³ªÁß¿¡ ÀÛ¾÷ÇØ¾ßµÈ´Ù.
619        return err;
620}
621
622
623
624
625int DSTAPI_ExecuteDSTSymbol(char *pUserInput)
626{
627        int err = 0;//statusOK;
628
629#ifdef _MAKEFILE_INCLUDE_TSHELL_
630        if ( DMW_ExecuteSymbol (pUserInput) < 0 )
631                err = -7100;//statusError;
632#endif
633
634        return err;
635}
636
637/********************************************************
638   Debug routines
639********************************************************/
640
641
642
643#if 0
644_____Debug_____()
645#endif
646
647static int tsprint(char *fmt, ...)
648{
649//      extern int DMW_DBG_Print(char *prefix, char *fmt, ...);
650//      extern int DMW_DBG_Print3(char *prefix, char *fmt,va_list ap);
651
652        static char msgPrefix[256]; // ¶ç¾î¾²±â¿ë °ø¹éµµ Æ÷ÇÔ½Ãų°Í.
653        va_list v;
654        int n=0;
655
656        if (!g_Trace_TShell)
657                return 0;
658
659//      printf("");
660        sprintf(msgPrefix, "[TShell] %s", fmt);//taskName
661
662        va_start(v, fmt);
663
664        n = printf(msgPrefix, v);
665        va_end(v);
666
667//      printf("");
668        return n;
669}
670
671
672#ifndef USE_CYGWIN
673
674#include <stdio.h>
675#include <unistd.h>
676#ifndef USE_CYGWIN
677#include <linux/reboot.h>
678#endif
679
680#include <signal.h>
681//#include <asm/sigcontext.h>
682
683#define DEBUG                           0
684
685
686typedef enum tag_SMMType {
687        SMMType_CODE,                   // Read & Execute
688        SMMType_DATA,                   // Read & Write
689        SMMType_OTHER,                  // Read Only or All
690        SMMType_STACK,
691        SMMType_UNUSED                  // None of Read/Write/Execute
692} SMMType;
693
694typedef struct tag_SharedMemoryMap {
695        SMMType Type;
696        unsigned long   StartAddress;
697        unsigned long   EndAddress;
698        char name[256];
699} SharedMemoryMap;
700
701SharedMemoryMap g_SMMTbl[256];
702int g_SMMTblCount = 0;
703
704//
705//      --> Shared Memory ¿µ¿ªÀº???
706//
707#define ISDATAADDR(v)   isStackAddress(v)
708#define ISCODEADDR(v)   isCodeAddress(v)
709
710int isStackAddress( unsigned long Address );
711int isCodeAddress( unsigned long Address );
712int ParseMaps( FILE *fp );
713
714unsigned long gpdDrvrGetErrLoc( void )
715{
716        register unsigned long __r;
717
718#ifdef USE_X86
719    __r = 0; 
720#else
721        asm ("move %0,$%1" : "=d" (__r) : "JK" (31));
722#endif
723        return __r;
724}
725
726unsigned long gpdDrvrGetErrContext( void )
727{
728        register unsigned long __r;
729
730#ifdef USE_X86
731    __r = 0;
732#else
733        asm ("move %0,$%1" : "=d" (__r) : "JK" (29));
734#endif
735        return __r;
736}
737
738unsigned long kMaxStackCheck = 100;
739unsigned int gpdDrvrGetCallChain( unsigned int skip, 
740                                                         unsigned int store, 
741                                                         unsigned long *buf, 
742                                                         unsigned long *stack )
743{
744        unsigned int result = 0;
745//      register unsigned long __r;
746        unsigned long stackCheck = 0;
747        register unsigned long v ;
748
749//      printf("|%s:%d| stack = 0x%x\n", __func__, __LINE__, (unsigned int)stack);
750
751#ifdef USE_X86
752    if (stack == NULL)
753        return 0;
754#else
755        if (stack == NULL)
756        { // get our stack pointer
757            asm ("move %0,$%1" : "=d" (__r) : "JK" (29));
758            stack = (unsigned long *) (__r & 0xfffffffc);
759        }
760#endif
761        // move up the stack and look for value.
762        while ((stackCheck < kMaxStackCheck) && (result < store))
763        {
764                if (!ISDATAADDR((unsigned long)stack))
765                        break;
766                       
767            v = *stack--;
768
769//              printf("|%s:%d| stack = 0x%x ==> 0x%x\n", __func__, __LINE__, stack, v);
770
771            if (ISCODEADDR(v)) // ISCODEADDR must be defined by Orion. It should validate that the memory is in the correct range.
772            {
773                if (skip)
774                { // just skip this one
775                    skip--;
776                }
777                else
778                { // store this one
779                    *buf++ = v;
780                    result++;
781                }
782            }
783            stackCheck++;
784        }
785        return result;
786}
787
788#ifdef _MAKEFILE_INCLUDE_TSHELL_
789char *find_function( unsigned long addr )
790{
791        int i;
792        char *ptr;
793//      char *fptr;
794        volatile unsigned long diff, old_diff=0xFFFFFFFF;
795        int found = 0;
796       
797        ptr = (char *)0;
798        for (i=0; DMW_SymbolTbl[i].name; i++) {
799                if (!(ISCODEADDR((unsigned long)DMW_SymbolTbl[i].value))) continue;
800               
801                diff = addr - ((unsigned long)DMW_SymbolTbl[i].value);
802               
803                if (old_diff > diff) {
804                        old_diff = diff;
805                        ptr = DMW_SymbolTbl[i].name;
806                        found = 1;
807//                      fptr = DMW_SymbolTbl[i].value;
808                }
809        }
810       
811        if ( found ) {
812                if ( strcmp("_etext", ptr) == 0 ) {
813                        return (char *)0;
814                } else
815                        return ptr;
816        } else
817                return (char *)0;
818}
819#endif
820
821void (*old_sigfunc[32+1])(int, int, struct sigcontext *sc);
822unsigned long IBuf[256];
823void sig_handler( int signo, int arg2, struct sigcontext *sc )
824{
825        unsigned long pc;
826        unsigned long sp;
827        unsigned int i, j;
828        unsigned long *ptr;
829       
830        if ( signo != SIGSEGV ) 
831                return;
832
833        printf("!!! %s (%d) !!!\n", signo == SIGSEGV ? "Segmentation Fault" : "Unknown", signo );
834
835#if 0
836        sigfillset( &sigset );
837        if ( sigprocmask( SIG_BLOCK, &sigset, &oldset ) < 0 ) {
838                printf("sigprocmask(): line=%d\n", __LINE__);
839                return;
840        }
841#endif
842       
843        {
844#ifndef USE_CYGWIN
845#ifdef USE_X86
846                unsigned long long *t = (unsigned long long *)&sc->eip;
847#else
848                unsigned long long *t = &sc->sc_pc;
849#endif
850                ptr = (unsigned long *)t;
851#endif
852        }
853        ptr += 1;
854        pc = *(ptr);
855#ifdef USE_X86
856    ptr = (unsigned long *)&sc->esp;
857#else
858        ptr = (unsigned long *)&sc->sc_regs[29];
859#endif
860
861        ptr += 1;
862        sp = *(ptr);
863//      curpc = gpdDrvrGetErrLoc();
864//      cursp = gpdDrvrGetErrContext();
865
866#if 1
867        printf("   PC       = 0x%08lX\n", pc );
868        printf("   SP       = 0x%08lX\n", sp );
869#endif
870
871        i = gpdDrvrGetCallChain( 0, 10, IBuf, (unsigned long *)sp );
872#if 1
873        printf("   Call Chain = %d\n", i );
874#ifdef _MAKEFILE_INCLUDE_TSHELL_
875                printf("      SP[%d] = 0x%08lX (%s)\n", -1, pc, find_function(pc) );
876#else
877                printf("      SP[%d] = 0x%08lX\n", -1, pc );
878#endif
879        for ( j=0; j<i; j++ ) {
880#ifdef _MAKEFILE_INCLUDE_TSHELL_
881                //if ( find_function(IBuf[j]) )
882                        printf("      SP[%d] = 0x%08lX (%s)\n", j, IBuf[j], find_function(IBuf[j]) ? find_function(IBuf[j]) : "Not Found");
883#else
884                printf("      SP[%d] = 0x%08lX\n", j, IBuf[j]);
885#endif
886        }
887#endif
888       
889    signal( signo, SIG_DFL );
890}
891
892void raise_segfault(void)
893{
894        int *ptr = 0;
895       
896        *ptr = 0xAA55AA55;
897}
898
899int RegisterSignalHandler( void )
900{
901        int ret = 0;
902        int i;
903
904#if 0
905        struct sigaction curSigact, OldSigact[25];
906        curSigact.sa_sigaction = NULL;
907        curSigact.sa_handler = sig_handler;
908        curSigact.sa_flags = SA_NOCLDSTOP | SA_ONESHOT | SA_NOMASK;
909        for (i=SIGHUP; i<=SIGSYS; i++) {
910                if ( i != SIGSEGV ) continue;
911                ret = sigaction( i, &curSigact, &OldSigact[i] );
912                if ( ret < 0 ) {
913                        printf("|%s:%d| ERROR, i=%d\n", __func__, __LINE__, i );
914                        return ret;
915                }
916        }
917#else
918        for (i=SIGHUP; i<=SIGSYS; i++) {
919                if ( i != SIGSEGV ) continue;
920            old_sigfunc[i] = (void (*)(int, int, struct sigcontext *))signal( i, (void (*)(int))sig_handler );
921                if ( (void (*)(int))old_sigfunc[i] == SIG_ERR ) {
922                        printf("|%s:%d| ERROR, i=%d\n", __func__, __LINE__, i );
923                        return ret;
924                }
925        }
926#endif
927        return ret;
928}
929
930FILE *OpenMaps()
931{
932        FILE *fp;
933        char pathName[256];
934       
935        sprintf( pathName, "/proc/%d/maps", (int)getpid() );
936        printf( "%s\n", pathName);
937       
938        fp = fopen( pathName, "r" );
939        if ( !fp )
940                perror("fopen()");
941               
942        return fp;
943}
944
945char tempMapBuf[1024];
946int ParseMaps( FILE *fp )
947{
948        char *nr;
949        int count;
950        unsigned long StartAddress, EndAddress;
951        SMMType Type;
952        char *ptr;
953        int flag;
954       
955        count = 0;
956        while(1){
957                nr = fgets( tempMapBuf, 1024, fp );
958                if ( nr == 0 )          // yzyeo <=  --> ==
959                        break;
960               
961                //
962                // parse it.
963                //
964
965                //      1
966                ptr = strchr( tempMapBuf, '-' );
967                if ( !ptr )     break;
968                *ptr = ' ';
969
970                ptr = tempMapBuf;
971                sscanf( ptr, "%lx", &StartAddress );
972               
973                //      2
974                ptr = strchr( tempMapBuf, ' ' );
975                if ( !ptr ) break;
976                ptr++;
977               
978                sscanf( ptr, "%lx", &EndAddress );
979               
980                // 3
981                ptr += 9;
982                flag = 0;
983                if ( ptr[0] == 'r' ) flag |= 0x8;
984                if ( ptr[1] == 'w' ) flag |= 0x4;
985                if ( ptr[2] == 'x' ) flag |= 0x2;
986                if ( ptr[3] == 'p' ) flag |= 0x1;
987               
988                if ( (flag & 0xE) == 0xA )              Type = SMMType_CODE;
989                else if ( (flag & 0xE) == 0xC ) Type = SMMType_DATA;
990                else if ( (flag & 0xE) == 0x0 ) Type = SMMType_UNUSED;
991                else if ( (flag & 0xF) == 0xF ) Type = SMMType_STACK;
992                else                                                    Type = SMMType_OTHER;
993               
994                // save it.
995                g_SMMTbl[count].StartAddress = StartAddress;
996                g_SMMTbl[count].EndAddress = EndAddress;
997                g_SMMTbl[count].Type = Type;
998                ptr = strchr( tempMapBuf, '/' );
999                if ( ptr ) 
1000                        strncpy( g_SMMTbl[count].name, ptr, 256 );
1001                else {
1002                        g_SMMTbl[count].name[0] = '\n';
1003                        g_SMMTbl[count].name[1] = '\0';
1004                }
1005                count++;
1006        } ;
1007
1008        g_SMMTblCount = count;
1009       
1010        return count;
1011}       
1012
1013int MakeMap(void)
1014{
1015        FILE *fp;
1016        int ret = 0;
1017#if DEBUG
1018        int i;
1019        int init=0;
1020#endif
1021
1022        fp = OpenMaps();
1023        if ( !fp ) {
1024                printf("|%s| ERROR, LINE=%d\n", __func__, __LINE__);
1025                return -1;
1026        }
1027       
1028        ret = ParseMaps( fp );
1029        if ( ret < 0 ) {
1030                printf("|%s| ERROR, LINE=%d\n", __func__, __LINE__);
1031                return -1;
1032        }
1033
1034#if DEBUG       
1035        if ( init == 0 ) {
1036                for (i=0; i<g_SMMTblCount; i++) {
1037                        printf("|%02d| 0x%08lX-0x%08lX:%s(%d)\t%s", i, g_SMMTbl[i].StartAddress, g_SMMTbl[i].EndAddress,
1038                                g_SMMTbl[i].Type == SMMType_CODE ? "CODE" :
1039                                g_SMMTbl[i].Type == SMMType_DATA ? "DATA" :
1040                                g_SMMTbl[i].Type == SMMType_OTHER ? "OTHER" : 
1041                                g_SMMTbl[i].Type == SMMType_STACK ? "STACK" : 
1042                                g_SMMTbl[i].Type == SMMType_UNUSED ? "UNUSED" : "Unknown", g_SMMTbl[i].Type, g_SMMTbl[i].name  );
1043                }
1044                init = 1;
1045        } 
1046#endif
1047        return 0;
1048}
1049
1050SMMType FindMemory( unsigned long Address )
1051{
1052        int i;
1053        int found = 0;
1054       
1055        for (i=0; i<g_SMMTblCount; i++) {
1056                if ( Address >= g_SMMTbl[i].StartAddress && Address <= g_SMMTbl[i].EndAddress ) {
1057                        found = 1;
1058                        break;
1059                }
1060        }
1061       
1062        if ( found )
1063                return g_SMMTbl[i].Type;
1064        else
1065                return SMMType_UNUSED;
1066}
1067
1068char *FindLibrary( unsigned long Address )
1069{
1070        int i;
1071        int found = 0;
1072       
1073        for (i=0; i<g_SMMTblCount; i++) {
1074                if ( Address >= g_SMMTbl[i].StartAddress && Address <= g_SMMTbl[i].EndAddress ) {
1075                        found = 1;
1076                        break;
1077                }
1078        }
1079       
1080        if ( found )
1081        {
1082            if ( g_SMMTbl[i].name[0] != '\0' )
1083                    return g_SMMTbl[i].name;
1084    }
1085   
1086        return NULL;
1087}
1088
1089int isStackAddress( unsigned long Address )
1090{
1091        SMMType type;
1092        extern unsigned int _init;
1093        extern unsigned int _etext;
1094
1095        if (Address >= (unsigned int)&_init && Address <= (unsigned int)&_etext)
1096                return 1;
1097
1098        type = FindMemory( Address );
1099        if ( type == SMMType_STACK )
1100                return 1;
1101
1102        return 0;
1103}
1104
1105int isCodeAddress( unsigned long Address )
1106{
1107        SMMType type;
1108        extern unsigned int _init;
1109        extern unsigned int _etext;
1110
1111        if (Address >= (unsigned int)&_init && Address <= (unsigned int)&_etext)
1112                return 1;
1113
1114        //
1115        // hwatk/050720
1116        // OTHER´Â ¾û¶×ÇÑ °ø°£±îÁö Æ÷ÇԵǴ °æ¿ì°¡ ÀÖ¾î »°´Ù.
1117        //     
1118        type = FindMemory( Address );
1119        if ( type == SMMType_CODE /*|| type == SMMType_OTHER*/ )
1120                return 1;
1121
1122        return 0;
1123}
1124
1125int isDataAddress( unsigned long Address )
1126{
1127        SMMType type;
1128//      extern unsigned int _init;
1129//      extern unsigned int _etext;
1130
1131        type = FindMemory( Address );
1132        if ( type == SMMType_DATA )
1133                return 1;
1134
1135        return 0;
1136}
1137
1138
1139void seg_dbg(void)
1140{
1141        printf("Start debug function for segmentation fault.\n");
1142
1143        MakeMap();
1144        RegisterSignalHandler();
1145}
1146
1147
1148
1149#endif
Note: See TracBrowser for help on using the repository browser.