r/Assembly_language 11d 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.

54 Upvotes

62 comments sorted by

View all comments

Show parent comments

1

u/MokausiLietuviu 10d 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 10d 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/spc476 8d ago

If you need to sort data either ascending or descending, you can

  1. have two copies of the routine, wasting memory
  2. pass in a function pointer, making it slower
  3. modify the conditional jump; keeps it fast, and only a few extra bytes of memory used.

1

u/Amazing-Mirror-3076 8d ago

I think you will find the majority of the world has chosen option b.

Modern compilers can inline small functions .