1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
| #include <args.h> #include <lib.h> #include <fs.h>
#define MAX_INPUT_BUF 1024 #define MAX_TOKEN_LEN 1024 #define MAX_CMD_ARGS 128 #define MAX_VAR_NAME_LEN 16 #define MAX_VAR_VALUE_LEN 16 #define MAX_SHELL_VARS 128 #define MAX_EXPANDED_STR_LEN (MAX_TOKEN_LEN * 2) #define UP 'A' #define DOWN 'B' #define OTHER -1 #define HISTFILESIZE 20 #define HISTORY_FILE "/.mos_history" #define WHITESPACE " \t\r\n" #define MAX_CMD_SUBST_OUTPUT_LEN (MAX_INPUT_BUF * 2) #define MAX_CMD_SUBST_BUFFERS 10
static char cmd_subst_output_pool[MAX_CMD_SUBST_BUFFERS][MAX_CMD_SUBST_OUTPUT_LEN]; static int cmd_subst_output_pool_idx = 0;
char* execute_command_substitution(const char* command_to_run, int parent_is_interactive);
static char history_lines[HISTFILESIZE][MAX_INPUT_BUF]; static int history_count = 0; static int history_add_idx = 0; static int history_latest_idx = -1; static int history_current_nav_offset = 0; static char current_typed_line[MAX_INPUT_BUF] = {0};
char expansion_buffer_pool[100][MAX_EXPANDED_STR_LEN]; int expansion_buffer_pool_index = 0; char* expand_string_variables(char *input_str); void *mymemmove(void *dest, const void *src, int n); void write_history(char *buf); void read_history(char ope[][600],int *sz);
typedef struct { char name[MAX_VAR_NAME_LEN + 1]; char value[MAX_VAR_VALUE_LEN + 1]; int is_exported; int is_readonly; int is_set; } ShellVar;
static ShellVar shell_vars[MAX_SHELL_VARS]; static int num_set_vars = 0;
void init_shell_vars(void); ShellVar* find_variable(const char *name); int set_variable(const char *name, const char *value, int export_flag, int readonly_flag, int update_flags_if_exists); int unset_variable(const char *name); void print_all_variables(void); char* get_variable_value(const char *name);
typedef struct ASTNode ASTNode;
typedef enum { NODE_ILLEGAL = 0, NODE_COMMAND, NODE_PIPELINE, NODE_LIST_SEMI, NODE_LIST_AMP, NODE_AND, NODE_OR, } ASTNodeType;
typedef enum { TOKEN_ERROR = 0, TOKEN_EOF = 1, TOKEN_EOL = 2, TOKEN_WORD, TOKEN_PIPE, TOKEN_SEMI, TOKEN_AMP, TOKEN_AND, TOKEN_OR, TOKEN_REDIR_IN, TOKEN_REDIR_OUT, TOKEN_REDIR_APP, } TokenType;
typedef struct { TokenType type; char value[MAX_TOKEN_LEN]; } Token;
typedef enum { REDIR_TYPE_IN, REDIR_TYPE_OUT, REDIR_TYPE_APP, } RedirType;
typedef struct RedirNode { RedirType type; char *filename; struct RedirNode *next; } RedirNode;
typedef struct { char *argv[MAX_CMD_ARGS]; int argc; RedirNode *redirects; } CMDNodeData;
typedef struct { ASTNode *left; ASTNode *right; } BinaryOpNodeData;
struct ASTNode { ASTNodeType type; union { CMDNodeData command; BinaryOpNodeData binary_op; } data; };
ASTNode *parse_list(void); void readline(char *buf, u_int n, int interactive); void free_ast_resources(void);
char strdup_pool[100][1000] = {0}; int strdup_pool_index = 0;
ASTNode astnode_pool[100] = {0}; int astnode_pool_index = 0;
RedirNode redirnode_pool[100] = {0}; int redirnode_pool_index = 0;
char* get_subst_output_buffer() { if (cmd_subst_output_pool_idx >= MAX_CMD_SUBST_BUFFERS) { printf("sh: too many command substitutions on one line\n"); if (MAX_CMD_SUBST_BUFFERS > 0) { return cmd_subst_output_pool[MAX_CMD_SUBST_BUFFERS -1]; } user_panic("cmd_subst_output_pool out of space and no fallback buffer"); } memset(cmd_subst_output_pool[cmd_subst_output_pool_idx], 0, MAX_CMD_SUBST_OUTPUT_LEN); return cmd_subst_output_pool[cmd_subst_output_pool_idx++]; }
char* execute_command_substitution(const char* command_to_run, int parent_is_interactive) { int pipe_fds[2]; int child_pid_for_sh_c; char *output_buffer = get_subst_output_buffer(); output_buffer[0] = '\0'; u_int output_len = 0; char read_char; int r;
if (pipe(pipe_fds) < 0) { printf("sh: pipe failed for command substitution\n"); return output_buffer; }
child_pid_for_sh_c = fork();
if (child_pid_for_sh_c < 0) { printf("sh: fork failed for command substitution\n"); close(pipe_fds[0]); close(pipe_fds[1]); return output_buffer; }
if (child_pid_for_sh_c == 0) { close(pipe_fds[0]); if (dup(pipe_fds[1], 1) < 0) { printf("sh: dup stdout to pipe failed in cmd_subst child\n"); exit(1); } close(pipe_fds[1]); char temp_cmd_buffer_for_argv[MAX_INPUT_BUF]; mystrcpy(temp_cmd_buffer_for_argv, command_to_run); char *sh_argv[] = {"sh.b", "-c", temp_cmd_buffer_for_argv, NULL}; spawn("/sh.b", sh_argv); exit(1); } else { close(pipe_fds[1]); while ((r = read(pipe_fds[0], &read_char, 1)) == 1) { if (output_len < MAX_CMD_SUBST_OUTPUT_LEN - 1) { output_buffer[output_len++] = read_char; } else { debugf("sh: command substitution output too long, truncated.\n"); while(read(pipe_fds[0], &read_char, 1) == 1); break; } } if (r < 0) { printf("sh: error reading from pipe in command substitution\n"); } output_buffer[output_len] = '\0';
close(pipe_fds[0]); wait(child_pid_for_sh_c, NULL);
while (output_len > 0 && (output_buffer[output_len - 1] == '\n' || output_buffer[output_len - 1] == '\r')) { output_buffer[--output_len] = '\0'; }
for (u_int i = 0; i < output_len; ++i) { if (output_buffer[i] == '\n' || output_buffer[i] == '\r') { output_buffer[i] = ' '; } } return output_buffer; } return get_subst_output_buffer(); }
void reset_allocators() { strdup_pool_index = 0; astnode_pool_index = 0; redirnode_pool_index = 0; expansion_buffer_pool_index = 0; cmd_subst_output_pool_idx = 0; }
char *user_strdup(const char *s) { if (!s) return NULL; size_t len = strlen(s) + 1; if (len > 1000) { user_panic("strdup: string too long"); } if (strdup_pool_index >= 100) { user_panic("strdup_pool out of space"); } char *new_s = strdup_pool[strdup_pool_index++]; memcpy(new_s, s, len); return new_s; }
ASTNode *alloc_ast_node(ASTNodeType type) { if (astnode_pool_index >= 100) { user_panic("astnode_pool out of space"); } ASTNode *node = &astnode_pool[astnode_pool_index++]; memset(node, 0, sizeof(ASTNode)); node->type = type; return node; }
RedirNode *alloc_redir_node() { if (redirnode_pool_index >= 100) { user_panic("redirnode_pool out of space"); } RedirNode *node = &redirnode_pool[redirnode_pool_index++]; memset(node, 0, sizeof(RedirNode)); return node; }
static const char *current_pos; static Token current_token; static Token peeked_token; static int has_peeked_token;
void skip_whitespace_and_comments() { while (*current_pos) { if (strchr(" \t\r\n", *current_pos)) { current_pos++; } else if (*current_pos == '#') { while (*current_pos && *current_pos != '\n') { current_pos++; } if (*current_pos == '\n') { current_pos++; } } else { break; } } }
Token get_next_raw_token() { Token token; memset(&token, 0, sizeof(Token)); token.type = TOKEN_ERROR;
skip_whitespace_and_comments();
if (*current_pos == '\0') { token.type = TOKEN_EOF; return token; }
if (mystrncmp(current_pos, "&&", 2) == 0) { token.type = TOKEN_AND; mystrncpy(token.value, "&&", 2); token.value[2] = '\0'; current_pos += 2; } else if (mystrncmp(current_pos, "||", 2) == 0) { token.type = TOKEN_OR; mystrncpy(token.value, "||", 2); token.value[2] = '\0'; current_pos += 2; } else if (mystrncmp(current_pos, ">>", 2) == 0) { token.type = TOKEN_REDIR_APP; mystrncpy(token.value, ">>", 2); token.value[2] = '\0'; current_pos += 2; } else if (*current_pos == '|') { token.type = TOKEN_PIPE; token.value[0] = '|'; token.value[1] = '\0'; current_pos++; } else if (*current_pos == ';') { token.type = TOKEN_SEMI; token.value[0] = ';'; token.value[1] = '\0'; current_pos++; } else if (*current_pos == '&') { token.type = TOKEN_AMP; token.value[0] = '&'; token.value[1] = '\0'; current_pos++; } else if (*current_pos == '<') { token.type = TOKEN_REDIR_IN; token.value[0] = '<'; token.value[1] = '\0'; current_pos++; } else if (*current_pos == '>') { token.type = TOKEN_REDIR_OUT; token.value[0] = '>'; token.value[1] = '\0'; current_pos++; } else if (*current_pos == '`') { token.type = TOKEN_WORD; int i = 0; token.value[i++] = *current_pos++; while (*current_pos && i < MAX_TOKEN_LEN - 1) { if (*current_pos == '`') { token.value[i++] = *current_pos++; break; } token.value[i++] = *current_pos++; } token.value[i] = '\0'; if (i > 1 && token.value[i-1] != '`') { printf("sh: unclosed backtick\n"); token.type = TOKEN_ERROR; } else if (i <= 1) { if (i==1 && token.value[0] == '`' && *current_pos == '\0') { token.type = TOKEN_ERROR; } } } else { token.type = TOKEN_WORD; int i = 0; while (*current_pos && !strchr(" \t\r\n", *current_pos) && !strchr("|;&<>`#", *current_pos) && i < MAX_TOKEN_LEN - 1) { if (mystrncmp(current_pos, "&&", 2) == 0 || mystrncmp(current_pos, "||", 2) == 0 || mystrncmp(current_pos, ">>", 2) == 0) { break; } token.value[i++] = *current_pos++; } token.value[i] = '\0'; if (i == 0) { if (*current_pos == '\0') token.type = TOKEN_EOF; else token.type = TOKEN_ERROR; } } return token; }
void tokenizer_init(const char *input) { current_pos = input; has_peeked_token = 0; current_token = get_next_raw_token(); }
Token consume_token() { Token old_current = current_token; if (current_token.type == TOKEN_EOF) return old_current;
if (has_peeked_token) { current_token = peeked_token; has_peeked_token = 0; } else { current_token = get_next_raw_token(); } return old_current; }
Token peek() { if (current_token.type == TOKEN_EOF) return current_token;
if (!has_peeked_token) { peeked_token = get_next_raw_token(); has_peeked_token = 1; } return peeked_token; }
ASTNode *parse_and_or(void); ASTNode *parse_pipeline(void); ASTNode *parse_command(void);
ASTNode *parse_line() { if (current_token.type == TOKEN_EOF || current_token.type == TOKEN_EOL) { return NULL; } return parse_list(); }
ASTNode *parse_list() { ASTNode *node = parse_and_or(); if (!node) { return NULL; }
while (current_token.type == TOKEN_SEMI || current_token.type == TOKEN_AMP) { TokenType op_type = current_token.type; consume_token();
if (current_token.type == TOKEN_EOF || current_token.type == TOKEN_EOL) { ASTNode *new_list_node = alloc_ast_node(op_type == TOKEN_SEMI ? NODE_LIST_SEMI : NODE_LIST_AMP); new_list_node->data.binary_op.left = node; new_list_node->data.binary_op.right = NULL; node = new_list_node; break; }
ASTNode *right_node = parse_and_or(); if (!right_node && (op_type == TOKEN_SEMI || (op_type == TOKEN_AMP && current_token.type != TOKEN_EOF && current_token.type != TOKEN_EOL ) ) ) { debugf("Syntax error after '%s'\n", op_type == TOKEN_SEMI ? ";" : "&"); return NULL; }
ASTNode *new_list_node = alloc_ast_node(op_type == TOKEN_SEMI ? NODE_LIST_SEMI : NODE_LIST_AMP); new_list_node->data.binary_op.left = node; new_list_node->data.binary_op.right = right_node; node = new_list_node; } return node; }
ASTNode *parse_and_or() { ASTNode *node = parse_pipeline(); if (!node) return NULL;
while (current_token.type == TOKEN_AND || current_token.type == TOKEN_OR) { TokenType op_type = current_token.type; consume_token(); ASTNode *right_node = parse_pipeline(); if (!right_node) { debugf("Syntax error: '%s' not followed by pipeline\n", op_type == TOKEN_AND ? "&&" : "||"); return NULL; } ASTNode *new_op_node = alloc_ast_node(op_type == TOKEN_AND ? NODE_AND : NODE_OR); new_op_node->data.binary_op.left = node; new_op_node->data.binary_op.right = right_node; node = new_op_node; } return node; }
ASTNode *parse_pipeline() { ASTNode *node = parse_command(); if (!node) return NULL;
while (current_token.type == TOKEN_PIPE) { consume_token(); ASTNode *right_node = parse_command(); if (!right_node) { debugf("Syntax error: '|' not followed by command\n"); return NULL; } ASTNode *new_pipe_node = alloc_ast_node(NODE_PIPELINE); new_pipe_node->data.binary_op.left = node; new_pipe_node->data.binary_op.right = right_node; node = new_pipe_node; } return node; }
ASTNode *parse_command() { if (current_token.type != TOKEN_WORD && current_token.type != TOKEN_REDIR_IN && current_token.type != TOKEN_REDIR_OUT && current_token.type != TOKEN_REDIR_APP) { if (current_token.type == TOKEN_EOF || current_token.type == TOKEN_EOL) return NULL; return NULL; }
ASTNode *cmd_node_ast = alloc_ast_node(NODE_COMMAND); CMDNodeData *cmd_data = &cmd_node_ast->data.command; RedirNode **next_redir_ptr = &cmd_data->redirects;
int parent_shell_is_interactive = iscons(0);
while (1) { if (current_token.type == TOKEN_WORD) { if (cmd_data->argc < MAX_CMD_ARGS - 1) { char *arg_after_var_expansion = expand_string_variables(current_token.value); char *final_arg_for_argv = arg_after_var_expansion;
char rebuilt_arg_buffer[MAX_EXPANDED_STR_LEN * 2]; rebuilt_arg_buffer[0] = '\0'; char *current_rebuilt_ptr = rebuilt_arg_buffer; const char *scan_ptr = arg_after_var_expansion;
while (*scan_ptr) { char *backtick_start = strchr(scan_ptr, '`'); if (backtick_start) { char *backtick_end = strchr(backtick_start + 1, '`'); if (backtick_end) { if (backtick_start > scan_ptr) { mystrncpy(current_rebuilt_ptr, scan_ptr, backtick_start - scan_ptr); current_rebuilt_ptr += (backtick_start - scan_ptr); } char cmd_to_subst[MAX_INPUT_BUF]; int cmd_len = backtick_end - (backtick_start + 1); if (cmd_len >= MAX_INPUT_BUF) cmd_len = MAX_INPUT_BUF -1; mystrncpy(cmd_to_subst, backtick_start + 1, cmd_len); cmd_to_subst[cmd_len] = '\0'; char *subst_output = execute_command_substitution(cmd_to_subst, parent_shell_is_interactive); if (subst_output) { mystrcat(current_rebuilt_ptr, subst_output); current_rebuilt_ptr += mystrlen(subst_output); } scan_ptr = backtick_end + 1; } else { mystrcat(current_rebuilt_ptr, scan_ptr); current_rebuilt_ptr += mystrlen(scan_ptr); scan_ptr += mystrlen(scan_ptr); } } else { mystrcat(current_rebuilt_ptr, scan_ptr); current_rebuilt_ptr += mystrlen(scan_ptr); break; } } *current_rebuilt_ptr = '\0';
if (rebuilt_arg_buffer[0] != '\0' || arg_after_var_expansion[0] == '\0') { final_arg_for_argv = user_strdup(rebuilt_arg_buffer); } else { final_arg_for_argv = user_strdup(arg_after_var_expansion); } cmd_data->argv[cmd_data->argc++] = final_arg_for_argv; } else { return NULL; } consume_token(); } else if (current_token.type == TOKEN_REDIR_IN || current_token.type == TOKEN_REDIR_OUT || current_token.type == TOKEN_REDIR_APP) { TokenType redir_op_type = current_token.type; consume_token(); if (current_token.type != TOKEN_WORD) { debugf("Syntax error: Redirection operator not followed by filename\n"); return NULL; } RedirNode *redir_node = alloc_redir_node(); if (redir_op_type == TOKEN_REDIR_IN) redir_node->type = REDIR_TYPE_IN; else if (redir_op_type == TOKEN_REDIR_OUT) redir_node->type = REDIR_TYPE_OUT; else if (redir_op_type == TOKEN_REDIR_APP) redir_node->type = REDIR_TYPE_APP;
char *filename_after_vars = expand_string_variables(current_token.value); char *final_filename = filename_after_vars; char rebuilt_fname_buffer[MAX_EXPANDED_STR_LEN * 2]; rebuilt_fname_buffer[0] = '\0'; char *current_rebuilt_fname_ptr = rebuilt_fname_buffer; const char *scan_fname_ptr = filename_after_vars; while(*scan_fname_ptr){ char *bt_start = strchr(scan_fname_ptr, '`'); if(bt_start){ char *bt_end = strchr(bt_start + 1, '`'); if(bt_end){ if(bt_start > scan_fname_ptr){ mystrncpy(current_rebuilt_fname_ptr, scan_fname_ptr, bt_start - scan_fname_ptr); current_rebuilt_fname_ptr += (bt_start - scan_fname_ptr); } char cmd_to_subst_fname[MAX_INPUT_BUF]; int cmd_len_fname = bt_end - (bt_start + 1); if(cmd_len_fname >= MAX_INPUT_BUF) cmd_len_fname = MAX_INPUT_BUF -1; mystrncpy(cmd_to_subst_fname, bt_start + 1, cmd_len_fname); cmd_to_subst_fname[cmd_len_fname] = '\0'; char *subst_out_fname = execute_command_substitution(cmd_to_subst_fname, parent_shell_is_interactive); if(subst_out_fname){ mystrcat(current_rebuilt_fname_ptr, subst_out_fname); current_rebuilt_fname_ptr += mystrlen(subst_out_fname); } scan_fname_ptr = bt_end + 1; } else { mystrcat(current_rebuilt_fname_ptr, scan_fname_ptr); current_rebuilt_fname_ptr += mystrlen(scan_fname_ptr); break; } } else { mystrcat(current_rebuilt_fname_ptr, scan_fname_ptr); current_rebuilt_fname_ptr += mystrlen(scan_fname_ptr); break; } } *current_rebuilt_fname_ptr = '\0'; if(rebuilt_fname_buffer[0] != '\0' || filename_after_vars[0] == '\0'){ final_filename = user_strdup(rebuilt_fname_buffer); } else { final_filename = user_strdup(filename_after_vars); } redir_node->filename = final_filename; consume_token(); *next_redir_ptr = redir_node; next_redir_ptr = &redir_node->next; } else { break; } } cmd_data->argv[cmd_data->argc] = NULL; if (cmd_data->argc == 0 && cmd_data->redirects == NULL) { return NULL; } return cmd_node_ast; }
void reset_expansion_buffer_pool() { expansion_buffer_pool_index = 0; }
char *get_expansion_buffer() { if (expansion_buffer_pool_index >= 100) { user_panic("expansion_buffer_pool out of space"); } memset(expansion_buffer_pool[expansion_buffer_pool_index], 0, MAX_EXPANDED_STR_LEN); return expansion_buffer_pool[expansion_buffer_pool_index++]; }
char * expand_string_variables( char *input_str) { if (!input_str || !strchr(input_str, '$')) { return user_strdup(input_str); } char *output_buf = get_expansion_buffer(); output_buf[0] = '\0'; char *out_ptr = output_buf; const char *in_ptr = input_str;
while (*in_ptr) { if (*in_ptr == '$') { in_ptr++; char var_name[MAX_VAR_NAME_LEN + 1]; int i = 0; while (*in_ptr && i < MAX_VAR_NAME_LEN && !strchr(" \t\r\n$|;&<>/`", *in_ptr) ) { var_name[i++] = *in_ptr++; } var_name[i] = '\0'; if (i > 0) { const char *var_value = get_variable_value(var_name); if (var_value) { size_t val_len = mystrlen(var_value); if ((out_ptr - output_buf) + val_len < MAX_EXPANDED_STR_LEN) { mystrcpy(out_ptr, var_value); out_ptr += val_len; } else { } } } else { if ((out_ptr - output_buf) < MAX_EXPANDED_STR_LEN -1) { *out_ptr++ = '$'; } } } else { if ((out_ptr - output_buf) < MAX_EXPANDED_STR_LEN - 1) { *out_ptr++ = *in_ptr++; } else { in_ptr++; } } } *out_ptr = '\0'; return output_buf; }
int is_inner_cmd(CMDNodeData *cmd) { if (mystrcmp(cmd->argv[0], "cd") == 0 || mystrcmp(cmd->argv[0], "pwd") == 0 || mystrcmp(cmd->argv[0], "exit") == 0 || mystrcmp(cmd->argv[0], "declare") == 0 || mystrcmp(cmd->argv[0], "unset") == 0 || mystrcmp(cmd->argv[0], "history") == 0) { return 1; } else { return 0; } }
void execute_inner_cmd(CMDNodeData *cmd) { if (mystrcmp(cmd->argv[0], "pwd") == 0) { if (cmd->argc > 1) { printf("pwd: expected 0 arguments; got %d\n", cmd->argc - 1); } else { char buf[1024] = {0}; syscall_get_cwd(buf); printf("%s\n", buf); } } else if (mystrcmp(cmd->argv[0], "cd") == 0) { char finalpath[1024] = {0}; if (cmd->argc == 1) { mystrcpy(finalpath, "/"); syscall_set_cwd(finalpath); } else if (cmd->argc == 2) { char cwd[1024] = {0}; syscall_get_cwd(cwd); int r; if ((r = get_final_path(cwd, cmd->argv[1], finalpath)) == 0) { syscall_set_cwd(finalpath); } else { if (r == 1) { printf("cd: The directory '%s' does not exist\n", cmd->argv[1]); } else if (r == 2) { printf("cd: '%s' is not a directory\n", cmd->argv[1]); } else if (r == -1) { printf("cd: error processing path (null args)\n"); } else if (r == -2) { printf("cd: path too long\n"); } else if (r == -3) { printf("cd: failed to normalize path\n"); } } } else if (cmd->argc > 2) { printf("cd: too many arguments\n"); } } else if (mystrcmp(cmd->argv[0], "exit") == 0) { exit(0); } else if (mystrcmp(cmd->argv[0], "declare") == 0) { int export_f = 0; int readonly_f = 0; int arg_idx = 1; char *name_val_pair = NULL; while (cmd->argv[arg_idx] && cmd->argv[arg_idx][0] == '-') { if (mystrcmp(cmd->argv[arg_idx], "-x") == 0) export_f = 1; else if (mystrcmp(cmd->argv[arg_idx], "-r") == 0) readonly_f = 1; else if (mystrcmp(cmd->argv[arg_idx], "-xr") == 0 || mystrcmp(cmd->argv[arg_idx], "-rx") == 0) { export_f = 1; readonly_f = 1; } else { printf("declare: invalid option %s\n", cmd->argv[arg_idx]); return; } arg_idx++; } if (cmd->argv[arg_idx]) { name_val_pair = cmd->argv[arg_idx]; } if (!name_val_pair) { print_all_variables(); } else { char name[MAX_VAR_NAME_LEN + 1]; char value_buf[MAX_VAR_VALUE_LEN + 1]; char *value_ptr = ""; char *eq_ptr = strchr(name_val_pair, '='); if (eq_ptr) { int name_len = eq_ptr - name_val_pair; if (name_len > MAX_VAR_NAME_LEN) {printf("sh: var name too long\n"); return; } mystrncpy(name, name_val_pair, name_len); name[name_len] = '\0'; value_ptr = eq_ptr + 1; if (mystrlen(value_ptr) > MAX_VAR_VALUE_LEN) { printf("sh: var value too long\n"); return; } mystrcpy(value_buf, value_ptr); value_ptr = value_buf; } else { if (mystrlen(name_val_pair) > MAX_VAR_NAME_LEN) { printf("sh: var name too long\n"); return; } mystrcpy(name, name_val_pair); } set_variable(name, value_ptr, export_f, readonly_f, 1); } } else if (mystrcmp(cmd->argv[0], "unset") == 0) { if (cmd->argc != 2) { printf("unset: usage: unset NAME\n"); return; } unset_variable(cmd->argv[1]); } else if (mystrcmp(cmd->argv[0], "history") == 0) { if (cmd->argc > 1) { printf("history: too many arguments\n"); return; } int start_idx; if (history_count == 0) return; if (history_count < HISTFILESIZE) start_idx = 0; else start_idx = history_add_idx; for (int i = 0; i < history_count; ++i) { int current_entry_idx = (start_idx + i) % HISTFILESIZE; printf("%s\n", history_lines[current_entry_idx]); } } }
int get_final_path(const char *cwd, const char *path, char *finalpath) { if (!cwd || !path || !finalpath) return -1; char constructed_path[MAXPATHLEN * 2]; if (path[0] == '/') { if (mystrlen(path) >= MAXPATHLEN) return -2; mystrcpy(constructed_path, path); } else { if (mystrlen(cwd) + 1 + mystrlen(path) + 1 > sizeof(constructed_path)) return -2; mystrcpy(constructed_path, cwd); if (mystrcmp(cwd, "/") != 0 && constructed_path[mystrlen(constructed_path) - 1] != '/') { mystrcat(constructed_path, "/"); } mystrcat(constructed_path, path); } if (normalize_path(constructed_path) < 0) return -3; if (path[0] != '/') { struct Stat st; int r_stat = stat(constructed_path, &st); if (r_stat < 0) return 1; if (st.st_isdir == 0) return 2; } mystrcpy(finalpath, constructed_path); return 0; }
int normalize_path(char *path_buf) { if (path_buf == NULL) return -1; char components[MAX_CMD_ARGS][MAXNAMELEN]; int comp_idx = 0; const char *p = path_buf; int is_absolute = (*p == '/');
if (is_absolute) { p++; while (*p == '/') p++; } while (*p) { char current_comp_val[MAXNAMELEN]; char *c_ptr = current_comp_val; while (*p != '/' && *p != '\0') { if (c_ptr - current_comp_val < MAXNAMELEN - 1) *c_ptr++ = *p; p++; } *c_ptr = '\0'; if (mystrcmp(current_comp_val, "..") == 0) { if (comp_idx > 0 && mystrcmp(components[comp_idx - 1], "..") != 0) comp_idx--; else if (!is_absolute) { if (comp_idx < MAX_CMD_ARGS) mystrncpy(components[comp_idx++], "..", MAXNAMELEN-1); else return -E_BAD_PATH; } } else if (mystrcmp(current_comp_val, ".") != 0 && current_comp_val[0] != '\0') { if (comp_idx < MAX_CMD_ARGS) mystrncpy(components[comp_idx++], current_comp_val, MAXNAMELEN-1); else return -E_BAD_PATH; } while (*p == '/') p++; } char *write_ptr = path_buf; if (is_absolute) *write_ptr++ = '/'; for (int i = 0; i < comp_idx; i++) { if (i > 0 || (is_absolute && comp_idx > 0 && i==0 && write_ptr > path_buf && *(write_ptr-1) != '/')) { if(write_ptr == path_buf && is_absolute && *path_buf == '/'){} else if (write_ptr > path_buf && *(write_ptr-1) != '/') { if (write_ptr - path_buf >= MAXPATHLEN -1) return -E_BAD_PATH; *write_ptr++ = '/'; } else if (write_ptr == path_buf && !is_absolute && i > 0) { if (write_ptr - path_buf >= MAXPATHLEN -1) return -E_BAD_PATH; *write_ptr++ = '/'; } } int len = mystrlen(components[i]); if ((write_ptr - path_buf) + len >= MAXPATHLEN) return -E_BAD_PATH; memcpy(write_ptr, components[i], len); write_ptr += len; } *write_ptr = '\0'; if (path_buf[0] == '\0') { if (is_absolute) mystrcpy(path_buf, "/"); else mystrcpy(path_buf, "."); } else if (is_absolute && write_ptr == path_buf + 1 && path_buf[0] == '/' && comp_idx == 0) { } else if (is_absolute && path_buf[0] == '/' && path_buf[1] == '/' && path_buf[2] == '\0'){ path_buf[1] = '\0'; }
return 0; }
void execute_ast(ASTNode *node) { if (!node) { return; } int child_pid; int pipe_fds[2];
switch (node->type) { case NODE_COMMAND: { CMDNodeData *cmd = &node->data.command; if (cmd->argc == 0 && cmd->redirects == NULL) return; if (cmd->argc == 0 && cmd->redirects != NULL) { debugf("sh: missing command for redirection\n"); return; } if (is_inner_cmd(cmd)) { execute_inner_cmd(cmd); break; } child_pid = fork(); if (child_pid < 0) user_panic("execute_ast: fork failed");
if (child_pid == 0) { RedirNode *redir = cmd->redirects; while (redir) { int open_flags = 0; int target_fd_std = -1; if (redir->type == REDIR_TYPE_IN) { open_flags = O_RDONLY; target_fd_std = 0; } else if (redir->type == REDIR_TYPE_OUT) { open_flags = O_WRONLY | O_CREAT | O_TRUNC; target_fd_std = 1; } else if (redir->type == REDIR_TYPE_APP) { open_flags = O_WRONLY | O_CREAT | O_APPEND; target_fd_std = 1; } int opened_fd = open(redir->filename, open_flags); if (opened_fd < 0) { printf("sh: cannot open %s\n", redir->filename); exit(1); } dup(opened_fd, target_fd_std); close(opened_fd); redir = redir->next; } int spawn_ret; char *spawn_argv[MAX_CMD_ARGS + MAX_SHELL_VARS + 1]; int spawn_argc = 0; if (mystrcmp(cmd->argv[0], "sh.b") == 0 || mystrcmp(cmd->argv[0], "sh") == 0 || mystrcmp(cmd->argv[0], "/sh.b") == 0 || mystrcmp(cmd->argv[0], "/sh") == 0) { for (int i = 0; i < cmd->argc; ++i) spawn_argv[spawn_argc++] = cmd->argv[i]; char env_str_pool[MAX_SHELL_VARS][MAX_VAR_NAME_LEN + MAX_VAR_VALUE_LEN + 3]; int env_str_idx = 0; for (int i = 0; i < MAX_SHELL_VARS; ++i) { if (shell_vars[i].is_set && shell_vars[i].is_exported) { if (spawn_argc < (MAX_CMD_ARGS + MAX_SHELL_VARS) && env_str_idx < MAX_SHELL_VARS) { char *current_env_str = env_str_pool[env_str_idx++]; current_env_str[0] = shell_vars[i].is_readonly ? '1' : '0'; current_env_str[1] = '\0'; mystrcat(current_env_str, shell_vars[i].name); mystrcat(current_env_str, "="); mystrcat(current_env_str, shell_vars[i].value); spawn_argv[spawn_argc++] = current_env_str; } else break; } } spawn_argv[spawn_argc] = NULL; spawn_ret = spawn(cmd->argv[0], spawn_argv); } else { spawn_ret = spawn(cmd->argv[0], (char **)cmd->argv); } if (spawn_ret < 0) { printf("sh: failed to spawn '%s' (err %d)\n", cmd->argv[0], spawn_ret); exit(127); } exit(0); } else { wait(child_pid, NULL); } break; } case NODE_PIPELINE: { if (pipe(pipe_fds) < 0) user_panic("pipe creation failed"); int pid1 = fork(); if (pid1 < 0) user_panic("fork for pipe left failed"); if (pid1 == 0) { close(pipe_fds[0]); dup(pipe_fds[1], 1); close(pipe_fds[1]); execute_ast(node->data.binary_op.left); exit(0); } int pid2 = fork(); if (pid2 < 0) user_panic("fork for pipe right failed"); if (pid2 == 0) { close(pipe_fds[1]); dup(pipe_fds[0], 0); close(pipe_fds[0]); execute_ast(node->data.binary_op.right); exit(0); } close(pipe_fds[0]); close(pipe_fds[1]); wait(pid1, NULL); wait(pid2, NULL); break; } case NODE_LIST_SEMI: execute_ast(node->data.binary_op.left); if (node->data.binary_op.right) execute_ast(node->data.binary_op.right); break; case NODE_LIST_AMP: child_pid = fork(); if (child_pid < 0) user_panic("fork for & failed"); if (child_pid == 0) { execute_ast(node->data.binary_op.left); exit(0); } if (node->data.binary_op.right) execute_ast(node->data.binary_op.right); break; case NODE_AND: execute_ast(node->data.binary_op.left); if (node->data.binary_op.right) execute_ast(node->data.binary_op.right); break; case NODE_OR: execute_ast(node->data.binary_op.left); if (node->data.binary_op.right) execute_ast(node->data.binary_op.right); break; default: user_panic("Unknown AST node type: %d", node->type); } }
char outbuf[20000]; char now_cmd_buf[1025];
int all_line_count; int now_line_index; char all_lines[25][1025]; char copy_buf[1024];
void readline(char *buf, u_int n, int interactive) { int r; u_int current_len; u_int cursor_pos; char c; u_int onscreen_cmd_len = 0;
if (n == 0) return;
if (history_current_nav_offset == 0) { mystrcpy(buf, current_typed_line); } else { int nav_idx_in_hist_array = (history_latest_idx - (history_current_nav_offset - 1) + HISTFILESIZE) % HISTFILESIZE; if (history_count > 0 && history_current_nav_offset <= history_count) { mystrcpy(buf, history_lines[nav_idx_in_hist_array]); } else { buf[0] = '\0'; } } current_len = mystrlen(buf); cursor_pos = current_len;
if (interactive && current_len > 0) { printf("\r$ "); for (u_int i = 0; i < current_len; ++i) printf("%c", buf[i]); onscreen_cmd_len = current_len; }
for (;;) { if ((r = read(0, &c, 1)) != 1) { if (r <= 0) { if (interactive && current_len == 0 && r == 0) printf("exit\n"); exit(0); } buf[current_len] = 0; return; }
int requires_full_reprint = 0;
if (c != 0x1b) { if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); history_current_nav_offset = 0; } }
if (c == 0x1b) { char seq[2]; if (read(0, &seq[0], 1) != 1) continue; if (seq[0] == '[') { if (read(0, &seq[1], 1) != 1) continue;
if (seq[1] == 'A') { if (history_count > 0) { if (history_current_nav_offset == 0) { mystrcpy(current_typed_line, buf); } if (history_current_nav_offset < history_count) { history_current_nav_offset++; int nav_idx_in_hist_array = (history_latest_idx - (history_current_nav_offset - 1) + HISTFILESIZE) % HISTFILESIZE; mystrcpy(buf, history_lines[nav_idx_in_hist_array]); current_len = mystrlen(buf); cursor_pos = current_len; requires_full_reprint = 1; } } } else if (seq[1] == 'B') { if (history_current_nav_offset > 0) { history_current_nav_offset--; if (history_current_nav_offset == 0) { mystrcpy(buf, current_typed_line); } else { int nav_idx_in_hist_array = (history_latest_idx - (history_current_nav_offset - 1) + HISTFILESIZE) % HISTFILESIZE; mystrcpy(buf, history_lines[nav_idx_in_hist_array]); } current_len = mystrlen(buf); cursor_pos = current_len; requires_full_reprint = 1; } } else if (seq[1] == 'D') { if (cursor_pos > 0) { cursor_pos--; requires_full_reprint = 1; } } else if (seq[1] == 'C') { if (cursor_pos < current_len) { cursor_pos++; requires_full_reprint = 1; } } } } else if (c == '\b' || c == 0x7f) { if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); history_current_nav_offset = 0; } if (cursor_pos > 0) { mymemmove(&buf[cursor_pos - 1], &buf[cursor_pos], current_len - cursor_pos + 1); cursor_pos--; current_len--; requires_full_reprint = 1; } } else if (c == 0x01) { if (cursor_pos != 0) { cursor_pos = 0; requires_full_reprint = 1;} } else if (c == 0x05) { if (cursor_pos != current_len) { cursor_pos = current_len; requires_full_reprint = 1;} } else if (c == 0x0B) { if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); history_current_nav_offset = 0; } if (cursor_pos < current_len) { buf[cursor_pos] = '\0'; current_len = cursor_pos; requires_full_reprint = 1; } } else if (c == 0x15) { if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); history_current_nav_offset = 0; } if (cursor_pos > 0) { mymemmove(&buf[0], &buf[cursor_pos], current_len - cursor_pos + 1); current_len -= cursor_pos; cursor_pos = 0; requires_full_reprint = 1; } } else if (c == 0x17) { if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); history_current_nav_offset = 0; } if (cursor_pos > 0) { u_int original_cursor_pos = cursor_pos; u_int end_of_deletion_span = cursor_pos; while (cursor_pos > 0 && strchr(" \t", buf[cursor_pos - 1])) cursor_pos--; u_int start_of_word_to_delete = cursor_pos; while (start_of_word_to_delete > 0 && !strchr(" \t", buf[start_of_word_to_delete - 1])) { start_of_word_to_delete--; } if (start_of_word_to_delete < end_of_deletion_span) { mymemmove(&buf[start_of_word_to_delete], &buf[end_of_deletion_span], current_len - end_of_deletion_span + 1); current_len -= (end_of_deletion_span - start_of_word_to_delete); cursor_pos = start_of_word_to_delete; requires_full_reprint = 1; } else { cursor_pos = original_cursor_pos; } } } else if (c == '\r' || c == '\n') { buf[current_len] = 0; if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); } else { mystrcpy(current_typed_line, buf); } if (interactive) printf("\n"); return; } else if (c >= 0x20 && c < 0x7f) { if (history_current_nav_offset != 0) { mystrcpy(current_typed_line, buf); history_current_nav_offset = 0; } if (current_len < n - 1) { if (cursor_pos < current_len) { mymemmove(&buf[cursor_pos + 1], &buf[cursor_pos], current_len - cursor_pos + 1); } buf[cursor_pos] = c; current_len++; cursor_pos++; requires_full_reprint = 1; } }
if (requires_full_reprint && interactive) { printf("\r"); printf("$ ");
for (u_int i = 0; i < current_len; ++i) { printf("%c", buf[i]); }
if (current_len < onscreen_cmd_len) { for (u_int i = 0; i < (onscreen_cmd_len - current_len); ++i) { printf(" "); } }
u_int effective_displayed_cmd_len = (current_len > onscreen_cmd_len) ? current_len : onscreen_cmd_len; for (u_int i = 0; i < (effective_displayed_cmd_len - cursor_pos); ++i) { printf("\b"); } onscreen_cmd_len = current_len; } } }
char input_buf[MAX_INPUT_BUF];
void usage(void) { printf("usage: sh [-ix] [script-file]\n"); exit(0); }
void load_history() { int fd, r, i; char line_buf[MAX_INPUT_BUF]; int line_len = 0; char c;
history_count = 0; history_add_idx = 0; history_latest_idx = -1;
fd = open(HISTORY_FILE, O_RDONLY); if (fd < 0) { return; }
char temp_history_load[HISTFILESIZE][MAX_INPUT_BUF]; int temp_count = 0;
while ((r = read(fd, &c, 1)) == 1) { if (c == '\n') { if (line_len > 0) { line_buf[line_len] = '\0'; if (temp_count < HISTFILESIZE) { mystrcpy(temp_history_load[temp_count++], line_buf); } else { for(i = 0; i < HISTFILESIZE - 1; ++i) { mystrcpy(temp_history_load[i], temp_history_load[i+1]); } mystrcpy(temp_history_load[HISTFILESIZE-1], line_buf); } line_len = 0; } } else if (line_len < MAX_INPUT_BUF - 1) { line_buf[line_len++] = c; } } if (line_len > 0) { line_buf[line_len] = '\0'; if (temp_count < HISTFILESIZE) { mystrcpy(temp_history_load[temp_count++], line_buf); } else { for(i = 0; i < HISTFILESIZE - 1; ++i) { mystrcpy(temp_history_load[i], temp_history_load[i+1]); } mystrcpy(temp_history_load[HISTFILESIZE-1], line_buf); } }
for (i = 0; i < temp_count; ++i) { mystrcpy(history_lines[history_add_idx], temp_history_load[i]); history_latest_idx = history_add_idx; history_add_idx = (history_add_idx + 1) % HISTFILESIZE; if (history_count < HISTFILESIZE) { history_count++; } } close(fd); history_current_nav_offset = 0; }
void save_history() { int fd, i, r; int start_idx;
fd = open(HISTORY_FILE, O_WRONLY | O_CREAT | O_TRUNC); if (fd < 0) { printf("sh: error saving history to %s\n", HISTORY_FILE); return; }
if (history_count == 0) { close(fd); return; }
if (history_count < HISTFILESIZE) { start_idx = 0; } else { start_idx = history_add_idx; }
for (i = 0; i < history_count; ++i) { int current_entry_idx = (start_idx + i) % HISTFILESIZE; r = write(fd, history_lines[current_entry_idx], mystrlen(history_lines[current_entry_idx])); if (r < 0) break; r = write(fd, "\n", 1); if (r < 0) break; } close(fd); }
void add_to_history(const char *cmd_line) { if ( cmd_line[0] == '\0') return;
if (history_count > 0 && mystrcmp(history_lines[history_latest_idx], cmd_line) == 0) { history_current_nav_offset = 0; return; }
mystrcpy(history_lines[history_add_idx], cmd_line); history_latest_idx = history_add_idx; history_add_idx = (history_add_idx + 1) % HISTFILESIZE; if (history_count < HISTFILESIZE) { history_count++; } history_current_nav_offset = 0; }
int main(int argc, char **argv) { init_shell_vars(); int interactive = iscons(0); int echocmds = 0; char *command_string_from_arg = NULL; int arg_idx_after_opts = 1;
if (argc > 1 && mystrcmp(argv[1], "-c") == 0) { if (argc > 2) { command_string_from_arg = argv[2]; interactive = 0; } else { printf("sh: -c option requires an argument\n"); exit(1); } } else if (argc > 1 && argv[1][0] != '-') { }
if (command_string_from_arg) { reset_allocators(); mystrcpy(input_buf, command_string_from_arg); if (echocmds) printf("+ %s\n", input_buf); const char* temp_scan = input_buf; while (*temp_scan && strchr(WHITESPACE, *temp_scan)) temp_scan++; if (*temp_scan != '#' && *temp_scan != '\0') { tokenizer_init(input_buf); ASTNode *ast = parse_line(); if (ast) execute_ast(ast); else if (input_buf[0] != '\0') printf("sh: syntax error in command string\n"); } exit(0); } if (!command_string_from_arg) { ARGBEGIN { case 'i': interactive = 1; break; case 'x': echocmds = 1; break; default: usage(); } ARGEND arg_idx_after_opts = ARGC(); } for (int i = arg_idx_after_opts; i < argc; ++i) { char *arg = argv[i]; if (arg[0] == '-' && (arg[1] == 'c' || arg[1] == 'i' || arg[1] == 'x')) { if (arg[1] == 'c' && i + 1 < argc) i++; continue; }
char *eq_ptr = strchr(arg, '='); if (eq_ptr && (eq_ptr != arg) && strchr(arg, '/') == NULL && strlen(arg) > 2) { char name[MAX_VAR_NAME_LEN + 1]; char value_buf[MAX_VAR_VALUE_LEN + 1]; int is_ro_flag = arg[0] - '0'; const char *name_start = arg + 1;
int name_len = eq_ptr - name_start; if (name_len > 0 && name_len <= MAX_VAR_NAME_LEN) { mystrncpy(name, name_start, name_len); name[name_len] = '\0'; if (mystrlen(eq_ptr + 1) <= MAX_VAR_VALUE_LEN) { mystrcpy(value_buf, eq_ptr + 1); set_variable(name, value_buf, 1, is_ro_flag, 0); } else { } } else { } arg_idx_after_opts = i + 1; } else { break; } }
if (argc > arg_idx_after_opts && !command_string_from_arg) { close(0); int r_open = open(argv[arg_idx_after_opts], O_RDONLY); if (r_open < 0) user_panic("open %s: %d", argv[arg_idx_after_opts], r_open); if (r_open != 0) { dup(r_open, 0); close(r_open); } interactive = 0; }
if (interactive){ printf("\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n"); printf(":: ::\n"); printf(":: MOS Shell (Command Control) ::\n"); printf(":: ::\n"); printf(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n"); }
load_history(); int first_prompt_cycle = 1;
for (;;) { reset_allocators(); memset(input_buf, 0, sizeof(input_buf));
if (interactive) { if (first_prompt_cycle) printf("\n$ "); else printf("$ "); }
if (history_current_nav_offset == 0) { current_typed_line[0] = '\0'; } readline(input_buf, sizeof input_buf, interactive);
if (input_buf[0] == '\0') { if (interactive) { first_prompt_cycle = 0; continue; } else { exit(0); } } first_prompt_cycle = 1;
if (echocmds) { printf("+ %s\n", input_buf); }
const char* temp_scan = input_buf; while (*temp_scan && strchr(WHITESPACE, *temp_scan)) temp_scan++; if (*temp_scan == '#' || *temp_scan == '\0') { first_prompt_cycle = 0; continue; }
add_to_history(input_buf); save_history(); tokenizer_init(input_buf); ASTNode *ast = parse_line();
if (ast) { execute_ast(ast); } else { if(input_buf[0] != '\0' && input_buf[0] != '#') { if (current_token.type != TOKEN_EOF && current_token.type != TOKEN_EOL && current_token.type != TOKEN_ERROR && current_token.type != 0 ) { printf("sh: syntax error near token '%s'\n", current_token.value); } else if (current_token.type == TOKEN_ERROR && current_token.value[0] != '\0'){ printf("sh: tokenizer error near '%s'\n", current_token.value); } else if (current_token.type != TOKEN_EOF && current_token.type != TOKEN_EOL){ printf("sh: syntax error\n"); } } } } return 0; }
int mystrncpy(char* dest, const char* src, int count) { char* start = dest; while (count && (*dest++ = *src++)) { count--; } if (count) { while (--count) { *dest++ = '\0'; } } return 0; }
int mystrncmp(const char *s1, const char *s2, int n) { size_t i = 0; if (n < 0) return 0; while (i < (size_t)n && s1[i] != '\0' && s2[i] != '\0') { if (s1[i] != s2[i]) { return (unsigned char)s1[i] - (unsigned char)s2[i]; } i++; } if (i < (size_t)n) { return (unsigned char)s1[i] - (unsigned char)s2[i]; } return 0; }
int mystrcmp(const char *str1, const char *str2) { while (*str1 && (*str1 == *str2)) { str1++; str2++; } return *(unsigned char *)str1 - *(unsigned char *)str2; }
int mystrcat(char* dest, const char* src) { char* ptr = dest; while (*ptr != '\0') ptr++; while ((*ptr++ = *src++) != '\0'); return 0; }
int mystrcpy(char* dest, const char* src) { while ((*dest++ = *src++) != '\0'); return 0; }
int mystrlen(const char *str) { size_t length = 0; while (str[length] != '\0') length++; return length; }
void init_shell_vars() { for (int i = 0; i < MAX_SHELL_VARS; ++i) { shell_vars[i].is_set = 0; shell_vars[i].name[0] = '\0'; shell_vars[i].value[0] = '\0'; shell_vars[i].is_exported = 0; shell_vars[i].is_readonly = 0; } num_set_vars = 0; }
ShellVar* find_variable(const char *name) { if (!name) return NULL; for (int i = 0; i < MAX_SHELL_VARS; ++i) { if (shell_vars[i].is_set && mystrcmp(shell_vars[i].name, name) == 0) { return &shell_vars[i]; } } return NULL; }
ShellVar* find_free_slot() { for (int i = 0; i < MAX_SHELL_VARS; ++i) { if (!shell_vars[i].is_set) return &shell_vars[i]; } return NULL; }
int set_variable(const char *name, const char *value, int export_flag, int readonly_flag, int update_flags_if_exists) { if (mystrlen(name) > MAX_VAR_NAME_LEN) return -1; if (value && mystrlen(value) > MAX_VAR_VALUE_LEN) return -1;
ShellVar *var = find_variable(name); if (var) { if (var->is_readonly) return -1; mystrcpy(var->value, value ? value : ""); if (update_flags_if_exists) { var->is_exported = export_flag; if (readonly_flag) var->is_readonly = 1; } } else { var = find_free_slot(); if (!var) return -1; mystrcpy(var->name, name); mystrcpy(var->value, value ? value : ""); var->is_exported = export_flag; var->is_readonly = readonly_flag; var->is_set = 1; num_set_vars++; } return 0; }
int unset_variable(const char *name) { ShellVar *var = find_variable(name); if (!var) return -1; if (var->is_readonly) return -1; var->is_set = 0; var->name[0] = '\0'; num_set_vars--; return 0; }
void print_all_variables() { for (int i = 0; i < MAX_SHELL_VARS; ++i) { if (shell_vars[i].is_set) { printf("%s%s%s=%s\n", shell_vars[i].is_exported ? "" : "", shell_vars[i].is_readonly ? "" : "", shell_vars[i].name, shell_vars[i].value); } } }
char* get_variable_value(const char *name) { ShellVar *var = find_variable(name); if (var && var->is_set) return var->value; return NULL; }
char *mystrchr(const char *str, char c) { while (*str) { if (*str == c) return (char *)str; str++; } if (c == '\0') return (char *)str; return NULL; }
void *mymemmove(void *dest, const void *src, int n) { unsigned char *d = (unsigned char *)dest; const unsigned char *s = (const unsigned char *)src; if (d < s) { for (int i = 0; i < n; i++) d[i] = s[i]; } else if (d > s) { for (int i = n; i > 0; i--) d[i - 1] = s[i - 1]; } return dest; }
|