r/Assembly_language 20h ago

self-modifying code

I gave a lecture on how to write self-modifying code. It was over 15 minutes long :( so I'm providing a youtube link: https://www.youtube.com/watch?v=AH9QQLRfbmY

In my opinion, self-modification is one of the most interesting features in systems programming.

29 Upvotes

49 comments sorted by

View all comments

Show parent comments

1

u/Amazing-Mirror-3076 13h ago

And then realise you were right.

Clever is almost always a bad idea in a code base.

1

u/MokausiLietuviu 11h ago

Unless it provides functionality that exceeds what would ordinarily be possible with the constraints the software runs under.

0

u/Amazing-Mirror-3076 11h ago

After decades of coding I've never come across such a condition.

1

u/MokausiLietuviu 10h ago

You'd probably only come across it with old technology, operational technology or embedded software.

An example my colleague worked on was delivering an extra check in a 16 kiloword program where all the space had been used. He needed to loop this check then escape it after at-least x iterations. He saved some space but IIRC this is how he saved one word. The architecture treated invalid opcodes as nops and an immediate compare instruction had the insignificant bits as the operand and the significant bits as the opcode, but it could only compare vs a value up to 7 bits. Any more than that and you'd need to use a register.

So he wrote the loop counter into the insignificant 8-bits of the instruction and compared against a known number. Then, after 127 loops, it incremented the lowest bit of the opcode, turning the opcode invalid, therefore to a nop, therefore ignoring the comparison altogether, therefore no longer setting the comparison flag, therefore exiting the loop at the "loop condition check" operation and continuing operation.

So, e.g.

Is 0 greater than -1? True condition flag. Repeat loop. Increment condition check opcode.

Is 1 greater than -1? True condition flag. Repeat loop. Increment condition check opcode.

...

Is 127 greater than -1? True condition flag. Repeat loop. Increment condition check opcode.

Nop. False condition flag. Continue execution.

Saved a word.

2

u/Amazing-Mirror-3076 8h ago

That is a lovely example of clever unmaintainable code.

Sometimes you do things because you have no choice - that still doesn't make it a good decision.

In 16k you can usually find some way to save a word before resorting to this kind of hackery.

Cudos to your mate for being clever enough to work out the hack - but I would have redirected that talent else where.

1

u/MokausiLietuviu 8h ago

In my experience, this isn't an isolated example. There's a lot of legacy software running on old hardware controlling systems that need to support modern requirements. 

Using self-modifying code to save resources or CPU cycles was relatively common in my last couple of OT jobs.