weezy20/replace-exe
A smol Zig library that lets a running executable replace (or delete) itself.
A smol Zig library that lets a running executable replace (or delete) itself.
This can be used, for instance, in applications implementing a self update feature keeping the current installation path intact.
Only windows, linux, and unix like systems (macOS, *BSD) are supported.
zig fetch --save git+https://github.com/weezy20/replace-exe.git
const exe = b.addExecutable(.{
...
});
// Add the replace_exe dependency
const libreplace_exe = b.dependency("replace_exe", .{});
exe.root_module.addImport("replace_exe", libreplace_exe.module("replace_exe"));
selfReplace or selfDelete from your code:const re = @import("replace_exe");
// Replace current executable with a new one
try re.selfReplace(allocator, "path/to/new/executable");
// Warning: Deletes current executable
try re.selfDelete();
Two demo applications are provided in the demo folder:
demo.zig is version 1 and calls selfReplace to replace itself with demo2.zig
Build the demo applications with:
zig build -Ddemo
Then run the first demo exe:
./zig-out/bin/demo delete # self-delete
./zig-out/bin/demo replace ?</path/to/new/exe> # self-replace; default path is ./zig-out/bin/demo2
Building the library as a shared object or static library for use with C/C++:
# This builds a .so shared library like libreplace-exe.so that you can link against
zig build -Dcapi -Dso -Doptimization=ReleaseFast
# Or if you prefer a static library:
zig build -Dcapi -Doptimization=ReleaseFast
This will put the header file replace_exe.h and the shared or static library in the zig-out/include & zig-out/lib folders respectively.
Example usage in C (using dynamic library): See demo.c
gcc demo/demo.c -Izig-out/include -Lzig-out/lib -lreplace-exe -o test
LD_LIBRARY_PATH=zig-out/lib ./test /path/to/new/executable
LD_LIBRARY_PATH=zig-out/lib ./test
Or if you prefer go (using cgo): See demo/main.go for an example.
libreplace-exe.a or libreplace-exe.so:go build -o demo-go demo/main.go
./demo-go replace /path/to/new/executable