首页 > 应用开发 > Java > 模拟CPU冷启动过程
/**
* CPU冷启动过程仿真
* 模拟从电源接通到操作系统加载的完整过程
*/public class CPUColdBootSimulator {
// CPU状态枚举
public enum CPUState {
RESET, REAL_MODE, PROTECTED_MODE, LONG_MODE, RUNNING, HALTED
}
// 寄存器组
public static class Registers { // 通用寄存器
public int eax, ebx, ecx, edx, esi, edi, ebp, esp; // 段寄存器
public int cs, ds, es, fs, gs, ss; // 控制寄存器
public int cr0, cr1, cr2, cr3, cr4; // 指令指针
public int eip; // 标志寄存器
public int eflags;
public void reset() {
eax = ebx = ecx = edx = esi = edi = ebp = 0;
esp = 0x7C00; // 初始栈指针
cs = 0xF000; // 复位向量段
ds = es = fs = gs = ss = 0;
eip = 0xFFF0; // 复位向量地址
eflags = 0x00000002; // 中断标志位关闭
cr0 = cr1 = cr2 = cr3 = cr4 = 0;
}
}
// 内存模拟
public static class Memory { private byte[] ram = new byte[1024 * 1024]; // 1MB模拟内存
public void initialize() { // 清零内存
for (int i = 0; i < ram.length; i++) {
ram[i] = 0;
}
// 设置BIOS ROM区域 (0xF0000 - 0xFFFFF)
initializeBIOS();
// 设置中断向量表 (0x00000 - 0x003FF)
initializeIVT();
}
private void initializeBIOS() { // 模拟BIOS代码
int biosBase = 0xF0000;
// 复位向量: JMP F000:E05B
writeByte(0xFFFF0, (byte)0xEA); // JMP far
writeByte(0xFFFF1, (byte)0x5B);
writeByte(0xFFFF2, (byte)0xE0);
writeByte(0xFFFF3, (byte)0x00);
writeByte(0xFFFF4, (byte)0xF0);
// BIOS入口点
String biosCode = "This is BIOS simulation area"; byte[] biosBytes = biosCode.getBytes(); for (int i = 0; i < biosBytes.length; i++) {
writeByte(biosBase + 0xE05B + i, biosBytes[i]);
}
}
private void initializeIVT() { // 设置中断向量表(前16个中断)
for (int i = 0; i < 16; i++) { int offset = i * 4; // 默认指向BIOS处理程序
writeWord(offset, 0xF000);
writeWord(offset + 2, 0xE000);
}
}
public byte readByte(int address) { if (address >= 0 && address < ram.length) { return ram[address];
} return 0;
}
public void writeByte(int address, byte value) { if (address >= 0 && address < ram.length) {
ram[address] = value;
}
}
public int readWord(int address) { return (readByte(address) & 0xFF) |
((readByte(address + 1) & 0xFF) << 8);
}
public void writeWord(int address, int value) {
writeByte(address, (byte)(value & 0xFF));
writeByte(address + 1, (byte)((value >> 8) & 0xFF));
}
public void loadBootSector(byte[] bootSector) { // 加载引导扇区到0x7C00
for (int i = 0; i < bootSector.length && i < 512; i++) {
writeByte(0x7C00 + i, bootSector[i]);
}
}
}
// BIOS模拟
public static class BIOS { private Memory memory; private Registers registers;
public BIOS(Memory memory, Registers registers) { this.memory = memory; this.registers = registers;
}
public void powerOnSelfTest() {
System.out.println("[BIOS] Power-On Self-Test (POST) starting...");
// 模拟硬件检测
simulateDelay(1000);
System.out.println("[BIOS] ✓ CPU detected");
simulateDelay(500);
System.out.println("[BIOS] ✓ Memory test: 640KB OK");
simulateDelay(300);
System.out.println("[BIOS] ✓ Video card initialized");
simulateDelay(200);
System.out.println("[BIOS] ✓ Keyboard controller ready");
// 检测引导设备
detectBootDevices();
System.out.println("[BIOS] POST completed successfully");
}
private void detectBootDevices() {
System.out.println("[BIOS] Detecting boot devices...");
String[] bootDevices = {"Floppy", "Hard Disk", "CD-ROM", "USB"}; for (String device : bootDevices) {
simulateDelay(100);
System.out.println("[BIOS] Checking " + device + "... OK");
}
// 设置引导顺序
System.out.println("[BIOS] Boot order: Floppy -> Hard Disk -> CD-ROM");
}
public boolean loadBootSector() {
System.out.println("[BIOS] Attempting to boot from Floppy...");
simulateDelay(800);
// 模拟读取引导扇区
byte[] bootSector = createBootSector();
memory.loadBootSector(bootSector);
// 验证引导扇区签名
int signature = memory.readWord(0x7DFE); if (signature == 0xAA55) {
System.out.println("[BIOS] ✓ Boot sector loaded successfully");
System.out.println("[BIOS] ✓ Valid boot signature found (0xAA55)"); return true;
} else {
System.out.println("[BIOS] ✗ Invalid boot signature: 0x" +
Integer.toHexString(signature)); return false;
}
}
private byte[] createBootSector() { byte[] sector = new byte[512];
// 简单的引导扇区代码
String bootCode = "Boot loader simulation - Stage 1"; byte[] codeBytes = bootCode.getBytes();
// 复制引导代码
for (int i = 0; i < codeBytes.length && i < 510; i++) {
sector[i] = codeBytes[i];
}
// 添加引导扇区签名
sector[510] = (byte)0x55;
sector[511] = (byte)0xAA;
return sector;
}
private void simulateDelay(int ms) { try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// CPU核心模拟
public static class CPU { private Registers registers = new Registers(); private Memory memory = new Memory(); private BIOS bios; private CPUState state = CPUState.RESET;
public CPU() { this.bios = new BIOS(memory, registers);
}
public void coldBoot() {
System.out.println("=== CPU COLD BOOT SEQUENCE STARTED ===");
// 阶段1: 复位
reset();
// 阶段2: BIOS初始化
biosInitialization();
// 阶段3: 引导加载
if (bootLoader()) { // 阶段4: 操作系统加载
loadOperatingSystem();
} else {
System.out.println("Boot failed! System halted.");
state = CPUState.HALTED;
}
System.out.println("=== CPU BOOT SEQUENCE COMPLETED ===");
}
private void reset() {
System.out.println("\n[CPU] Phase 1: Reset");
System.out.println("[CPU] Applying power...");
simulateDelay(100);
registers.reset();
memory.initialize();
System.out.println("[CPU] ✓ Registers initialized");
System.out.println("[CPU] ✓ Memory controller ready");
System.out.println("[CPU] Reset vector: F000:FFF0");
state = CPUState.REAL_MODE;
}
private void biosInitialization() {
System.out.println("\n[CPU] Phase 2: BIOS Initialization");
// 执行BIOS代码
bios.powerOnSelfTest();
System.out.println("[CPU] ✓ BIOS initialization complete");
System.out.println("[CPU] Jumping to boot loader...");
// 设置CS:IP指向引导扇区
registers.cs = 0x0000;
registers.eip = 0x7C00;
}
private boolean bootLoader() {
System.out.println("\n[CPU] Phase 3: Boot Loader");
if (!bios.loadBootSector()) { return false;
}
// 模拟引导加载器执行
System.out.println("[BootLoader] Stage 1 executing...");
simulateDelay(500);
System.out.println("[BootLoader] ✓ Real mode setup complete");
// 加载第二阶段引导程序
System.out.println("[BootLoader] Loading stage 2...");
simulateDelay(300);
// 切换到保护模式
System.out.println("[BootLoader] Switching to protected mode...");
enableProtectedMode();
System.out.println("[BootLoader] ✓ Protected mode active");
System.out.println("[BootLoader] ✓ Stage 2 loaded and executing");
return true;
}
private void enableProtectedMode() { // 设置保护模式位
registers.cr0 |= 0x1;
state = CPUState.PROTECTED_MODE;
// 更新段寄存器
registers.cs = 0x08; // 代码段选择子
registers.ds = registers.es = registers.ss = 0x10; // 数据段选择子
System.out.println("[BootLoader] CR0 = 0x" + Integer.toHexString(registers.cr0));
}
private void loadOperatingSystem() {
System.out.println("\n[CPU] Phase 4: Operating System Load");
System.out.println("[Kernel] Loading kernel image...");
simulateDelay(800);
System.out.println("[Kernel] ✓ Kernel loaded at 0x100000");
System.out.println("[Kernel] Initializing system services...");
simulateDelay(600);
System.out.println("[Kernel] ✓ Memory management initialized");
System.out.println("[Kernel] ✓ Process scheduler ready");
System.out.println("[Kernel] ✓ Device drivers loaded");
// 切换到长模式(64位)
if (enableLongMode()) {
System.out.println("[Kernel] ✓ 64-bit mode activated");
state = CPUState.LONG_MODE;
}
System.out.println("[Kernel] Starting init process...");
simulateDelay(400);
state = CPUState.RUNNING;
System.out.println("[Kernel] ✓ System fully operational");
// 显示系统信息
displaySystemInfo();
}
private boolean enableLongMode() { // 检查CPU是否支持长模式
System.out.println("[Kernel] Checking 64-bit support...");
simulateDelay(200);
// 模拟设置长模式
registers.cr0 |= 0x80000000;
registers.cr4 |= 0x20;
return true;
}
private void displaySystemInfo() {
System.out.println("\n=== SYSTEM INFORMATION ===");
System.out.println("CPU State: " + state);
System.out.println("Memory: 1024MB");
System.out.println("Boot Device: Virtual Floppy");
System.out.println("Kernel: JavaOS v1.0");
System.out.println("Architecture: x86_64");
}
private void simulateDelay(int ms) { try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 获取当前CPU状态
public CPUState getState() { return state;
}
public Registers getRegisters() { return registers;
}
public Memory getMemory() { return memory;
}
}
// 测试程序
public static void main(String[] args) {
System.out.println("Java CPU Cold Boot Simulator");
System.out.println("============================\n");
CPU cpu = new CPU();
cpu.coldBoot();
// 显示最终状态
System.out.println("\n=== FINAL CPU STATE ===");
System.out.println("CPU State: " + cpu.getState());
System.out.println("EIP: 0x" + Integer.toHexString(cpu.getRegisters().eip));
System.out.println("CR0: 0x" + Integer.toHexString(cpu.getRegisters().cr0));
}
}/**
* 引导加载器第二阶段模拟
*/public class BootLoaderStage2 {
public static class BootParams { public int memoryMapAddress; public int memoryMapEntries; public int bootDevice; public String commandLine;
public BootParams() { this.memoryMapAddress = 0x5000; this.memoryMapEntries = 10; this.bootDevice = 0x80; // 第一个硬盘
this.commandLine = "root=/dev/sda1 ro";
}
}
public static class KernelLoader {
public boolean loadKernel() {
System.out.println("[KernelLoader] Parsing kernel image...");
// 模拟ELF文件解析
if (!parseELFHeader()) { return false;
}
System.out.println("[KernelLoader] ✓ ELF header validated");
System.out.println("[KernelLoader] Loading kernel segments...");
// 加载代码段
loadCodeSegment(); // 加载数据段
loadDataSegment(); // 设置BSS段
setupBSS();
System.out.println("[KernelLoader] ✓ Kernel image loaded successfully"); return true;
}
private boolean parseELFHeader() { // 模拟ELF头验证
System.out.println("[KernelLoader] Checking ELF magic..."); // 这里应该检查实际的ELF魔数
return true;
}
private void loadCodeSegment() {
System.out.println("[KernelLoader] Loading .text segment at 0x100000"); // 模拟加载代码
}
private void loadDataSegment() {
System.out.println("[KernelLoader] Loading .data segment at 0x200000"); // 模拟加载数据
}
private void setupBSS() {
System.out.println("[KernelLoader] Zeroing .bss segment at 0x300000"); // 模拟清零BSS段
}
public void jumpToKernel(BootParams params) {
System.out.println("[KernelLoader] Transferring control to kernel...");
System.out.println("[KernelLoader] Entry point: 0x100000");
System.out.println("[KernelLoader] Boot params: " + params.commandLine);
// 这里在实际系统中会执行远跳转到内核入口点
System.out.println("[KernelLoader] ✓ Control transferred to kernel");
}
}
public static void simulateStage2Boot() {
System.out.println("\n=== BOOT LOADER STAGE 2 ===");
BootParams params = new BootParams(); KernelLoader loader = new KernelLoader();
if (loader.loadKernel()) {
loader.jumpToKernel(params);
} else {
System.out.println("[KernelLoader] ✗ Failed to load kernel");
}
}
public static void main(String[] args) {
simulateStage2Boot();
}
}# 编译所有Java文件javac CPUColdBootSimulator.java# 运行冷启动模拟java CPUColdBootSimulator# 运行第二阶段引导模拟java BootLoaderStage2
这个Java模拟程序提供了:
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048206/viewspace-3098645/ ,如需转载,请注明出处,否则将追究法律责任。