dlopen from memory?

后端 未结 4 814
故里飘歌
故里飘歌 2020-11-27 04:30

I\'m looking for a way to load generated object code directly from memory.

I understand that if I write it to a file, I can call dlopen to dynamically load its symbo

4条回答
  •  悲&欢浪女
    2020-11-27 04:51

    I needed a solution to this because I have a scriptable system that has no filesystem (using blobs from a database) and needs to load binary plugins to support some scripts. This is the solution I came up with which works on FreeBSD but may not be portable.

    void *dlblob(const void *blob, size_t len) {
        /* Create shared-memory file descriptor */
        int fd = shm_open(SHM_ANON, O_RDWR, 0);
        ftruncate(fd, len);
        /* MemMap file descriptor, and load data */
        void *mem = mmap(NULL, len, PROT_WRITE, MAP_SHARED, fd, 0);
        memcpy(mem, blob, len);
        munmap(mem, len);
        /* Open Dynamic Library from SHM file descriptor */
        void *so = fdlopen(fd,RTLD_LAZY);
        close(fd);
        return so;
    }
    

    Obviously the code lacks any kind of error checking etc, but this is the core functionality.

    ETA: My initial assumption that fdlopen is POSIX was wrong, this appears to be a FreeBSD-ism.

提交回复
热议问题