Qcloud1223 / COMP461905

Course project for Operating Systems at XJTU: A basic x86-64 dynamic linker.
13 stars 4 forks source link

mmap failed: Invalid argument #2

Closed free1ze closed 2 years ago

free1ze commented 2 years ago

environment: VMWare20, Ubuntu 16

enconter "Invalid argument" error using mmap(), printed by perror(). I was iteraing through the Program Headers, trying to map some space for PT_LOAD type segments. I always get this error the second time I call mmap(). My code here:

# MapLibrary.c
# ...
Elf64_Phdr *phdr = malloc(sizeof(Elf64_Phdr));
void *addr = NULL;
for(int i=0; i<ph_num; i++){
    <redacted>

    if(phdr->p_type == PT_LOAD){
        int prot = 0;
        prot |= (phdr->p_flags && PF_R)? PROT_READ : 0;
        prot |= (phdr->p_flags && PF_W)? PROT_WRITE : 0;
        prot |= (phdr->p_flags && PF_X)? PROT_EXEC : 0;
        <redacted>
        DEBUG_PRINT(("addr: %d\n", addr));

    #...
    }
}

and I get output like this

(gdb) r
Starting program: /work/COMP461905/build/run-openlib ./test_lib/SimpleMul.so multiply 1 2 3
addr: -134262784
mmap failed: Invalid argument   #error here
addr: -1

I wonder if it is because the wrong argument as indicated, or some other reasons like the defacts of VMWare virtual environment.

Qcloud1223 commented 2 years ago

Note that mmap is a quite tricky system call, and one of the goals of this project is to help you get more familiar with it.

A little detour from your question, you may want to check both your addr and len fed to mmap, because it want your required address to be page-aligned.

Your direct question comes from your output line DEBUG_PRINT(("addr: %d\n", addr));, where void* has a length of 8, while %d tries to interpret its upper 4 bytes. Remember the lecture when the teacher told you why having two weak definitions is a bad thing, because it could interpret int as a double and vice versa?

According to the man page of mmap, mmap will return -1 on failure, so you should think of other reasons when you see such an odd, unfriendly negative value.

You should turn to the man page to find out how to map the second segment, and that should not be discussed here.

Qcloud1223 commented 2 years ago

I wonder if it is because the wrong argument as indicated, or some other reasons like the defacts of VMWare virtual environment.

Also, we are not doing something quite sophisticated or hacking here, so do not blame the VM unless you are very very sure:)

free1ze commented 2 years ago

I get it. I did not align the offset to the page size, which will cause "Invalid argument" error using mmap(). APPRECIATE🌹