Author Topic: Question about compressed programs  (Read 966 times)

0 Members and 4 Guests are viewing this topic.

Offline lis05Topic starter

  • Contributor
  • Posts: 14
  • Country: pl
    • Github
Question about compressed programs
« on: November 25, 2026, 03:31:44 pm »
Hello,

I have an idea for a new compression system that could help reduce size of program code. It would work by first compressing the entire program code, then adding a small interpreter that would read the compressed program instruction by instruction (decompressing each instruction on the fly), and then interpret that instruction.

Cool thing about this idea is that, because the interpreter can work with, in theory, any language it interprets, this system can be made crossplatform. The host MCU may be running on ARM, while the compressed program is compiled for RV32I (it is super simple, has base 40 instructions, so the interpreter is very tiny).

It preserves 100% functional correctness: it works with native symbols, it works with native code using functions from compressed code (by adding stubs which invoke the interpreter when called). It also uses very little ram, practically constant amount.

The core condition that this system has to satisfy is I + C < O, where I is the size of the interpreter program, C is the size of the compressed program, and O is the size of the original uncompressed program.

The drawback of this system: it is going to be slow. I am talking 20x - 800x slower than the original, uncompressed program. So in my opinion it is only feasible for cold-path code like logging, errors, one-time parsing of some configuration files, etc.

My question to experienced people working with constrained devices: would this be actually usable, and would the performance / risk of using an interpreter be acceptable? Under what conditions?

=========

P.S. I have already prototyped this privately for RV32EC compressed code on RV32IC device,  but it is currently very... raw... as it was more of an experiment. Some numbers: it can run lua(108KiB) 30x slower (saving 20KiB) or 350x slower (saving 30KiB); it can also run https://github.com/paladin-t/my_basic(178KiB) 78x slower (saving 58KiB) or 600x slower (saving 75KiB). Basically, it can save a lot of memory, but is very slow.
 

Offline lis05Topic starter

  • Contributor
  • Posts: 14
  • Country: pl
    • Github
Re: Question about compressed programs
« Reply #1 on: November 25, 2026, 03:33:54 pm »
I should also add that the threshold of where using compressed code becomes actually beneficial is around 30-40KiB of original program. The interpreter + decompressor can be as tiny as 3-4KiB
 

Online fchk

  • Frequent Contributor
  • **
  • Posts: 429
  • Country: de
Re: Question about compressed programs
« Reply #2 on: November 25, 2026, 06:14:55 pm »
Your suggestion reminds me of Forth systems. In Forth you have 'words', instructions. The most basic ones are implemented in native code. Everything else uses these. The whole thing runs in what is called a Forth machine, a small virtual machine running the byte code.

https://en.wikipedia.org/wiki/Forth_(programming_language)

This programming language is more than 40 years old and designed in the 8 bit era with its limitations in mind and was used in many applications and on many architectures. Since you expand the opcode set by create new words using old ones you get a higher level of abstraction and higher code density as by simply compressing simple machine instrctions.

And yes, it's a way of programming you most likely are not used to, but just this makes it so incredible efficient.
 

Offline lis05Topic starter

  • Contributor
  • Posts: 14
  • Country: pl
    • Github
Re: Question about compressed programs
« Reply #3 on: November 25, 2026, 06:20:40 pm »
That's interesting, indeed close to what I explained. Although there is one difference, Forth requires you to write in Forth. My idea was based around processing original, 100% unmodified object files. So basically, everything compiled for risc-v will be able to run after it is processed by this system, so it can work with C, assembly, Rust etc
 

Offline nimish

  • Regular Contributor
  • *
  • Posts: 213
  • Country: us
Re: Question about compressed programs
« Reply #4 on: November 25, 2026, 06:22:40 pm »
This is what self extracting archives use, no? Staple a decompressor to the zip file.

Or, simply interpreted programming languages could be this. "Compress" your C into a much smaller scripting lang at the cost of adding the interpreter to your program. You've basically invented the rationale behind the (J)VM.

Likely something that needs tuning and measuring for every single problem.
 

Online Siwastaja

  • Super Contributor
  • ***
  • Posts: 11472
  • Country: fi
Re: Question about compressed programs
« Reply #5 on: November 25, 2026, 07:12:08 pm »
Compressed firmware images are a thing, but only when the issue is lack of flash memory but there's abundance of RAM. Most common MCU configuration is 5-10x more flash than RAM so whole program compression with boot-time decompress doesn't make sense. So that leaves special systems e.g. with external RAM but no or little external flash.

So I guess you are after a bufferless (or small buffer) program compression? Something that decompresses on the fly while program runs? There, use cases would be plentiful, you could use that smaller MCU with less flash to do more, and wouldn't hit the RAM limit while doing so. The problem is speed, and that I believe is serious enough. Whole-program decompress into RAM buffer only incurs boot delay, after that running from RAM is at least as fast, sometimes faster than from flash. But if you are going to decompress instruction by instruction it would become so slow that you would need to limit the mechanism to some slow functions only. Which means you would need to identify these functions. While performance isn't always critical, I can see your run-time decompress would be so slow that even functions we usually don't think as performance critical would become too slow, so correct identification would matter, you couldn't just put 98% into the slow, compressed region and hand-pick a few special ISRs.

Besides, machine code (ARM, RISC-V, whatever) is relatively space-efficient already, so the gain isn't huge. Of course some instructions and patterns repeat. But if you can take 50% off from 50% of the codebase, that's just 25%, ignoring the decompressor's flash use.

And, compressing part of the project might well mean that stuff like Link-Time Optimization has less to work with, so it might end up eating into the gains, or worst case, net-negative.

The main use case for ideas like this is salvaging a project that needs to run on undersized hardware. Usually on embedded projects sizing the memory of the system isn't too difficult - handwave an approximation and get two notches larger device even if it costs $2 more. Expecting to build a 50-60K firmware? Get the 256K microcontroller. Expecting to build a 500K firmware and the gadget needs to cost less than $2 each? Then the primary path is questioning the design choices and possibly serious bloat removal, not firmware compression.

But that leaves the secondary path that your firmware is already quite lean and well-designed, and you really need to deliver those features, and the hardware is what it is and you can't make it any larger. For those niches, why not. If you get it working, it will be useful to some.

I have been actually in that game since our smart heating controller became much more than just smart heating controller, and with thousands of devices shipped and installed, we are not one of those who deprecate the support, and running two product lines on parallel would be significant alternative cost. So yes, we would be exactly in your niche. Our product is also simultaneously flash and RAM constrained so boot-time decompress is out of question. But so far, "flash diets" have been the recurring solution. Which is perfect job for parallel AI agents to do because they have the perseverance to do thorough job with test benches and verifying behavioral bit-identity. A single prompt is needed to replace a 10K library with a custom-written one which does just the subset needed in 1K, saving 90%, being faster, easier to read and maintain because it's smaller, less buggy as the library had bugs and workarounds to them. At least for me, continuing this seems the way forward, and program compression seems like a very last resort after all bloat and unnecessary features have been carefully wed out and the whole codebase optimized for size (grunt work that can be automated nowadays thanks to modern tools).

But it sure is something to experiment on and there will be special cases where it is useful.
 
The following users thanked this post: Kilrah

Online gf

  • Super Contributor
  • ***
  • Posts: 1841
  • Country: de
Re: Question about compressed programs
« Reply #6 on: November 25, 2026, 08:11:38 pm »
I have an idea for a new compression system that could help reduce size of program code. It would work by first compressing the entire program code, then adding a small interpreter that would read the compressed program instruction by instruction (decompressing each instruction on the fly), and then interpret that instruction.

If the program is a compressed stream (gzip, lz4 or whatsoever), how do you locate and access random access targets (e.g. jump targets) in the stream w/o sequential scanning?

(Or do you just talk about compact instruction encoding like thumb. etc?)
 

Offline lis05Topic starter

  • Contributor
  • Posts: 14
  • Country: pl
    • Github
Re: Question about compressed programs
« Reply #7 on: November 25, 2026, 09:02:22 pm »
I appreciate the replies!

@nimish

First of all, this is different from an unpacker. Unpacker requires to decompress the program into memory, so you end up using more total memory than the original program. Here, we actually use only C + D + I bytes (where C is the size of the compressed code, D is the size of the decompressor, and I is some additional small constant amount of RAM the interpreter needs). An unpacker would use something like C + O (where O is the original program).

Regarding VMs, it kind of works like that, but then there is another layer of generic compression. A VM works with a bytecode, but the system I described works compressed bytecode. It is much smaller (in my tests, rv32ec instructions can be almost halved in size!), and theoretically can work with any compression (lz, grammar, entropy, etc).

@Siwastaja

I agree with your points. This is pretty much the very last resort, when you have a program that is too large, you cannot make it smaller, and you cannot upgrade hw. In that specific, (unrealistic?) scenario this is the only way to run that program.

@gf

I should have probably described the architecture eariler.

The whole pipeline starts with 2 object files,: guest and native. Guest represent code that we want to compress, and it has to be compiled for RV32EC. Native code represents code that we want to keep uncompressed (for performance reasons, or as external code we don't really want to compress), and it can be in any ISA. I have an idea of how to make native architecture different from guest, but for this time, assume it is RV32I.

From high-level perspective, we will link guest and native code in a way which will put all guest code in an unsused segment of memory (like 0xfff00000..0xfffffff). This way, whenever we read an instruction that loads / calls something, we can check whether that something belongs to guest (has the 0xfff... prefix) or not. If it belongs to guest, we use the decompressor to fetch the thing. Suppose we want to read an integer that is embedded in a .guest.rodata section at 0xfff00004. Then, knowing that the compressed section begins at 0xfff00000, we can ask the decompressor to decode the word at position 0x4..0x8 in the compressed payload.

After we do this linkage, we separate guest code from native code. Next, we find addressable symbols: symbols in guest section which are taken an address of in any part of the code. Why? Because suppose a function accepts a pointer to another function. Compressed code can't really be accessed by pointers, so we need to generate stubs for each symbol that needs to have a static address. We scan relocations to find such symbols, and then emit two things:

1. A section with stubs, where each stub (in pseudocode) looks like:
Code: [Select]
stub_<original_symbol>:
    jal x31, <symbol that calls the interpreter machinery>

Here, we have a stub_<symbol> for each symbol which will jump directly to the function which handles native -> guest calls. It will see x31, subtract it from the beginning of the stubs section (to get the index of the symbol this stub represents).The handler will then read the position of that symbol in the compressed payload, and simply run the interpreter from that place.

2. A table which is used in previous point, and contains offsets into the compressed payload for each stub:
Code: [Select]
    .word 0x00010dfc /* slot 176: <symbol 1> */
    .word 0x000088fa /* slot 180: <symbol 2 */
...

After we have this informations, we link again, but this time we replace each addressable symbol <symbol> in the entire program with its stub_<symbol>. For this I used --wrap which does exactly that with the linker.

Having this done, we can attach the interpreter, decompressor, link everything once again (without linking the 0xfff... section, as it is now compressed and stored somewhere the interpreter knows how to access it) and it's ready!

====

This is actually just the very, very shallow description of how it works. It is much more complicated, there are many optimizations done. For example, I have a profiler which reorders functions in the compressed payload in a way which makes hotter code be faster to decompress. I also implemented another profiler which can shuffle symbols around such that 95% of all cold code is placed in guest, and 5% hot code is placed in native code. This helps improve the performance 2-3 times, but unfortunately the overhead of compressed code is soooo large I need the hot code to be about 0.5% for this system to actually run at near-native speeds...

I have a public version of this which is very outdated, but is essentially what i described above: https://github.com/lis05/sseocb. I didn't really know whether there is a point in making the whole thing public, but if anyone here would be interested to take a look, I can update the public repo and hopefully write some meaningful description. Unfortunately, I only had about 3 months to work on it, so its heavily vibecoded, and I want to make a clean rewrite (which is pretty much the reason I made this post, to see if there is a point in spending any more time on such a bizzare idea)

 

Offline ejeffrey

  • Super Contributor
  • ***
  • Posts: 4876
  • Country: us
Re: Question about compressed programs
« Reply #8 on: November 25, 2026, 09:07:00 pm »
I'm not sure exactly what you mean by compressed here.  i.e., you say you can execute riscv code on an arm -- but is that actual riscv code compressed with lzw or is this an instruction encoding optimized for density?

Compressing code with conventional compression of course works, but it is usually decompressed at program load time so that jumps can resolve natively.  It's possible to do it dynamically on a block by block basis but it adds overhead and complexity.

Using a high density instruction set and interpreting it goes back a long way.  Forth, java bytecode, pascal p-code, and probably many more were all designed to have very simple interpreters and also high code density and platform independence.  Generally stack based VMs have smaller code than register based CPUs, and the difference quickly makes up for the very small interpreter.  These examples are mostly for specific high level languages, but there is no reason that they couldn't be used by many languages.  The JVM in particular has hosted a bunch of other languages, although they all end up tied to Javas object model.

Finally there are compressed instruction sets like the RISC-V "C" extension and Thumb. They are language indepenent but don't acheive the degree of compression that the other options do.
 

Offline lis05Topic starter

  • Contributor
  • Posts: 14
  • Country: pl
    • Github
Re: Question about compressed programs
« Reply #9 on: November 25, 2026, 09:11:45 pm »
Quote
I'm not sure exactly what you mean by compressed here.  i.e., you say you can execute riscv code on an arm -- but is that actual riscv code compressed with lzw or is this an instruction encoding optimized for density?

For now I have not tried this, but in theory, some (or entire) of the program can be compiled for RV32IC, compressed with some lz77 compressor, and then interpreted by an interpreter that runs on an ARM device. The only issue is how to link risc-v and arm/any other host ISA, but that is something I will have figured out in the future. For now, all my tests have been on RV32IMC device where the compressed code was compiled for RV32EC.

Regarding bytecode: the idea is that this system can (ideally) compress ANY binary. And it achieves increadible results compared to plain C extension of RISC-V (around 50-60% compressor of RV32EC binary).
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 30431
  • Country: nl
    • NCT Developments
Re: Question about compressed programs
« Reply #10 on: November 25, 2026, 09:16:18 pm »
I think you should start with compressing binaries first and see how much space savings you can achieve. As others noted: modern day machine code is pretty compact already meaning compression ratios aren't going to be very good.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 
The following users thanked this post: Siwastaja

Offline lis05Topic starter

  • Contributor
  • Posts: 14
  • Country: pl
    • Github
Re: Question about compressed programs
« Reply #11 on: November 25, 2026, 09:24:34 pm »
Code: [Select]
    Bench (Native)   Lv  vP% Total Flash    Saved   Slowdown
    ------------------------------------------------------------
    my_basic         L4  67%  133.8K   -44.2K (24.8%)     48x
    (178.0 KB)       L6  59%  120.3K   -57.8K (32.4%)     79x
                     L7  52%  109.5K   -68.5K (38.5%)    385x
                     L8  48%  103.1K   -74.9K (42.1%)    632x

    lua              L4  79%   95.6K   -12.6K (11.7%)     28x
    (108.2 KB)       L6  72%   88.7K   -19.5K (18.0%)     37x
                     L7  65%   81.8K   -26.4K (24.4%)    145x
                     L8  61%   78.4K   -29.8K (27.6%)    356x

    tinyscheme       L4  81%   40.9K    -1.4K ( 3.2%)    219x
    (42.3 KB)        L6  74%   38.0K    -4.3K (10.2%)    255x
                     L7  66%   34.9K    -7.4K (17.5%)    463x
                     L8  63%   33.6K    -8.7K (20.6%)    659x



Here are some numbers from my tests. There are 3 programs, my_basic, lua and tinyscheme (all 3 are some interpreters, i like interactiveness). Lv denotes compression level used in the code (current i am using blaris, another thing I posted in microcontrollers forum). vP% is how well the code is compressed. Total Flash is how large the entire thing is (compressed payload + interpreter + decoder + anything else needed). Slowdown is how much slower it is compared to  running the program without any compression whatsoever (Native).

Native is compiled for RV32EC with -Oz, so it is already super compact. And yet, savings are relatively substantial in my opinion.
 

Offline PGPG

  • Super Contributor
  • ***
  • Posts: 1366
  • Country: pl
Re: Question about compressed programs
« Reply #12 on: November 25, 2026, 10:00:31 pm »
I have an idea for a new compression system that could help reduce size of program code.

I was almost sure that times when you had to be very carry about your program size are long gone.

Around 1990 we have build GAL & serial EEPROM programmer based on 8751. As we wanted to be able to add new GALs and EEPROMs to a programmed list without a need to send us our programmer to erase its 8751 EPROM and program it with new features we decided to fit everything in RAM. 8751 has 128 bytes of RAM (yes bytes, not kbytes). In 128 bytes we had:
- uC stack,
- Forth stack,
- second stack for data to be programmed,
- Forth-like program code (only needed by us instructions were available).
The Forth program was loaded and then interpreted. About 10 uC instructions were needed to execute one Forth instruction so it worked about 10 times slower compared to assemble code.
Almost always when program reached its main loop and run the instruction to load some data to be programmed (how many - top value at Forth stock decided) the loaded data destroyed already executed (interpreted) introduction part of program.
The interpreter was written by my brother. Forth programs (separate for each programmed device family) were written by me. I had to very carefully control RAM use (with single byte accuracy). uC stack and Forth stack were rising against one another and Program and data stack were also rising against each other (beginning of program against top of stack). I had instruction to set were the border between these two areas was located. I always used it at the far beginning of my code based on how many nested loops I had in program. Each nested loop needed extra 2 bytes at uC stack and knowing how many bytes I will have at Forth stack I could left for these two stacks enough bytes to make them touching but not destroying one by another.
Some actions like serial sending data on one pin with clock at another pin (pin numbers according to values at Forth stack) were just one Foth-like instructions.

Nowadays no one care so about memory. If not enough you just use uC with 2 times bigger Flash. And Flash allows to introduce new functionality by upgrade.
 

Offline Kilrah

  • Supporter
  • ****
  • Posts: 2048
  • Country: ch
Re: Question about compressed programs
« Reply #13 on: November 25, 2026, 10:35:11 pm »
when you have a program that is too large, you cannot make it smaller, and you cannot upgrade hw.
...AND have plenty of processing time to spare, little in the way of timing constraints, how does it work with interrupts,... Yeah, 28x slowdown to save 11% flash doesn't seem to be a very likely/realistic scenario. if all your "x" were "%" maybe something will be able to use it  :-//
« Last Edit: November 25, 2026, 10:51:24 pm by Kilrah »
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4674
  • Country: us
Re: Question about compressed programs
« Reply #14 on: November 25, 2026, 10:49:02 pm »
Were you aware of https://bellard.org/lzexe/ ?
It was very useful back in the days of MSDOS 2 and 40Mbyte hard drives.
(Decompressed whole programs to ram; no speed penalty, no interpretation, usually loaded and decompressed more quickly than the full sized program would, since disks were especially slow back then.)


Cisco routers also decompressed their code from eprom or tftp to ram, back in the day. (Might have been my fault!)



 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->