1

I'm trying to write a function that has mmap within it, however when I try to access the memory from main(), it gets a segfault. Does anyone have any idea why?

Please ignore the MPI headers - it's for the later part of the project. I have commented out the mprotect line to see that it is an mmap fault as opposed to the handler not necessarily working

net_map.cpp:

#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "net_map.h"

using namespace std;

void handler(int sig, siginfo_t* info, void* other)
{
    void* address = info->si_addr;

    cout << "\nSegfault Detected! [Address: " << address << "]\n" << endl;

    int unprotectresult = mprotect(address, SIZE, PROT_READ|PROT_WRITE|PROT_EXEC);

    if (unprotectresult == 0)
    {
        cout << "\nSuccessful mprotect (memory unprotected)!\n" << endl;
    }else 
    {
        cout << "\nMprotect unsuccessful\n" << endl;
    }
}

void netmap (char filename[], char* mapped)
{
    int file;

    file = open(filename, O_RDWR);

    mapped = (char*) mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0);

    if (mapped == MAP_FAILED)
    {
        cout << "\nMap Failed!" << endl;
    }

    cout << mapped << endl;
}

main.cpp

#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <unistd.h>
#include <array>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <array>
#include "net_map.h"


using namespace std;

int main(int argc, char* argv[])
{

    struct sigaction segaction;

    memset(&segaction, 0, sizeof(segaction));
    segaction.sa_flags = SA_SIGINFO;
    sigemptyset(&segaction.sa_mask);
    segaction.sa_sigaction = handler;
    sigaction(SIGSEGV, &segaction, NULL);

    int i;

    char* mapped;

    networkpage sheet;

    char filename[] = "hello.txt";

    netmap(filename, mapped);

    sheet.address = (void*)mapped;

    cout << "\nAddress: " << sheet.address << endl;

    //mprotect(sheet.address, SIZE, PROT_NONE);

    memcpy(sheet.address, "k", 1);

    munmap(sheet.address, SIZE);

    return 0;
}
Paradowski
  • 719
  • 1
  • 13
  • 17
  • 1
    Your `netmap` function does not return mapped address - it assigns value to local parameter. You'd need to pass mapped pointer by pointer or reference, for it to work. You could also change it to just return the value. – yachoor Mar 20 '19 at 12:16
  • Thanks so much! Passed by reference and it's working perfectly now – Will James Mar 20 '19 at 12:51

0 Answers0