xref: /aosp_15_r20/external/toybox/toys/pending/bootchartd.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* bootchartd.c - bootchartd is commonly used to profile the boot process.
2  *
3  * Copyright 2014 Bilal Qureshi <[email protected]>
4  * Copyright 2014 Kyungwan Han <[email protected]>
5  *
6  * No Standard
7 
8 USE_BOOTCHARTD(NEWTOY(bootchartd, 0, TOYFLAG_STAYROOT|TOYFLAG_USR|TOYFLAG_BIN))
9 
10 config BOOTCHARTD
11   bool "bootchartd"
12   default n
13   depends on TOYBOX_FORK
14   help
15     usage: bootchartd {start [PROG ARGS]}|stop|init
16 
17     Record boot chart data into /var/log/bootlog.tgz
18 
19     start: start background logging; with PROG, run PROG,
20            then kill logging with SIGUSR1
21     stop:  send SIGUSR1 to all bootchartd processes
22     init:  start background logging; stop when getty/xdm is seen
23           (for init scripts)
24 
25     Under PID 1: as init, then exec $bootchart_init, /init, /sbin/init
26 */
27 
28 #define FOR_bootchartd
29 #include "toys.h"
30 
GLOBALS(char timestamp[32];long msec;int proc_accounting;pid_t pid;)31 GLOBALS(
32   char timestamp[32];
33   long msec;
34   int proc_accounting;
35 
36   pid_t pid;
37 )
38 
39 static void dump_data_in_file(char *fname, int wfd)
40 {
41   int rfd = open(fname, O_RDONLY);
42 
43   if (rfd != -1) {
44     xwrite(wfd, TT.timestamp, strlen(TT.timestamp));
45     xsendfile(rfd, wfd);
46     close(rfd);
47     xwrite(wfd, "\n", 1);
48   }
49 }
50 
dump_proc_data(FILE * fp)51 static int dump_proc_data(FILE *fp)
52 {
53   struct dirent *pid_dir;
54   int login_flag = 0;
55   pid_t pid;
56   DIR *proc_dir = opendir("/proc");
57 
58   fputs(TT.timestamp, fp);
59   while ((pid_dir = readdir(proc_dir))) {
60     char filename[64];
61     int fd;
62 
63     if (!isdigit(pid_dir->d_name[0])) continue;
64     sscanf(pid_dir->d_name, "%d", &pid);
65     sprintf(filename, "/proc/%d/stat", pid);
66     if ((fd = open(filename, O_RDONLY)) != -1 ) {
67       char *ptr;
68       ssize_t len;
69 
70       if ((len = readall(fd, toybuf, sizeof(toybuf)-1)) < 0) {
71         xclose(fd);
72         continue;
73       }
74       toybuf[len] = 0;
75       close(fd);
76       fputs(toybuf, fp);
77       if (TT.pid != 1) continue;
78       if ((ptr = strchr(toybuf, '('))) {
79         char *tmp = strchr(++ptr, ')');
80 
81         if (tmp) *tmp = 0;
82       }
83       // Checks for gdm, kdm or getty
84       if ((strchr("gkx", *ptr) && ptr[1] == 'd' && ptr[2] == 'm')
85         || strstr(ptr, "getty")) login_flag = 1;
86     }
87   }
88   closedir(proc_dir);
89   fputc('\n', fp);
90   return login_flag;
91 }
92 
parse_config_file(char * fname)93 static int parse_config_file(char *fname)
94 {
95   size_t len = 0;
96   char  *line = 0;
97   FILE *fp = fopen(fname, "r");
98 
99   if (!fp) return 0;
100   for (;getline(&line, &len, fp) != -1; line = 0) {
101     char *ptr = line;
102 
103     while (*ptr == ' ' || *ptr == '\t') ptr++;
104     if (!*ptr || *ptr == '#' || *ptr == '\n') continue;
105     if (strstart(&ptr, "SAMPLE_PERIOD=")) {
106       TT.msec = xparsemillitime(ptr);
107       if (TT.msec<1) TT.msec = 1;
108     } else if (strstart(&ptr, "PROCESS_ACCOUNTING="))
109       if (strstart(&ptr, "\"on\"") || strstart(&ptr, "\"yes\""))
110         TT.proc_accounting = 1;
111     free(line);
112   }
113   fclose(fp);
114 
115   return 1;
116 }
117 
create_tmp_dir()118 static char *create_tmp_dir()
119 {
120   char *dir_list[] = {"/tmp", "/mnt", "/boot", "/proc"}, **target = dir_list;
121   char *dir, dir_path[] = "/tmp/bootchart.XXXXXX";
122 
123   if ((dir = mkdtemp(dir_path))) {
124     xchdir((dir = xstrdup(dir)));
125 
126     return dir;
127   }
128   while (mount("none", *target, "tmpfs", (1<<15), "size=16m")) //MS_SILENT
129     if (!++target) perror_exit("can't mount tmpfs");
130   xchdir(*target);
131   if (umount2(*target, MNT_DETACH)) perror_exit("Can't unmount tmpfs");
132 
133   return *target;
134 }
135 
start_logging()136 static void start_logging()
137 {
138   struct timespec ts;
139   int sfd = xcreate("proc_stat.log",  O_WRONLY|O_CREAT|O_TRUNC, 0644),
140       dfd = xcreate("proc_diskstats.log",  O_WRONLY|O_CREAT|O_TRUNC, 0644);
141   FILE *proc_ps_fp = xfopen("proc_ps.log", "w");
142   long tcnt = 60 * 1000 / TT.msec;
143 
144   if (tcnt <= 0) tcnt = 1;
145   if (TT.proc_accounting) {
146     xclose(xcreate("kernel_procs_acct", O_WRONLY|O_CREAT|O_TRUNC, 0666));
147     acct("kernel_procs_acct");
148   }
149   while (--tcnt && !toys.signal) {
150     clock_gettime(CLOCK_BOOTTIME, &ts);
151     sprintf(TT.timestamp, "%ld.%02d\n", (long) ts.tv_sec,
152         (int) (ts.tv_nsec/10000000));
153     dump_data_in_file("/proc/stat", sfd);
154     dump_data_in_file("/proc/diskstats", dfd);
155     // stop proc dumping in 2 secs if getty or gdm, kdm, xdm found
156     if (dump_proc_data(proc_ps_fp))
157       if (tcnt > 2 * 1000 / TT.msec) tcnt = 2 * 1000 / TT.msec;
158     fflush(0);
159     msleep(TT.msec);
160   }
161   xclose(sfd);
162   xclose(dfd);
163   fclose(proc_ps_fp);
164 }
165 
stop_logging(char * tmp_dir,char * prog)166 static void stop_logging(char *tmp_dir, char *prog)
167 {
168   char host_name[32];
169   int kcmd_line_fd;
170   time_t t;
171   struct tm st;
172   struct utsname uts;
173   FILE *hdr_fp = xfopen("header", "w");
174 
175   if (TT.proc_accounting) acct(NULL);
176   if (prog) fprintf(hdr_fp, "profile.process = %s\n", prog);
177   gethostname(host_name, sizeof(host_name));
178   time(&t);
179   localtime_r(&t, &st);
180   memset(toybuf, 0, sizeof(toybuf));
181   strftime(toybuf, sizeof(toybuf), "%a %b %e %H:%M:%S %Z %Y", &st);
182   fprintf(hdr_fp, "version = TBX_BCHARTD_VER 1.0.0\n");
183   fprintf(hdr_fp, "title = Boot chart for %s (%s)\n", host_name, toybuf);
184   if (uname(&uts) < 0) perror_exit("uname");
185   fprintf(hdr_fp, "system.uname = %s %s %s %s\n", uts.sysname, uts.release,
186       uts.version, uts.machine);
187   memset(toybuf, 0, sizeof(toybuf));
188   if ((kcmd_line_fd = open("/proc/cmdline", O_RDONLY)) != -1) {
189     ssize_t len;
190 
191     if ((len = readall(kcmd_line_fd, toybuf, sizeof(toybuf)-1)) > 0) {
192       toybuf[len] = 0;
193       while (--len >= 0 && !toybuf[len]) continue;
194       for (; len > 0; len--) if (toybuf[len] < ' ') toybuf[len] = ' ';
195     } else *toybuf = 0;
196   }
197   fprintf(hdr_fp, "system.kernel.options = %s", toybuf);
198   close(kcmd_line_fd);
199   fclose(hdr_fp);
200   memset(toybuf, 0, sizeof(toybuf));
201   snprintf(toybuf, sizeof(toybuf), "tar -zcf /var/log/bootlog.tgz header %s *.log",
202       TT.proc_accounting ? "kernel_procs_acct" : "");
203   system(toybuf);
204 
205   // We created a tmpdir then lazy unmounted it, why are we deleting files...?
206   if (tmp_dir) {
207     unlink("header");
208     unlink("proc_stat.log");
209     unlink("proc_diskstats.log");
210     unlink("proc_ps.log");
211     if (TT.proc_accounting) unlink("kernel_procs_acct");
212     rmdir(tmp_dir);
213   }
214 }
215 
signal_pid(pid_t pid,char * name)216 static int signal_pid(pid_t pid, char *name)
217 {
218   if (pid != TT.pid) kill(pid, SIGUSR1);
219   return 0;
220 }
221 
bootchartd_main()222 void bootchartd_main()
223 {
224   pid_t lgr_pid;
225   int bchartd_opt = 0; // 0=PID1, 1=start, 2=stop, 3=init
226 
227   TT.pid = getpid();
228   TT.msec = 200;
229 
230   if (*toys.optargs) {
231     if (!strcmp("start", *toys.optargs)) bchartd_opt = 1;
232     else if (!strcmp("stop", *toys.optargs)) bchartd_opt = 2;
233     else if (!strcmp("init", *toys.optargs)) bchartd_opt = 3;
234     else error_exit("Unknown option '%s'", *toys.optargs);
235 
236     if (bchartd_opt == 2) {
237       char *process_name[] = {"bootchartd", NULL};
238 
239       names_to_pid(process_name, signal_pid, 0);
240       return;
241     }
242   } else if (TT.pid != 1) error_exit("not PID 1");
243 
244   // Execute the code below for start or init or PID1
245   if (!parse_config_file("bootchartd.conf"))
246     parse_config_file("/etc/bootchartd.conf");
247 
248   memset(toybuf, 0, sizeof(toybuf));
249   if (!(lgr_pid = xfork())) {
250     char *tmp_dir = create_tmp_dir();
251 
252     sigatexit(generic_signal);
253     raise(SIGSTOP);
254     if (!bchartd_opt && !getenv("PATH"))
255       putenv("PATH=/sbin:/usr/sbin:/bin:/usr/bin");
256     start_logging();
257     stop_logging(tmp_dir, bchartd_opt == 1 ? toys.optargs[1] : NULL);
258     return;
259   }
260   waitpid(lgr_pid, NULL, WUNTRACED);
261   kill(lgr_pid, SIGCONT);
262 
263   if (!bchartd_opt) {
264     char *pbchart_init = getenv("bootchart_init");
265 
266     if (pbchart_init) execl(pbchart_init, pbchart_init, NULL);
267     execl("/init", "init", (void *)0);
268     execl("/sbin/init", "init", (void *)0);
269   }
270   if (bchartd_opt == 1 && toys.optargs[1]) {
271     pid_t prog_pid;
272 
273     if (!(prog_pid = xfork())) xexec(toys.optargs+1);
274     waitpid(prog_pid, NULL, 0);
275     kill(lgr_pid, SIGUSR1);
276   }
277 }
278