Would APEs work with D?
Raimondo Mancino
rmancino at gmail.com
Mon May 17 11:08:33 UTC 2021
Hello,
assuming that I have little experience with assembly, so I
couldn't check if the ape.S is actually compatible, and that I
also still have little experience with D:
I was reading [this very interesting
article](https://justine.lol/ape.html) and while reading it I had
the impression that it would be possible to produce D APEs.
It does require some ABI changes as far as I can tell, but I
think that excluding Phobos (since it would require more work to
get started) a simple hello world using
[Cosmopolitan](https://github.com/jart/cosmopolitan/) would do
the job (maybe we could have more complex code compiling with
`@pragma(mangle)` for ABI compatibility and interop).
If we look at Cosmopolitan's hello.c:
```c
/* Compile with:
gcc -g -O -static \
-fno-pie -no-pie -mno-red-zone -nostdlib -nostdinc \
-o hello.com hello.c \
-Wl,--oformat=binary -Wl,--gc-sections
-Wl,-z,max-page-size=0x1000 -fuse-ld=bfd \
-Wl,-T,ape.lds \
-include cosmopolitan.h \
crt.o ape.o cosmopolitan.a
*/
#include "libc/stdio/stdio.h"
int main() {
printf("%s\n", "hello world");
return 0;
}
```
My guess is that we could produce a portable executable with
Cosmopolitan and thus write something like this in our hello.d:
```d
/* I am not sure how would we compile this, but
* I guess it's going to be something like:
gdc -g -O -static \
-fno-pie -fuse-ld=bfd -mno-red-zone
-fno-druntime
-o hello.com hello.d
-Wl,--oformat=binary -Wl,--gc-sections
-Wl,-z,max-page-size=0x1000 -fuse-ld=bfd \
-Wl,-T,ape.lds
crt.o ape.o cosmopolitan.a
*/
@pragma(lib, "cosmopolitan"); // or in dub.sdl/.json
@nogc: // I am not sure whether the default GC would work
extern(C) int printf(const char*, ...) @trusted nothrow;
extern(C) int main() {
printf("%s\n", "hello world");
return 0;
}
```
If I understand correctly, the needed steps would be:
1. Build the binary
2. Write PE magic number
3. Write BIOS boot sector (if needed)
4. Write sh compatible execution script (load executable code
through qemu)
5. Write platform-specific sections and tables (ELF, *BSD, ...)
6. Put executable code and data sections
7. PKZIP magic (if needed)
What do you think about it?
More information about the D.gnu
mailing list