Compare commits

..

15 Commits

Author SHA1 Message Date
Michael
e9cf02e428 fix: flip decrement/increment on comparison
- this prevents wrapping size_t below 0
2026-10-13 21:11:20 +02:00
Michael
cfe3d40fc6 fix: move ownership of line to oldline
- set line to null when moved
- also, free line when loading from history
2026-10-13 21:09:18 +02:00
Michael
913449e500 fix: memory bug due to use of wrong line size 2026-10-13 21:00:05 +02:00
Michael
6672ecac58 fix: immediately continue when empty line is read 2026-10-13 20:45:29 +02:00
Michael
c8b5621df1 fix: when set, free oldline after reading line 2026-10-13 20:43:44 +02:00
Michael
37aab9b79b fix: only overwrite oldline when going up from last history position 2026-10-13 20:35:01 +02:00
Michael
ea1d6f617a feat: update readme 2026-10-10 01:52:11 +02:00
Michael
0794ed12ed feat: history browsing with arrow keys 2026-10-10 01:44:12 +02:00
Michael
a1df9fca4f fix: resize arrays as much as needed 2026-10-10 01:04:11 +02:00
Michael
a7cbe7b32c feat: history
- fix: move many things to heap
2026-10-10 00:49:26 +02:00
Michael
28d6123c4c feat: history file 2026-10-09 22:52:06 +02:00
Michael
2396e4c869 feat: pretty colors! 2026-10-09 16:41:04 +02:00
Michael
7dc85ea994 fix: programs inherit environ 2026-10-09 15:22:24 +02:00
Michael
4c150fe869 feat: add readme 2026-10-09 15:21:38 +02:00
Michael
9a82b590e7 feat: line editor 2026-10-09 15:04:13 +02:00
4 changed files with 613 additions and 35 deletions

View File

@@ -7,13 +7,15 @@ CFLAGS ?= -Wall
ifeq ($(RELEASE),true) ifeq ($(RELEASE),true)
CFLAGS += -O3 CFLAGS += -O3
else
CFLAGS += --debug
endif endif
.PHONY: clean .PHONY: clean grind release-$(RELEASE)
all: dist/msh all: dist/msh
dist/msh: $(SOURCES) dist dist/msh: $(SOURCES) dist release-$(RELEASE)
$(CC) -o $@ $(SOURCES) $(CFLAGS) $(CC) -o $@ $(SOURCES) $(CFLAGS)
dist: dist:
@@ -21,3 +23,6 @@ dist:
clean: clean:
rm -rf dist rm -rf dist
grind:
valgrind --leak-check=full --show-leak-kinds=all ./dist/msh

13
README.md Normal file
View File

@@ -0,0 +1,13 @@
# MSH
- a toy shell implementation in C
## What it can do
- handle text input
- run binaries
- change directory
- command history
## What it can't do
- any sort of scripting, variables
- memory safety

70
src/ansi.h Normal file
View File

@@ -0,0 +1,70 @@
#define ANSI_ESC "\x1b"
#define ANSI_FG_BLACK "\x1b[30m"
#define ANSI_FG_RED "\x1b[31m"
#define ANSI_FG_GREEN "\x1b[32m"
#define ANSI_FG_YELLOW "\x1b[33m"
#define ANSI_FG_BLUE "\x1b[34m"
#define ANSI_FG_PURPLE "\x1b[35m"
#define ANSI_FG_CYAN "\x1b[36m"
#define ANSI_FG_WHITE "\x1b[37m"
#define ANSI_FG_BLACK_BRIGHT "\x1b[90m"
#define ANSI_FG_RED_BRIGHT "\x1b[91m"
#define ANSI_FG_GREEN_BRIGHT "\x1b[92m"
#define ANSI_FG_YELLOW_BRIGHT "\x1b[93m"
#define ANSI_FG_BLUE_BRIGHT "\x1b[94m"
#define ANSI_FG_PURPLE_BRIGHT "\x1b[95m"
#define ANSI_FG_CYAN_BRIGHT "\x1b[96m"
#define ANSI_FG_WHITE_BRIGHT "\x1b[97m"
#define ANSI_FG_BLACK_BOLD "\x1b[1;30m"
#define ANSI_FG_RED_BOLD "\x1b[1;31m"
#define ANSI_FG_GREEN_BOLD "\x1b[1;32m"
#define ANSI_FG_YELLOW_BOLD "\x1b[1;33m"
#define ANSI_FG_BLUE_BOLD "\x1b[1;34m"
#define ANSI_FG_PURPLE_BOLD "\x1b[1;35m"
#define ANSI_FG_CYAN_BOLD "\x1b[1;36m"
#define ANSI_FG_WHITE_BOLD "\x1b[1;37m"
#define ANSI_FG_BLACK_BRIGHT_BOLD "\x1b[1;90m"
#define ANSI_FG_RED_BRIGHT_BOLD "\x1b[1;91m"
#define ANSI_FG_GREEN_BRIGHT_BOLD "\x1b[1;92m"
#define ANSI_FG_YELLOW_BRIGHT_BOLD "\x1b[1;93m"
#define ANSI_FG_BLUE_BRIGHT_BOLD "\x1b[1;94m"
#define ANSI_FG_PURPLE_BRIGHT_BOLD "\x1b[1;95m"
#define ANSI_FG_CYAN_BRIGHT_BOLD "\x1b[1;96m"
#define ANSI_FG_WHITE_BRIGHT_BOLD "\x1b[1;97m"
#define ANSI_BG_BLACK "\x1b[0;40m"
#define ANSI_BG_RED "\x1b[0;41m"
#define ANSI_BG_GREEN "\x1b[0;42m"
#define ANSI_BG_YELLOW "\x1b[0;43m"
#define ANSI_BG_BLUE "\x1b[0;44m"
#define ANSI_BG_PURPLE "\x1b[0;45m"
#define ANSI_BG_CYAN "\x1b[0;46m"
#define ANSI_BG_WHITE "\x1b[0;47m"
#define ANSI_BG_BLACK_BRIGHT "\x1b[0;100m"
#define ANSI_BG_RED_BRIGHT "\x1b[0;101m"
#define ANSI_BG_GREEN_BRIGHT "\x1b[0;102m"
#define ANSI_BG_YELLOW_BRIGHT "\x1b[0;103m"
#define ANSI_BG_BLUE_BRIGHT "\x1b[0;104m"
#define ANSI_BG_PURPLE_BRIGHT "\x1b[0;105m"
#define ANSI_BG_CYAN_BRIGHT "\x1b[0;106m"
#define ANSI_BG_WHITE_BRIGHT "\x1b[0;107m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define ANSI_UNKNOWN -1
#define ANSI_CURSOR_LEFT 0
#define ANSI_CURSOR_RIGHT 1
#define ANSI_CURSOR_UP 2
#define ANSI_CURSOR_DOWN 3
#define ANSI_DELETE_WORD 4
#define ANSI_CURSOR_LEFT_WORD 5
#define ANSI_CURSOR_RIGHT_WORD 6
#define ANSI_CURSOR_UP_WORD 7
#define ANSI_CURSOR_DOWN_WORD 8

554
src/msh.c
View File

@@ -7,12 +7,20 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <sys/utsname.h> #include <sys/utsname.h>
#include <errno.h> #include <errno.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "ansi.h"
#define ESC \x1B #define HISTORY_FILE_NAME "/history.log"
#define LOCAL_SHARE_DIRNAME "/.local/share/msh"
#define DEFAULTLINECAPACITY 256
#define DEFAULTTOKENSCAPACITY 64
#define DEFAULTHISTORYCAPACITY 128
const int LINESIZE = 512;
int cd(int argc, char** argv) { int cd(int argc, char** argv) {
if (argc != 1) { if (argc != 1) {
@@ -35,77 +43,499 @@ void pretty_path_home(char** path) {
} }
int main(int argc, char** argv) { int read_ansi() {
char* tokens[LINESIZE] = {}; switch (getchar()) {
char** args; case '[':
char line[LINESIZE] = {}; switch(getchar()) {
char* tokenwork; case 'A':
char* token; return ANSI_CURSOR_UP;
char* newline; case 'B':
int ntokens = 0; return ANSI_CURSOR_DOWN;
case 'C':
return ANSI_CURSOR_RIGHT;
case 'D':
return ANSI_CURSOR_LEFT;
case '1':
switch(getchar()) {
case ';':
switch(getchar()) {
// CTRL
case '5':
// ALT
case '3':
switch (getchar()) {
case 'C':
return ANSI_CURSOR_RIGHT_WORD;
case 'D':
return ANSI_CURSOR_LEFT_WORD;
}
break;
}
break;
}
break;
}
break;
case 127:
case 8:
return ANSI_DELETE_WORD;
default:
return ANSI_UNKNOWN;
}
return ANSI_UNKNOWN;
}
// Find the length of the prefix until the last occurrence of a rejected character
size_t strnrcspn(char* str, size_t n, char* reject) {
size_t i;
int seenaccept = 0;
for (i = n - 1; i > 0; i--) {
// If this is NOT a reject character
if(strchr(reject, str[i]) == NULL) {
seenaccept = 1;
continue;
} else {
if (seenaccept == 1) {
break;
}
}
}
return i;
}
// Find the length of the prefix until the first occurrence of a rejected character after an offset
size_t strnocspn(char* str, size_t n, size_t o, char* reject) {
size_t i;
int seenaccept = 0;
for (i = o; i < n; i++) {
// If this is NOT a reject character
if(strchr(reject, str[i]) == NULL) {
seenaccept = 1;
continue;
} else {
if (seenaccept == 1) {
break;
}
}
}
return i;
}
char* status_string(int status) {
switch (status) {
case 0:
return "";
}
return "❗";
}
int main(int argc, char** argv) {
int retval = 0;
char* line = NULL;
size_t linecapacity = 0;
char prompt[DEFAULTLINECAPACITY] = {};
size_t linelen = 0;
char* tokenwork = NULL;
size_t tokenworkcapacity = 0;
char** tokens = NULL;
size_t tokenscapacity = 0;
size_t ntokens = 0;
char** history = NULL;
size_t historycapacity = 0;
size_t historyi = 0;
size_t historyoffset = 0;
char* oldline = NULL;
int i;
int pid; int pid;
int laststatus = 0; int laststatus = 0;
int wstatus; int wstatus;
char pwd[LINESIZE] = {}; char pwd[DEFAULTLINECAPACITY] = {};
char* pwd_disp; char* pwd_disp;
char* user; char* user;
char* host; char* host;
struct utsname uts = {}; struct utsname uts = {};
char* sharedir = NULL;
char* historyfilepath = NULL;
FILE* historyfile = NULL;
user = secure_getenv("USER"); user = secure_getenv("USER");
int result = uname(&uts); int result = uname(&uts);
if (result != 0) { if (result != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno)); fprintf(stderr, "Error: %s\n", strerror(errno));
return errno; retval = errno;
goto cleanup;
} }
host = uts.nodename; host = uts.nodename;
struct termios term, orig_term;
tcgetattr(fileno(stdin), &term);
orig_term = term;
// disable echo and icanon (don't wait for newline)
term.c_lflag &= ~(ECHO | ICANON);
char* homedir = secure_getenv("HOME");
if (homedir == NULL) {
fprintf(stderr, "Error: $HOME is not specified\n");
retval = 1;
goto cleanup;
}
sharedir = malloc(strlen(homedir) + strlen(LOCAL_SHARE_DIRNAME) + 1);
if (sharedir == NULL) {
retval = 1;
goto cleanup;
}
sharedir = strcpy(sharedir, homedir);
if (sharedir == NULL) {
retval = 1;
goto cleanup;
}
sharedir = strcat(sharedir, LOCAL_SHARE_DIRNAME);
if (sharedir == NULL) {
retval = 1;
goto cleanup;
}
result = mkdir(sharedir, S_IRWXU);
if (result != 0 && errno != EEXIST) {
fprintf(stderr, "Error: %s\n", strerror(errno));
retval = 1;
goto cleanup;
}
historyfilepath = malloc(strlen(sharedir) + strlen(HISTORY_FILE_NAME) + 1);
if (historyfilepath == NULL) {
retval = 1;
goto cleanup;
}
historyfilepath = strcpy(historyfilepath, sharedir);
if (historyfilepath == NULL) {
retval = 1;
goto cleanup;
}
historyfilepath = strcat(historyfilepath, HISTORY_FILE_NAME);
if (historyfilepath == NULL) {
retval = 1;
goto cleanup;
}
int historyfilefd = open(historyfilepath, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR);
if (historyfilefd == -1) {
fprintf(stderr, "Error: could not open history file: %s\n", strerror(errno));
retval = 1;
goto cleanup;
}
historyfile = fdopen(historyfilefd, "w");
if (historyfile == NULL) {
fprintf(stderr, "Error: could not open history file fd: %s\n", strerror(errno));
retval = 1;
goto cleanup;
}
// Initialize memory
tokens = calloc(DEFAULTTOKENSCAPACITY, sizeof(char*));
if (tokens == NULL) {
retval = 1;
goto cleanup;
}
memset(tokens, 0, DEFAULTTOKENSCAPACITY * sizeof(char*));
tokenscapacity = DEFAULTTOKENSCAPACITY;
tokenwork = malloc(DEFAULTLINECAPACITY);
if (tokenwork == NULL) {
retval = 1;
goto cleanup;
}
tokenworkcapacity = DEFAULTLINECAPACITY;
historycapacity = DEFAULTHISTORYCAPACITY;
history = calloc(historycapacity, sizeof(char*));
if (history == NULL) {
retval = 1;
goto cleanup;
}
memset(history, 0, historycapacity);
// Main loop
while(1) { while(1) {
char* result = getcwd(pwd, LINESIZE - 1); char* result = getcwd(pwd, DEFAULTLINECAPACITY - 1);
if (result == NULL) { if (result == NULL) {
return 1; retval = 1;
goto cleanup;
} }
pwd_disp = pwd; pwd_disp = pwd;
pretty_path_home(&pwd_disp); pretty_path_home(&pwd_disp);
if (laststatus != 0) {
fprintf(stdout, "❌");
}
fprintf(stdout, "%s@%s %s$ ", user, host, pwd_disp);
char* fgets_res = fgets(line, LINESIZE, stdin);
if (fgets_res == NULL) { snprintf(
prompt,
DEFAULTLINECAPACITY,
ANSI_BG_BLUE ANSI_FG_BLACK
"%s" // status
" %s" // user
"@"
ANSI_FG_BLACK
"%s " // host
ANSI_COLOR_RESET ANSI_FG_BLUE
""
ANSI_FG_BLUE
"%s" // directory
ANSI_COLOR_RESET
"$ "
ANSI_COLOR_RESET,
status_string(laststatus), user, host, pwd_disp
);
printf("%s", prompt);
// prepare for input
linelen = 0;
int readc;
int cursor = 0;
tcsetattr(fileno(stdin), 0, &term);
line = malloc(DEFAULTLINECAPACITY);
linecapacity = DEFAULTLINECAPACITY;
memset(line, 0, linecapacity);
historyoffset = 0;
while ((readc = getchar()) != '\n') {
if (readc == EOF) {
printf("^D\n"); printf("^D\n");
return 0; retval = 0;
goto cleanup;
} }
newline = strrchr(line, '\n'); if (readc == '\x1b') {
if (newline != NULL) { int ansi = read_ansi();
newline[0] = 0; if (ansi == ANSI_CURSOR_LEFT) {
if (cursor > 0) {
cursor--;
}
} else if (ansi == ANSI_CURSOR_RIGHT) {
if (cursor < linelen) {
cursor++;
} }
for (tokenwork = line, i = 0; ; tokenwork = NULL, i++) { } else if (ansi == ANSI_CURSOR_UP || ansi == ANSI_CURSOR_DOWN) {
token = strtok(tokenwork, " \t"); int load_from_hist = 1;
if (ansi == ANSI_CURSOR_UP && historyoffset < historyi) {
historyoffset++;
if (historyoffset == 1) {
if (oldline != NULL) {
free(oldline);
}
oldline = line;
line = NULL;
}
} else if (ansi == ANSI_CURSOR_DOWN && historyoffset > 0) {
historyoffset--;
// We just went back to the last line, load from oldline
if (historyoffset == 0) {
free(line);
line = oldline;
linelen = strlen(line);
linecapacity = linelen + 1;
cursor = linelen;
oldline = NULL;
// Don't look up from history
load_from_hist = 0;
}
} else {
// We didn't change our line (already at top or bottom)
load_from_hist = 0;
}
if (load_from_hist == 1) {
char* historyline = history[historyi - (historyoffset)];
size_t historylinelen = strlen(historyline);
if (line != NULL) {
free(line);
}
line = malloc(historylinelen + 1);
if (line == NULL) {
retval = 1;
goto cleanup;
}
line = strcpy(line, historyline);
if (line == NULL) {
retval = 1;
goto cleanup;
}
cursor = historylinelen;
linecapacity = historylinelen + 1;
linelen = historylinelen;
}
} else if (ansi == ANSI_DELETE_WORD) {
if (cursor > 0) {
// 0123 56
size_t index = strnrcspn(line, cursor, " \t");
memmove(line + index, line + cursor, linecapacity - cursor);
linelen -= cursor - index;
cursor = index;
}
} else if (ansi == ANSI_CURSOR_LEFT_WORD) {
size_t index = strnrcspn(line, cursor, " \t");
cursor = index;
} else if (ansi == ANSI_CURSOR_RIGHT_WORD) {
size_t index = strnocspn(line, linelen, cursor, " \t");
cursor = index;
}
} else if (readc == 127) {
// backspace
if (cursor > 0) {
cursor--;
linelen--;
}
if (cursor == linelen) {
line[cursor] = 0;
} else {
memmove(line + cursor, line + cursor + 1, linecapacity - (cursor));
}
} else {
// We are typing
if (cursor != linelen) {
memmove(line + cursor + 1, line + cursor, linecapacity - cursor - 1);
}
line[cursor] = readc;
cursor++;
linelen++;
// Are we out of capacity? Double line length
while (linelen >= linecapacity - 1) {
linecapacity *= 2;
line = realloc(line, linecapacity);
if (line == NULL) {
fprintf(stderr, "Error: Failed to re-allocated line buffer");
retval = 1;
goto cleanup;
}
memset(line + linecapacity / 2, 0, linecapacity / 2);
}
}
// Manual echo
printf(ANSI_ESC "[2K" ANSI_ESC "[0G" "%s%s", prompt, line);
for (int j = 0; j < linelen - cursor; j++) {
printf(ANSI_ESC "[D");
}
fflush(stdout);
}
// oldline is only valid while reading
if (oldline != NULL) {
free(oldline);
oldline = NULL;
}
putc('\n', stdout);
tcsetattr(fileno(stdin), 0, &orig_term);
line[linelen] = 0;
if (linelen == 0) {
free(line);
line = NULL;
continue;
}
fprintf(historyfile, "%s\n", line);
fflush(historyfile);
while (tokenworkcapacity + 1 < linelen) {
tokenworkcapacity *= 2;
tokenwork = realloc(tokenwork, tokenworkcapacity);
}
memset(tokenwork, 0, tokenworkcapacity);
tokenwork = strncpy(tokenwork, line, linelen);
if (tokenwork == NULL) {
retval = 1;
goto cleanup;
}
while (historyi >= historycapacity) {
historycapacity *= 2;
history = reallocarray(history, historycapacity, sizeof(char*));
if (history == NULL) {
retval = 1;
goto cleanup;
}
memset(history + historyi, 0, (historycapacity - historyi) * sizeof(char*));
}
// change ownership of line to history
history[historyi++] = line;
line = NULL;
char* tokensarg = tokenwork;
ntokens = 0;
// Split into tokens
for (;; ntokens++) {
char* token = strtok(tokensarg, " \t");
if (token == NULL) { if (token == NULL) {
break; break;
} }
tokens[i] = token; tokens[ntokens] = token;
while (ntokens >= tokenscapacity - 1) {
tokenscapacity *= 2;
tokens = reallocarray(tokens, tokenscapacity, sizeof(char*));
}
// required to be NULL for second strtok invocation
if (tokensarg != NULL) {
tokensarg = NULL;
}
} }
ntokens = i;
tokens[ntokens] = NULL; tokens[ntokens] = NULL;
args = &tokens[1]; char** args = &tokens[1];
if (ntokens == 0) { if (ntokens == 0) {
continue; continue;
@@ -114,7 +544,8 @@ int main(int argc, char** argv) {
// Shell builtins // Shell builtins
if (strcmp("exit", tokens[0]) == 0) { if (strcmp("exit", tokens[0]) == 0) {
printf("Goodbye!\n"); printf("Goodbye!\n");
return 0; retval = 0;
goto cleanup;
} }
if (strcmp("cd", tokens[0]) == 0) { if (strcmp("cd", tokens[0]) == 0) {
@@ -122,17 +553,76 @@ int main(int argc, char** argv) {
continue; continue;
} }
if (strcmp("history", tokens[0]) == 0) {
for (int i = 0; i < historycapacity; i++) {
if (history[i] == NULL) {
break;
}
printf("%.3d: %s\n", i, history[i]);
}
laststatus = 0;
continue;
}
// Execute command // Execute command
pid = fork(); pid = fork();
if(pid == 0) { if(pid == 0) {
return execvpe(tokens[0], tokens, NULL); retval = execvpe(tokens[0], tokens, environ);
goto cleanup;
} else { } else {
waitpid(pid, &wstatus, 0); waitpid(pid, &wstatus, 0);
laststatus = WEXITSTATUS(wstatus); laststatus = WEXITSTATUS(wstatus);
} }
}
cleanup:
if (sharedir != NULL) {
free(sharedir);
}
if (historyfilepath != NULL) {
free(historyfilepath);
}
if (historyfile != NULL) {
fflush(historyfile);
fclose(historyfile);
}
if (line != NULL) {
free(line);
}
if (oldline != NULL) {
free(oldline);
}
if (tokenwork != NULL) {
free(tokenwork);
}
if (tokens != NULL) {
free(tokens);
}
if (history != NULL) {
for (int i = 0; i < historycapacity; i++) {
if (history[i] != NULL) {
free(history[i]);
} }
} }
free(history);
}
tcsetattr(fileno(stdin), 0, &orig_term);
return retval;
}