[erlang-questions] Loading a copy of a module under a different name

Dmitry Kolesnikov dmkolesnikov@REDACTED
Mon Jul 29 14:34:05 CEST 2019

Hello Luca,

I would not give you a straight answer about NIF but I know for sure it is not enough just to load Erlang module in cases of lists. You need to load native library as well.

Typically NIF module has an association with library http://erlang.org/doc/tutorial/nif.html <http://erlang.org/doc/tutorial/nif.html>.
Please note that lists is BIF module, you might not be able to re-bind it with other lib.

I would suggest you to study meck implementation. It deals a lot with module re-loading
https://github.com/eproxus/meck <https://github.com/eproxus/meck>
https://github.com/eproxus/meck/blob/master/src/meck_code.erl <https://github.com/eproxus/meck/blob/master/src/meck_code.erl>

Best Regards,

> On 29 Jul 2019, at 11.28, Luca Tansini <luca.tansini95@REDACTED> wrote:
> Hi all,
> I’m trying to load into the VM a copy of a module under a different name.
> The way I’m trying to do it is:
> 	- get the binary of the module with code:get_object_code(mod_name)
> 	- replace the module name inside the binary (otherwise the code loader won’t accept it)
> 	- reload it with code:load_binary(new_name, “”, RenamedBinary)
> here is some sample code showing the approach: https://pastebin.com/HpdUR0eU <https://pastebin.com/HpdUR0eU>.
> This approach seems to work as long as the original module doesn’t contain any NIFs.
> In that case the module is still loaded (not always, I’ve found at least one exception, more below), but then gives runtime errors when NIFs are trying to be run.
> For instance this is what happens with the lists module:
> >> module_cp:load_module_copy(lists).
> {module,xists}
> >> xists:seq(1,10).
> [1,2,3,4,5,6,7,8,9,10]
> >> xists:reverse([1,2,3,4]).
> ** exception error: undefined function erlang:nif_error/1
>      in function  xists:reverse/2 (xists.erl, line 95)
> For the erlang module instead, even the code loading fails:
> >> module_cp:load_module_copy(erlang).
> {error,badfile}
> =ERROR REPORT==== 26-Jul-2019::13:10:11 ===
> Loading of  failed: badfile
> =ERROR REPORT==== 26-Jul-2019::13:10:11 ===
> beam/beam_load.c(2284): Error loading function xrlang:garbage_collect/2: op bif0 u x:
>   no specific operation found
> I’m not very familiar with how NIFs work and are loaded, but is there a workaround for this?
> Maybe renaming only the module attribute is not enough.
> I’m on MacOS running Erlang/OTP 20 [erts-9.3].
> Thank you
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190729/7df7267b/attachment.htm>

More information about the erlang-questions mailing list