Core
XWSH Core: Command parsing algorithm, thread model, error handling, and internal state management.
Categories:
4 minute read
Command Parsing Algorithm
XWSH uses the xwsh_split_cmdline() function (xwmd/cli/xwsh/core.c:126) to split a command line string into an argument array. The algorithm employs a single-pass strategy, modifying the input string in place to avoid additional memory allocation.
Algorithm Principle
xwer_t xwsh_split_cmdline(char * line, xwsz_t * argc, char * argv[], xwsz_t argvsize)
{
char * p = line;
xwsz_t count = 0;
char * start = NULL;
xwer_t rc = XWOK;
while (*p) {
if ((NULL == start) && (' ' == *p)) {
p++; // Skip leading spaces
} else {
if (NULL == start) {
start = p; // Record argument start position
}
if (*p == ' ') {
if (count < argvsize) {
*p = '\0'; // Terminate current argument
argv[count] = start; // Save argument pointer
count++;
} else {
rc = -E2BIG; // Too many arguments error
break;
}
start = NULL; // Reset start position
}
p++;
}
}
// ... Handle the last argument
}
Algorithm Characteristics
- Time complexity O(n): Only traverses the string once
- In-place modification: Replaces spaces with
\0, does not copy the string - Argument pointer array: The
argvarray stores pointers to parts of the original string - Error detection:
- Returns
-E2BIGwhen argument count exceedsargvsize - Maximum argument count:
XWSH_MAX_PARAM_NUM(16)
- Returns
Argument Format Limitations
- No quote support: Cannot handle arguments with spaces (e.g.
"file name") - Simple splitting: Splits only by spaces; consecutive spaces are treated as a single delimiter
- Trailing spaces: Automatically ignores trailing spaces at the end of the command
Thread Model
XWSH provides two thread running modes to suit different application scenarios.
Mode Comparison
| Feature | Standalone Thread Mode (xwsh_start()) |
Embedded Mode (xwsh_init() + xwsh_loop()) |
|---|---|---|
| Thread Resources | Requires dedicated stack space | Uses caller’s thread stack |
| Thread Management | XWSH internally creates and manages thread | User controls the loop call |
| Priority | XWSH_THD_PRIORITY (realtime priority downgrade) |
Same as caller’s thread |
| Use Case | Standalone CLI task | Integration into an existing task loop |
Standalone Thread Mode
// xwmd/cli/xwsh/mi.c:24
#define XWSH_THD_PRIORITY XWOS_SKD_PRIORITY_DROP(XWOS_SKD_PRIORITY_RT_MAX, 0)
xwer_t xwsh_start(xwstk_t * stack, xwsz_t stack_size)
{
struct xwos_thd_attr attr;
xwos_thd_attr_init(&attr);
attr.name = "xwsh.thd";
attr.stack = stack;
attr.stack_size = stack_size;
attr.priority = XWSH_THD_PRIORITY;
attr.detached = true;
attr.privileged = true;
return xwos_thd_init(&xwsh_thd, &xwsh_thdd, &attr,
xwsh_thd_mainfunc, NULL);
}
Thread main function (xwsh_thd_mainfunc):
- Displays system logo and version information
- Initializes CherryRL readline library
- Loops reading and executing commands
- Supports thread freeze (
xwos_cthd_freeze())
Embedded Mode
void xwsh_init(void)
{
xwsh_show_logo(); // Display logo
xwsh_cherryrl_init(); // Initialize readline
}
void xwsh_loop(char * buf)
{
char * line = xwsh_cherryrl_readline(buf);
if (line != NULL) {
xwsh_run_cmdline(line); // Execute command
}
}
Usage Pattern:
xwsh_init();
while (!exit_condition) {
char buf[XWSH_MAXINPUT];
xwsh_loop(buf);
// Other task logic can be added here
}
Error Handling
XWSH follows the XWOS error handling specification; all APIs return xwer_t type error codes.
Common Error Codes
| Error Code | Value | Meaning | Trigger Condition |
|---|---|---|---|
XWOK |
0 | Success | Normal operation completed |
-EINVAL |
-22 | Invalid parameter | Parameter check failed |
-EEXIST |
-17 | Already exists | Command name conflict |
-E2BIG |
-7 | Too many arguments | Exceeded XWSH_MAX_PARAM_NUM |
Error Handling Pattern
xwer_t example_function(type param)
{
xwer_t rc = XWOK;
if (!param) {
rc = -EINVAL;
goto err_param;
}
// Main logic
// ...
return XWOK;
err_param:
return rc;
}
MISRA-C Compliance:
- At most two
returnstatements per function - Use
gotofor error cleanup - Label naming:
err_<reason>
Internal State Management
Command Table Management
// xwmd/cli/xwsh/core.c:36-37
static const struct xwsh_cmd * xwsh_ext_cmd_table = NULL;
static xwsz_t xwsh_ext_cmd_table_size = 0;
Lookup priority (xwsh_find_cmd()):
- Internal command table (
xwsh_cmd_table) - External command table (
xwsh_ext_cmd_table)
Duplicate name check (xwsh_set_ext_cmd_table()):
- External commands vs internal commands
- Mutual check among external commands
Buffer Management
| Buffer | Size | Purpose | Definition Location |
|---|---|---|---|
| Input buffer | XWSH_MAXINPUT (128) |
Stores single line input | mi.h:27 |
| Prompt buffer | XWSH_RL_PROMPT_MAXSIZE (64) |
Stores colored prompt | readline.c:32 |
| History buffer | XWSH_RL_HISTORY_MAXSIZE (1024) |
Command history | readline.c:33 |
Resource Footprint Statistics
- Code size: Approximately 3-5 KB (depending on configuration)
- Stack space: Standalone mode requires 1-2 KB stack space
- Static memory: Approximately 1.2 KB (buffers)
- No dynamic memory allocation: Suitable for resource-constrained embedded environments
Performance Characteristics
Time Complexity Analysis
| Operation | Time Complexity | Description |
|---|---|---|
| Command parsing | O(n) | n is the input string length |
| Command lookup | O(m) | m is the command table size |
| Argument splitting | O(n) | Single traversal |
| History retrieval | O(1) | Ring buffer |
Memory Access Patterns
- Sequential access: Linear traversal of the string during command parsing
- Pointer reference: The
argvarray stores pointers without copying string content - Cache-friendly: Contiguous memory layout, reducing cache misses
Design Constraints
Hard Limits
- Input length: Single command line no more than 128 characters (
XWSH_MAXINPUT) - Argument count: No more than 16 arguments (
XWSH_MAX_PARAM_NUM) - History: At most 1024 bytes of history
- Command name: No length limit, but must end with
\0
Soft Constraints
- Thread safety: External command table should be set before startup and is read-only at runtime
- Context restrictions:
xwsh_start(): Interrupt, Interrupt Bottom Half, Threadxwsh_init()/xwsh_loop(): Thread
- Standard library dependency: Requires
stdio.hfor input/output