blob: b5a942cfb72ea2b1a859926885dd181b49416abb [file] [log] [blame]
Elliott Hughes59760182015-04-25 11:49:04 -07001#include <signal.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002#include <stdio.h>
3#include <stdlib.h>
4#include <string.h>
Elliott Hughes59760182015-04-25 11:49:04 -07005#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08006
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08007#define TOOL(name) int name##_main(int, char**);
8#include "tools.h"
9#undef TOOL
10
Elliott Hughesad2c07e2016-04-11 13:25:25 -070011static struct {
12 const char* name;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080013 int (*func)(int, char**);
14} tools[] = {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080015#define TOOL(name) { #name, name##_main },
16#include "tools.h"
17#undef TOOL
18 { 0, 0 },
19};
20
Elliott Hughes59760182015-04-25 11:49:04 -070021static void SIGPIPE_handler(int signal) {
22 // Those desktop Linux tools that catch SIGPIPE seem to agree that it's
23 // a successful way to exit, not a failure. (Which makes sense --- we were
24 // told to stop by a reader, rather than failing to continue ourselves.)
25 _exit(0);
26}
27
Elliott Hughesad2c07e2016-04-11 13:25:25 -070028int main(int argc, char** argv) {
Elliott Hughes59760182015-04-25 11:49:04 -070029 // Let's assume that none of this code handles broken pipes. At least ls,
30 // ps, and top were broken (though I'd previously added this fix locally
31 // to top). We exit rather than use SIG_IGN because tools like top will
32 // just keep on writing to nowhere forever if we don't stop them.
33 signal(SIGPIPE, SIGPIPE_handler);
34
Elliott Hughesad2c07e2016-04-11 13:25:25 -070035 char* cmd = strrchr(argv[0], '/');
36 char* name = cmd ? (cmd + 1) : argv[0];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080037
Elliott Hughesad2c07e2016-04-11 13:25:25 -070038 for (size_t i = 0; tools[i].name; i++) {
39 if (!strcmp(tools[i].name, name)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080040 return tools[i].func(argc, argv);
41 }
42 }
43
44 printf("%s: no such tool\n", argv[0]);
Elliott Hughes22b35672016-04-12 08:40:43 -070045 return 127;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046}
Elliott Hughesad2c07e2016-04-11 13:25:25 -070047
48int toolbox_main(int argc, char** argv) {
49 // "toolbox foo ..." is equivalent to "foo ..."
50 if (argc > 1) {
51 return main(argc - 1, argv + 1);
52 }
53
54 // Plain "toolbox" lists the tools.
55 for (size_t i = 1; tools[i].name; i++) {
56 printf("%s%c", tools[i].name, tools[i+1].name ? ' ' : '\n');
57 }
58 return 0;
59}