c - 内核开发、内存分配器和 kprintf() 奇怪的输出

标签 c pointers kernel

我目前正在开发一个小型内核项目,以了解有关系统开发的更多信息。我面临一个奇怪的错误:我刚刚制作并调试了一个简单的内存分配器(仅 kmalloc() 和 kfree() 函数),并且它工作得很好。当我打印 kmalloc() 返回的指针的地址时,除了 1 个指针之外,一切正常!当我打印该指针的地址两次(使用 kprintf("addr = %x (%x)", i64, i64))时,我看到“addr = 0000 (F018)”。 这是代码和输出:

Output on QEMU

CKernel.c:

#include "system.h"
#include "multiboot.h"
#include "util/util.h"
#include "cpu/cpu.h"
#include "video/video.h"
#include "memory/mem.h"

void kmain(multiboot_info_t* mbt)
{
    //Current status : 32 bits, protected mode
    //init
    vga_setup();
    gdt_install();
    idt_install(); //TODO : ISRs ! (actually the only interrupt handler is a method that just print "INTERRUPT" and iret)
    cpu_detect(); //TODO : Special handle INVALID_OPCODE
    //TODO : Install PAGING //Need basic DYNAMIC ALLOCATION
    //TODO : Install KHEAP

    u8* i8 = kmalloc(1, 0);
    *i8 = 244;
    kprintf("i8 = %d, addr = %X", *i8, i8);

    u32* i32 = kmalloc(sizeof(u32), 0);
    *i32 = 12;
    kprintf("i32 = %d, addr = %X", *i32, i32);

    kfree(i8);

    u64* i64 = kmalloc(sizeof(u64), 0);
    *i64 = 29999344;
    kprintf("i64 = %d, addr = %x (%X) (%x)", *i64, i64, i64, i64);
    kprintf("%d %x %X", i64, i64, i64);

    //Install ACPI
    //Install PIC
    //Install LAPIC / IOAPIC
    //Install FPU

    /*asm("   movb $0xFF, %al \n \
              outb %al, $0xA1 \n \
              outb %al, $0x21 \n");*/ //PIC DISABLING (DEBUG)
    //asm("sti"); //INTERRUPT ENABLING (DEBUG)
    //asm("int $0x0"); //INT CALL (DEBUG)

    //print done message, to see that everything went well
    kprint("[MAIN] DONE !", 1);

    //kprintf("Lower memory : %dk (0x%x)   Upper memory : %dk (0x%X)", mbt->mem_lower, mbt->mem_lower, mbt->mem_upper, mbt->mem_upper);

    //kter_install();

    //loop infinetely
    while(1) asm("hlt");
}

kmalloc.c:

#include "../system.h"
#include "util/util.h"

typedef struct
{
    u32 size;
    u8 status;
} __attribute__ ((packed)) block_header_t;

#define KHEAP_BASE_START 0xF000
#define KHEAP_BASE_END 0xFFFF

u8 base_heap_initialized = 0;

static void merge_free_blocks();

//Possible improvements : SECURITY : ADD a MAGIC number in the header, so that free() verify that it's a valid block (and malloc too)

void* kmalloc(u32 size, u8 align)
{
    u32 i;

    if(align == 0) align = size;

    //No need to merge as kfree() did it for us, right ?
    //merge_free_blocks();

    if(!base_heap_initialized)
    {
        block_header_t* base_block = (block_header_t*) KHEAP_BASE_START;
        base_block->size = KHEAP_BASE_END - (((u32) base_block) + sizeof(block_header_t));
        base_block->status = 0;
        base_heap_initialized = 1;
    }

    i = KHEAP_BASE_START;
    while(i < KHEAP_BASE_END)
    {
        block_header_t* currentBlock = (block_header_t*) i;
        //kprintf("Looking block at %X... (addr = %X) (size = %d) (status = %s)", i, i+sizeof(block_header_t), currentBlock->size, (currentBlock->status ? "RESERVED" : "FREE"));

        //Check if the current block is free and large enough
        if(!currentBlock->status && currentBlock->size >= size)
        {
            //Apply alignment contraints
            int am = 0;
            while((((u32)currentBlock)+sizeof(block_header_t)+am) % align != 0)
            {
                //kprint("Alignment : 1B used.", 0);
                am++;
                size++;
            }

            //Recheck size after alignment contraints
            if(currentBlock->size >= size)
            {
                int oldSize = currentBlock->size;
                if(oldSize - size > 5)
                {
                    currentBlock->size = size;
                    //Split the block if it is big
                    block_header_t* newblock = (block_header_t*) (i+sizeof(block_header_t)+currentBlock->size);
                    newblock->size = oldSize-size-5;
                    newblock->status = 0;
                    //kprintf("Setting up new block at %X (size = %d) (cbS = %d)", newblock, newblock->size, currentBlock->size);
                }
                //Mark the block as reserved
                currentBlock->status = 1;
                //Return the block
                //kprintf("Returning addr %X", ((u32) (((u32)currentBlock)+sizeof(block_header_t)+am)));
                return ((void*) ((u32)currentBlock)+sizeof(block_header_t)+am);
            }
        }
        //The current block did not match, skipping to next block
        i += (currentBlock->size+sizeof(block_header_t));
    }
    //Heap is full : returning null
    kprint("[GRAVE] [ERROR] The kernel HEAP is FULL ! Returned pointer to NULL !", 2);
    return ((void*) 0);
}

void kfree(void* pointer)
{
    block_header_t* blockHeader = (block_header_t*) (pointer - sizeof(block_header_t));
    blockHeader->status = 0;

    merge_free_blocks();
}

static void merge_free_blocks()
{
    block_header_t* currBlock;
    u32 i = KHEAP_BASE_START;

    while(i < KHEAP_BASE_END)
    {
        currBlock = (block_header_t*) i;
        if(!currBlock->status)
        {
            //Joining free regions
            block_header_t* nextBlock;
            while(!(nextBlock = (block_header_t*) i+sizeof(block_header_t)+currBlock->size)->status)
            {
                currBlock->size+= (sizeof(block_header_t)+nextBlock->size);
                i+=(sizeof(block_header_t)+nextBlock->size);
            }
            i += (sizeof(block_header_t)+((u32)currBlock));
        }
        else
            i+= (sizeof(block_header_t)+((u32)currBlock));
    }
}

kprintf() 函数:

static void vkprintf(const char* args, va_list ap)
{
    char buffer[32];

    vga_text_puts("[KERNEL] ", 0b00001111);
    while(*args)
    {
        if(*args == '%')
        {
            switch(*(++args))
            {
                case 'u':
                    utoa(va_arg(ap, u32), buffer);
                    vga_text_puts(buffer, 0b00000111);
                    break;
                case 'i': case 'd':
                    itoa(va_arg(ap, int32_t), buffer);
                    vga_text_puts(buffer, 0b00000111);
                    break;
                case 'X': /// TODO: make it standardized
                    i2hex(va_arg(ap, u32), buffer, 8);
                    vga_text_puts(buffer, 0b00000111);
                    break;
                case 'x':
                    i2hex(va_arg(ap, u32), buffer, 4);
                    vga_text_puts(buffer, 0b00000111);
                    break;
                case 'y':
                    i2hex(va_arg(ap, u32), buffer, 2);
                    vga_text_puts(buffer, 0b00000111);
                    break;
                case 's':
                    {
                        char* temp = va_arg(ap, char*);
                        vga_text_puts(temp, 0b00000111);
                        break;
                    }
                case 'c':
                    vga_text_putc((int8_t)va_arg(ap, int32_t), 0b00000111);
                    break;
                default:
                    vga_text_putc(*args, 0b00000111);
                    break;
            }
        }
        else
        {
            vga_text_putc(*args, 0b00000111);
        }

        args++;
    }
    vga_text_putc('\n', 0b00000111);
}

void kprintf(const char* args, ...)
{
    va_list ap;
    va_start(ap, args);
    vkprintf(args, ap);
    va_end(ap);
}

如果这不准确,我很抱歉,如果您需要更多详细信息,请告诉我...这个问题并不重要,因为指针似乎有正确的地址,但这很奇怪,我想知道为什么... 感谢您的阅读!

最佳答案

好的,问题解决了!这只是 u64 和我的所有 itoa() i2hex() 函数的一个错误:它们最多接受 32 位,因此缓冲区上仍然有 32 位,由 printf 而不是其他参数(地址)读取!感谢您的回答,一些程序员兄弟,您引导我找到了解决方案!

关于c - 内核开发、内存分配器和 kprintf() 奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45461578/

相关文章:

c++ - GCC 如何处理宏中的引号?

windows - WDK 10 - 无法以安装了 SDK7 的 Windows 7 为目标

c++ - 等待信号量的进程调度

operating-system - 为什么我们需要为每个 CPU 单独的内核堆栈

c - PIC32速度: Optimizing c code

c - LD_PRELOADing malloc 和 free

c++ - 在 C 或 C++ 中跟踪按键

c++ - 方法调用返回空值

c - [] 和 * 的位置

c - 指针NULL问题