3030#include < android-base/file.h>
3131#include < android-base/logging.h>
3232
33+ static bool KernelConsolePresent (const std::string& cmdline) {
34+ size_t pos = 0 ;
35+ while (true ) {
36+ pos = cmdline.find (" console=" , pos);
37+ if (pos == std::string::npos) return false ;
38+ if (pos == 0 || cmdline[pos - 1 ] == ' ' ) return true ;
39+ pos++;
40+ }
41+ }
42+
43+ static bool SetupConsole () {
44+ if (mknod (" /dev/console" , S_IFCHR | 0600 , makedev (5 , 1 ))) {
45+ PLOG (ERROR) << " unable to create /dev/console" ;
46+ return false ;
47+ }
48+ int fd = -1 ;
49+ int tries = 50 ; // should timeout after 5s
50+ // The device driver for console may not be ready yet so retry for a while in case of failure.
51+ while (tries--) {
52+ fd = open (" /dev/console" , O_RDWR);
53+ if (fd != -1 ) break ;
54+ std::this_thread::sleep_for (100ms);
55+ }
56+ if (fd == -1 ) {
57+ PLOG (ERROR) << " could not open /dev/console" ;
58+ return false ;
59+ }
60+ ioctl (fd, TIOCSCTTY, 0 );
61+ dup2 (fd, STDIN_FILENO);
62+ dup2 (fd, STDOUT_FILENO);
63+ dup2 (fd, STDERR_FILENO);
64+ close (fd);
65+ return true ;
66+ }
67+
3368static void RunScript () {
3469 LOG (INFO) << " Attempting to run /first_stage.sh..." ;
3570 pid_t pid = fork ();
@@ -48,43 +83,25 @@ static void RunScript() {
4883namespace android {
4984namespace init {
5085
51- void StartConsole () {
52- if (mknod (" /dev/console" , S_IFCHR | 0600 , makedev (5 , 1 ))) {
53- PLOG (ERROR) << " unable to create /dev/console" ;
54- return ;
55- }
86+ void StartConsole (const std::string& cmdline) {
87+ bool console = KernelConsolePresent (cmdline);
88+
5689 pid_t pid = fork ();
5790 if (pid != 0 ) {
5891 int status;
5992 waitpid (pid, &status, 0 );
6093 LOG (ERROR) << " console shell exited with status " << status;
6194 return ;
6295 }
63- int fd = -1 ;
64- int tries = 50 ; // should timeout after 5s
65- // The device driver for console may not be ready yet so retry for a while in case of failure.
66- while (tries--) {
67- fd = open (" /dev/console" , O_RDWR);
68- if (fd != -1 ) {
69- break ;
70- }
71- std::this_thread::sleep_for (100ms);
72- }
73- if (fd == -1 ) {
74- LOG (ERROR) << " Could not open /dev/console, errno = " << errno;
75- _exit (127 );
76- }
77- ioctl (fd, TIOCSCTTY, 0 );
78- dup2 (fd, STDIN_FILENO);
79- dup2 (fd, STDOUT_FILENO);
80- dup2 (fd, STDERR_FILENO);
81- close (fd);
8296
97+ if (console) console = SetupConsole ();
8398 RunScript ();
84- const char * path = " /system/bin/sh" ;
85- const char * args[] = {path, nullptr };
86- int rv = execv (path, const_cast <char **>(args));
87- LOG (ERROR) << " unable to execv, returned " << rv << " errno " << errno;
99+ if (console) {
100+ const char * path = " /system/bin/sh" ;
101+ const char * args[] = {path, nullptr };
102+ int rv = execv (path, const_cast <char **>(args));
103+ LOG (ERROR) << " unable to execv, returned " << rv << " errno " << errno;
104+ }
88105 _exit (127 );
89106}
90107
0 commit comments