aboutsummaryrefslogtreecommitdiff
path: root/toys/main.c
blob: bd15d60222d4b649f0509208f6e961796cf0d983 (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
/* vi: set ts=4 :*/
/* Toybox infrastructure.
 *
 * Copyright 2006 Rob Landley <rob@landley.net>
 *
 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
 */

#include <stdio.h>
#include <strings.h>

/*
name
main()
struct
usage (short long example info)
path (/usr/sbin)
*/

int toybox_main(void)
{
	printf("toybox\n");
	return 0;
}

int toysh_main(void)
{
	printf("toysh\n");
}

// The monster fun applet list.

struct toy_list {
	char *name;
	int (*toy_main)(void);
} toy_list[] = {
	{"toybox", toybox_main},
	{"toysh", toysh_main}
};

// Global context for this applet.

struct toy_context {
	struct toy_list *which;
	int argc;
	char **argv;
	char buf[4096];
//	toy_union toydata;
} toys;

struct toy_list *find_toy_by_name(char *name)
{
	int top, bottom, middle;

	// If the name starts with "toybox", accept that as a match.  Otherwise
	// skip the first entry, which is out of order.

	if (!strncmp(name,"toybox",6)) return toy_list;
	bottom=1;

	// Binary search to find this applet.

	top=(sizeof(toy_list)/sizeof(struct toy_list))-1;
	for(;;) {
		int result;
		
		middle=(top+bottom)/2;
		if(middle<bottom || middle>top) return NULL;
		result = strcmp(name,toy_list[middle].name);
		if(!result) return toy_list+middle;
		if(result<0) top=--middle;
		else bottom=++middle;
	}
}

int main(int argc, char *argv[])
{
	char *name;

	// Record command line arguments.
	toys.argc = argc;
	toys.argv = argv;

	// Figure out which applet got called.
	name = rindex(argv[0],'/');
	if (!name) name = argv[0];
	else name++;
	toys.which = find_toy_by_name(name);

	if (!toys.which) {
		dprintf(2,"No behavior for %s\n",name);
		return 1;
	}
	return toys.which->toy_main();
}