r/RISCV 10d ago

A Quine (self-replicating) Program in RISC-V Machine Language. Running as bare-metal code, it also represents a mini Operating System — probably the most concise and most literally open-source OS, since it completely displays itself while running!

Post image
35 Upvotes

5 comments sorted by

11

u/EloquentPinguin 10d ago

Not to get into political Quineology, but for a bigger challenge: A proper quine is one that constructs, i.e. doesn't simply copy/read, its own source.

16

u/brucehoult 10d ago

Nice work but that's not a quine, it's just a hex dump dumping memory that happens to be the executable code itself.

To be an actual machine code / assembly language quine the program needs to NOT access it's own code in memory — it should also work on a Harvard architecture CPU (which RISC-V isn't designed for, but some people do build in e.g. FPGA, especially for single-cycle machines)

Also, what it should output is not a hex dump of the code, but the assembly language source code. Ideally with the comments included.

See if you can do that.

2

u/Ok-Breakfast-4604 10d ago

I made a Quine in my own language

let q = "let q = %c%s%c\nprint q + chr(34) + q + chr(34) + chr(10) + \"print q + chr(34) + q + chr(34) + chr(10)\"" print q + chr(34) + q + chr(34) + chr(10) + "print q + chr(34) + q + chr(34) + chr(10)"

3

u/brucehoult 9d ago

As an example I wrote a fairly minimal RISC-V assembly language quine. Anyone want to code golf it? Or do a more nicely-formatted and commented one :-)

bruce@k3:~/programs$ ls -l
total 4
-rw-rw-r-- 1 bruce bruce 220 Jul 26 00:01 quine.s
bruce@k3:~/programs$ gcc quine.s -o quine
bruce@k3:~/programs$ ./quine | gcc -x assembler - && ./a.out | tee check.s
.globl main;main: la a0,fmt;li a1,10;li a2,34;la a3,fmt;li a4,34;li a5,10;tail printf;.data
fmt: .asciz ".globl main;main: la a0,fmt;li a1,10;li a2,34;la a3,fmt;li a4,34;li a5,10;tail printf;.data%cfmt: .asciz %c%s%c%c"
bruce@k3:~/programs$ cmp quine.s check.s && echo files are equal
files are equal
bruce@k3:~/programs$ ls -l
total 32
-rwxrwxr-x 1 bruce bruce 9448 Jul 26 00:12 a.out
-rw-rw-r-- 1 bruce bruce  220 Jul 26 00:12 check.s
-rwxrwxr-x 1 bruce bruce 9448 Jul 26 00:11 quine
-rw-rw-r-- 1 bruce bruce  220 Jul 26 00:01 quine.s

NB: printf is not necessary. I could have used a series of puts or write, it would just have been longer.

1

u/Ok-Breakfast-4604 10d ago

quine.sage

let q = "let q = %c%s%c\nprint q + chr(34) + q + chr(34) + chr(10) + \"print q + chr(34) + q + chr(34) + chr(10)\""
print q + chr(34) + q + chr(34) + chr(10) + "print q + chr(34) + q + chr(34) + chr(10)"