Website title

Computing: The Details
Lex's blog of curious computer-related shenanigans.

Blog post

Solving Advent of Code 2022 on the Sinclair ZX Spectrum: Part 3

Published: 2023-03-16

This blog post is also available in video form! Watch it on YouTube

Part of a series of posts: < Previous in series

If this doesn't make sense, see part 1

Day 9

See the problem description on adventofcode.com/2022/day/9

The idea for this task was that you're tracking the end of a rope as it swings around. The rope is split into discrete segments, each segment occupies a cell in a square grid, and moves from cell to cell chasing the segment ahead of it. There's a bunch of rules for which cell it moves to. The movement rules are a little odd, and annoying to implement, but not too much of a problem. The challenge is to track the end of the rope as the head of the rope moves around. Initially the rope is only two segments long, but then for the second part of the task it's ten segments long.

The answer that I need to provide for each part is the number of squares that the tail of the rope visited. At first this seems easy, just keep a count of the number of squares visited so far. Each time the tail moves, increment the count. But this only works if the tail never crosses over its own path. So actually I should only count a step if it moves onto a space that's never been used before.

As explained in part 2 of this series, I have been prototyping solutions in python. For day 9, once I had made my initial prototype, I then used it to analyse the size of the problem.

I first checked the size of the grid that the rope moves around in. This isn't specified in the input file. All I know is where the rope starts and how it moves. I calculated the extents of the rope's movement, and I found that the range in X is 234 units, and the range in Y is 286 units. This means that for the Y axis, the range of movement is greater than can fit in a byte. My Y coordinates need to be at least 9 bit numbers, which practically means they should be 16 bit numbers. The X coordinates could fit in one byte if I am careful with where the origin is.

Now consider that I need to track where the tail of the rope has been before, so I know what to count and what not to count. I could do this by keeping a list of all the places that the rope has been to. When I move the rope, I can check if the new tail coordinates are in that list. If they are, I know not to add to the count. Otherwise I will add one to the count.

As the list grows, it becomes more costly to lookup values in this list. The other option is to have a 2D array that is as large as I expect the grid to be, and have each element be a flag to indicate if that cell has been visited. Indexing into this grid will be fast regardless of how long the path gets.

So which of these methods should I use?

Well, first we need to consider how much memory I have available. I have 48k. I lose about 7k to the video memory. I lose about 9k to the input file. I will probably need about 2k for the program code. That leaves me with roughly 30k for any data structures that I need.

So, let's see about keeping a list of all the squares I've visited. For the first part of the task, I visit about 6000 squares. For each one I need to keep the X and Y coordinates. If I use a 16 bit number for each one, that's 4 bytes per square. This means I need about 24k for my list. That will fit in my 30k of free space. As mentioned previously, I could probably get this down to 18k since the range of X values I need will fit in one byte, allowing me to use only 3 bytes per coordinate.

Okay, so that will work, but I suspect it will be very slow. Let's see if the other method will work.

I need a 2D array of flags. I know I need at least 234*286 flags. That's nearly 67 thousand flags. Clearly I can't have a byte for each flag, since that would be about 67k, and I only have 30k. However, a byte could store 8 flags quite easily. If I pack the flags in like this then I only need about 8k for all the flags. This is much more compact than the list method, and has the big advantage that it is less likely to break for larger inputs.

If I was to use a longer input file that visited more spaces, the list gets longer, and the lookup time gets longer with it. Whereas the grid of flags has a constant lookup time. The grid method limits the range of coordinates a little more, but I can future proof it a little by using that spare space I have to make the grid larger in each direction.

If I use a grid that's 336*336 cells in size, that means I use 14k for the grid, and I have comfortable margins around what my input file uses, so hopefully it would work for lots of other input files too.

Something I would love to see in Advent of Code is more detail on the constraints that the file was generated with. I would love to know the exact limits of the generated files, so that I could be more certain about how my program will handle files other than my own.

I have to do quite a bit of arithmetic to set each flag in the grid. Since it's just a huge bitmap, I need to calculate which byte contains the flag I want to set, calculate which bit of that byte is the right flag, set that bit without disturbing any other bits, and then write it back to the bitmap.

Once the rope stops moving, I then iterate over the whole grid and count the number of bits in each byte. I haven't yet experimented with keeping a count as I move through the input file. I'm not sure if it will be faster or not, but I want to find out.

So that was day 9. This one feels kinda tricky because I don't know if my program would work for all possible inputs. It works for my input data, and I've tried to make it support a wide range of values, but I'll never know for sure if it supports them all.

Anyway, it works for me, so I'm calling that one complete and moving on to day 10.

Full listing on GitHub

Day 10

See the problem description on adventofcode.com/2022/day/10

Day 10's task was curious. The first part felt like many of the other tasks that have gone before, but the second part ended with rendering a bitmap image of some text. The text is the answer. To do this you have to simulate a really simple CPU.

The simulation of the CPU is the easy part. For this task I want to talk about the bitmap image rendering part. The ZX Spectrum video RAM is split into two parts, the first contains a bitmap image with one bit per pixel. The second section encodes all the colour data, and a few other attributes. The screen is split into 8x8 pixel squares, and each square can only have two colours. The bitmap selects which of the two colours is visible for each pixel.

If you've played many games on the ZX Spectrum, you've probably seen the effects of this, when a player walks in front of an object on the screen that is normally a different colour, the program must choose only one pair of colours to draw, and so sometimes the player colours leak onto the object that they're close to, or vice versa.

In the case of my solution to this task, I'm happy with the default black text on a beige background, so I needn't change anything in the colour data section of the video RAM. I only need to update the bitmap area. There is one non-obvious thing about the bitmap data though. It's not in the order you might expect.

It would be convenient if the pixels were all in order, left to right, top to bottom. They aren't. They do go from left to right in order, but each time you get to the end of a line, you jump down by 8 pixels and reset to the start of the line. That is, until you get to about one third of the way down the screen, then you jump back up to line 2, and repeat this process until you've visited every pixel in the top third of the screen, then you do the same on the middle third of the screen, and then once more on the last third.

This might seem odd at first, but there is a good technical reason for this order. I'll not get into the details here, but it simplifies some of the video hardware. So now I have to deal with this surprising order of lines in my code. It's not actually too hard to do, since the last three bits of the high byte directly control the Y coordinate within a single square, and the bitmap I need to render fits in a one square high strip.

I did spend a while getting this wrong, and rendered all sorts of garbage to the screen before I finally got all the maths right. I bet this was a frustration shared by most 80s game developers who had to deal with this.

The computation was simple enough though, just requiring some careful thought about how things align when drawing the bitmap.

So that was day 10. Quite a fun one.

Full listing on GitHub

Day 11

See the problem description on adventofcode.com/2022/day/11

I didn't like this particular task. It felt so much more tedious than everything that went before. Certainly the least fun task so far.

If we ignore all the flavour text around the task description for this one, it reduces to just applying simple arithmetic to some numbers over and over again. There was no need for large data structures, the memory footprint is fairly low for this task.

If you just follow the instructions provided, then the numbers you will be dealing with get really big. Way too big to fit in a 32 bit number. They grow exponentially and quickly become too big to handle in a reasonable time. The insight you were supposed to find was that the arithmetic needn't use such big numbers.

The important thing to notice is that you can do all of your addition modulo some fairly small number. Unfortunately, despite making use of this, the largest numbers I had to deal with still got wider than 32 bits, so I had to make a copy of my maths library that could handle 48 bit integers.

Now, the rest of the logic for this task is nothing worth talking about, but something that is worth talking about is the amount of time I spent debugging this one.

There is something that I had failed to take into account. Whenever I tested this program, I got the right answer for the first part, and I got a wrong answer for the second part. What was really strange was that I got a different wrong answer each time even if I hadn't changed anything. So clearly something was very wrong.

I started debugging this and stepped through the computation in the debugger in my emulator. At each step it seemed that the computation was all correct. I stepped through the first few iterations of the algorithm, and they all worked. I jumped a few hundred steps ahead, still correct. Then I jumped a much longer way ahead and found that one of the numbers was wrong.

Hmm. How am I going to find out at which exact point the computation that I am doing in the emulator diverges from the python reference code that worked fine. Well to do this I decided to modify the emulator. I added in some custom code that would save a particular range of memory from the emulator into a file each time it reached a particular instruction that I chose because it wasn't used anywhere else in my program or in the ROM.

I then wrote some more python code to decode this memory dump and compare it to what my python implementation was doing. I found the exact time at which the first error occurred, many minutes into the program run time. Once I knew how far to step into the program, I started the debugger again, stepped to the right place, and … it worked fine.

This was really frustrating. This was by far the most effort I had put into debugging one of these programs. All of the logic in my program was correct. I could see that even if it started with wrong values, it still did the right computation each time. Something else in the system was messing with the values in the middle of the computation.

After hours debugging, I suddenly realised what it was, and the solution was simple.

Most of the binary operations in my maths library use the IY register to point to the second operand. The IY register is also used by the BASIC ROM without saving and restoring it. This would be fine if there was no ROM code running, and you'd think that would be the case while my code is running, but actually it's not.

I was already saving and restoring the IY register value for the purposes of calling into the ROM's print routines, since it expects IY to be untouched. But what I had missed was that the timer interrupt handler uses it too.

The reason this hasn't been a problem before is because none of my programs have ever needed to run for as long as this one does. It takes about 9 hours to complete. The emulator that I use can go several hundred times faster than real time, so it only takes about 90 seconds on my laptop. The fact is that the timer interrupt only uses IY if the timer counter overflows. The counter overflows approximately once every 22 minutes. Naturally that happens many times if you're running your code for 9 hours.

I disabled interrupts, and ran my code again, it worked first time.

None of the other programs had hit this issue, because they all ran in less than 20 minutes. They did still need fixing though, since the timer is always running, and so depending on when the program starts they might hit this same issue.

I spent a long time looking for this bug. It turned out to be a really simple fix.

Full listing on GitHub

Part of a series of posts: < Previous in series

Blog post

Solving Advent of Code 2022 on the Sinclair ZX Spectrum: Part 2

Published: 2023-01-08

This blog post is also available in video form! Watch it on YouTube

Part of a series of posts: < Previous in series | Next in series >

If this doesn't make sense, see part 1

Day 6

See the problem description on adventofcode.com/2022/day/6

This is gonna be a quick one. The task for day 6 is fairly simple. You need to scan a sliding window across a string, and detect when all the characters in that window form a unique set.

Parts 1 and 2 are the same except for the window size.

There's really nothing interesting in the code for this one, none of it was tricky to do in assembly, so I won't dwell here. Days 7 and 8 are more exciting.

Full listing on GitHub

Day 7

See the problem description on adventofcode.com/2022/day/7

When I first read the details for this challenge, I thought it was going to be a nightmare to implement in assembly. The input file resembles a shell session output, where a user is moving around a file system with cd, and checking the sizes of files in the directories they enter. The files and directories all have names but the full path names are never specified, only implied by the route the user takes through the file system.

I was expecting to build some kind of tree data structure, but at first I thought I was going to have to track file names, which meant dealing with strings of unknown sizes. This is easy to do in a high level language, even C style strings would feel like luxury for this purpose. But actually it turns out I don't need to think about the file names at all.

I looked closely at the description for this task before I started writing my input parsing code. The answers I need are just the sizes of some specific directories. I never actually need to know what the name of any file is. At least, not for the purposes of getting an answer.

But perhaps I do need the file names for parsing the tree? After all, I only know what directory the user is in by its name. Well, actually I discovered that in this fantasy shell session, the user is very predictable. They always descend into directories in order, and descend all the way to the leaves of each directory before continuing on to the next directory.

With this in mind, most of the input file can be ignored, and in fact there's several places in my parsing code where I simply skip over parts of the input.

The first line in the file tells us nothing, as far as I can tell from the examples I have seen, this line is always the same, so I can ignore it. Any line that says "$ ls" can just be ignored. I know that the user always does this after entering a directory. As soon as I see "$ cd <some_dir>", I already know that the next line will be "$ ls", so I can ignore it. Whenever I see a line that starts with a number, I only need to read the number, then I can skip over the rest of the line since the file name doesn't matter at all. The lines that start with "dir" are also safe to ignore entirely. As we've established already: the name doesn't matter, and that's the only real information on those lines.

Most of the input for this task is just thrown away.

Upon discovering all of this, I first wrote some python code that implements the algorithm I need. Having seen the difficulty start to ramp up by now, I had decided that from here on I probably needed to have a working prototype in a high level language before I tried to write any assembly code. Before I show you how I solved day 7, let's take a quick detour into how I prototyped solutions in python and then ported them to assembly.

A side bar about prototyping

python, for me, is an ideal language for Advent of Code. It's easy to write, and the built in data structures and string processing routines make parsing of the input really easy. The problem is that once I have a python solution, I need to translate it into assembly code. For some operations this translation is really obvious. Simple arithmetic is easy, for example. But for other things it's not so obvious. Let me show you.

Let's sum a list of numbers in python.

#!/usr/bin/env python3

inp="""123
234
345
456
567
678
"""

print(sum(map(int,inp.strip().split('\n'))))

The list starts off as text, which needs to be parsed, each line is one number. Here this is done by splitting the input into lines, and then casting each one to an int. I've used the map function to do this, and I've also used the built in sum function. None of this is available to me in assembly code.

Now I'm going to split up these nested function calls.

lines = inp.strip().split('\n')
nums = map(int, lines)
print(sum(nums))

Then I need to get rid of the string split and the int conversion. I don't have a string split function in assembly, and actually I don't need one, I can eliminate the need for it. I'm going to loop over each character in the input. I'm using a while loop here instead of a for loop because they look more like assembly code. I'd like to use goto really, since that's closest to what assembly code looks like, but python doesn't have goto, so I can't. I'm using the name hl for the loop counter, and you'll see why soon.

hl = 0
num = 0
nums = []
while True:
    a = ord(inp[hl])
    d = a - 48
    if d >= 0 and d < 10:
        num *= 10
        num += d
    elif a == ord('\n'):
        nums.append(num)
        num = 0
    else:
        break
    hl += 1

print(sum(nums))

For each character, I first assume the character is a digit, convert it from ascii into numeric form, then check if it actually is a digit, as I had assumed. If it is, I multiply num by ten and add on the new digit. This is the number parsing algorithm I mentioned in the previous video. If the character is actually a newline, however, I have finished parsing the number, and I can add it to the list.

I then reset the number for the next line. If ever I find a character that's none of these things, then I've finished iterating. I always deliberately make sure there's a null character at the end of my input file, so in python I can emulate this by just adding one to the end of this string.

Now I see another opportunity to optimise this. I don't want to construct a list in assembly code if I can avoid it, and in fact the sum operation doesn't really need to keep a list of all the numbers to sum. Let's just take a running total while I'm parsing the input. I'll also move the loop counter increment statement to the start of the loop, which will make more sense when we look at the assembly code.

hl = -1
num = 0
total = 0
while True:
    hl += 1
    a = ord(inp[hl])
    d = a - 48
    if d >= 0 and d < 10:
        num *= 10
        num += d
    elif a == ord('\n'):
        total += num
        num = 0
    else:
        break

print(total)

So now I have some python code that really doesn't look like python any more. Normally you'd never write python code like this. It looks awful as python code, but it looks great as a prototype for some assembly code.

Let's look at the assembly that I wrote based on this.

start:
    push iy
    ld hl, inp-1 l hl points to start of input
loop:
    inc hl ; hl += 1
    ld a, (hl) ; a = inp[hl]
    sub 48
    cp 10
    jp nc, not_a_digit ; if a >= 0 and a < 10
    ; num *= 10
    ld ix, num
    call multen32le
    ; tmp = a
    ld iy, tmp
    ld (iy), a
    ; num += tmp
    call add32le
    jp loop
not_a_digit:
    cp (10 - 48) ; check for newline
    jp nz, not_a_newline
    ; total += num
    ld ix, total
    ld iy, num
    call add32le
    ; num = 0
    ld (iy), 0
    ld (iy+1), 0
    ld (iy+2), 0
    ld (iy+3), 0
    jp loop
not_a_newline:
    ; end of the file
    ; convert total to string and print it...

You can see why I chose the names hl and a in the python code. These are actually register names on the Z80. This really helps follow what's going on when I translate my python code. It's not a direct translation, as you can see, but it's much easier to go from this python code than it is to go from the initial python code.

The assembly code makes use of my 32 bit add function and string conversion function from the math library that I wrote.

My math library does also have a number parsing function, but I avoided using it here just for demonstration purposes.

So that's how I've been prototyping in python each day. There's a bunch of other things that I do that I won't go into detail for. Things like turning some function variables and arguments into globals, eliminating tuple returns, putting return values in globals, and sometimes even mocking up struct field access. This process made it much easier to get the assembly code right each day. I still had to do lots of debugging, but at least I had a good reference implementation to debug against, and a good starting point for writing my code.

Okay, let's get back to day 7's challenge.

so, I wrote my python code, and I made it look as much like assembly as I could, then I translated the program. For the reasons I explained earlier, there's a bunch of places where it just skips over parts of the input. It skips over the ls lines, the dir lines, and the names of files.

The algorithm builds a tree structure, but you can see that it only stores the links to the other nodes, and a total size for the current node. As mentioned, the names are not important. There's a cursor stack specifically for remembering how to backtrack during parsing. Once the whole tree is parsed, I can recurse the whole tree and add the sizes of child nodes on to parent nodes. Finally, since all the nodes are the same size and stored sequentially, I can then easily iterate over all nodes to compute the answers without having to use recursion.

A little while after getting all of this working, I discovered that I don't actually need to understand the hierarchy of the file system at all. I don't need any of the links between nodes. The only reason I had them was so that I could recurse across the tree structure after I parsed it, but actually I can do the operation that requires recursion during the parsing step. I just add the size of each child node to the parent node whenever I find a "cd .." command. This means I never need recursion for this task at all, only iteration. Perhaps at some point I'll implement this optimisation in my code, but for now it is a missed opportunity.

Day 7 was an interesting challenge with a deceptively noisy input file. So far it's the only challenge where there's been any redundancy in the input file. It took me a really long time to see that despite the fact that the input file represents a tree structure, I never need to recurse across it.

I don't think I would have discovered this if I hadn't been looking so hard for optimisations. For me this is part of the magic of challenging myself to use an assembly language for these tasks. If I had just been using python for this, I wouldn't have bothered looking out for these optimisations.

Full listing on GitHub

Day 8

See the problem description on adventofcode.com/2022/day/8

Okay, on to day 8, last one for this post, and it should be fairly quick.

In this one you have to find particular trees in a grid. Essentially looking for a tall tree with lots of shorter trees around it. I've hugely oversimplified the problem description there, but the interesting part here is another optimisation that I made in the parsing step.

This is an optimisation that is obvious in hindsight, but I probably wouldn't have thought about it if I was using a high level language to solve this problem.

For my solution to this task, there's not really an input parsing step. Well, technically there is one, but it's probably not doing what you think. You might expect me to parse the digits in the file, convert them from ascii values into plain numeric values, maybe even insert them into an array, and then start to process the data. But actually the absolute height of the trees, which is what these numbers represent, is not so important.

The important part is the differences between pairs of trees. I don't need to convert the ascii characters to numbers, because ascii has quite sensibly decided to put all the digits right next to each other in order. If I subtract the ascii value for 4 from the ascii value for 7, then I get the number 3. I needn't bother convert these numbers first, since I would get the same result here anyway.

So, I don't have much set up effort to do before I start computing the result for this task. I need to know how wide the grid is, and how tall it is, so I know how far to iterate, and how to calculate the memory address of each tree digit. But that's all. When it comes to the computation, the raw values from the file are just fine. I don't need to put them into an array or list either. I can just load them directly from where the file is in memory.

As for the rest of the solution to day 8, well I'm sure you can imagine it, it's just iterating over a grid in various ways, and performing simple arithmetic as you do so.

Full listing on GitHub

Part of a series of posts: < Previous in series | Next in series >

Blog post

Solving Advent of Code 2022 on the Sinclair ZX Spectrum: Part 1

Published: 2023-01-03

This blog post is also available in video form! Watch it on YouTube

Part of a series of posts: Next in series >

Advent of Code is a programming challenge and competition that runs during the 25 days of Advent.

I decided that this year that my challenge to myself for Advent of Code would be to solve each day's challenge with a Sinclair ZX Spectrum program.

The Sinclair ZX Spectrum was a popular British home computer from the early 1980s. It has 48k of RAM. That's not much by today's standards.

I happen to have one in working order, and wanted an excuse to use it more. So I thought this would be a fun way to do that.

Can I do all 25 days on the ZX Spectrum? (Spoiler alert! ... I stopped before I reached the end)

Introduction

Okay, first of all let's see what I'm in for.

Each day of AoC comes in two parts. That's a total of 50 challenges. For each challenge you get a description of the challenge, an input file that you need to process to complete the challenge, and finally a place to submit your answer to see if you got it right.

If you're aiming to get on the leaderboard then you have to be awake at the right time and code as fast as you can. Only the first 100 correct answers score points each day. That's 5AM for me here in England. I'm not aiming for leaderboard positions this year, I'm just having fun with retro computing. So I'm gonna wake up whenever I like.

Each day has two challenges, and normally they're very closely related. Often the first one sets you up nicely for the second one, but sometimes it doesn't. As the days go on, you have to be more clever with how you solve the problems. There's often an obvious solution that's way too computationally expensive to get a result in a reasonable time, and then a more creative solution that's quite fast.

So in summary, what we need to do each day is: parse the input file, process the parsed data to get the answer to part 1, process the input again but this time calculate the answer to part 2.

Of course we only know part 2 after doing part 1. Sometimes you can calculate both answers with one pass over the input data, but at least at first that's not helpful.

I have quite a lot of programming experience, so to make this fun I need to make it harder. So now let's look at how I've made this hard for myself.

The target (The ZX Spectrum)

I've made things hard for myself by choosing a difficult platform to write programs for.

The Sinclair ZX Spectrum from 1982 has only 48kb of RAM. It has a clock speed of about 3.5MHz. You're probably watching this video on a device with a clock that's almost 1000 times faster than this.

Okay, so it's slow, and it hasn't got much RAM. Doesn't this just mean it will take longer? Well, it will take longer, for sure. But there's other problems too. How do I write programs for this machine?

If you start up the machine then all you get is a BASIC interpreter. I mean BASIC as in the language. But it is also basic in that it's not a feature rich development environment that you might expect to use on a modern PC.

I could write BASIC programs for this machine, but BASIC is slow, has some annoying constraints, and also lacks certain operations that I'd have to reimplement with my own functions, which would be much slower than machine code versions. So that's the decision essentially made for me. If I want the performance I need for some of the more intense AoC challenges, then I need to produce machine code.

I've never found a compiler for any language that I'm happy with for the Z80, which is the CPU inside the ZX Spectrum. So instead I decided to make things extra hard for myself and write all of my solution code in Z80 Assembly language. This means all the algorithms and data structures I need, I will need to implement them myself.

RAM is also a problem. I have only 48k. About 7k of that is used by the graphics system. Using this for computation would put garbage on the screen, so I'd like to avoid it if possible. I need to use some of the screen space for outputting the answers anyway. So I'm already down to a practical limit of 41k.

Before I started this adventure I had a look at the size of the input files from the previous year, and I found that most of them are less than 10k about five of them were larger than this, the largest being 20k on day 22.

The input text is unique to each player, and is generated by the server for you. Your answer is different to everyone else's, but I'm not sure how much the input size varies. It might be possible that there's a slight difference in size between players, I'm not sure.

Anyway, I started with the assumption that 20k will be the upper bound. I'm sure that'll be enough, right? (in the biz, this is known as foreshadowing)

So that leaves me with 21k of space for my program. I thought that sounded like a lot at first. But then I remembered that I also need any working data structures to fit in the remaining space. Turns out most programs fit into 2k including space for small variables, so that leaves 19k for any data structures I need. Still, that should be plenty of space, right? (in the biz, this is known as foreshadowing repeating a joke)

Time for your spoiler warning. From here on expect some mild spoilers for the AoC challenges.

The plan

I'm going to cover days one to five in this post, and then later days will be in future posts. I won't be going into much detail for some of the easier challenges, but I will go into lots of detail for the more interesting ones that required a little bit of creativity. You've probably already seen other people describing their algorithms in detail if you're into this kind of thing, so I'll try to focus on the challenges that are unique to using a ZX Spectrum for these kinds of programs.

Days one to five were all fairly simple. We'll start at the beginning, with day one, and the first challenge that I have to overcome.

Day 1

See the problem description on adventofcode.com/2022/day/1

At the heart of the ZX Spectrum is the Zilog Z80 CPU. People often call this an 8-bit microprocessor. A pet peeve of mine is how people use phrases like these and don't qualify them. If someone says "This is an 8 bit processor", what do they actually mean? Do they mean that the address bus is 8 bits wide? Do they mean that the widest part of the data path is 8 bits? Do they mean that the general purpose registers are 8 bits wide?

So let's clarify this statement for the Z80. It has a 16 bit address bus and an 8 bit data bus, it has registers that are either 8 bits wide or 16 bits wide depending on the operation. The widest adders in the machine are 16 bits wide. So is this an 8 bit micro? Or a 16 bit micro?

Either way, the largest adder I have access to is a 16 bit adder. But actually the more convenient ones to use are the 8 bit adders. So this means the largest integer that I can use with the built in hardware is 2 to the power of 16 minus one. That's 65,535. So here's problem one: this is not big enough for AoC. Regular AoC players will know that the numbers often get big.

It's common for lots of modern machines to have at least 32 bit adders and 32 bit registers. This lets you get numbers up to almost 4.3 billion. This should be plenty for this task. I had hoped that it would be big enough for all of the tasks. (in the biz, this is known as foreshadowing murdering a joke)

So, my first task was to implement 32 bit addition, and also parsing of base 10 numbers. Let's start with adding: there's a pair of registers on the Z80 that make this really easy to do. the IX and IY registers can point to the starting position in RAM of each of the two numbers to add, and then I can load the right bytes from each one using the load instructions that use offsets from the IX and IY registers. Below is the function I wrote for this. It works because you can do a 32 bit add by doing four 8 bit adds, as long as you remember to pass the carry output bit from each add operation to the next higher order add operation.

add32le: ; (ix) = (ix) + (iy)
    push af
    or a
    ld a,(ix)
    adc a,(iy)
    ld (ix), a
    ld a, (ix+1)
    adc a,(iy+1)
    ld (ix+1), a
    ld a, (ix+2)
    adc a,(iy+2)
    ld (ix+2), a
    ld a, (ix+3)
    adc a,(iy+3)
    ld (ix+3), a
    pop af
    ret

Okay, now for number parsing. That means I need multiplication. The algorithm I used for parsing decimal was to parse the first digit, add it to an accumulator, and then for each additional character I find, I multiply the accumulator by 10 and then add on the digit I just found until I run out of digits.

My multiplier implementation is fairly simple, it iterates over the bits of one number, multiplying by two or adding the current value each time. This is a fairly common approach and it works well for this size of number. The problem is that when I parse a number from the input file, I need to do this multiply step once for each digit in the number. There's about 2000 numbers in the file for day 1, usually about 4 digits each. That's 8000 multiplications I need to do. My multiplier isn't unreasonably slow, but it's certainly on the critical path for parsing decimal numbers for day 1.

mul32le: ; (ix) = (ix) * (iy)
    push bc
    push de
    push hl
    push iy
    ; Copy (ix) to (tmp2)
    ld bc, 4
    push ix
    pop hl
    ld de, mul32le_tmp2
    ldir
    ; Copy (iy) to (tmp1)
    ld bc, 4
    push iy
    pop hl
    ld de, mul32le_tmp1
    ldir
    ; set (ix) to 0
    ld (ix+0), 0
    ld (ix+1), 0
    ld (ix+2), 0
    ld (ix+3), 0
    ; 32 step multiply loop
    ld b, 32
    ;ld iy, mul32le_tmp2
    ld de, 4
mul32le_loop:
    ld iy, mul32le_tmp1 ; 20
    call sra32le_iy
    ld iy, mul32le_tmp2 ; 20
    call c, add32le
    call dbl32le_iy
    djnz mul32le_loop
    pop iy
    pop hl
    pop de
    pop bc
    ret
mul32le_tmp1:
    db 0,0,0,0
mul32le_tmp2:
    db 0,0,0,0

Since I know that I only need to multiply by 10 while I'm parsing a number, I can actually create an optimised multiply function that's specifically for multiplying by ten. How does it work?

Well let's start with multiplying by two, multiplying a number by two in binary is really easy. You know from primary school maths that if you need to multiply a decimal number by 10 then you just shift everything over by one digit and put a zero in the units place. Well, as we move from base 10 to base 2, that same shift operation turns from times-ten into times-two. Most CPUs have shift instructions, and the Z80 is no exception. I can multiply by 2 really fast. In fact it's a part of the algorithm for arbitrary multiplication already. But 2 is not 10. So how do I use this information to make multiplying by 10 really fast?

Well, add is quite fast, so if I can build my times-ten just using shifts and adds then I can make times ten be really fast. Let's take X, shift it once to get 2X, we'll keep that for later. Now let's shift 2X again, twice more, to get 8X. Now I can add 2X and 8X together to get 10X.

; Optimised multiply by 10
; (ix) = (ix) * 10
; decomposes 10 into sum of powers of two
; x * 10 === (x * 2) + (x * 8) === dbl(x) + dbl(dbl(dbl(x)))
; three doubles plus an add
multen32le:
    push bc
    push de
    push hl
    push iy
    ; (ix) = (ix) * 2
    call dbl32le
    ; (tmp1) = (ix)
    ld bc, 4
    push ix
    pop hl
    ld de, multen32le_tmp1
    ldir
    ; (ix) = (ix) * 2
    call dbl32le
    ; (ix) = (ix) * 2
    call dbl32le
    ; (ix) = (ix) + (tmp1)
    ld iy, multen32le_tmp1
    call add32le
    pop iy
    pop hl
    pop de
    pop bc
    ret
multen32le_tmp1:
    db 0,0,0,0

My arbitrary multiply function does 64 one-bit shifts and 32 additions. My newly optimised X10 function does 3 one-bit shifts, and 1 addition. That's a huge improvement.

With number parsing going fast, and 32 bit addition working, day 1 becomes easy. I'll spare you the details, it's just adding some numbers together and deciding which one is biggest.

Full listing on GitHub

Day 2

See the problem description on adventofcode.com/2022/day/2

Since I had all the infrastructure I had implemented for day 1, it was really easy to get day 2 done.

Day 2 was slightly more complicated than day 1, but not much. The challenge involved evaluating total scores from games of Rock Paper Scissors according to some scoring formula. There wasn't anything in day 2 that was particularly difficult. The only new technique I used here was pre-computing a look up table of values for the scores. I used two different tables to look up the scores given by the outcome of each game. The scoring was different in each part of the challenge, hence I needed a different look up table for each one.

Nothing new enough or exciting enough to discus for day 2.

Full listing on GitHub

Day 3

See the problem description on adventofcode.com/2022/day/3

Day 3, still quite early on. The difficulty has not ramped up yet. This is a fairly simple task, but it's an opportunity to talk about parsing, and how I'm actually getting the input files on to the ZX Spectrum.

Well, first of all, when I'm coding I'm actually using an emulator. I have been verifying that my code runs on real hardware too, but during development it's much nicer to have an emulator with a debugger.

Programs are normally loaded on to the ZX Spectrum via a compact cassette, although you can actually use anything that produces a suitable signal. I have used my laptop headphone output to load programs during testing without needing a cassette. I have been using cassettes occasionally too though, for fun.

My build process for my code includes a step where the program and the input file are each turned into the format that the ZX Spectrum can load. These files can be loaded directly by an emulator, or can be converted into .wav audio files. I've been using the .wav method to test on real hardware and to record onto cassettes.

These files need to know where in memory they will be loaded. A third file, which is a small BASIC program, is the first file to be loaded. It runs automatically and loads the other files in the right places automatically. It loads the main program, which starts at address 0x8000, and then the input text, which is loaded at 0xA000. This gives me plenty of space for each of these. I have about 24k of space starting at 0xA000, so that should be plenty of space for even the largest of the input files that I'm anticipating (foreshadowing). The program has an 8k block to use. If the program ever gets bigger than this then it will start to overlap with the input text.

The program knows that the input will start at 0xA000, so to read the input text, it just starts reading from that part of the memory. On modern systems you often find that a program will open a file, and only load a part of it into memory at once, often it doesn't need to store the whole thing in memory, it can stream it from the storage medium as it processes it, and discard the parts it has already processed. On the ZX Spectrum this is not an option. You have to load the whole file, or none of the file. If I wanted to process this in parts, I will have to split it into multiple different files and load one at a time.

Here's an example of a parsing function. If BC points to the start of a line in the file, then running this code puts the length of the line in register E. Of course, it produces incorrect results for lines longer than 255 characters. It also fails for lines of length 0, in which case is returns the length of the next line in the file plus one. These limitations are known, and are not problematic for the given puzzle input.

length_loop:
    ; get the length of this line
    inc bc
    inc e
    ld a, (bc)
    cp 10 ;check for line feed
    jp nz, length_loop
    ; e is now the line length

Another issue is that the user experience is very different for files on tapes. The user has to locate the file on the tape, or sit and wait for the tape to play all the way to the file that the program wants. The ZX Spectrum can't control the tape player. Imagine if you had to manually control the start location of the read head on your hard disk to load a file.

My solution for day 3 is often jumping around the file while parsing it. Since it sometimes needs to scan across several lines at the same time. Having the whole thing in memory is actually really convenient for this purpose. In part 2 there's a need to scan three lines at the same time. This function finds the starts of the next three lines in the file:

find_lines:
    ; upon arriving at find_lines, hl should point to the first char in the first line
    ld (line1_start), hl
find_line_2:
    inc hl
    ld a, (hl)
    cp 0
    jp z, part2_done
    cp 10 ; check for newline
    jp nz, find_line_2
    inc hl
    ld (line2_start), hl
find_line_3:
    inc hl
    ld a, (hl)
    cp 10 ; check for newline
    jp nz, find_line_3
    inc hl
    ld (line3_start), hl
found_lines:
    ; we now have three pointers, one pointing to each line in this group

Anyway, the rest of the details for part 3 are not particularly interesting. Let's move on.

Full listing on GitHub

Day 4

See the problem description on adventofcode.com/2022/day/4

Day 4 also wasn't particularly interesting. It was just basic arithmetic over and over again. It didn't take me long to implement a solution using things I'd already experienced in the first few days.

Full listing on GitHub

Day 5

See the problem description on adventofcode.com/2022/day/5

Day 5 was interesting because it was the first one that required me to implement a data structure that I hadn't given much thought to before.

In modern high level languages you get lots of things easy. Suppose you need a LIFO queue, (Last In, First Out) you can just summon one from the eather with a single line of code. I'm writing Z80 assembly, I have to bring all my own data structures.

The disadvantage of this is obvious, but the advantage is that I can make optimisations that are specific to my current use case.

For day 5 there was an interesting task to do. Lifting crates with a virtual crane, and placing them on other stacks of crates, in a particular order. Essentially you have a bunch of LIFO stacks and you have to pop and push from them in a particular order.

Parsing the input for this task was a little bit annoying, because there's a kind of ascii art representation of the stacks at the start. It looks nice, but it's not the most helpful thing for machine readability. Here's the example they provide:

    [D]    
[N] [C]    
[Z] [M] [P]
 1   2   3 

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

The first thing I do for day 5 is count up all the crates. This total is going to be the biggest any of my stacks could possibly get. So I reserve that much space for each stack. Then I put the character that represents each container into my freshly allocated LIFOs in the right order.

I decided that I wouldn't bother to track how many items were in each LIFO, since they were not going to get particularly big anyway. So what I did was make sure that the remaining elements in a LIFO were all spaces, so that I can find the top by scanning along until I hit a space.

In hindsight this wasn't a great idea. It's not fast at all, and it only saves about 9 bytes of memory, I had plenty to spare, actually. Anyway, the second part of the task asked me to pop multiple items at once from a LIFO. I hadn't planned for this when I wrote the solution to part 1, so I got a bit lazy, and this made the solution really slow.

The problem was that the items that I popped from one LIFO now needed to be pushed onto the next LIFO in reverse order (or in the same order, depending on how you look at it). There's a much better way to do this, but my solution was simply to move the items to a temporary LIFO, and then move them out of there onto the target. This one goes really slow. It takes about fifteen minutes to finish computing both results for this one. I need to go back and optimise my solution for day 5 at some point.

Full listing on GitHub

Part of a series of posts: Next in series >

Blog post

Echo is broken in Bash

Published: 2022-12-02 Updated: 2023-02-12

This blog post is also available in video form! Watch it on YouTube

Introduction

If you're reading this, you probably know what Bash is. For those that don't: Bash is the Bourne Again SHell, an open source shell compatible with the Bourne Shell, but that probably doesn't actually mean much if you're not already in the know. It's a computer program that interprets commands, launching other programs as requested, and passing data between them. It's the basis of a whole lot of bits of glue between other unix programs you use day to day. Bash is part of many software stacks that our modern way of life depends on.

Now I'm about to tell you just how badly the echo command in Bash is broken.

... what's that? ... I think I can hear the reader through the screen...

"But echo is such a simple command!? what could possibly be wrong with it?"

Nope. It's not simple. There's a lot of details. Strap in!

Quick side note for beginners: it's easy to confuse terminal emulators and shells when you first come to use them, because almost every time you use a terminal emulator, it's because you want to use your shell. They're two independent programs. The terminal emulator renders the output of a program to your screen. Bash is just one such program you might want to use this way. Terminal emulators don't have to launch shells when they start up. Shells are just programs after all. You don't have to use bash, you could be using a superior shell program. Similarly and separately: you don't have to use the terminal emulator that came with your linux distro, you could use a superior one. But anyway, if you are a beginner, don't let this worry you too much.

A quick quiz

Let's start with a nice easy quiz. How well do you know Bash?

Q1. What will this command output?

echo foo

Answer: foo, of course. That's an easy one.

Q2. How about if you pass the echo command something that looks like a program argument? What will this command output?

echo -a

Answer: -a, which makes sense. -a doesn't mean anything to echo, so it just prints it out verbatim.

Q3. What about some other letters? What does this output?

echo -b
echo -c
echo -d

Answer:

-b
-c
-d

Q4. Yeah, all of those do the same. Looks like a pattern is emerging, but how about this next one?

echo -e

Well, you know by the way I'm asking that the answer is different this time, so I guess this is the end of the quiz, but the right answer is "it prints nothing". I would also accept "Well technically it does print something. It prints one newline character." ... yes, well done, you are awarded a gold star that says "pedant" on it.

So, clearly echo is doing some argument parsing. It's not just blindly reproducing what you pass to it. Let's come back to this later.

What's the problem?

Suppose you're debugging a Bash script. You find that somewhere in the middle you get an error like bash: llvm-ar: command not found, but you're really sure that you've got all of llvm installed, so your first debugging step is to add echo $PATH to your script just before the llvm-ar command, perhaps the path is set to find a half-baked llvm install somewhere else. We all do this. We all use echo to print out the contents of a variable sometimes. And this is fine, especially if that variable is $PATH, since it's very unlikely to hit the issue I'm going to talk about.

Now, consider that you might be generating a list of arguments to pass to some other program. Here's a short script that will find the text "-right" in the file static/style.css. A not-unreasonable task.

pattern='-e -right'
grep $pattern static/style.css

If you run this script, you get the output anyone would expect. For example, perhaps the result looks like this:

    margin-right: 10px;
    padding-right:0.2em;
    margin-right: 0;

Great. Everything is working fine, nothing to see here. But what if the script is a bit more complicated and you end up needing to debug it at some point. Perhaps you need to know what the pattern variable is set to at that point just before the grep command.

pattern='-e -right'
echo $pattern

I tricked you! the quiz isn't over!

Q5. What does the above script print out?

Answer:

-right

huh!? where is the -e? It's obvious that the -e is missing here, but if the assignment was much earlier in the script, and the result not clear, then this could be a real headache to debug.

It doesn't matter that the text came from a variable, it looks like -e which is special for echo, and so it does the special thing instead of echoing -e. This means that echo $VAR will not always echo the value of the variable VAR. This is the fundamental problem with echo, as implemented in bash.

You cannot reliably use echo to output the contents of a variable1. It's not possible, and I think that's a bug in bash's echo implementation.

Of course, no amount of quoting can help you here. Here's a few attempts that still do not echo '-e':

$ export VAR=-e
$ echo $VAR

$ echo "$VAR"

$ echo '$VAR'
$VAR
$ echo '-e'

$ echo '-''e'

$ 

The quotes are removed by bash before echo ever sees the variable contents. So quoting does not solve this problem. Quoting does solve some other problems though, and failure to quote variables properly is actually the cause of lots of bugs. Maybe I should make a post about shell injection some time?

Another thing people sometimes try is adding in dashes. A lot of unix utilities use a single or double dash to indicate the end of parsing of dash-prefixed arguments. Bash's echo does no such thing.

$ echo - -e
- -e
$ echo -- -e
-- -e
$

Anyway, there's workarounds for when this is a problem, I'll get to those soon, but first let's look at an actual bug caused by not considering this behaviour of echo.

zipgrep, it's not you, it's your Arch linux package

zipgrep is a program that has a bug that exists because of this behaviour of echo. I'm sure there's lots of others, but this is the first one I found when looking for bugs like this in common tools that you might expect to find installed by default on some linux distros.

zipgrep is a tool that will search for a particular pattern of text in all the files in a zip file and tell you which ones match.

I'm going to make a file called foo which contains the word bar, then I'm going to zip that up as foo.zip and if I ask the unzip program to list all the files in foo.zip, it tells me that there's one called foo, as expected.

$ echo 'bar' > foo
$ zip foo.zip foo
  adding: foo (stored 0%)
$ unzip -Z1 foo.zip
foo
$

Now, let's ask zipgrep if it can find bar inside this zip file.

$ zipgrep bar foo.zip
foo:bar
$

No surprises here, it finds that the foo file contains bar, so it tells us that. great! that worked!

Now let's make a file called "-e", which just contains the word bar, let's put that in a zip file, I'll call it e.zip.

$ echo 'bar' > -e
$ zip e.zip -- -e
  adding: -e (stored 0%)
$

This is fine, and it all worked. if I list the files found in the zip file, I see that there is one file, and it is called "-e".

$ unzip -Z1 e.zip
-e
$

Maybe you can see where this is going.

Now I ask zipgrep to look for bar again, this time in e.zip. It should find a file called "-e" which contains bar. What it actually does is fail with a strange error message.

$ zipgrep bar e.zip
caution: filename not matched: 
$

Let's have a look at why this is. The answer is fairly simple. zipgrep first generates a list of all the filenames in the zip file, then for each name in that list, it escapes the filename by echoing it into this sed command, and then extracts just that file from the zip, and finally is able to grep that file for the pattern we're interested in.

    # Escape (or re-escape) shell-special characters in the archive
    # member name, "i".
    i=` echo "$i" | \
     sed -e 's/\\\\/\\\\\\\\/g' -e 's/|/\\\|/g' -e 's/&/\\\&/g' `

Let's just evaluate that echo|sed command step-by-step. The only file name is -e so that's the value of the i variable initially.

i=` echo "$i" | sed -e 's/\\\\/\\\\\\\\/g' -e 's/|/\\\|/g' -e 's/&/\\\&/g' `
i=` echo "-e" | sed -e 's/\\\\/\\\\\\\\/g' -e 's/|/\\\|/g' -e 's/&/\\\&/g' ` # substitue value of i
i=` echo      | sed -e 's/\\\\/\\\\\\\\/g' -e 's/|/\\\|/g' -e 's/&/\\\&/g' ` # equivalent to the above
i='' # the sed command operates on the empty string, the result is the empty string

Later on, zipgrep uses that empty string as the filename argument to the unzip command.

    # Globally, send fd 4 to stdout.  In the pipeline, send normal
    # stdout to fd 4, and send grep status to fd 3.  Collect fd 3
    # with ``.
    exec 4>&1
    status_grep=` ( \
     ( unzip -p-L "$zipfile" "$i" | \
     egrep $opt "$pat" 1>&4 ; echo $? >&3 ) 4>&1 | \
     sed "s|^|${i}:|" 1>&4 \
     ) 3>&1 `

Sure enough that's the cause of the strange error message we see.

$ unzip -p-L e.zip ""
caution: filename not matched: 
$

We can fix this! printf is kinda like a glorified version of echo, it behaves mostly like printf in C.

Let's replace this echo with a printf. Now the string will be printed exactly as it is passed to printf, it will not be interpreted as anything special.

<    i=` echo "$i" | \
---
>    i=` printf '%s' "$i" | \

The interesting thing about this bug is that it is specific to systems that package zipgrep such that it uses Bash as the interpreter. Some other shells do not do this with their echo commands, and I suspect that zipgrep was written with one of these in mind. The Arch linux package (at the time of writing) packages zipgrep to use Bash. Debian (at the time of writing) packages zipgrep "properly" such that it uses dash (Debian Almquist SHell) as the interpreter, since dash is what provides /bin/sh on Debian. Arch uses Bash as /bin/sh.

I think this highlights an even more fundamental issue with the design of Linux distributions, and programs that run on them. There are so many different options for what shell to use as /bin/sh. Which one is correct? What features can a program rely on? A program specifies what interpreter should be used to run it, but it's up to the operating system which interpreter is actually used. When a program specifies that it is to be run with /bin/sh, what does that mean? Does it really not care if you use Bash, Dash, Ash, Zsh? There are linux or unix systems that use each of these shells as the default for /bin/sh.

But wait! There's more! Fascinating workarounds ahead!

There's another option for working around this interesting echo behaviour, one that wouldn't work for fixing the zipgrep bug, but one that might be useful to know. To figure out what it is, let's look at what "-e" and "-n" actually do, and how Bash's echo implementation handles them.

The first place to look is the Bash man page, which explains its echo implementation. You can see that it mentions the optional arguments "-e", "-n" and "-E". we're less interested in "-E" because on most systems it's ignored.

"-n" simply prevents the final newline character being printed. You can see the effects of this in your terminal by comparing these two echos...

$ echo foo
foo
$
$ echo -n foo
foo$

"-e" enables interpreting of escape sequences. There's a big list of them. A common one is \n, which inserts a newline when escape sequences are enabled.

$ echo 'foo\nbar'
foo\nbar
$
$ echo -e 'foo\nbar'
foo
bar
$

We can also remove the final newline by using -n like this...

$ echo -e -n 'foo\nbar'
foo
bar$

Note that it's fairly common for unix programs to allow multiple single-char options to be specified next to each other. This next command is exactly the same as the previous command where we have the "-e" and the "-n" separate.

$ echo -enenenen 'foo\nbar'
foo
bar$

You can see it doesn't even matter how many times we specify each of the options. But if we add an option that isn't recognised then suddenly all of the options in that one argument are ignored. So here, "-enx" gets echoed exactly as we typed it...

$ echo -enx 'foo\nbar'
-enx foo\nbar
$

So if we have a variable and we want to print its value to the screen, we can take advantage of this fact, and this is how the second workaround option works: add a space to the end of the argument. We need to be careful to add double quotes so that the space becomes part of the first argument, if there is one.

So suppose foo contained -e, normally this would cause us a problem, but this time there's also a space character at the end, which is not a valid echo option, this whole argument is treated as not-special, and is just printed as-is.

$ export foo='-e'
$ echo "$foo "
-e 
$

there's an additional space character at the end, but in this case we don't actually care about that, it's not like we can see a space character at the end of a line anyway.

Hmm what's that? You have a terminal that renders little dots where trailing spaces are? Quiet you!

Anyway, this wouldn't have worked for our zipgrep fix, since we're using the result as an argument to another program, rather than simply printing it to the screen. If there was an extra space character in there then it wouldn't work, so printf is still the best way to do this in general.

Now that we're done talking about how the bash implementation of echo is tricky, I wanna take a moment to look at other echo implementations. Almost every shell has its own implementation of echo, let's look at these shells:

bash, dash, zsh, fish, tcsh, xonsh

Each one of these has echo as a built in command, so let's type the same thing into every one of these shells, and see what each one does. This is the command we will use:

echo - - -n "foo\bar\\ntext``"

So let's go! Here are the outputs of this command from each of those shells:

bash

- - -n foo\bar\ntest

dash

- - -n foar
test

zsh

n -n foar
test

fish

- - -n foo\bar\ntest``

tcsh

- - -n foar\ntest

xonsh

- - -n foar\ntest``

Remember that we're now not just comparing the echo behaviours across shells, but we're also allowing other shell features to have an influence here, for example string escaping, argument splitting, and command substitution.

Each of these shells does something unique with this input. That's six different shells, and six different results.

A challenge for you

The quiz continues! but this time I'm not telling the answer. Update: I have actually posted some answers in the update section below

I'll leave you with a challenge. The challenge is to get Bash's echo to output the following two bytes and nothing more: -n

Just those two bytes. Just a dash, followed by a lower case N. You're not allowed to have additional characters before or after them, so you can't use the trailing space trick from before. You must only use echo, no piping the output to another program to post-process it. And since you need just those two bytes, that means no newline character at the end.

For a while I thought that it was impossible, but actually it is possible to do, and it's especially fun to give as a challenge to friends that haven't read this post yet, so challenge your friends!

You can check if you've got it right by piping the output to a hex dump utility such as xxd. A successful attempt looks like this:

$ echo ...your.input.here... | xxd
00000000: 2d6e                                     -n 
$

Footnotes

1

Okay, technically that's not true, but the answer relies on other Bash features that preprocess the string so that echo will re-process the string back in to the original. It's ugly: echo -e "${VAR//\\/\\\\}\n\c". It works by using the \n\c escape sequence in -e mode to make sure the string is never a valid option argument, and it defuses escape sequences from the input string by escaping them with extra backslashes using Bash's string substitution syntax. It's not neat, it's going to raise questions in code review, but it does technically get the job done.

UPDATE: Follow up Q and A

(published 2023-02-12)

You all enjoyed that post! So here's some answers to questions you asked. Spoilers ahead for the challenge!

Non-solutions

Some people suggested some things that don't work, or appear to work visually but are doing something different.

The first category was using dashes, but that doesn't work.

$ echo -n - -n
- -n$
$ echo -n -- -n
-- -n$

I suspect that the people who thought echo -n - -n would work were accidentally using Zsh instead of Bash.

Some other people used the backspace character (or its escape sequence) as part of their solution. This is not a valid solution. It appears to work in the terminal, because of how the backspace is interpreted, but it fails the rigourous test with xxd.

For example, you can print a backspace character at the start, which does nothing, but isn't a valid option. The character is there even though you can't see it.

echo -en '\b-n'

Another attempt is to have the backspace at the end, after a sacrificial character

echo -en '-n \b'

Solutions

There's a few solutions that use escape sequences to generate one or both of the characters in the sequence. These are all the same concept, they prevent echo from interpreting them as options, but are then parsed as escape sequences if -e is specified.

Here's a few of these:

echo -en '\u002dn'
echo -en '\055n'
echo -en '-\u006e'

The next solution is the one that I found first. This is where the special escape sequence \c is used. This escape sequence doesn't evaluate to some other character. It actually makes echo stop outputting anything after the \c. There's nothing there anyway, but its presence prevents the option from being valid

echo -e '-n\c'

Bending the rules without breaking them

Some smart arses very clever people found ways to bend the rules so they technically complied with the requirements but didn't solve the problem the way I intended. Here's one...

echo -n - ; echo -n n

Yep, it only uses echo, it prints the two characters I asked for and nothing else, it doesn't pipe the output anywhere. Nicely done! I can't be too mad.

Then someone did this:

echo -n n-

And, yeah, I suppose I wasn't explicit that they have to be in the right order, but I reject this "solution" regardless!