Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I load a library from a memory stream?

Tags:

c++

Can I load a library from a memory stream? For example my library is encoded a file. I check some conditions and decrypt the file into a memory stream. Now I need to load the decrypted library from that stream into my application and use its functions etc.

like image 688
Andrey Bushman Avatar asked Aug 20 '13 10:08

Andrey Bushman


People also ask

What is a memory stream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

How memory stream works in c#?

The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty.


1 Answers

In windows, A DLL can only be loaded from a file - as the links suggested, you can create a ramdisk and install that as a drive, but there is no way around the DLL needing to be loading through an file that exists in a filesystem. Part of the reason for this is that the DLL is "demand loaded", that is the system does not load the entire file into memory at once, it loads the parts that are actually being used, 4KB (typically) at a time. It is also not swapped out to the swap area, it is just discarded and re-loaded from the DLL if the system is running short of memory.

Linux works in a very similar way (I know it uses the same kind of demand-loading by default, but not sure if there is a way around it), so I don't believe there is any other way there either, but I haven't looked into it at depth.

Of course, if all you want is a piece of code that you can use in your application, and you want to store that as encrypted/compressed/whatever in your exectuable file, what you can do is allocate some executable memory (in Windows, you can use VirtualAlloc to allocate executable memory). However, you need to ensure that you relocate any absolute memory addresses in your code if you do that, so you will need to store the relocation information in your executable.

Clearly, the easy solution is to unpack your content into a file in the filesystem, and load from there.

like image 118
Mats Petersson Avatar answered Oct 20 '22 22:10

Mats Petersson