内核启动第一个应用程序

时间:2023-02-21 08:52:29

先列出代码:

static int noinline init_post(void)
{
	free_initmem();
	unlock_kernel();
	mark_rodata_ro();
	system_state = SYSTEM_RUNNING;
	numa_default_policy();

	if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
		printk(KERN_WARNING "Warning: unable to open an initial console.\n");

	(void) sys_dup(0);
	(void) sys_dup(0);

	if (ramdisk_execute_command) {
		run_init_process(ramdisk_execute_command);
		printk(KERN_WARNING "Failed to execute %s\n",
				ramdisk_execute_command);
	}

	/*
	 * We try each of these until one succeeds.
	 *
	 * The Bourne shell can be used instead of init if we are
	 * trying to recover a really broken machine.
	 */
	if (execute_command) {
		run_init_process(execute_command);
		printk(KERN_WARNING "Failed to execute %s.  Attempting "
					"defaults...\n", execute_command);
	}
	run_init_process("/sbin/init");
	run_init_process("/etc/init");
	run_init_process("/bin/init");
	run_init_process("/bin/sh");

	panic("No init found.  Try passing init= option to kernel.");
}

这个函数的流程:

sys_open((const char __user *) "/dev/console", O_RDWR, 0) 

(void) sys_dup(0);

(void) sys_dup(0);

上面三段代码首先打开/dev/console,然后复制2个相同的节点。这三个文件就用于标准输入,标准输出,标准错误

接下来:

	if (ramdisk_execute_command) {
		run_init_process(ramdisk_execute_command);
		printk(KERN_WARNING "Failed to execute %s\n",
				ramdisk_execute_command);
	}

ramdisk_execute_command 对应于:

static int __init rdinit_setup(char *str)
{
	unsigned int i;

	ramdisk_execute_command = str;
	/* See "auto" comment in init_setup */
	for (i = 1; i < MAX_INIT_ARGS; i++)
		argv_init[i] = NULL;
	return 1;
}
__setup("rdinit=", rdinit_setup);

执行bootargs中的"rdinit="的字段,而我们的bootargs为:bootargs=noinitrd root=/dev/mtdblock3 init=/linuxrc console=ttySAC0

没有发现,所以这段代码是没执行的。

接着分析:

if (execute_command) {
		run_init_process(execute_command);
		printk(KERN_WARNING "Failed to execute %s.  Attempting "
					"defaults...\n", execute_command);
	}


execute_command对应于:

static int __init init_setup(char *str)
{
 unsigned int i;

 execute_command = str;
 /*
  * In case LILO is going to boot us with default command line,
  * it prepends "auto" before the whole cmdline which makes
  * the shell think it should execute a script with such name.
  * So we ignore all arguments entered _before_ init=... [MJ]
  */
 for (i = 1; i < MAX_INIT_ARGS; i++)
  argv_init[i] = NULL;
 return 1;
}
__setup("init=", init_setup);

所以现在执行:run_init_process(“init=/linuxrc”);
注意:

只要run_init_process的参数是存在的,那么这个函数只要正常运行,就会一去不复返。如果挂接文件系统没有出错,到这里,第一个应用程序就可以启动了。