Segfault on mprotect increasing memory

58 Views Asked by At

I am working on a computer with 8GB of memory with Ubuntu 20.04. I read a 4 GB file into memory, and now I want to create a virtual memory buffer using the memory that remains after the 4GB file. After reading the 4GB file, System Monitor says I have approximately 2.5 GB available.

In order to know how much memory I can use under program control, I wrote a program that uses "less /proc/meminfo | grep MemAvailable" to determine available memory. That returns a value that very closely matches what System Monitor says is available.

I subtract an arbitrary 100MB because I don't want to use all available memory. That leaves just over 2.4GB for my buffer size. System Monitor says I have more than that available.

I create a virtual memory buffer with protection set to 10MB. I increase that to the requested size with mprotect:

int grow_mmap(void * address, size_t new_length) {

    int64_t ret_val = mprotect(address, new_length, PROT_READ | PROT_WRITE);

    char buf[1024];
    strcpy(buf, strerror(errno));
    printf("%d --> %s\n", errno, buf);  

    if (ret_val != 0) {
        printf("Error increasing memory: %s\n", strerror(errno)); }

    return ret_val;

}

But at the line "strcpy(buf, strerror(errno))" I get this segfault message:

Program received signal SIGSEGV, Segmentation fault. __GI___pthread_rwlock_rdlock (rwlock=0x7ffff7fa4980 <__libc_setlocale_lock>) at pthread_rwlock_rdlock.c:24 24 pthread_rwlock_rdlock.c: No such file or directory.

I query errno:

(gdb) p errno Program received signal SIGSEGV, Segmentation fault. __errno_location () at ../csu/errno-loc.c:25 25 ../csu/errno-loc.c: No such file or directory. The program being debugged was signaled while in a function called from GDB. GDB remains in the frame where the signal was received. To change this behavior use "set unwindonsignal on". Evaluation of the expression containing the function (__errno_location) will be abandoned. When the function is done executing, GDB will silently stop.

If I lower the requested amount to 100 MB or 500 MB then it succeeds.

I have used this program many times, but never with a buffer size > 500MB.

So my question is: under the circumstances described above, how can I determine how much of the available memory I can use with mprotect? This is mission critical software, so no other userspace programs are running that would use memory.

Thanks for any help.

0

There are 0 best solutions below