ARM Integrator-CP IRQ、Timer、PIC、任务、模块与 ELF32

来源:OSDev Wiki· 阅读原文 ↗

本页面或章节使用 I、我、我们 或 我们 来指代读者或编辑者。应予编辑,应改写为百科全书式的语气。

ARM Integrator-CP IRQ、Timer、PIC、任务、模块与 ELF32

页面 描述
IRQ、Timer 与 PIC 本演示仅使用 IRQ、Timer 和 PIC。
IRQ、Timer、PIC 与任务 本页展示如何使用定时器在任务之间切换,并在前一页的基础上构建。
IRQ、Timer、PIC、任务与 MM 本页展示如何集成虚拟内存,并在前一页的基础上构建。
带分页内核的虚拟内存 本页展示一种使内核空间分页的方法。

作者

我 Pancakes 编写本文,以帮助你快速入门使用 QEMU 甚至真实硬件进行 ARM 开发。我曾为模拟器和真实硬件编写过软件,但本文目前仅在 QEMU 上测试过。如发现问题,请进行任何必要的修改。另外,如果你觉得本文有用、有意见或建议,请通过 [email protected] 告知我。


简介

你应该来自前面的某个页面。如果你一直跟着做,我更推荐最后一个页面。好了,时刻已到。你现在已准备好了解一种附加模块的方法,甚至还有一个将 ELF32 模块加载到用户空间的演示。

首先我们将介绍将文件附加到内核镜像末尾的方法。然后我们将看看如何将 ELF32 模块加载到用户空间。

附加模块

Python 脚本

此脚本将模块填充到 32 位边界,以便读取时对齐,并插入特殊头部以便定位。头部包含若干字段,参见下方 C 代码中为该头部定义的结构体。模块可以通过 slots 字段在头部中呈现自己的字段。

#!/usr/bin/python3
import sys
import struct

def attach(srcf, dstf, typf):
	sfd = open(srcf, "rb")
	sfd.seek(0, 2)
	sz = sfd.tell()
	sfd.seek(0, 0)
	sd = sfd.read(sz)
	sfd.close()

	pad = len(sd) & 3
	if pad > 0:
		pad = 4 - pad
	else:
		pad = 0

	dfd = open(dstf, "r+b")
	dfd.seek(0, 2)
	psz = dfd.tell()
	ppad = psz & 3
	if ppad > 0:
		ppad = 4 - ppad
	else:
		ppad = 0
	dfd.write(b'B' * ppad)
	dfd.write(struct.pack('IIII', sz + pad, 0x12345678, 0xedcba987, int(typf)))
	dfd.write(sd)
	#print('sz+pad=%s' % (sz + pad))
	if pad > 0:
		dfd.write(b'A' * pad)
	#print('[ATTACHMOD] spad:%s tpad:%s %s [%s bytes] ----> %s (old sz:%s new sz:%s)' % (pad, ppad, srcf, sz, dstf,  hex(psz), hex(dfd.tell())))
	dfd.close()
	return sz

srcf = sys.argv[1]
dstf = sys.argv[2]
typf = sys.argv[3]

attach(srcf, dstf, typf)

要附加模块,你可以这样做:

    ./attachmod.py mymodule mykernelimage 1

其中 1 是一个 32 位整数值。我在下方的内核代码中使用值 1 来判断它是否为 ELF32 模块,如果是,则将其加载到新创建的用户地址空间中。

模块枚举代码

#ifndef KMOD_H
#define KMOD_H
#include "stdtypes.h"

typedef struct _KATTMOD {
	uint32			size;
	uint32			signatureA;
	uint32			signatureB;
	uint32			type;
	uint32			slot[];
} KATTMOD;

KATTMOD *kPkgGetNextMod(KATTMOD *mod);
KATTMOD *kPkgGetFirstMod();
uintptr kPkgGetTotalLength();
#endif

#include "kmod.h"

extern uint8 _EOI;

/*
	Get the next module after the specified module.
*/
KATTMOD *kPkgGetNextMod(KATTMOD *mod) {
	KATTMOD		*n;
	
	n = (KATTMOD*)((uintptr)mod + mod->size + sizeof(KATTMOD));
	
	/* make sure there actually exists another module after this one */
	if (n->signatureA != 0x12345678 || ~n->signatureA != n->signatureB) {
		kprintf("next mod not found\n");
		return 0;
	}
	
	return n;
}

uintptr kPkgGetTotalLength() {
	KATTMOD			*m, *lm;
	
	lm = 0;
	for (m = kPkgGetFirstMod(); m; m = kPkgGetNextMod(m)) {
		lm = m;
	}
	
	if (!lm) {
		return (uintptr)&_EOI;
	}
	
	return lm->size + (uintptr)lm + sizeof(KATTMOD) + 1;
}

/*
	Locate first module, if any exists, at end of our image.
*/
KATTMOD *kPkgGetFirstMod() {
	uint32		*p;
	uint32		x;
	uintptr		_p;
	
	_p = (uintptr)&_EOI - 4 * 20;
        /* OR... _p = (uintptr)&kPkgGetFirstMod - 4 * 20.. if not _EOI symbol 
      
          With GCC and -Os the code below might emit the signature. So you might
          need to create a dummy function below this one (should come after this
          one in text section), and reference that instead. With _EOI symbol you
          should have no problems unless this function appears with in the range
          and your using GCC -Os (optimize for size)
        */
	_p = _p & ~0x3;
	
	/* find signature of first module */
	for (p = (uint32*)_p, x = 0; x < 256; ++x) {
		/*
			This is a very tricky situation. We do not want the compiler
			to emit these sequence of bytes neither through an immediate
			operand or through optimization.
		*/
		if (p[x] == 0x12345678 && p[x + 1] == ~p[x]) {
			/* backup 32-bits (4 bytes) so we grab the size placed by attachmod.py */
			return (KATTMOD*)&p[x - 1];
		}
	}
	
	return 0;
}

枚举附加到镜像的模块:

        KATTMOD   *m;

	for (m = kPkgGetFirstMod(); m; m = kPkgGetNextMod(m)) {
        }

加载 ELF 模块

下面的代码是将 ELF32 加载到内存所需的绝对最小代码。它跳过了许多检查和其他高级特性。

ELF 二进制代码

int _start(unsigned int *smmio) {
	int		x;

	for (;;) {
		for (x = 0; x < 0xfffff; ++x);
		smmio[0] = 'G';
		smmio[0] = 'K';
	}
	return 0;
}

编译方法:

arm-eabi-gcc -nostdlib -nostartfiles -ffreestanding -std=gnu99 main.c -o main 
arm-eabi-ld main.o -o main -Ttext 0x80000000 -N


关于 -N 标志。LD 会生成较大的文件,其中各节的文件偏移等于虚拟地址。参见 https://sourceware.org/ml/binutils/2009-04/msg00099.html

内核代码

此处内核代码的第一部分假设你一直跟随本系列页面的其他页面。因此我不打算深入解释其中的大部分内容。但本质上,我会检查模块的类型是否为 KMODTYPE_ELFUSER,如果是,则找到一个空闲的任务槽,并将其交给一个执行镜像实际加载的函数。

	#define KMODTYPE_ELFUSER			1
	/*
		create a task for any attached modules of the correct type
	*/
	kprintf("looking at attached modules\n");
	for (m = kPkgGetFirstMod(); m; m = kPkgGetNextMod(m)) {
		kprintf("looking at module\n");
		if (m->type == KMODTYPE_ELFUSER) {
			/* find free task structure */
			for (x = 0; x < 0x10; ++x) {
				if (!ks->threads[x].valid) {
					break;
				}
			}
			
			if (x >= 0x10) {
				PANIC("out-of-task-slots");
			}
			
			kelfload(&ks->threads[x], (uintptr)&m->slot[0], m->size);
		}
	}

当然还有 kelfload 的实现。这只是一个非常简单的实现,仅作为演示将镜像载入内存,没有任何高级功能。

typedef uint16 Elf32_Half;
typedef uint32 Elf32_Word;
typedef uint32 Elf32_Off;
typedef uint32 Elf32_Addr;

#define EI_NIDENT 16
typedef struct {
        unsigned char   e_ident[EI_NIDENT];
        Elf32_Half      e_type;
        Elf32_Half      e_machine;
        Elf32_Word      e_version;
        Elf32_Addr      e_entry;
        Elf32_Off       e_phoff;
        Elf32_Off       e_shoff;
        Elf32_Word      e_flags;
        Elf32_Half      e_ehsize;
        Elf32_Half      e_phentsize;
        Elf32_Half      e_phnum;
        Elf32_Half      e_shentsize;
        Elf32_Half      e_shnum;
        Elf32_Half      e_shtrndx;
} ELF32_EHDR;

#define EM_ARM			40

typedef struct {
       Elf32_Word      sh_name;
       Elf32_Word      sh_type;
       Elf32_Word      sh_flags;
       Elf32_Addr      sh_addr;
       Elf32_Off       sh_offset;
       Elf32_Word      sh_size;
       Elf32_Word      sh_link;
       Elf32_Word      sh_info;
       Elf32_Word      sh_addralign;
       Elf32_Word      sh_entsize;
} ELF32_SHDR;

int kelfload(KTHREAD *th, uintptr addr, uintptr sz) {
	ELF32_EHDR			*ehdr;
	ELF32_SHDR			*shdr;
	uint32				x, y;
	uintptr				page, oldpage;
	KSTATE				*ks;
	uint8				*fb;
	
	kprintf("loading elf into memory space\n");
	
	ks = (KSTATE*)KSTATEADDR;
	
	ehdr = (ELF32_EHDR*)addr;
	if (ehdr->e_machine != EM_ARM) {
		kprintf("kelfload: not ARM machine!\n");
		return 0;
	}
	
	if (ehdr->e_ident[4] != 0x1) {
		kprintf("kelfload: not ELF32 object\n");
		return 0;
	}
	
	kvmm2_init(&th->vmm);
	th->pc = ehdr->e_entry;
	th->valid = 1;
	th->cpsr = 0x60000000 | ARM4_MODE_USER;
	/* set stack */
	th->sp = 0x90001000;
	/* pass address of serial output as first argument */
	th->r0 = 0xa0000000;
	/* map serial output mmio */
	kvmm2_mapsingle(&th->vmm, 0xa0000000, 0x16000000, TLB_C_AP_FULLACCESS);
	/* map stack page (4K) */
	kvmm2_allocregionat(&th->vmm, 1, 0x90000000, TLB_C_AP_FULLACCESS);

	/* map address space so we can work directly with it */
	kvmm2_getphy(&ks->vmm, (uintptr)th->vmm.table, &page);
	oldpage = arm4_tlbget1();
	arm4_tlbset1(page);
	/* flush TLB */
        asm("mcr p15, #0, r0, c8, c7, #0");

	// e_shoff - section table offset
	// e_shentsize - size of each section entry
	// e_shnum - count of entries in table
	for (x = 0; x < ehdr->e_shnum; ++x) {
		shdr = (ELF32_SHDR*)(addr + ehdr->e_shoff + x * ehdr->e_shentsize);
		if (shdr->sh_addr != 0) {
			/* load this into memory */
			// sh_offset - byte offset in module
			// sh_size - size of section in module 
			// sh_addr - address to load at
			kvmm2_allocregionat(&th->vmm, kvmm2_rndup(shdr->sh_size), shdr->sh_addr, TLB_C_AP_FULLACCESS);
			fb = (uint8*)(addr + shdr->sh_offset);
			/* copy */
			for (y = 0; y < shdr->sh_size; ++y) {
				((uint8*)shdr->sh_addr)[y] = fb[y];
			}
		}
	}
	
	/* restore previous address space */
	arm4_tlbset1(oldpage);
        /* flush the TLB */
        asm("mcr p15, #0, r0, c8, c7, #0");
}

当然它只是最小实现,但应该足以让你开始并改进它!

完整源码

你可以通过以下方式访问完整源码:

    git clone http://kmcg3413.net/armthin.git
    git checkout origin/bINT_TIMER_PIC_TASKS_VMM_MOD_ELF

head(master 分支)可能包含超出本页的更多工作。

继续深入

至此你几乎拥有一个功能完整的内核。你还缺少对设备驱动、服务等的更好支持。你也到了可以根据设计构建不同内核类型的阶段。你还缺少用于用户空间内存分配的系统调用。另外,你需要进程和线程,而不是我们现在这种更原始的类似任务的设计。另外,你需要正确处理用户空间的异常,例如终止出错的进程或线程。另外,同步原语以及定时器和睡眠等常见服务也缺失。不过,也许你并不需要这些,而且你有某种非常出色的设计!?好吧,我的建议是尽情编码!

你可以继续跟随我,也可以按自己的方向分支出去,但在下一页我们将创建实际的进程和线程,改进异常处理,并通过系统调用为线程添加几个基本服务。

由于没有更好的名称,继续前往 阶段 2。

来源与翻译说明

本文根据原文快照翻译,保留原有代码、数值、技术限定及历史背景。原文中的命令与运行结果不代表本站已实际执行验证。

原文:ARM Integrator-CP IRQTimerPICTasksMMAndMods;离线修订号:28001。对应原文版本

原作者:OSDev Wiki 社区贡献者。原文及引用资料的版权与许可声明继续适用:版权声明 许可说明

评论

暂无评论