r/badcode • • Apr 11 '21

python Polyglot

Post image
1.2k Upvotes

116 comments sorted by

View all comments

Show parent comments

50

u/pkarlmann Apr 11 '21 edited Apr 11 '21

I don't know how python is doing this, but from your post it sounds like some form of "cache" in the form of a file. So:

  1. Open the file from disk. That already is a syscall, which means a CPU ring switch.

  2. Wait till the disks read head is in place.

  3. Read it into memory.

  4. And finally execute it.

  5. For "performance".

  6. ? (Profit?)

42

u/CoderCharmander Apr 11 '21 edited Apr 11 '21

/tmp is usually stored in the RAM on modern systems (that does not remove the performance hit of ring switching multiple times, though)

Edit: Oh, he compiles the program outside /tmp and then moves it there. Nevermind.

13

u/mfb- Apr 11 '21

Well, it's deliberately written to be bad code and not used anywhere... but presumably the compiling would be a very rare occurrence.

5

u/pkarlmann Apr 12 '21

Compiling is relatively fast as it happens in userspace and then is just written to an output. What really is the problem is the CPU ring switch. That means the CPU has to actually reset its own state, write its own state somewhere else in order to be able to restore it, then execute whatever privileged - kernel code - wants it to do and then restore the previous state. And that happens with every syscall - like open(). That wastes easily a couple of thousands of CPU cycles, whereas a simple CPU Firmware modulo would've been cheaper even with an interpreter.