원본보다 재는 도구가 먼저 틀렸다
옛 DOS 전략 게임 한 편을 맥과 아이폰에서 다시 짓고 있습니다. 원본을 에뮬레이터에서 그대로 돌려 정답지로 쓰고, Swift 로 옮긴 엔진은 같은 입력에서 저장 상태의 바이트와 난수까지 원본과 같아야 통과합니다. 녹화로 닿기 어려운 갈래는 원본 기계어를 CPU 에뮬레이터에서 화면 없이 돌려 견줍니다. 10월 22일에 시작해 닷새 동안 커밋이 137개 쌓였고, 대조는 Claude 와 함께 했습니다.
그동안 원본과 엔진이 어긋난다고 볼 뻔한 일 가운데 여럿은 원본도 엔진도 건드리지 않고 둘을 견주는 도구를 고쳐서 풀렸습니다. 도구가 헐거워서 어긋남을 못 본 일도 있었습니다. 뒤의 것이 더 위험합니다. 통과했다는 답은 아무도 다시 들여다보게 만들지 않으니까요.
난수가 어긋났는데 시험이 통과했다
10월 23일 아침, 전투 기록 하나를 새로 견주면서 엔진을 일부러 틀리게 한 변이 아홉 개를 하나씩 넣어 돌렸습니다. 변이는 대조가 틀린 것을 정말 잡는지 보려고 엔진의 한 줄을 바꿔 둔 판입니다. 그중 피해 셈의 덤 하나를 뺀 변이가 중간의 한 차례에서 난수만 어긋났는데, 시험은 통과했습니다.
시험은 차례마다 보고를 한 줄씩 찍습니다. 원본과 다른 바이트가 몇 개인지와 난수가 같은지가 한 줄에 함께 들어가고, 난수가 틀리면 두 값을 부등호로 이어 적습니다. 실패 조건은 "다름"이라는 글자가 든 줄 가운데 "다름 0"이 아닌 줄을 찾는 식이었습니다. 바이트가 모두 같고 난수만 틀리면 그 줄은 "다름 0"으로 시작하니 걸리지 않았습니다. 난수가 틀렸다는 표시는 보고에 찍혔지만, 시험은 그 표시를 보지 않았습니다.
같은 식을 쓰던 시험이 하나 더 있었습니다. 같은 날 새벽 2시에 넣은 전투 차례 시험이었고, 그 뒤 여섯 시간 동안 커밋 열세 개가 쌓이는 내내 그대로였습니다. 그 시험을 넣을 때도 변이 여덟 개를 돌려 여섯이 걸렸습니다. 바이트로만 실패할 수 있는 시험이었으니 걸린 여섯은 모두 바이트를 바꾼 변이였고, 변이를 돌리고 있었는데도 구멍이 보이지 않은 까닭이 거기 있습니다. 지금은 두 시험 모두 난수가 어긋나도 실패합니다. 나머지 전투 시험은 처음부터 그랬습니다.
안 걸린 변이가 시험의 빈칸을 가리켰다
이 일 뒤로 변이 결과는 "몇 개 중 몇 개"로 적고, 안 걸린 변이마다 까닭을 문서에 남깁니다. 까닭은 대개 셋 가운데 하나였습니다.
하나는 변이를 넣어도 식이 같아지는 경우입니다. 10월 26일 화면 옆 칸을 원본이 그린 160판과 견줬을 때 변이 24개 중 22개가 걸렸습니다. 남은 하나는 막대 상한을 하나 늘린 것인데, 막대를 반 높이로 그리니 둘이 같은 높이가 되어 그림이 같았습니다.
둘째는 입력이 경계에 닿지 않은 경우입니다. 같은 160판에서 속도 셈의 상한을 하나 올린 변이는 어느 판도 그 경계에 닿지 않았습니다. 앞의 전투 기록은 9개 중 6개였고, 남은 셋은 그 기록의 피해가 모두 1이라 피해 셈을 바꿔도 결과가 같았습니다. 이런 빈칸은 판을 더하면 메워집니다. 대화 갈래 하나는 처음 판으로 22개 중 18개만 걸렸는데, 문턱에 꼭 맞는 값을 넣은 판을 더하자 22개가 모두 걸렸습니다.
셋째는 재는 곳 밖에 남는 값입니다. 전투가 끝난 뒤 원본이 묻는 두 화면은 12개 중 11개가 걸렸습니다. 남은 하나는 화면에서 고른 수량을 원본이 스택에만 두었다가 버리는 자리라, 저장 상태에는 견줄 것이 없습니다.
변이가 대조를 재는 자라면, 대조가 엔진의 어디를 지나갔는지는 또 하나의 자입니다. 10월 25일 원본 대조 시험이 지나간 엔진 줄을 세는 도구를 만들었고, 첫 값은 8,158줄 중 6,494줄(79.6%)이었습니다. 같은 날 제가 남은 역공학을 마저 하자고 해서, 문서에 "코드로만 옮김"이라 적어 둔 96곳을 갈랐습니다. 상태나 대사 번호가 갈리는 갈래를 화면 없는 원본과 무작위로 견주는 묶음 여섯을 돌리자 8,219줄 중 6,907줄(84.0%)이 됐습니다. 남은 갈래는 문서에 줄마다 적어 두었습니다.
원본이 끝없이 돈 것은 도구 탓이었다
10월 25일, 화면 없는 원본에서 하루가 지날 때 도는 함수를 여러 번 불렀더니 원본이 끝없이 돌았습니다. 원본 탓으로 적기 전에 두 가지를 돌려 봤습니다. 상태를 하나도 바꾸지 않은 스냅숏으로 불러도 멈췄고, 스택을 맨 위에서 시작하게 하면 멈추지 않았습니다. 도구가 함수에서 돌아온 뒤 스택 포인터를 되돌리지 않아 부를 때마다 스택이 1KB씩 깊어졌고, 아홉 번쯤에 지역 변수를 7KB 쓰는 길 찾기 함수가 스택 아래의 전역 자료를 덮은 것이었습니다. 지금은 돌아오면 레지스터 여섯을 부르기 전 값으로 되돌립니다.
디스어셈블 스크립트도 틀렸습니다. 16비트 코드의 가까운 호출은 목표가 64KB 구간 안에서 감기는데, 스크립트는 감지 않고 찍었습니다. 구간 뒤쪽의 함수를 앞쪽에서 부르면 목표가 64KB 작게 나왔고, 10월 23일 그 값으로 화면 하나의 자리를 문서와 엔진 주석에 적었습니다. 그 자리는 전혀 다른 함수의 한가운데였습니다. 같은 날 바로잡았고, 지금은 목표가 함수 첫머리가 아니면 64KB 앞뒤를 봅니다.
잘라 읽고, 섞어 셌다
10월 26일에는 화면을 다시 그릴 때 어떤 함수가 불리는지 추적하다가, 결과를 끝부분만 남기고 잘라 읽는 바람에 날짜를 그리는 함수가 안 불린다고 봤습니다. 전체를 찍자 불리고 있었습니다.
10월 23일에는 한 전투에서 주고받은 횟수를 값이 바뀐 줄로 셌습니다. 같은 값을 다시 쓰면 줄에 보이지 않고, 피해가 0인 차례는 막대도 그대로입니다(열여덟 번 중 일곱 번이 피해 0이었습니다). 두 방법을 섞어 열여섯 번으로 세어 문서에 적었다가, 11분 뒤 열여덟 번으로 고쳤습니다. 지금은 차례마다 0과 1을 오가는 값으로 셉니다.
화면 없는 도구를 처음 돌린 날에는 넣은 Enter 가 하나씩 사라졌습니다. 키 버퍼를 비우는 자리를 키를 기다리는 자리로 본 탓이었습니다. 시간도 흐르지 않았는데, 타이머 틱 경계가 늘 인터럽트가 꺼진 자리에 떨어져서였습니다. 원본이 키를 기다릴 때만 키를 넣는 녹화 도구는 확인 창을 메뉴로 알고 거절 쪽을 고른 적이 있습니다. 상태는 바뀌지 않아 그 기록은 그대로 썼고 도구는 고쳤지만, 고친 뒤로는 아직 돌려 보지 않았습니다.
정리하면
시험이 통과하면 그 시험이 무엇으로 실패할 수 있는지부터 봅니다. 보고에 찍히는 것과 실패 조건이 보는 것은 다를 수 있습니다.
변이는 몇 개 중 몇 개가 걸렸는지와 안 걸린 까닭까지 적습니다. 식이 같아진 변이는 그렇다고 적고, 입력이 닿지 않았으면 판을 더하고, 재는 곳 밖의 값은 못 잰다고 남깁니다.
원본이 이상하게 굴면 원본에 대해 적기 전에, 도구의 조건만 바꾼 판으로 한 번 더 돌립니다.
잘라 읽은 출력으로는 "안 불린다"고 말하지 않습니다. 값이 바뀐 줄로 센 횟수는 같은 값이 다시 쓰인 차례를 빠뜨립니다.
도구가 보여 준 것을 지금으로 읽은 다른 주의 기록은 따로 적었습니다. 재는 자가 틀렸던 다른 날의 기록도 있습니다.
I am rebuilding an old DOS strategy game for the Mac and the iPhone. The original runs unchanged in an emulator as the answer key, and the engine ported to Swift passes only when, from the same input, the bytes of the saved state and even the random numbers match the original. Branches that recordings rarely reach are compared by running the original machine code in a CPU emulator with no screen. I started on October 22, 137 commits piled up over five days, and the comparisons were done together with Claude.
Over that time, several of the cases where I nearly concluded that the original and the engine disagreed were resolved without touching either one, by fixing the tool that compares them. There were also times when a tool was too loose to see a mismatch at all. The second kind is more dangerous. A passing answer gives nobody a reason to look again.
The random numbers diverged and the test passed
On the morning of October 23, while comparing a new battle recording, I put in nine mutations one at a time, each making the engine wrong on purpose. A mutation is a version of the engine with one line changed, to see whether the comparison really catches something wrong. One of them, which removed a single bonus from the damage calculation, diverged only in the random numbers at one turn in the middle, and the test passed.
The test prints one report line per turn. How many bytes differ from the original and whether the random numbers match go on the same line, and when the random numbers differ, the two values are written joined by an inequality sign. The failure condition looked among the lines containing "differs" for any that did not read "differs 0". If every byte matched and only the random number was wrong, that line began with "differs 0" and was not caught. The mark saying the random numbers were wrong was printed in the report, but the test never looked at it.
One more test used the same condition. It was a battle turn test added at 2 a.m. the same day, and it stayed that way for the six hours in which thirteen commits piled up after it. When that test went in, I ran eight mutations as well, and six were caught. Since the test could fail only on bytes, the six it caught were all mutations that changed bytes, and that is why the hole did not show even though mutations were being run. Both tests now fail when the random numbers diverge too. The other battle tests did so from the start.
The mutations that slipped through pointed at blanks in the tests
Since then, mutation results are written as "n of N", and for each mutation that slips through, the reason goes into the notes. The reason was usually one of three.
One is when the formula comes out the same even with the mutation in. On October 26, comparing the side panel of the screen against 160 cases drawn by the original, 22 of 24 mutations were caught. One of the remaining ones raised a bar's upper limit by one, but the bar is drawn at half height, so the two came out the same height and the picture was identical.
The second is when the input never reaches a boundary. In the same 160 cases, for a mutation that raised the upper limit of the speed calculation by one, no case ever reached that limit. The battle recording above was 6 of 9, and for the remaining three, the damage in that recording was always 1, so changing the damage calculation left the result the same. Blanks like these fill in when cases are added. One dialogue branch caught only 18 of 22 with its first cases, and once cases with values sitting exactly on the threshold were added, all 22 were caught.
The third is a value that stays outside what is being measured. The two screens the original asks after a battle caught 11 of 12. The remaining one is a place where the original keeps the quantity chosen on screen only on the stack and then discards it, so there is nothing to compare in the saved state.
If mutations are a ruler for the comparisons, where the comparisons pass through the engine is another ruler. On October 25 I made a tool that counts the engine lines the tests against the original pass through, and the first value was 6,494 of 8,158 lines (79.6%). The same day I asked to finish the remaining reverse engineering, so I worked through the 96 places the notes had marked "ported from code only". Running six batches of randomized comparisons against the screenless original, covering branches that split on state or dialogue line number, brought it to 6,907 of 8,219 lines (84.0%). The remaining branches are listed line by line in the notes.
The original looping forever was the tool's fault
On October 25, calling the day-passing function several times in the screenless original made it loop forever. Before writing it down as the original's fault, I tried two things. Called with a snapshot whose state had not been changed at all, it still hung, and with the stack starting at the very top, it did not. The tool was not restoring the stack pointer after returning from a function, so the stack sank 1KB deeper with every call, and around the ninth call a pathfinding function using 7KB of local variables overwrote the global data below the stack. Now, on return, it restores six registers to their values from before the call.
The disassembly script was wrong too. In 16-bit code, a near call's target wraps around within a 64KB segment, but the script printed it without wrapping. When a function near the end of the segment was called from near the start, the target came out 64KB too small, and on October 23 I used that value to write the location of one screen into the notes and an engine comment. That location was in the middle of an entirely different function. It was corrected the same day, and now, when a target is not the start of a function, the script looks 64KB before and after.
Read truncated, counted with mixed methods
On October 26, while tracing which functions are called when the screen is redrawn, I read the result with only its tail kept, and concluded that the function that draws the date was not being called. Printing all of it showed it was being called.
On October 23, I counted the exchanges in one battle by the lines where a value changed. Writing the same value again does not show up in those lines, and on turns with 0 damage the bar does not move either (seven of the eighteen were 0 damage). I mixed the two methods, counted sixteen and wrote that in the notes, then corrected it to eighteen 11 minutes later. Now I count with a value that flips between 0 and 1 every turn.
On the first day I ran the tool with no screen, the Enter presses I fed in went missing one at a time. A place that empties the key buffer had been taken for a place that waits for a key. Time did not pass either, because the timer tick boundary always fell where interrupts were switched off. The recording tool, which feeds keys only when the original is waiting for one, once took a confirmation box for a menu and picked the decline option. The state did not change, so that recording was used as it was and the tool was fixed, but it has not been run again since the fix.
In short
When a test passes, I first look at what it is able to fail on. What gets printed in the report and what the failure condition looks at can be different things.
For mutations, I write down how many out of how many were caught and why the others slipped through. A mutation that comes out the same is noted as such, a boundary the input never reached gets more cases, and a value outside what is measured is recorded as something that cannot be measured.
When the original behaves strangely, before writing anything about the original, I run it once more with only the tool's conditions changed.
From truncated output I do not say "not called". A count taken from the lines where a value changed misses the turns where the same value was written again.
The case from another week, where I took what a tool showed as the present state, is written up separately. There is also a record of another day when the ruler was wrong.