Catch exception thrown from memory references

By default an exception can only occur during a function call or a throw. If we needs to catch excpetions thrown from trapping instructions, using the `-fnon-call-exceptions`.



Generate code that allows trapping instructions to throw exceptions. Note that this requires platform-specific runtime support that does not exist everywhere. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as SIGALRM. 




using namespace std;

static void
sigsegv_handler (int signo)
    throw 0;

main (int argc, char *argv[])
    int *ptr = nullptr;
    int res;

    signal (SIGSEGV, sigsegv_handler);

    try {
        res = *ptr;
    } catch (...) {
        cout << "exception" << endl;

    return res;
g++ -fnon-call-exceptions -o sig sig.cpp


Load shared libraries with preferred base address

For performance, sometimes we need to adjust the address space layout. The following way allows the shared or executable object to be loaded with preferred base address.

When the dynamic link maps the shared object, the virtual address of segment(that in ELF program header) will be used as the mapping address hints.

Type 1
Link with text-segment starting address.

# Adjust base address to 0x10000 */
gcc -shared ... -Wl,-Ttext-segment=0x10000

Type 2
We can adjust the virtual address of loaded segment by linker scripts.

0x1 Get link script template

gcc -shared -Wl,--verbose > ld.script

Clear the contents before and after the ‘equal sign’.

0x2 Adjust the base address

    /* Adjust base address to 0x10000 */
    . = SEGMENT_START("text-segment", 0x10000) + SIZEOF_HEADERS;

0x3 Link with script

gcc -shared ... -Wl,-T ld.script