News for hackers. Stuff that matters.
Re:On self-modifying executables in Rust by interroboink on Friday January 28, 2022 @06:19PM (#30121855)
EDIT: This is about modifying code in memory; the article is actually more about modifying the executable file on disk — oops (:

----

One example:

My understanding is that static initialization in C/C++ is sometimes done with self-modifying code.

Eg:

  ExpensiveObject &getInstance() {
      static ExpensiveObject obj;
      return obj;
  }
So, the first time through, the generated assembly would run some "if object is not initialized, run the constructor" conditional code. Then, it would rewrite itself to not do that check for subsequent calls.

Obviously, that's all in the "hidden behind the scenes" generated assembly code, and the rust compiler could pull similar tricks, but you might also want to allow client code to do such things, for extreme performance cases.

Re:On self-modifying executables in Rust by mmozeiko on Saturday January 29, 2022 @02:37AM (#30124551)
That's not really what's happening with such C++ code. `static` variables are placed in normal writeable global memory. Only difference with such static is that compiler generates extra "bool" variable and checks it to initialize obj only on first run (threadsafe on C++11 and up).

You can see example here: https://godbolt.org/z/7f1qbh5r5

There are no code modifications - all compiler generated is extra byte check ("if" statement) and then acquire/release lock around constructor to be threadsafe.

Re:On self-modifying executables in Rust by interroboink on Tuesday February 01, 2022 @11:39PM (#30173776)
Some more good discussion here: https://stackoverflow.com/questions/63568992/can-compilers-g...

I guess it's not commonplace these days, but it is still allowed, it seems. I feel like my initial run-in with the concept was on some embedded systems stuff long ago, so maybe that was a more esoteric compiler.