1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <sys/reboot.h>
5#include <sys/wait.h>
6#include <unistd.h>
7
8#include <cutils/android_reboot.h>
9#include <cutils/partition_utils.h>
10
11const char *mkfs = "/system/bin/make_ext4fs";
12
13int setup_fs(const char *blockdev)
14{
15    char buf[256], path[128];
16    pid_t child;
17    int status, n;
18    pid_t pid;
19
20        /* we might be looking at an indirect reference */
21    n = readlink(blockdev, path, sizeof(path) - 1);
22    if (n > 0) {
23        path[n] = 0;
24        if (!memcmp(path, "/dev/block/", 11))
25            blockdev = path + 11;
26    }
27
28    if (strchr(blockdev,'/')) {
29        fprintf(stderr,"not a block device name: %s\n", blockdev);
30        return 0;
31    }
32
33    snprintf(buf, sizeof(buf), "/sys/fs/ext4/%s", blockdev);
34    if (access(buf, F_OK) == 0) {
35        fprintf(stderr,"device %s already has a filesystem\n", blockdev);
36        return 0;
37    }
38    snprintf(buf, sizeof(buf), "/dev/block/%s", blockdev);
39
40    if (!partition_wiped(buf)) {
41        fprintf(stderr,"device %s not wiped, probably encrypted, not wiping\n", blockdev);
42        return 0;
43    }
44
45    fprintf(stderr,"+++\n");
46
47    child = fork();
48    if (child < 0) {
49        fprintf(stderr,"error: setup_fs: fork failed\n");
50        return 0;
51    }
52    if (child == 0) {
53        execl(mkfs, mkfs, buf, NULL);
54        exit(-1);
55    }
56
57    while ((pid=waitpid(-1, &status, 0)) != child) {
58        if (pid == -1) {
59            fprintf(stderr, "error: setup_fs: waitpid failed!\n");
60            return 1;
61        }
62    }
63
64    fprintf(stderr,"---\n");
65    return 1;
66}
67
68
69int main(int argc, char **argv)
70{
71    int need_reboot = 0;
72
73    while (argc > 1) {
74        if (strlen(argv[1]) < 128)
75            need_reboot |= setup_fs(argv[1]);
76        argv++;
77        argc--;
78    }
79
80    if (need_reboot) {
81        fprintf(stderr,"REBOOT!\n");
82        android_reboot(ANDROID_RB_RESTART, 0, 0);
83        exit(-1);
84    }
85    return 0;
86}
87