1 /*
2  * Copyright (c) 2015, Freescale Semiconductor, Inc.
3  * Copyright 2016-2021 NXP
4  * All rights reserved.
5  *
6  * SPDX-License-Identifier: BSD-3-Clause
7  *
8  * POSIX getopt for Windows
9  * Code given out at the 1985 UNIFORUM conference in Dallas.
10  *
11  * From std-unix@ut-sally.UUCP (Moderator, John Quarterman) Sun Nov  3 14:34:15 1985
12  * Relay-Version: version B 2.10.3 4.3bsd-beta 6/6/85; site gatech.CSNET
13  * Posting-Version: version B 2.10.2 9/18/84; site ut-sally.UUCP
14  * Path: gatech!akgua!mhuxv!mhuxt!mhuxr!ulysses!allegra!mit-eddie!genrad!panda!talcott!harvard!seismo!ut-sally!std-unix
15  * From: std-unix@ut-sally.UUCP (Moderator, John Quarterman)
16  * Newsgroups: mod.std.unix
17  * Subject: public domain AT&T getopt source
18  * Message-ID: <3352@ut-sally.UUCP>
19  * Date: 3 Nov 85 19:34:15 GMT
20  * Date-Received: 4 Nov 85 12:25:09 GMT
21  * Organization: IEEE/P1003 Portable Operating System Environment Committee
22  * Lines: 91
23  * Approved: jsq@ut-sally.UUC
24  * Here's something you've all been waiting for:  the AT&T public domain
25  * source for getopt(3).  It is the code which was given out at the 1985
26  * UNIFORUM conference in Dallas.  I obtained it by electronic mail
27  * directly from AT&T.  The people there assure me that it is indeed
28  * in the public domain
29  * There is no manual page.  That is because the one they gave out at
30  * UNIFORUM was slightly different from the current System V Release 2
31  * manual page.  The difference apparently involved a note about the
32  * famous rules 5 and 6, recommending using white space between an option
33  * and its first argument, and not grouping options that have arguments.
34  * Getopt itself is currently lenient about both of these things White
35  * space is allowed, but not mandatory, and the last option in a group can
36  * have an argument.  That particular version of the man page evidently
37  * has no official existence, and my source at AT&T did not send a copy.
38  * The current SVR2 man page reflects the actual behavor of this getopt.
39  * However, I am not about to post a copy of anything licensed by AT&T.
40  */
41 
42 #include <assert.h>
43 #include <stdarg.h>
44 #include <stdlib.h>
45 #include <stdio.h>
46 
47 #include "fsl_common.h"
48 #include "fsl_str.h"
49 
50 #include "fsl_component_generic_list.h"
51 #include "fsl_component_serial_manager.h"
52 
53 #include "fsl_shell.h"
54 
55 /*
56  * The OSA_USED macro can only be defined when the OSA component is used.
57  * If the source code of the OSA component does not exist, the OSA_USED cannot be defined.
58  * OR, If OSA component is not added into project event the OSA source code exists, the OSA_USED
59  * also cannot be defined.
60  * The source code path of the OSA component is <MCUXpresso_SDK>/components/osa.
61  *
62  */
63 #if defined(OSA_USED)
64 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
65 #include "fsl_component_common_task.h"
66 #else
67 #include "fsl_os_abstraction.h"
68 #endif
69 
70 #endif
71 
72 /*******************************************************************************
73  * Definitions
74  ******************************************************************************/
75 #if defined(OSA_USED)
76 #define SHELL_WRITEX SHELL_WriteSynchronization
77 #else
78 #define SHELL_WRITEX SHELL_Write
79 #endif
80 
81 #if defined(OSA_USED)
82 #if (defined(USE_RTOS) && (USE_RTOS > 0U))
83 static OSA_MUTEX_HANDLE_DEFINE(s_shellMutex);
84 #define SHELL_MUTEX_CREATE()   (void)OSA_MutexCreate(s_shellMutex)
85 #define SHELL_ENTER_CRITICAL() (void)OSA_MutexLock(s_shellMutex, osaWaitForever_c)
86 #define SHELL_EXIT_CRITICAL()  (void)OSA_MutexUnlock(s_shellMutex)
87 #else
88 #define SHELL_MUTEX_CREATE()
89 #define SHELL_ENTER_CRITICAL()
90 #define SHELL_EXIT_CRITICAL()
91 #endif
92 #else
93 #ifdef SDK_OS_FREE_RTOS
94 #include "FreeRTOS.h"
95 #include "queue.h"
96 #include "semphr.h"
97 static QueueHandle_t s_shellMutex;
98 
99 #define SHELL_MUTEX_CREATE()   s_shellMutex = xSemaphoreCreateMutex()
100 #define SHELL_ENTER_CRITICAL() (void)xSemaphoreTakeRecursive(s_shellMutex, portMAX_DELAY)
101 #define SHELL_EXIT_CRITICAL()  (void)xSemaphoreGiveRecursive(s_shellMutex)
102 #else /* BM case*/
103 #define SHELL_MUTEX_CREATE()
104 #define SHELL_ENTER_CRITICAL()
105 #define SHELL_EXIT_CRITICAL()
106 #endif
107 #endif
108 
109 #define KEY_ESC (0x1BU)
110 #define KET_DEL (0x7FU)
111 
112 #define SHELL_EVENT_DATA_ARRIVED (1U << 0)
113 #define SHELL_EVENT_DATA_SENT    (1U << 1)
114 
115 #define SHELL_SPRINTF_BUFFER_SIZE (64U)
116 
117 /*! @brief A type for the handle special key. */
118 typedef enum _fun_key_status
119 {
120     kSHELL_Normal   = 0U, /*!< Normal key */
121     kSHELL_Special  = 1U, /*!< Special key */
122     kSHELL_Function = 2U, /*!< Function key */
123 } fun_key_status_t;
124 
125 /*! @brief Data structure for Shell environment. */
126 typedef struct _shell_context_handle
127 {
128     list_label_t commandContextListHead; /*!< Command shellContextHandle list queue head */
129     serial_handle_t serialHandle;        /*!< Serial manager handle */
130     uint8_t
131         serialWriteHandleBuffer[SERIAL_MANAGER_WRITE_HANDLE_SIZE];   /*!< The buffer for serial manager write handle */
132     serial_write_handle_t serialWriteHandle;                         /*!< The serial manager write handle */
133     uint8_t serialReadHandleBuffer[SERIAL_MANAGER_READ_HANDLE_SIZE]; /*!< The buffer for serial manager read handle */
134     serial_read_handle_t serialReadHandle;                           /*!< The serial manager read handle */
135     char *prompt;                                                    /*!< Prompt string */
136 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
137 
138 #if defined(OSA_USED)
139 
140 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
141     common_task_message_t commontaskMsg; /*!< Message for common task */
142 #else
143     uint8_t event[OSA_EVENT_HANDLE_SIZE]; /*!< Event instance */
144     uint8_t taskId[OSA_TASK_HANDLE_SIZE]; /*!< Task handle */
145 #endif
146 
147 #endif
148 
149 #endif
150     char line[SHELL_BUFFER_SIZE];                          /*!< Consult buffer */
151     char hist_buf[SHELL_HISTORY_COUNT][SHELL_BUFFER_SIZE]; /*!< History buffer*/
152     char printBuffer[SHELL_SPRINTF_BUFFER_SIZE];           /*!< Buffer for print */
153     uint32_t printLength;                                  /*!< All length has been printed */
154     uint16_t hist_current;                                 /*!< Current history command in hist buff*/
155     uint16_t hist_count;                                   /*!< Total history command in hist buff*/
156     enum _fun_key_status stat;                             /*!< Special key status */
157     uint8_t cmd_num;                                       /*!< Number of user commands */
158     uint8_t l_pos;                                         /*!< Total line position */
159     uint8_t c_pos;                                         /*!< Current line position */
160     volatile uint8_t notificationPost;                     /*!< The serial manager notification is post */
161     uint8_t exit;                                          /*!< Exit Flag*/
162     uint8_t printBusy : 1;                                 /*!< Print is busy */
163     uint8_t taskBusy : 1;                                  /*!< Task is busy */
164 } shell_context_handle_t;
165 
166 #if 0
167 #define SHELL_STRUCT_OFFSET(type, field) ((size_t) & (((type *)0)->field))
168 #define SHEEL_COMMAND_POINTER(node) \
169     ((shell_command_t *)(((uint32_t)(node)) - SHELL_STRUCT_OFFSET(shell_command_t, link)))
170 #else
171 #define SHEEL_COMMAND_POINTER(node) \
172     ((shell_command_t *)(((uint32_t)(node)) - (sizeof(shell_command_t) - sizeof(list_element_t))))
173 #endif
174 /*******************************************************************************
175  * Prototypes
176  ******************************************************************************/
177 static shell_status_t SHELL_HelpCommand(shell_handle_t shellHandle, int32_t argc, char **argv); /*!< help command */
178 
179 static shell_status_t SHELL_ExitCommand(shell_handle_t shellHandle, int32_t argc, char **argv); /*!< exit command */
180 
181 static int32_t SHELL_ParseLine(const char *cmd, uint32_t len, char *argv[]); /*!< parse line command */
182 
183 static int32_t SHELL_StringCompare(const char *str1, const char *str2, int32_t count); /*!< compare string command */
184 
185 static void SHELL_ProcessCommand(shell_context_handle_t *shellContextHandle, const char *cmd); /*!< process a command */
186 
187 static void SHELL_GetHistoryCommand(shell_context_handle_t *shellContextHandle,
188                                     uint8_t hist_pos); /*!< get commands history */
189 
190 static void SHELL_AutoComplete(shell_context_handle_t *shellContextHandle); /*!< auto complete command */
191 
192 static shell_status_t SHELL_GetChar(shell_context_handle_t *shellContextHandle,
193                                     uint8_t *ch); /*!< get a char from communication interface */
194 
195 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
196 static void SHELL_Task(void *param); /*!<  Shell task*/
197 #endif
198 
199 /*******************************************************************************
200  * Variables
201  ******************************************************************************/
202 
203 static SHELL_COMMAND_DEFINE(help, "\r\n\"help\": List all the registered commands\r\n", SHELL_HelpCommand, 0);
204 static SHELL_COMMAND_DEFINE(exit, "\r\n\"exit\": Exit program\r\n", SHELL_ExitCommand, 0);
205 
206 static char s_paramBuffer[SHELL_BUFFER_SIZE];
207 
208 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
209 #if defined(OSA_USED)
210 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
211 #else
212 /*
213  * \brief Defines the serial manager task's stack
214  */
215 static OSA_TASK_DEFINE(SHELL_Task, SHELL_TASK_PRIORITY, 1, SHELL_TASK_STACK_SIZE, false);
216 #endif
217 #endif /* OSA_USED */
218 #endif /* SHELL_NON_BLOCKING_MODE */
219 /*******************************************************************************
220  * Code
221  ******************************************************************************/
222 
223 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
SHELL_SerialManagerRxCallback(void * callbackParam,serial_manager_callback_message_t * message,serial_manager_status_t status)224 static void SHELL_SerialManagerRxCallback(void *callbackParam,
225                                           serial_manager_callback_message_t *message,
226                                           serial_manager_status_t status)
227 {
228     shell_context_handle_t *shellHandle;
229 
230     assert(callbackParam);
231     assert(message);
232 
233     shellHandle = (shell_context_handle_t *)callbackParam;
234 
235     if (0U == shellHandle->notificationPost)
236     {
237         shellHandle->notificationPost = 1U;
238 #if defined(OSA_USED)
239 
240 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
241         shellHandle->commontaskMsg.callback      = SHELL_Task;
242         shellHandle->commontaskMsg.callbackParam = shellHandle;
243         (void)COMMON_TASK_post_message(&shellHandle->commontaskMsg);
244 #else
245         (void)OSA_EventSet((osa_event_handle_t)shellHandle->event, SHELL_EVENT_DATA_ARRIVED);
246 #endif
247 
248 #else
249         SHELL_Task(shellHandle);
250 #endif
251     }
252 }
253 #endif
254 
SHELL_WriteBuffer(char * buffer,int32_t * indicator,char val,int len)255 static void SHELL_WriteBuffer(char *buffer, int32_t *indicator, char val, int len)
256 {
257     shell_context_handle_t *shellContextHandle;
258     int i              = 0;
259     shellContextHandle = (shell_context_handle_t *)(void *)buffer;
260 
261     for (i = 0; i < len; i++)
262     {
263         if ((*indicator + 1) >= (int32_t)SHELL_SPRINTF_BUFFER_SIZE)
264         {
265 #if (!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
266             if (NULL == shellContextHandle->serialHandle)
267             {
268                 for (uint32_t index = 0; index < ((uint32_t)*indicator); index++)
269                 {
270                     (void)putchar(shellContextHandle->printBuffer[index]);
271                 }
272             }
273             else
274 #endif
275             {
276                 (void)SerialManager_WriteBlocking(shellContextHandle->serialWriteHandle,
277                                                   (uint8_t *)shellContextHandle->printBuffer, (uint32_t)*indicator);
278             }
279 
280             shellContextHandle->printLength += (uint32_t)*indicator;
281             *indicator = 0;
282         }
283 
284         shellContextHandle->printBuffer[*indicator] = val;
285         (*indicator)++;
286     }
287 }
288 
SHELL_Sprintf(void * buffer,const char * formatString,va_list ap)289 static int SHELL_Sprintf(void *buffer, const char *formatString, va_list ap)
290 {
291     shell_context_handle_t *shellContextHandle;
292     uint32_t length;
293     shellContextHandle = (shell_context_handle_t *)buffer;
294 
295     length = (uint32_t)StrFormatPrintf(formatString, ap, (char *)buffer, SHELL_WriteBuffer);
296     shellContextHandle->printLength += length;
297     return (int32_t)length;
298 }
299 
300 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
SHELL_Task(void * param)301 static void SHELL_Task(void *param)
302 #else
303 void SHELL_Task(shell_handle_t shellHandle)
304 #endif
305 {
306 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
307     shell_context_handle_t *shellContextHandle = (shell_context_handle_t *)param;
308 #else
309     shell_context_handle_t *shellContextHandle = (shell_context_handle_t *)shellHandle;
310 #endif
311     uint8_t ch;
312 
313     if (NULL != shellContextHandle)
314     {
315         uint32_t osaCurrentSr = 0U;
316 
317         osaCurrentSr                         = DisableGlobalIRQ();
318         shellContextHandle->notificationPost = 0U;
319         if (shellContextHandle->taskBusy > 0U)
320         {
321             EnableGlobalIRQ(osaCurrentSr);
322             return;
323         }
324         shellContextHandle->taskBusy = 1U;
325         EnableGlobalIRQ(osaCurrentSr);
326 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
327 
328 #if defined(OSA_USED)
329 
330 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
331 #else
332         osa_event_flags_t ev = 0;
333 
334         do
335         {
336             if (KOSA_StatusSuccess == OSA_EventWait((osa_event_handle_t)shellContextHandle->event, osaEventFlagsAll_c,
337                                                     0U, osaWaitForever_c, &ev))
338             {
339                 if (0U != (ev & SHELL_EVENT_DATA_ARRIVED))
340 #endif
341 
342 #endif
343 
344 #endif
345         {
346             shellContextHandle->notificationPost = 0U;
347             do
348             {
349                 if ((bool)shellContextHandle->exit)
350                 {
351                     if (shellContextHandle->serialReadHandle != NULL)
352                     {
353                         (void)SerialManager_CloseReadHandle(shellContextHandle->serialReadHandle);
354                         shellContextHandle->serialReadHandle = NULL;
355                     }
356                     if (shellContextHandle->serialWriteHandle != NULL)
357                     {
358                         (void)SerialManager_CloseWriteHandle(shellContextHandle->serialWriteHandle);
359                         shellContextHandle->serialWriteHandle = NULL;
360                     }
361                     break;
362                 }
363                 if (kStatus_SHELL_Success != (shell_status_t)SHELL_GetChar(shellContextHandle, &ch))
364                 {
365                     /* If error occurred when getting a char, exit the task and waiting the new data arriving. */
366                     break;
367                 }
368 
369                 /* Special key */
370                 if (ch == KEY_ESC)
371                 {
372                     shellContextHandle->stat = kSHELL_Special;
373                     continue;
374                 }
375                 else if (shellContextHandle->stat == kSHELL_Special)
376                 {
377                     /* Function key */
378                     if ((char)ch == '[')
379                     {
380                         shellContextHandle->stat = kSHELL_Function;
381                         continue;
382                     }
383                     shellContextHandle->stat = kSHELL_Normal;
384                 }
385                 else if (shellContextHandle->stat == kSHELL_Function)
386                 {
387                     shellContextHandle->stat = kSHELL_Normal;
388 
389                     switch ((char)ch)
390                     {
391                         /* History operation here */
392                         case 'A': /* Up key */
393                             SHELL_GetHistoryCommand(shellContextHandle, (uint8_t)shellContextHandle->hist_current);
394                             if (shellContextHandle->hist_current < (shellContextHandle->hist_count - 1U))
395                             {
396                                 shellContextHandle->hist_current++;
397                             }
398                             break;
399                         case 'B': /* Down key */
400                             SHELL_GetHistoryCommand(shellContextHandle, (uint8_t)shellContextHandle->hist_current);
401                             if (shellContextHandle->hist_current > 0U)
402                             {
403                                 shellContextHandle->hist_current--;
404                             }
405                             break;
406                         case 'D': /* Left key */
407                             if ((bool)shellContextHandle->c_pos)
408                             {
409                                 (void)SHELL_WRITEX(shellContextHandle, "\b", 1);
410                                 shellContextHandle->c_pos--;
411                             }
412                             break;
413                         case 'C': /* Right key */
414                             if (shellContextHandle->c_pos < shellContextHandle->l_pos)
415                             {
416                                 (void)SHELL_WRITEX(shellContextHandle,
417                                                    &shellContextHandle->line[shellContextHandle->c_pos], 1);
418                                 shellContextHandle->c_pos++;
419                             }
420                             break;
421                         default:
422                             /* MISRA C-2012 Rule 16.4 */
423                             break;
424                     }
425                     continue;
426                 }
427                 /* Handle tab key */
428                 else if ((char)ch == '\t')
429                 {
430 #if SHELL_AUTO_COMPLETE
431                     /* Move the cursor to the beginning of line */
432                     uint32_t i;
433                     for (i = 0; i < (uint32_t)shellContextHandle->c_pos; i++)
434                     {
435                         (void)SHELL_WRITEX(shellContextHandle, "\b", 1);
436                     }
437                     /* Do auto complete */
438                     SHELL_AutoComplete(shellContextHandle);
439                     /* Move position to end */
440                     shellContextHandle->l_pos = (uint8_t)strlen(shellContextHandle->line);
441                     shellContextHandle->c_pos = shellContextHandle->l_pos;
442 #endif
443                     continue;
444                 }
445                 /* Handle backspace key */
446                 else if ((ch == KET_DEL) || ((char)ch == '\b'))
447                 {
448                     /* There must be at last one char */
449                     if (shellContextHandle->c_pos == 0U)
450                     {
451                         continue;
452                     }
453 
454                     shellContextHandle->l_pos--;
455                     shellContextHandle->c_pos--;
456 
457                     if (shellContextHandle->l_pos > shellContextHandle->c_pos)
458                     {
459                         (void)memmove(&shellContextHandle->line[shellContextHandle->c_pos],
460                                       &shellContextHandle->line[shellContextHandle->c_pos + 1U],
461                                       (uint32_t)shellContextHandle->l_pos - (uint32_t)shellContextHandle->c_pos);
462                         shellContextHandle->line[shellContextHandle->l_pos] = '\0';
463                         (void)SHELL_WRITEX(shellContextHandle, "\b", 1);
464                         (void)SHELL_WRITEX(shellContextHandle, &shellContextHandle->line[shellContextHandle->c_pos],
465                                            strlen(&shellContextHandle->line[shellContextHandle->c_pos]));
466                         (void)SHELL_WRITEX(shellContextHandle, "  \b", 3);
467 
468                         /* Reset position */
469                         uint32_t i;
470                         for (i = (uint32_t)shellContextHandle->c_pos; i <= (uint32_t)shellContextHandle->l_pos; i++)
471                         {
472                             (void)SHELL_WRITEX(shellContextHandle, "\b", 1);
473                         }
474                     }
475                     else /* Normal backspace operation */
476                     {
477                         (void)SHELL_WRITEX(shellContextHandle, "\b \b", 3);
478                         shellContextHandle->line[shellContextHandle->l_pos] = '\0';
479                     }
480                     continue;
481                 }
482                 else
483                 {
484                     /* MISRA C-2012 Rule 15.7 */
485                 }
486 
487                 /* Input too long */
488                 if (shellContextHandle->l_pos >= (SHELL_BUFFER_SIZE - 1U))
489                 {
490                     shellContextHandle->l_pos = 0U;
491                 }
492 
493                 /* Handle end of line, break */
494                 if (((char)ch == '\r') || ((char)ch == '\n'))
495                 {
496                     static char endoflinechar = '\0';
497 
498                     if (((uint8_t)endoflinechar != 0U) && ((uint8_t)endoflinechar != ch))
499                     {
500                         continue;
501                     }
502                     else
503                     {
504                         endoflinechar = (char)ch;
505                         /* Print new line. */
506                         (void)SHELL_WRITEX(shellContextHandle, "\r\n", 2U);
507                         /* If command line is not NULL, will start process it. */
508                         if (0U != strlen(shellContextHandle->line))
509                         {
510                             SHELL_ProcessCommand(shellContextHandle, shellContextHandle->line);
511                         }
512                         /* Print prompt. */
513                         (void)SHELL_WRITEX(shellContextHandle, shellContextHandle->prompt,
514                                            strlen(shellContextHandle->prompt));
515                         /* Reset all params */
516                         shellContextHandle->c_pos = shellContextHandle->l_pos = 0;
517                         shellContextHandle->hist_current                      = 0;
518                         (void)memset(shellContextHandle->line, 0, sizeof(shellContextHandle->line));
519                         continue;
520                     }
521                 }
522 
523                 /* Normal character */
524                 if (shellContextHandle->c_pos < shellContextHandle->l_pos)
525                 {
526                     (void)memmove(&shellContextHandle->line[shellContextHandle->c_pos + 1U],
527                                   &shellContextHandle->line[shellContextHandle->c_pos],
528                                   (uint32_t)shellContextHandle->l_pos - (uint32_t)shellContextHandle->c_pos);
529                     shellContextHandle->line[shellContextHandle->c_pos] = (char)ch;
530                     (void)SHELL_WRITEX(shellContextHandle, &shellContextHandle->line[shellContextHandle->c_pos],
531                                        strlen(&shellContextHandle->line[shellContextHandle->c_pos]));
532                     /* Move the cursor to new position */
533                     uint32_t i;
534                     for (i = (uint32_t)shellContextHandle->c_pos; i < (uint32_t)shellContextHandle->l_pos; i++)
535                     {
536                         (void)SHELL_WRITEX(shellContextHandle, "\b", 1);
537                     }
538                 }
539                 else
540                 {
541                     shellContextHandle->line[shellContextHandle->l_pos] = (char)ch;
542                     (void)SHELL_WRITEX(shellContextHandle, &shellContextHandle->line[shellContextHandle->l_pos], 1);
543                 }
544 
545                 ch = 0;
546                 shellContextHandle->l_pos++;
547                 shellContextHandle->c_pos++;
548             } while (0U == shellContextHandle->exit);
549         }
550 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
551 
552 #if defined(OSA_USED)
553 
554 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
555 #else
556             }
557         } while (1U == gUseRtos_c); /* USE_RTOS = 0 for BareMetal and 1 for OS */
558 #endif
559 
560 #endif
561 
562 #endif
563         osaCurrentSr                 = DisableGlobalIRQ();
564         shellContextHandle->taskBusy = 0U;
565         EnableGlobalIRQ(osaCurrentSr);
566     }
567 }
568 
SHELL_HelpCommand(shell_handle_t shellHandle,int32_t argc,char ** argv)569 static shell_status_t SHELL_HelpCommand(shell_handle_t shellHandle, int32_t argc, char **argv)
570 {
571     shell_context_handle_t *shellContextHandle = (shell_context_handle_t *)shellHandle;
572     shell_command_t *shellCommandContextHandle;
573     list_element_handle_t p = LIST_GetHead(&shellContextHandle->commandContextListHead);
574 
575     while (p != NULL)
576     {
577         shellCommandContextHandle = SHEEL_COMMAND_POINTER(p);
578         if ((shellCommandContextHandle->pcHelpString != NULL) && (bool)strlen(shellCommandContextHandle->pcHelpString))
579         {
580             (void)SHELL_WRITEX(shellContextHandle, shellCommandContextHandle->pcHelpString,
581                                strlen(shellCommandContextHandle->pcHelpString));
582         }
583 
584         p = LIST_GetNext(p);
585     }
586     return kStatus_SHELL_Success;
587 }
588 
SHELL_ExitCommand(shell_handle_t shellHandle,int32_t argc,char ** argv)589 static shell_status_t SHELL_ExitCommand(shell_handle_t shellHandle, int32_t argc, char **argv)
590 {
591     shell_context_handle_t *shellContextHandle = (shell_context_handle_t *)shellHandle;
592     /* Skip warning */
593     (void)SHELL_WRITEX(shellContextHandle, "\r\nSHELL exited\r\n", strlen("\r\nSHELL exited\r\n"));
594     shellContextHandle->exit = (uint8_t) true;
595     return kStatus_SHELL_Success;
596 }
597 
SHELL_ProcessCommand(shell_context_handle_t * shellContextHandle,const char * cmd)598 static void SHELL_ProcessCommand(shell_context_handle_t *shellContextHandle, const char *cmd)
599 {
600     shell_command_t *tmpCommand = NULL;
601     const char *tmpCommandString;
602     int32_t argc;
603     char *argv[SHELL_BUFFER_SIZE] = {0};
604     list_element_handle_t p;
605     uint8_t flag = 1;
606     uint8_t tmpCommandLen;
607     uint8_t tmpLen;
608     uint8_t i = 0;
609 
610     tmpLen = (uint8_t)strlen(cmd);
611     argc   = SHELL_ParseLine(cmd, tmpLen, argv);
612 
613     if ((argc > 0))
614     {
615         p = LIST_GetHead(&shellContextHandle->commandContextListHead);
616         while (p != NULL)
617         {
618             tmpCommand       = SHEEL_COMMAND_POINTER(p);
619             tmpCommandString = tmpCommand->pcCommand;
620             tmpCommandLen    = (uint8_t)strlen(tmpCommandString);
621             /* Compare with space or end of string */
622             if ((cmd[tmpCommandLen] == ' ') || (cmd[tmpCommandLen] == (char)0x00))
623             {
624                 if (SHELL_StringCompare(tmpCommandString, argv[0], (int32_t)tmpCommandLen) == 0)
625                 {
626                     /* support commands with optional number of parameters */
627                     if (tmpCommand->cExpectedNumberOfParameters == (uint8_t)SHELL_IGNORE_PARAMETER_COUNT)
628                     {
629                         flag = 0;
630                     }
631                     else if ((tmpCommand->cExpectedNumberOfParameters == 0U) && (argc == 1))
632                     {
633                         flag = 0;
634                     }
635                     else if (tmpCommand->cExpectedNumberOfParameters > 0U)
636                     {
637                         if ((argc - 1) == (int32_t)tmpCommand->cExpectedNumberOfParameters)
638                         {
639                             flag = 0;
640                         }
641                     }
642                     else
643                     {
644                         flag = 1;
645                     }
646                     break;
647                 }
648             }
649             p = LIST_GetNext(p);
650         }
651         if (NULL == p)
652         {
653             tmpCommand = NULL;
654         }
655     }
656 
657     if ((tmpCommand != NULL) && (flag == 1U))
658     {
659         (void)SHELL_Write(
660             shellContextHandle,
661             "\r\nIncorrect command parameter(s).  Enter \"help\" to view a list of available commands.\r\n\r\n",
662             strlen(
663                 "\r\nIncorrect command parameter(s).  Enter \"help\" to view a list of available commands.\r\n\r\n"));
664     }
665     else if (tmpCommand != NULL)
666     {
667         tmpLen = (uint8_t)strlen(cmd);
668         /* Compare with last command. Push back to history buffer if different */
669         if (tmpLen != (uint8_t)SHELL_StringCompare(cmd, shellContextHandle->hist_buf[0], (int32_t)strlen(cmd)))
670         {
671             for (i = SHELL_HISTORY_COUNT - 1U; i > 0U; i--)
672             {
673                 (void)memset(shellContextHandle->hist_buf[i], (int)'\0', SHELL_BUFFER_SIZE);
674                 tmpLen = (uint8_t)strlen(shellContextHandle->hist_buf[i - 1U]);
675                 (void)memcpy(shellContextHandle->hist_buf[i], shellContextHandle->hist_buf[i - 1U], tmpLen);
676             }
677             (void)memset(shellContextHandle->hist_buf[0], (int)'\0', SHELL_BUFFER_SIZE);
678             tmpLen = (uint8_t)strlen(cmd);
679             (void)memcpy(shellContextHandle->hist_buf[0], cmd, tmpLen);
680             if (shellContextHandle->hist_count < SHELL_HISTORY_COUNT)
681             {
682                 shellContextHandle->hist_count++;
683             }
684         }
685         (void)tmpCommand->pFuncCallBack(shellContextHandle, argc, argv);
686     }
687     else
688     {
689         (void)SHELL_Write(
690             shellContextHandle,
691             "\r\nCommand not recognized.  Enter 'help' to view a list of available commands.\r\n\r\n",
692             strlen("\r\nCommand not recognized.  Enter 'help' to view a list of available commands.\r\n\r\n"));
693     }
694 }
695 
SHELL_GetHistoryCommand(shell_context_handle_t * shellContextHandle,uint8_t hist_pos)696 static void SHELL_GetHistoryCommand(shell_context_handle_t *shellContextHandle, uint8_t hist_pos)
697 {
698     uint32_t i;
699     uint32_t tmp;
700 
701     if (shellContextHandle->hist_buf[0][0] == '\0')
702     {
703         shellContextHandle->hist_current = 0;
704         return;
705     }
706 
707 #if 0 /*hist_pos is passed from hist_current. And hist_current is only changed in case 'A'/'B',as hist_count is 3 \
708          most, it can't be more than 3  */
709     if (hist_pos >= SHELL_HISTORY_COUNT)
710     {
711         hist_pos = SHELL_HISTORY_COUNT - 1U;
712     }
713 #endif
714 
715     tmp = strlen(shellContextHandle->line);
716     /* Clear current if have */
717     if (tmp > 0U)
718     {
719         (void)memset(shellContextHandle->line, (int)'\0', tmp);
720         for (i = 0U; i < tmp; i++)
721         {
722             (void)SHELL_WRITEX(shellContextHandle, "\b \b", 3);
723         }
724     }
725 
726     shellContextHandle->l_pos = (uint8_t)strlen(shellContextHandle->hist_buf[hist_pos]);
727     shellContextHandle->c_pos = shellContextHandle->l_pos;
728     (void)memcpy(shellContextHandle->line, shellContextHandle->hist_buf[hist_pos], shellContextHandle->l_pos);
729     (void)SHELL_WRITEX(shellContextHandle, shellContextHandle->hist_buf[hist_pos],
730                        strlen(shellContextHandle->hist_buf[hist_pos]));
731 }
732 
SHELL_AutoComplete(shell_context_handle_t * shellContextHandle)733 static void SHELL_AutoComplete(shell_context_handle_t *shellContextHandle)
734 {
735     int32_t minLen;
736     list_element_handle_t p;
737     shell_command_t *tmpCommand = NULL;
738     const char *namePtr;
739     const char *cmdName;
740 
741     minLen  = (int32_t)SHELL_BUFFER_SIZE;
742     namePtr = NULL;
743 
744     /* Empty tab, list all commands */
745     if (shellContextHandle->line[0] == '\0')
746     {
747         (void)SHELL_HelpCommand(shellContextHandle, 0, NULL);
748         return;
749     }
750 
751     (void)SHELL_WRITEX(shellContextHandle, "\r\n", 2);
752 
753     /* Do auto complete */
754     p = LIST_GetHead(&shellContextHandle->commandContextListHead);
755     while (p != NULL)
756     {
757         tmpCommand = SHEEL_COMMAND_POINTER(p);
758         cmdName    = tmpCommand->pcCommand;
759         if (SHELL_StringCompare(shellContextHandle->line, cmdName, (int32_t)strlen(shellContextHandle->line)) == 0)
760         {
761             /* Show possible matches */
762             (void)SHELL_Printf(shellContextHandle, "%s    ", cmdName);
763             if (minLen > ((int32_t)strlen(cmdName)))
764             {
765                 namePtr = cmdName;
766                 minLen  = (int32_t)strlen(namePtr);
767             }
768         }
769         p = LIST_GetNext(p);
770     }
771     /* Auto complete string */
772     if (namePtr != NULL)
773     {
774         (void)memcpy(shellContextHandle->line, namePtr, (uint32_t)minLen);
775     }
776     SHELL_PrintPrompt(shellContextHandle);
777     (void)SHELL_WRITEX(shellContextHandle, shellContextHandle->line, strlen(shellContextHandle->line));
778     return;
779 }
780 
SHELL_StringCompare(const char * str1,const char * str2,int32_t count)781 static int32_t SHELL_StringCompare(const char *str1, const char *str2, int32_t count)
782 {
783     while ((bool)(count--))
784     {
785         if (*str1++ != *str2++)
786         {
787             return (int32_t)(*(str1 - 1) - *(str2 - 1));
788         }
789     }
790     return 0;
791 }
792 
SHELL_ParseLine(const char * cmd,uint32_t len,char * argv[])793 static int32_t SHELL_ParseLine(const char *cmd, uint32_t len, char *argv[])
794 {
795     uint32_t argc;
796     char *p;
797     uint32_t position;
798 
799     /* Init params */
800     (void)memset(s_paramBuffer, (int)'\0', len + 1U);
801     (void)memcpy(s_paramBuffer, cmd, len);
802 
803     p        = s_paramBuffer;
804     position = 0;
805     argc     = 0;
806 
807     while (position < len)
808     {
809         /* Skip all blanks */
810         while ((position < len) && ((char)(*p) == ' '))
811         {
812             *p = '\0';
813             p++;
814             position++;
815         }
816 
817         if (position >= len)
818         {
819             break;
820         }
821 
822         /* Process begin of a string */
823         if (*p == '"')
824         {
825             p++;
826             position++;
827             argv[argc] = p;
828             argc++;
829             /* Skip this string */
830             while ((*p != '"') && (position < len))
831             {
832                 p++;
833                 position++;
834             }
835             /* Skip '"' */
836             *p = '\0';
837             p++;
838             position++;
839         }
840         else /* Normal char */
841         {
842             argv[argc] = p;
843             argc++;
844             while (((char)*p != ' ') && (position < len))
845             {
846                 p++;
847                 position++;
848             }
849         }
850     }
851     return (int32_t)argc;
852 }
853 
SHELL_GetChar(shell_context_handle_t * shellContextHandle,uint8_t * ch)854 static shell_status_t SHELL_GetChar(shell_context_handle_t *shellContextHandle, uint8_t *ch)
855 {
856     shell_status_t status;
857 
858 #if (!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
859     if (NULL == shellContextHandle->serialHandle)
860     {
861         int ret;
862         ret = getchar();
863         if (ret > 0)
864         {
865             *ch    = (uint8_t)ret;
866             status = kStatus_SHELL_Success;
867         }
868         else
869         {
870             status = kStatus_SHELL_Error;
871         }
872     }
873     else
874 #endif
875     {
876 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
877         uint32_t length = 0;
878 
879         (void)SerialManager_TryRead(shellContextHandle->serialReadHandle, ch, 1, &length);
880 
881         if (length > 0U)
882         {
883             status = kStatus_SHELL_Success;
884         }
885         else
886         {
887             status = kStatus_SHELL_Error;
888         }
889 #else
890         status = (shell_status_t)SerialManager_ReadBlocking(shellContextHandle->serialReadHandle, ch, 1);
891 #endif
892     }
893 
894     return status;
895 }
896 
SHELL_Init(shell_handle_t shellHandle,serial_handle_t serialHandle,char * prompt)897 shell_status_t SHELL_Init(shell_handle_t shellHandle, serial_handle_t serialHandle, char *prompt)
898 {
899     shell_context_handle_t *shellContextHandle;
900     serial_manager_status_t status = kStatus_SerialManager_Error;
901     (void)status;
902 
903     assert(shellHandle);
904 #if !(!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
905     assert(serialHandle);
906 #endif
907     assert(prompt);
908     assert(SHELL_HANDLE_SIZE >= sizeof(shell_context_handle_t));
909 
910     shellContextHandle = (shell_context_handle_t *)shellHandle;
911 
912     /* memory set for shellHandle */
913     (void)memset(shellHandle, 0, SHELL_HANDLE_SIZE);
914 
915 #if (!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
916     if (NULL == serialHandle)
917     {
918     }
919     else
920 #endif
921     {
922 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
923 
924 #if defined(OSA_USED)
925 
926 #if (defined(SHELL_USE_COMMON_TASK) && (SHELL_USE_COMMON_TASK > 0U))
927         (void)COMMON_TASK_init();
928 #else
929         if (KOSA_StatusSuccess != OSA_EventCreate((osa_event_handle_t)shellContextHandle->event, 1U))
930         {
931             return kStatus_SHELL_Error;
932         }
933 
934         if (KOSA_StatusSuccess !=
935             OSA_TaskCreate((osa_task_handle_t)shellContextHandle->taskId, OSA_TASK(SHELL_Task), shellContextHandle))
936         {
937             return kStatus_SHELL_Error;
938         }
939 #endif
940 
941 #endif
942 
943 #endif
944     }
945 
946     shellContextHandle->prompt       = prompt;
947     shellContextHandle->serialHandle = serialHandle;
948 
949 #if (!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
950     if (NULL == serialHandle)
951     {
952     }
953     else
954 #endif
955     {
956         shellContextHandle->serialWriteHandle = (serial_write_handle_t)&shellContextHandle->serialWriteHandleBuffer[0];
957         status = SerialManager_OpenWriteHandle(shellContextHandle->serialHandle, shellContextHandle->serialWriteHandle);
958         assert(kStatus_SerialManager_Success == status);
959 
960         shellContextHandle->serialReadHandle = (serial_read_handle_t)&shellContextHandle->serialReadHandleBuffer[0];
961         status = SerialManager_OpenReadHandle(shellContextHandle->serialHandle, shellContextHandle->serialReadHandle);
962         assert(kStatus_SerialManager_Success == status);
963 
964 #if (defined(SHELL_NON_BLOCKING_MODE) && (SHELL_NON_BLOCKING_MODE > 0U))
965         status = SerialManager_InstallRxCallback(shellContextHandle->serialReadHandle, SHELL_SerialManagerRxCallback,
966                                                  shellContextHandle);
967         assert(kStatus_SerialManager_Success == status);
968 #endif
969         (void)status;
970     }
971 
972     (void)SHELL_RegisterCommand(shellContextHandle, SHELL_COMMAND(help));
973     (void)SHELL_RegisterCommand(shellContextHandle, SHELL_COMMAND(exit));
974     SHELL_MUTEX_CREATE();
975     (void)SHELL_Write(shellContextHandle, "\r\nCopyright  2020  NXP\r\n", strlen("\r\nCopyright  2020  NXP\r\n"));
976     SHELL_PrintPrompt(shellContextHandle);
977 
978     return kStatus_SHELL_Success;
979 }
980 
SHELL_RegisterCommand(shell_handle_t shellHandle,shell_command_t * shellCommand)981 shell_status_t SHELL_RegisterCommand(shell_handle_t shellHandle, shell_command_t *shellCommand)
982 {
983     shell_context_handle_t *shellContextHandle = (shell_context_handle_t *)shellHandle;
984     assert(shellHandle);
985     assert(shellCommand);
986 
987     /* memory set for shellHandle */
988     (void)memset(&shellCommand->link, 0, sizeof(shellCommand->link));
989 
990     (void)LIST_AddTail(&shellContextHandle->commandContextListHead, &shellCommand->link);
991 
992     return kStatus_SHELL_Success;
993 }
994 
SHELL_UnregisterCommand(shell_command_t * shellCommand)995 shell_status_t SHELL_UnregisterCommand(shell_command_t *shellCommand)
996 {
997     assert(shellCommand);
998 
999     (void)LIST_RemoveElement(&shellCommand->link);
1000 
1001     /* memory set for shellHandle */
1002     (void)memset(&shellCommand->link, 0, sizeof(shellCommand->link));
1003 
1004     return kStatus_SHELL_Success;
1005 }
1006 
SHELL_Write(shell_handle_t shellHandle,const char * buffer,uint32_t length)1007 shell_status_t SHELL_Write(shell_handle_t shellHandle, const char *buffer, uint32_t length)
1008 {
1009     shell_context_handle_t *shellContextHandle;
1010     uint32_t primask;
1011     shell_status_t status;
1012 
1013     assert(shellHandle);
1014     assert(buffer);
1015 
1016     if (!(bool)length)
1017     {
1018         return kStatus_SHELL_Success;
1019     }
1020 
1021     shellContextHandle = (shell_context_handle_t *)shellHandle;
1022 
1023     primask = DisableGlobalIRQ();
1024     if ((bool)shellContextHandle->printBusy)
1025     {
1026         EnableGlobalIRQ(primask);
1027         return kStatus_SHELL_Error;
1028     }
1029     shellContextHandle->printBusy = 1U;
1030     EnableGlobalIRQ(primask);
1031 #if (!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
1032     if (NULL == shellContextHandle->serialHandle)
1033     {
1034         status = kStatus_SHELL_Success;
1035         for (uint32_t index = 0; index < length; index++)
1036         {
1037             (void)putchar(buffer[index]);
1038         }
1039     }
1040     else
1041 #endif
1042     {
1043         status = (shell_status_t)SerialManager_WriteBlocking(shellContextHandle->serialWriteHandle, (uint8_t *)buffer,
1044                                                              length);
1045     }
1046 
1047     shellContextHandle->printBusy = 0U;
1048 
1049     return status;
1050 }
1051 
SHELL_Printf(shell_handle_t shellHandle,const char * formatString,...)1052 int SHELL_Printf(shell_handle_t shellHandle, const char *formatString, ...)
1053 {
1054     shell_context_handle_t *shellContextHandle;
1055     uint32_t length;
1056     uint32_t primask;
1057     va_list ap;
1058 
1059     assert(shellHandle);
1060     assert(formatString);
1061 
1062     shellContextHandle = (shell_context_handle_t *)shellHandle;
1063 
1064     primask = DisableGlobalIRQ();
1065     if ((bool)shellContextHandle->printBusy)
1066     {
1067         EnableGlobalIRQ(primask);
1068         return -1;
1069     }
1070     shellContextHandle->printBusy = 1U;
1071     EnableGlobalIRQ(primask);
1072 
1073     va_start(ap, formatString);
1074 
1075     shellContextHandle->printLength = 0U;
1076     length                          = (uint32_t)SHELL_Sprintf(shellHandle, formatString, ap);
1077 #if (!defined(SDK_DEBUGCONSOLE_UART) && (defined(SDK_DEBUGCONSOLE) && (SDK_DEBUGCONSOLE != 1)))
1078     if (NULL == shellContextHandle->serialHandle)
1079     {
1080         for (uint32_t index = 0; index < length; index++)
1081         {
1082             (void)putchar(shellContextHandle->printBuffer[index]);
1083         }
1084     }
1085     else
1086 #endif
1087     {
1088         (void)SerialManager_WriteBlocking(shellContextHandle->serialWriteHandle,
1089                                           (uint8_t *)shellContextHandle->printBuffer, length);
1090     }
1091     va_end(ap);
1092 
1093     shellContextHandle->printBusy = 0U;
1094     return (int32_t)shellContextHandle->printLength;
1095 }
1096 
SHELL_WriteSynchronization(shell_handle_t shellHandle,const char * buffer,uint32_t length)1097 shell_status_t SHELL_WriteSynchronization(shell_handle_t shellHandle, const char *buffer, uint32_t length)
1098 {
1099     shell_status_t status;
1100 
1101     assert(SHELL_checkRunningInIsr() == false);
1102 
1103     SHELL_ENTER_CRITICAL();
1104     status = SHELL_Write(shellHandle, buffer, length);
1105 
1106     SHELL_EXIT_CRITICAL();
1107 
1108     return status;
1109 }
1110 
SHELL_PrintfSynchronization(shell_handle_t shellHandle,const char * formatString,...)1111 int SHELL_PrintfSynchronization(shell_handle_t shellHandle, const char *formatString, ...)
1112 {
1113     shell_status_t status;
1114     shell_context_handle_t *shellContextHandle;
1115     va_list ap;
1116     uint32_t length;
1117 
1118     assert(SHELL_checkRunningInIsr() == false);
1119 
1120     shellContextHandle = (shell_context_handle_t *)shellHandle;
1121 
1122     SHELL_ENTER_CRITICAL();
1123     va_start(ap, formatString);
1124     length = (uint32_t)SHELL_Sprintf(shellHandle, formatString, ap);
1125 
1126     status = SHELL_Write(shellHandle, (const char *)shellContextHandle->printBuffer, length);
1127     va_end(ap);
1128     SHELL_EXIT_CRITICAL();
1129 
1130     return (status == kStatus_SHELL_Success) ? (int)length : 0;
1131 }
SHELL_ChangePrompt(shell_handle_t shellHandle,char * prompt)1132 void SHELL_ChangePrompt(shell_handle_t shellHandle, char *prompt)
1133 {
1134     shell_context_handle_t *shellContextHandle;
1135     assert(shellHandle);
1136     assert(prompt);
1137 
1138     shellContextHandle = (shell_context_handle_t *)shellHandle;
1139 
1140     shellContextHandle->prompt = prompt;
1141     SHELL_PrintPrompt(shellContextHandle);
1142 }
1143 
SHELL_PrintPrompt(shell_handle_t shellHandle)1144 void SHELL_PrintPrompt(shell_handle_t shellHandle)
1145 {
1146     shell_context_handle_t *shellContextHandle;
1147     assert(shellHandle);
1148 
1149     shellContextHandle = (shell_context_handle_t *)shellHandle;
1150 
1151     (void)SHELL_Write(shellContextHandle, "\r\n", 2U);
1152     (void)SHELL_Write(shellContextHandle, shellContextHandle->prompt, strlen(shellContextHandle->prompt));
1153 }
1154