Reputation: 150
Is there any computer program that can display on console or any other medium the instructions that composed it? Does any computer language have capabilities for this? Is it possible?
Upvotes: 0
Views: 603
Reputation: 364180
Its own source code?
Write a quine, techniques for which differ by language:
Or as Samuel shows, a program that opens its own source file via the filesystem.
Or output the machine instructions it compiles to?
For that, you can write a program that runs a disassembler on itself, like Linux objdump -drWC
(optionally with -Mintel
for x86). e.g. on Linux, argv[0]
is normally the command name. It might or might not be a full path, but that's enough for a toy program.
#include <spawn.h>
int main(){
posix_spawn(NULL, "/usr/bin/objdump", NULL, NULL, (char*[]){"objdump", "-drwC", "/proc/self/exe", NULL}, NULL);
// execution continues here; unlike execve we didn't replace our own process
// optional: waitpid(child_pid, &status, WUNTRACED | WCONTINUED);
}
I used posix_spawn
just to see how it works (and if it works with NULL for envp
like Linux execve
allows, and most of the other optional things including the child_pid). The system(3)
library function or fork
+exec*
system calls can do the equivalent.
(Linux /proc/self/exe
is always the current process's executable. But that would get objdump
to disassemble itself, not your program. /dev/fd/0
after your program redirects stdin from /proc/self/exe
would work.)
Upvotes: 0
Reputation: 21
You don't need to explicitly read the file in your program to achieve this. If you run the following command in Python it would also work:
def write_itself():
code = 'def write_itself():\n\t code = {!r}\n\t print(code.format(code)) \nwrite_itself()'
print(code.format(code))
write_itself()
Upvotes: 1
Reputation: 734
A short python example:
Assuming that the source code is in the file /path/to/file.py
#!/usr/bin/env python3
with open('/path/to/file.py') as file:
print(file.read())
This is a very contrived example, but it illustrates the point.
EDIT
By the definition of a quine this is technically cheating as it takes input by reading its own source file
Upvotes: 0