init.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <stdio.h>
  2. #include <syscall.h>
  3. #include <errno.h>
  4. #include <wait.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. void set_console(void) {
  8. int _stdin = syscall_open("/dev/ttyS0", 0, 0);
  9. int _stdout = syscall_open("/dev/ttyS0", 1, 0);
  10. int _stderr = syscall_open("/dev/ttyS0", 1, 0);
  11. if (_stdout < 0) {
  12. _stdout = syscall_open("/dev/null", 1, 0);
  13. _stderr = syscall_open("/dev/null", 1, 0);
  14. }
  15. (void)_stderr;
  16. (void)_stdin;
  17. }
  18. void set_hostname(void) {
  19. FILE * f = fopen("/etc/hostname", "r");
  20. if (!f) {
  21. /* set fallback hostname */
  22. sethostname("localhost", 4);
  23. } else {
  24. char tmp[128];
  25. fgets(tmp, 128, f);
  26. char * nl = strchr(tmp, '\n');
  27. if (nl) *nl = '\0';
  28. sethostname(tmp, strlen(tmp));
  29. }
  30. }
  31. int start_options(char * args[]) {
  32. int cpid = syscall_fork();
  33. if (!cpid) {
  34. char * _envp[] = {
  35. "LD_LIBRARY_PATH=/lib:/usr/lib",
  36. "PATH=/bin:/usr/bin",
  37. "USER=root",
  38. "HOME=/home/root",
  39. NULL,
  40. };
  41. syscall_execve(args[0], args, _envp);
  42. syscall_exit(0);
  43. } else {
  44. int pid = 0;
  45. do {
  46. pid = wait(NULL);
  47. if (pid == cpid) {
  48. break;
  49. }
  50. } while ((pid > 0) || (pid == -1 && errno == EINTR));
  51. }
  52. syscall_reboot();
  53. return 0;
  54. }
  55. int main(int argc, char * argv[]) {
  56. set_console();
  57. set_hostname();
  58. if (argc > 1) {
  59. if (!strcmp(argv[1], "--vga")) {
  60. return start_options((char *[]){"/bin/terminal-vga","-l",NULL});
  61. } else if (!strcmp(argv[1], "--migrate")) {
  62. return start_options((char *[]){"/bin/migrate",NULL});
  63. } else if (!strcmp(argv[1], "--headless")) {
  64. return start_options((char *[]){"/bin/getty",NULL});
  65. } else {
  66. /* Pass it to the compositor... */
  67. return start_options((char *[]){"/bin/compositor","--",argv[1],NULL});
  68. }
  69. }
  70. return start_options((char *[]){"/bin/compositor",NULL});
  71. }