summaryrefslogtreecommitdiff
path: root/src/user/app/shell/builtins.c
blob: e272cf35b5613217a306a390469709ad8701e236 (plain)
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
#include "builtins.h"
#include "shell.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static void cmd_cat(int argc, const char **argv) {
	// TODO loop over argv

	FILE *file;
	static char buf[512];

	if (argv[1])
		file = fopen(argv[1], "r");
	else
		file = file_clone(stdin);

	if (!file) {
		eprintf("couldn't open");
		return;
	}

	for (;;) {
		int len = fread(buf, 1, sizeof buf, file);
		if (len <= 0) break;
		fwrite(buf, 1, len, stdout);
	}
	fclose(file);
}

static void cmd_echo(int argc, const char **argv) {
	bool newline = true;
	int i = 1;

	if (!strcmp("-n", argv[i])) {
		i++;
		newline = false;
	}

	printf("%s", argv[i++]);
	for (; argv[i]; i++)
		printf(" %s", argv[i]);
	if (newline)
		printf("\n");
}

void cmd_hexdump(int argc, const char **argv) {
	// TODO loop over argv
	// TODO use fopen/fread
	static uint8_t buf[512];
	int fd, len;

	fd = _syscall_open(argv[1], strlen(argv[1]), 0);
	if (fd < 0) {
		eprintf("couldn't open %s", argv[1]);
		return;
	}

	len = _syscall_read(fd, buf, sizeof buf, 0);
	for (int i = 0; i < len; i += 16) {
		printf("%08x  ", i);

		for (int j = i; j < i + 8 && j < len; j++)
			printf("%02x ", buf[j]);
		printf(" ");
		for (int j = i + 8; j < i + 16 && j < len; j++)
			printf("%02x ", buf[j]);
		printf(" |");

		for (int j = i; j < i + 16 && j < len; j++) {
			char c = '.';
			if (0x20 <= buf[j] && buf[j] < 0x7f) c = buf[j];
			printf("%c", c);
		}
		printf("|\n");
	}

	close(fd);
}

static void cmd_ls(int argc, const char **argv) {
	// TODO loop over argv
	FILE *file;
	static char buf[512];

	if (argv[1]) {
		int len = strlen(argv[1]);
		memcpy(buf, argv[1], len + 1); // TODO no overflow check

		if (buf[len-1] != '/') {
			buf[len] = '/';
			buf[len+1] = '\0';
		}

		file = fopen(buf, "r");
	} else {
		file = fopen("/", "r");
	}

	if (!file) {
		eprintf("couldn't open");
		return;
	}

	for (;;) {
		int len = fread(buf, 1, sizeof buf, file);
		if (len <= 0) break;
		for (int i = 0; i < len; i++)
			if (buf[i] == '\0') buf[i] = '\n';
		fwrite(buf, 1, len, stdout);
	}
	fclose(file);
}

static void cmd_touch(int argc, const char **argv) {
	// TODO loop over argv
	int fd = _syscall_open(argv[1], strlen(argv[1]), OPEN_CREATE);
	if (fd < 0) {
		eprintf("couldn't touch %s\n", argv[1]);
		return;
	}
	close(fd);
}

struct builtin builtins[] = {
	{"cat", cmd_cat},
	{"echo", cmd_echo},
	{"hexdump", cmd_hexdump},
	{"ls", cmd_ls},
	{"touch", cmd_touch},
	{NULL, NULL},
};